deer-flow/backend/tests/test_scheduler_agent_repository.py
Totoro 35cdcab1c5
feat(scheduled-tasks): signals, honest notices and fair queueing for server-started runs (RFC #6340, 2/2) (#6393)
* feat(scheduler): lifecycle rules, goal/limit parity and coded errors for scheduled tasks

- Migration 0031: nullable scheduled_tasks.unmet_streak_after_seq (internal
  streak boundary) and stop_condition (the user's stop rule, own column).
- Stop rule is normalized (stop_rule.py) and appended only at launch; the
  stored prompt never contains it. Wording adapts when scheduler.tool_enabled
  is off.
- Willem 1: page-created tasks get goal evaluation, <standing_notes>, the
  previous-run reference and own-schedule stop; request_stop and the
  scheduled capability no longer require an origin conversation.
- Repository: single reactivation choke point raising
  ScheduledTaskLimitsExhausted; streak boundary moves on goal/prompt/stop
  condition/note changes (not on resume); goal-check failures neither count
  nor reset the streak; pause of a finished task returns "finished"; trials
  on a paused task keep the host pause marker.
- New repository reads: automatic_runs_used_for, active_run_status_for,
  list_manageable_from_thread, thread_relation/thread_run on thread tasks,
  task_ids_for_thread, run_number, and run_number/total_tokens/summary on
  run history rows.
- REST: goal/max_runs/end_at/stop_condition on create and PATCH (null
  clears, naive end_at = task timezone), resume recomputes from now with an
  optional renewal body, once_time_passed, task_finished, limits_exhausted,
  scheduler_not_running on create, trigger returns outcome/existing/thread_id,
  task responses add automatic_runs_used and active_run_status.
- Coded errors {code, message, params} for routes, shared validation and the
  chat capability (scheduled_task_errors.py), pinned by
  contracts/scheduled_task_errors_contract.json; goal notes contract v2 with
  check_failure_codes, scheduled_origin_key and host_run_errors (host_notes.py).
- /api/features adds scheduled_tasks {available, running, tool_enabled,
  min_interval_seconds}; ScheduledTaskService.is_running.
- Docs: six README scheduler sections, API.md scheduled tasks section
  (breaking error shape), CONFIGURATION.md, AGENTS notes, CHANGELOGs.
- Tests: migration 0031, stop rule, error contract, run listing, lifecycle
  over HTTP, repository, service and capability cases; updated tests for the
  new error shape, finished-task pause and head revision.

* feat(scheduler): conversation update/resume, run-conversation authority and readable launches

- schedule_task: update and resume actions, stop_condition and clear_fields
  parameters, plain parameter types (value rules come back as coded results),
  rewritten docstrings for schedule_task and stop_scheduled_task.
- Capability: update/resume share the REST validation and error codes;
  interactive turns in a task's run conversation may manage that task;
  scheduled runs keep only own-stop; grants require a running scheduler.
- Results: compact JSON-safe task views with local times, display card/text,
  last run in list, timezone_source/browser_timezone, now_local; no ISO, user,
  lease or origin fields; stop_instructions removed.
- Timezone: explicit > browser (context.client_timezone, validated in
  start_run and never forwarded to the run config) > not needed for intervals
  and offset run_at > timezone_required.
- Trial gate accepts natural direct requests after acknowledgements and
  particles; trial results report thread_id and existing.
- Scheduled launches: stable message id scheduled-<task_run_id>, server-owned
  deerflow_scheduled_origin metadata with the user-language parts, run thread
  title for fresh-thread tasks.
- Worker records goal continuations in the verdict; lead prompt language rule
  covers stored task text and scheduled runs.
- Docs: six READMEs, CONFIGURATION, API, runtime/tools AGENTS, CHANGELOGs.

* feat(frontend): scheduled-task core types, formatting, errors and glossary

- throwGatewayApiError now throws GatewayApiError (status, code, params,
  rawMessage); message stays the string detail or detail.message
- scheduled-task types gain stop_condition, automatic_runs_used,
  active_run_status, origin/notes, run_number/total_tokens/summary, thread
  relation, trigger result, renewal and scheduled origin; isTaskBusy and
  hasActiveRun helpers
- api: fetchScheduledTask, resume with optional renewal body, typed trigger
  result and update payload with null clears
- hooks: polling at 3 s while a run is active (list, thread list, run
  history), useScheduledTask with live gating and final 404, useInView,
  localized error toasts; run history refreshes tasks when a run finishes
- new pure modules: errors.ts (contract code to localized copy), format.ts
  (relative task times, viewer time, display zone), status.ts, actions.ts,
  run-error.ts; describeTaskSchedule in cron.ts; goal-outcome adds unchecked
  goal checks, describeTaskOutcome and parseStopRunId
- features: scheduled_tasks block with defaults when missing
- buildRunContext sends client_timezone
- titleOfThread takes a localized untitled label; breadcrumb names scheduled
  tasks and agents; reference chips use the localized untitled label
- schedule input: shared browserTimeZone, labelled selects, aria-pressed
  type toggles, interval minimum from the hint template
- i18n: all PR1 scheduled-task keys in en-US and zh-CN, glossary fixes,
  recipe instructions moved into i18n
- e2e mocks follow the new task, trigger, resume, thread-task and features
  shapes; expectNoRawIdentifiers helpers for e2e and DOM tests
- tests for errors, format, cron, status, actions, goal outcome, run errors,
  hooks, run context, thread titles and features; scheduled e2e copy updated

* feat(frontend): list-first scheduled tasks page with outcomes and editable goals

- page.tsx is now a thin composition of components/workspace/scheduled-tasks:
  status tabs (All/Active/Paused/Finished) and search over the task list,
  ?task_id= deep link with router.replace on selection, ?thread_id= chip
  with Show all, empty state, scheduler-off notice and unavailable state
- task list rows show the schedule in words and one status line (next run,
  running now, paused by agent, auto-paused, finished by its cap)
- task detail: status badge, actions from availableActions with reasons,
  More actions menu (Duplicate, Copy task ID, Delete), outcome notice,
  Runs / Stops when / Each run's goal / Does / Notes from chat / History,
  origin chat link; success toasts for every action
- run rows: run number or Trial run, summary, goal and assumption badges,
  continuations, tokens, Open chat link; raw errors and the evaluator
  reason only behind Details
- create/edit/duplicate dialog with goal, stop condition, safety caps and
  advanced agent/context options; PATCH sends only changed fields, null
  clears a cap
- renew dialog raises or removes caps and resumes in one request; a
  limits_exhausted Resume opens it
- removed i18n keys the old page used; added feedback.resumedNoTime
- recorded en-3 and zh-1 page fixtures; scheduled e2e specs rewritten for
  the new page; DOM tests for the detail and the form dialog
- CHANGELOG entries and the frontend AGENTS.md scheduled-task note

* feat(frontend): live schedule card, run conversation provenance and header entry

- schedule_task results (create, update, pause, resume, trial, delete) become
  an assistant:scheduled-task message group rendered as a live card: schedule,
  next run, stop condition with the safety cap, goal, where results go, Run
  once now, Pause/Resume and Open task; the card polls the task only while it
  is on screen and shows deleted, scheduler-off and limits-exhausted states
- one card per task per assistant turn; the card group is not a turn boundary
  for usage, branching, editing, outline or skill attribution
- a human message with deerflow_scheduled_origin stays a human group with
  scheduledOrigin and renders as a "Scheduled run / Trial run" block with the
  task instructions, stop condition and notes collapsed; the launched text is
  never shown and the message is not editable
- readable step labels for schedule_task actions and stop_scheduled_task
- ThreadScheduledTasksButton replaces the header link: hidden without tasks,
  shows the count, links to the task (or the chat filter), and a run's chat
  links to its task
- recorded en-3 / zh-1 chat and run-thread fixtures; chat-card and run-thread
  e2e specs; unit and DOM tests for parsing, grouping, turn boundaries, card,
  run block, header button, step labels and reconnect hydration
- i18n: header.countLabelOne added, unused card.next removed; CHANGELOG and
  frontend AGENTS.md notes

* fix(scheduler): address verification findings

Move the scheduled-task lifecycle guidance from backend/AGENTS.md into the persistence guide and leave a one-line pointer, so the effective AGENTS.md chains for agents/middlewares, sandbox and subagents stay under the 98304-byte hard limit enforced by scripts/check_agent_guidance.py in lint-check.

* fix(scheduler): address review findings

* fix(gateway): no-transform on SSE responses

All four text/event-stream responses (thread run create stream, join,
existing-run GET/POST stream, stateless create stream) now take their
headers from app/gateway/sse_headers.py and send
Cache-Control: no-cache, no-transform, so compressing proxies such as
Next's rewrite proxy stop buffering streams. Content-Location and
X-Accel-Buffering are unchanged; scheduled and MCP-notification runs keep
stream_mode=None.

Tests pin the headers on every SSE route and fail on a literal no-cache
header left in routers. Docs: API.md SSE headers note, CHANGELOGs.

* feat(scheduler): per-owner run cap and fair queue selection

New scheduler.max_concurrent_runs_per_user (default 2, 0 = off, effective
min(cap, max_concurrent_runs)) caps launching/running scheduled runs per task
owner. claim_queued_run checks it right after the global count under the same
budget lock, so it is atomic across workers and Pods. list_queued_runs ranks
same-thread FIFO heads per owner with ROW_NUMBER() OVER (PARTITION BY owner)
and orders the batch by that rank, so the drain is owner-fair even with the
cap off; owners at their cap drop out before the batch limit. Orphan rows
(task deleted while queued) are never held back by the cap.

Gateway lifespan passes the startup value; the service constructor default
stays 0. Docs: config.example.yaml (config_version 54), CONFIGURATION.md,
the six READMEs, backend AGENTS.md, CHANGELOGs (behavior change flagged).
The live-task quota is untouched.

* feat(scheduler): durable lifecycle events for the originating chat

When a chat-created schedule is paused by the agent, auto-paused or finishes,
finalization now reports task_stopped / task_paused / task_finished, only on a
live -> paused/finished transition. The new finish_task_at_end_condition
replaces the three inline "mark completed" blocks (admission rejected as ended,
claim-time skip, complete_if_ended), so every site emits exactly once.

The scheduler's finalization observer is always installed. It writes
scheduled_task_events rows for the originating chat in the same transaction as
the state change, deduplicated on (task_id, anchor, event), with a title
snapshot, stop condition, run number, last run outcome and the chat's newest
run as placement anchor. Lookups fall back on bad stored data; only database
errors propagate. Manual trials drop only run_* events. The IM step keeps
PR1's selection until B4.

New GET /api/threads/{thread_id}/scheduled-task-events (owner check, caller's
rows, oldest first); rows survive task deletion and go with the chat.
Migration 0032_activity_and_task_events adds the events table plus the
run-origin column/index and read-state tables used later, each object guarded
on its own. Contract scheduled_goal_notes v3 pins the lifecycle vocabulary.
Docs: API.md, migrations chain, backend AGENTS.md, six READMEs, CHANGELOGs.

* feat(scheduler): honest, localized and self-contained IM notices

Every scheduled-task IM notice is now enqueued by the finalization observer
in the transaction that records the outcome, one message per occurrence
(task_stopped > task_paused > task_finished > run_failed > run_unmet >
run_completed; a once task sends only its run event). The merged auto-pause
replaces the separate unmet + pause messages, agent stops and finishes now
notify, and recovery-finalized runs notify exactly once. Idle finishes use a
deterministic idle: key derived from the lifecycle anchor. The old
non-transactional enqueue in handle_run_completion is removed.

New app/channels/capabilities.py holds CHANNEL_CAPABILITIES with a
proactive_notifications flag (adds the missing qq entry); only push-capable
providers (WeCom) get rows, /api/channels/providers returns the flag, and the
worker ends legacy rows for other providers as terminal failed.

New app/scheduler/notification_text.py renders en-US/zh-CN text: title, what
happened (plus the last run's outcome), the tasks page's one-line run summary
(redacted) when the agent replied, and a closing line. No IDs, no links, no
public_base_url. Locale is the owner's new `locale` preference, else the new
channel_connections.notification_locale (default en-US).

Docs: config.example.yaml (config_version 55), CONFIGURATION.md, API.md,
channels AGENTS.md, six READMEs, CHANGELOGs (behavior change flagged).

* feat(gateway): thread origin, activity feed and read markers for server-created threads

Runs started by the server for a user (scheduler, IM channels, GitHub
agents, extension handles, MCP notifications) now carry a server-owned
metadata.deerflow_origin {kind, provider?, namespace?} (new harness module
deerflow.runtime.run_origin, pinned by contracts/thread_origin_contract.json).
It is stamped only from request.state.run_origin or by the internal channel
caller; run admission drops client copies from both metadata and
config.metadata, and thread create/patch strip it. RunRepository derives
runs.origin_kind on put and on create_thread_operation_atomic (agent runs
only), and gains latest_change().

New ThreadReadRepository keeps a per-user, never-decreasing read position
(thread_read_markers) and a per-user read clock (thread_read_versions).
POST /api/threads/{id}/read marks a thread read, thread search items carry
unread, and thread delete removes the markers. GET /api/thread-activity pages
the caller's run changes over the run-change clock, returns only threads
changed by server-originated runs plus read_version, and 503s without SQL;
/api/features reports thread_activity.available.

Docs: API.md, gateway AGENTS.md (condensed to stay under its budget),
CHANGELOGs.

* fix(scheduler): adapt PR2 to PR1 follow-ups

PR1 moved the scheduled-task lifecycle rules out of backend/AGENTS.md into
the persistence guide and grew the sandbox AGENTS.md chain to within 267
bytes of its hard limit. The per-owner queue-fairness detail now lives in
the persistence guide next to the lifecycle rules (backend/AGENTS.md keeps
the cap and a link), so check_agent_guidance passes again.

PR1's goal-outcome unit test pinned scheduled_goal_notes_contract version 2;
PR2 bumps it to 3 (lifecycle vocabulary only, the v2 keys are unchanged).

* fix(scheduled-tasks): polish from live acceptance

- zh schedule wording: an interval of one unit reads 每分钟 / 每小时 / 每秒,
  and a saved interval of whole days reads 每天 / 每 2 天 (Every day / Every 2
  days) instead of 每 1 分钟 or 每 24 小时; several units keep the number
- zh spacing: 已于{time} 满足 and 在{time} 的运行中 now leave a space between
  the interpolated time and the Chinese after it; a copy test guards every
  scheduled-task zh string against a placeholder glued to Chinese
- run summary: when the first line of the final reply only leads in to a list
  (ends with ":" or ":"), the list items follow it as plain text (bullets,
  numbering, checkboxes, bold, code and links stripped), joined with ";" for
  CJK text and "; " otherwise, within the 160-character cap
- a schedule_task result (create, update, pause, resume, trial, delete) that
  arrives in a chat invalidates that chat's task list, the tasks list and the
  named task, so the header button and cards update without waiting for the
  idle poll; results already in the loaded history do not refetch
- e2e and unit fixtures are now the live acceptance recordings (DeepSeek
  Flash, demo data, fictional names): live-weekday.json (create, trial, edit,
  pause, resume in one zh chat) and live-minute.json (per-minute chat, run 1
  and run 2, paused by the agent), fetched with GET from the demo Gateway and
  trimmed; the hand-shaped en-3 / zh-1 fixtures are removed and the chat-card,
  run-thread and tasks-page specs run in both locales over the recorded data

* docs(changelog): reference #6378 for the scheduled-tasks entries

* docs(agents): shorten the scheduled-task pointer to stay under the guidance limit

* test(scheduled-tasks): pin the live takes to their recorded time zone

The live fixtures were recorded in Asia/Shanghai, and an interval task
reads in the viewer's zone, so the 16:48 assertions failed on UTC CI
runners. Pin the browser zone in the two live-take e2e specs and the
zh live-take unit test.

* feat(frontend): thread origin, activity polling, read markers and task events core

Frontend core for server-created threads and schedule lifecycle events
(PR2 F1); the sidebar markers (F2) and the chat event line (F3) build on it.

- core/threads/origin.ts: threadOriginOf reads metadata.deerflow_origin,
  then channel_source (github -> GitHub origin), then a legacy
  scheduled_task_id; key and kinds pinned to
  contracts/thread_origin_contract.json. labelOfThreadOrigin and the now
  exported labelOfChannelProvider(provider, t) use the new localized
  threads.origin.providers names (飞书, 企业微信, ...), with the English map
  (gaining GitHub) only as the fallback.
- core/threads/activity.ts: useThreadActivity polls /api/thread-activity
  every 15 s (focus refetch, never in the background, off unless
  features.thread_activity.available). The first response only seeds the
  cursor; server-origin threads, a truncated page or a higher read_version
  invalidate the thread lists, a scheduled thread also ["scheduled-tasks"];
  an invalid cursor re-seeds. useMarkThreadRead debounces POST /read by 1 s,
  skips a thread whose cached unread is false, patches the search and
  infinite caches optimistically and stores the returned read_version so a
  tab's own read does not refetch its lists. AgentThread gains unread.
- core/scheduled-tasks/events.ts: ScheduledTaskEvent, the events query
  (["scheduled-tasks","thread-events",id], one fetch per saved chat, not
  gated on the task list so a deleted task's lines stay, refetched when a
  task of the chat changes status or finishes a run), describeTaskEvent
  (en/zh copy, title and condition as segments, last-run suffix, See that
  run / Open task) and placeTaskEvents (end of the after_run_id turn, else
  the tail, ordered by created_at); lifecycle names pinned to contract v3.
- features: thread_activity (default unavailable); channels:
  proactive_notifications on providers.
- Locale sync: the I18nProvider reports the UI language and a signed-in
  preference session saves it as the new `locale` preference when the
  account's differs (and on every switch), so IM notices follow the UI
  language; nothing is written with auth disabled.
- i18n: threads.* (unread, origin labels, provider names),
  scheduledTasks.events.*, history.waitingForSlot (now shown for queued run
  rows), channels.scheduledUpdates.*.
- e2e mocks: thread activity feed and controller, POST /read, the events
  route, providers with proactive_notifications, search unread, features
  thread_activity (off by default). Preference e2e mocks return the UI
  locale so they keep asserting only their own edits.
- Docs: frontend AGENTS.md, CHANGELOGs.

* fix(scheduled-tasks): keep untouched end times and drop a chat filter the new task is not in

- The edit, duplicate and renew dialogs keep a stored end time's instant
  while its field still shows it. A minute-precision wall value cannot
  keep seconds or name the later 01:30 of a DST fall-back, so a
  title-only edit moved the cap an hour earlier, and raising the run
  limit re-sent the end time without its seconds.
- Creating or duplicating a task from a chat's task view drops the chat
  filter when the new task does not belong to that chat, instead of
  showing "This task isn't one of this chat's tasks".

* feat(frontend): origin markers and unread state in the thread lists

Server-created threads (PR2 F2) now say who created them and whether they
are new, in the sidebar and on the Chats page, and reach an open sidebar
without a reload.

- ThreadOriginIcon (thread-channel-source.tsx): clock for a scheduled run,
  the provider mark for IM threads, the GitHub mark (new in
  ChannelProviderIcon) for GitHub threads, a puzzle piece for extensions;
  the localized "Scheduled run" / "From Feishu" / "From GitHub" / "From an
  extension" label is its accessible name and tooltip. ThreadChannelIcon
  stays exported as a wrapper, and the provider chip tooltip is localized
  (no more "Feishu channel").
- Unread dot after the title (aria-hidden dot plus sr-only "Unread"); the
  row aria-label becomes "{title}, unread" / "{title},未读". Never shown for
  the open thread.
- WorkspaceSidebar mounts useThreadActivity once.
- useMarkOpenThreadRead (components/workspace/chats): the default and
  custom-agent chat pages mark the thread read once its metadata has
  loaded, when its cached unread flips to true while open, when the tab
  becomes visible, and from onFinish (a send or a joined run ended). Each
  trigger goes through useMarkThreadRead, so it is debounced and a no-op
  while the cached unread is false.
- Tests: thread-origin-icon and recent-chat-list DOM tests (en/zh, active
  row, no raw identifiers), use-mark-open-thread-read DOM tests,
  e2e thread-activity.spec.ts (new scheduled run appears unread within one
  fake-clock poll without a reload, opening it posts /read and clears the
  dot, a read on another device clears it, IM and GitHub markers, zh
  labels, the Chats page, no polling when unavailable);
  thread-history.spec.ts now finds the localized origin icon.
- Docs: frontend AGENTS.md, CHANGELOGs.

* feat(frontend): schedule event line in the originating chat and channel notice support

The chat that created a schedule now says when the schedule paused or
ended, and the channel cards say which apps receive scheduled task updates
(PR2 F3).

- ScheduledTaskEventLine (mockup m2, marker 4): a dashed, muted row with
  the describeTaskEvent text (title in <strong>, stop condition clamped to
  one line with the full text in its tooltip, last-run suffix), the time
  via formatTaskTime and a right-aligned "See that run" (run chat) or
  "Open task" link. PauseCircle for paused, CircleCheck for finished and
  once-done, CircleX for once-failed. role="note", aria-label "Scheduled
  task update" / "定时任务通知", data-task-id and data-event-id only.
- MessageList takes scheduledTaskEvents and renders placeTaskEvents output
  through a new VirtualMessageList.renderAfterGroup, so each line sits at
  the end of its after_run_id turn inside the group's measured row (also
  when the list virtualizes); lines with nowhere to go render at the tail.
- Both chat pages load useThreadScheduledTaskEvents (not gated on the task
  list, so the lines stay after a task is deleted). The custom-agent page
  passes its agent so "See that run" opens the run on that agent's route.
- ChannelScheduledUpdates: "Scheduled task updates: sent here" / "... not
  available for this app yet" (定时任务通知:会发送到这里 / 此应用暂不支持)
  on the Settings provider cards and under each sidebar channel row; nothing
  when an older backend does not report proactive_notifications.
- e2e mock controller: setScheduledTasks.
- Tests: scheduled-task-event-line and channel-scheduled-updates DOM tests
  (every kind in en and zh, hrefs, clamp, no raw identifiers, Chinese
  title), MessageList placement DOM tests; e2e
  scheduled-task-chat-events.spec.ts (the line appears with the card's
  "Paused by agent" without a reload, See that run opens the run chat,
  anchored vs tail placement, two events in time order, the line survives
  task deletion and Open task shows the task is gone; en-3 and zh-1) and
  channels.spec.ts (WeCom sent here, Feishu not yet; en and zh).
- Docs: frontend AGENTS.md, CHANGELOGs.

* fix(scheduled-tasks): tie pause notices to the pause they describe

- Paused by agent links and times only the run named in last_error. When
  that run is not loaded, the notice shows no link and the task's own time
  instead of an earlier run that also asked to stop.
- The outcome notice reads the latest history page whichever page is
  shown, so browsing older runs no longer swaps the auto-pause reason and
  "Open latest run" to an earlier miss. It shares that page's request.

* fix(scheduler): address PR2 review findings

- Event lines: hold an event whose anchor run is on an unloaded history
  page instead of placing it at the bottom (hasMoreHistory); tail fallback
  only for fully loaded (branched/pruned) history or no anchor.
- Idle-finish anchor follows its reason: end:<iso> only for an end_at
  finish, seq:<n> otherwise, so a later end-time finish is not deduplicated
  away by an earlier max_runs finish.
- Observer takes FOR SHARE on the originating threads_meta row, so a racing
  thread delete cannot leave an orphan event line.
- One taskPagePath (core), re-exported by the card.
- Notification locales derived from NotificationLocale; /preferences uses it.
- IM notices drop generic reasons (goal_not_met_yet, unknown) instead of
  repeating the sentence.
- Localized provider names on Settings cards, sidebar rows and setup dialog.
- zh event lines: no space after a Chinese title (Latin-aware gap).
- Unread row label keeps the origin marker; chats page keeps the time as a
  description.
- Sidebar shows the scheduled-updates line only for connected apps;
  Settings says "available after you connect" for unconnected push apps.
- Event line keeps a real space before the time.

* fix(scheduled-tasks): three lifecycle gaps found while re-checking review classes

- The edit form compares a cron in the form its schedule input emits, so an
  untouched "0 09 * * 0,6" is not re-sent as "0 9 * * 6,0" and a title-only
  edit no longer re-arms or refuses a finished task.
- Chat resume asks for a timezone, as update does, when a naive end_at would
  land in the UTC placeholder of a zone-free task.
- Re-arming a task clears a host pause marker, as resume does, so a later
  manual pause no longer reads as "Paused by agent".

* test(scheduler): consolidate PR2 backend test setup

- Fold the repeated task, origin-chat and observer setup of the
  lifecycle-event repository tests into one lifecycle_task builder.
- Build the per-owner-cap services through one _capped_service builder
  that keeps every cap explicit at the call site.
- Table the five SSE route header checks into one parametrized test with
  the same routes, bodies and Content-Location expectations.
- Reuse bind_wecom and hoist repeated local imports in the event tests.

Every case and assertion is kept; collected cases are unchanged.

* test(frontend): consolidate PR2 thread activity and origin test setup

Extract shared builders and helpers in the frontend tests PR2 adds, with
every case, input and assertion kept:

- activity.test.ts: seededClient/apply helpers and one LIST_KEYS constant
  replace the per-test seed, spy and apply boilerplate.
- mark-read.dom.test.tsx: newClient() and advance() replace the repeated
  QueryClient wrapper and fake-timer act blocks.
- origin.test.ts: the English and Chinese label checks become tables; the
  no-English-name check now runs on every Chinese row.
- thread-activity.spec.ts: a scheduledRun() builder replaces four inline
  copies of the scheduled run thread.
- channels.spec.ts: the PR2 block uses setLocaleCookie and one card helper.

Collected cases are unchanged (unit 211, e2e 60); no test was removed.

* fix(scheduled-tasks): keep the notice's latest-runs query from refreshing older pages

useLatestScheduledTaskRuns kept React Query's default refetch on mount,
focus and reconnect, so going offline and back while an older history page
was shown fetched the latest page again. Refreshing stays with the history,
which refreshes the latest page only while it is shown.

* fix(scheduler): two gaps found in live acceptance

- A fresh scheduled run thread is named when it launches. The worker
  copied the title to the thread list only when the run ended, so the
  sidebar, which now shows the new run thread at once, listed it as
  untitled while it ran.
- A task capped at one run finishes with "its one run is done" /
  "唯一一次运行已完成" in the chat event line and the IM notice, instead
  of "all 1 runs are done".

* test(scheduled-tasks): let the viewer's time carry its own day label

Between 16:00 and 24:00 UTC, UTC and Asia/Shanghai are on different days,
so the run prompt shows "Tomorrow 01:00 · Today 09:00 your time" and the
fixed "01:00 · 09:00 your time" assertion failed depending on the hour.

* test(scheduler): expect the one-run finish copy in service notices

* fix(gateway): create a scheduled run thread with its title

Pre-setting the name after start_run raced the thread row, which the run
worker creates asynchronously: live, one of two run threads still reached
the sidebar untitled. Run admission now creates a new thread with the title
its run input carries, which the worker would copy only at run end.

* docs(changelog): reference #6393 for the scheduled-task signal entries

* fix(scheduled-tasks): route event-line run links by the agent that ran them

The originating chat's agent was used for "See that run", but a task's
agent can change after the chat created it, so the link could open the run
chat on another agent's route. Lifecycle events now record run_agent_name,
the task's agent when the run finished (edits are refused while a run is
active), and the line routes by it.

* fix(scheduled-tasks): load up to the route's maximum of chat event lines

The chat loads its lifecycle events once, and the route's default of 50
would silently drop the oldest lines of a chat with many schedules. Ask
for the maximum, 200.

* fix(threads): keep activity reads and the first cursor in step with the lists

- Accepting the first activity cursor refreshes the thread lists once. The
  lists load on their own, possibly before a run the seed already counts,
  and later polls start after it, so such a thread never appeared.
- A local read whose returned read clock jumps past that one read also
  covers reads on other devices; the lists are refreshed instead of the
  clock silently skipping those threads' stale unread dots.
- An invalid cursor re-seeds through the same path, so it refreshes once.

* docs(agents): bring the middlewares guidance chain back under the hard limit

#6378 and #6363 each fit the budget, but together the middlewares AGENTS.md
chain on main is 98,425 bytes, 121 over the 98,304 hard limit, so Lint
Check fails on main. Move the scheduled-task recovery, launch-update and
queue-timeout rules from backend/AGENTS.md into the persistence guide's
lifecycle section, which backend/AGENTS.md already points to. The chain is
now 98,067 bytes.

* fix(helm): bump the chart's config_version to 55

config.example.yaml moved to 55 in this PR, so the Helm chart's
validate-chart drift check failed. The chart's embedded config needs no
field changes: the new scheduler and channel keys have defaults.

---------

Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
2026-10-07 10:22:15 +08:00

781 lines
45 KiB
Python

import asyncio
import os
import uuid
from contextlib import asynccontextmanager
from datetime import UTC, datetime, timedelta
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
import pytest
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from deerflow.persistence.base import Base
from deerflow.persistence.postgres_schema import build_asyncpg_connect_args
from deerflow.persistence.run import RunRepository
from deerflow.persistence.run.model import RunRow
from deerflow.persistence.scheduled_task_events import ScheduledTaskEventRow
from deerflow.persistence.scheduled_task_runs import ScheduledTaskAdmissionRejected, ScheduledTaskRunRepository
from deerflow.persistence.scheduled_task_runs.model import ScheduledTaskRunRow
from deerflow.persistence.scheduled_tasks import ScheduledTaskLimitsExhausted, ScheduledTaskRepository
from deerflow.persistence.scheduled_tasks.model import ScheduledTaskRow
from deerflow.persistence.scheduled_tasks.sql import ActiveScheduledTaskMutationConflict
from deerflow.persistence.thread_meta.model import ThreadMetaRow
NOW = datetime(2026, 10, 3, 8, tzinfo=UTC)
VERDICT = {"satisfied": False, "blocker": "goal_not_met_yet", "reason": "missing evidence", "evidence_summary": "none", "relied_on_assumption": False, "stand_down_reason": "max_continuations"}
@pytest.fixture(params=["sqlite", "postgres"])
def database_backend(request):
return request.param
@asynccontextmanager
async def database(tmp_path, *, backend="sqlite"):
schema = None
if backend == "postgres":
uri = os.environ.get("TEST_POSTGRES_URI")
if not uri:
pytest.skip("requires TEST_POSTGRES_URI (real Postgres scheduler contracts)")
parts = urlsplit(uri)
scheme = "postgresql+asyncpg" if parts.scheme in {"postgres", "postgresql"} else parts.scheme
query = urlencode([(key, value) for key, value in parse_qsl(parts.query, keep_blank_values=True) if key not in {"sslmode", "channel_binding"}])
uri = urlunsplit(parts._replace(scheme=scheme, query=query))
schema = f"scheduler_contract_{uuid.uuid4().hex}"
engine = create_async_engine(uri, connect_args=build_asyncpg_connect_args(schema))
else:
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'agent-schedules.db'}")
try:
async with engine.begin() as conn:
if schema:
await conn.execute(text(f'CREATE SCHEMA "{schema}"'))
await conn.run_sync(lambda sync: Base.metadata.create_all(sync, tables=[ScheduledTaskRow.__table__, ScheduledTaskRunRow.__table__, RunRow.__table__, ThreadMetaRow.__table__, ScheduledTaskEventRow.__table__]))
sf = async_sessionmaker(engine, expire_on_commit=False)
yield sf, ScheduledTaskRepository(sf), ScheduledTaskRunRepository(sf)
finally:
if schema:
async with engine.begin() as conn:
await conn.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))
await engine.dispose()
async def task(repo, task_id="task", **extra):
return await repo.create(
task_id=task_id,
user_id="owner",
thread_id=None,
context_mode="fresh_thread_per_run",
assistant_id=None,
title="report",
prompt="write report",
schedule_type="interval",
schedule_spec={"every_seconds": 3600},
timezone="UTC",
next_run_at=NOW,
origin_thread_id="origin",
**extra,
)
async def occurrence(sf, repo, task_id="task", suffix="1", *, trigger="scheduled", verdict=None, durable_status="success"):
occurrence_id, run_id = f"occ-{suffix}", f"run-{suffix}"
await repo.create(run_record_id=occurrence_id, task_id=task_id, thread_id=f"thread-{suffix}", scheduled_for=NOW, trigger=trigger, status="running")
await repo.update_status(occurrence_id, status="running", run_id=run_id, started_at=NOW)
async with sf() as session:
session.add(RunRow(run_id=run_id, thread_id=f"thread-{suffix}", user_id="owner", status=durable_status, goal_verdict=verdict, metadata_json={"scheduled_task_id": task_id, "scheduled_task_run_id": occurrence_id}, created_at=NOW))
await session.commit()
return occurrence_id, run_id
async def complete(tasks, occurrence_id, run_id, *, status="success", verdict=None, error=None):
return await tasks.complete_run("task", user_id="owner", task_run_id=occurrence_id, run_id=run_id, status=status, error=error, finished_at=NOW, goal_verdict=verdict)
@pytest.mark.asyncio
async def test_origin_scope_notes_and_serialized_deadline(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
created = await task(tasks, end_at=NOW + timedelta(days=1))
assert created["end_at"] == (NOW + timedelta(days=1)).isoformat()
assert len(await tasks.list_by_user_and_thread("owner", "origin")) == 1
assert await tasks.append_standing_note("task", user_id="owner", origin_thread_id="wrong", note="develop branch") is None
updated = await tasks.append_standing_note("task", user_id="owner", origin_thread_id="origin", note="develop branch")
assert updated["standing_notes"] == ["develop branch"]
await occurrence(sf, runs)
with pytest.raises(ActiveScheduledTaskMutationConflict, match="active"):
await tasks.append_standing_note("task", user_id="owner", origin_thread_id="origin", note="another note")
@pytest.mark.asyncio
async def test_owner_quota_serializes_concurrent_creates_and_counts_paused(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
for index in range(19):
await task(tasks, f"task-{index}")
await tasks.update("task-0", user_id="owner", updates={"status": "paused"})
results = await asyncio.gather(task(tasks, "a"), task(tasks, "b"), return_exceptions=True)
assert sum(isinstance(result, dict) for result in results) == 1
assert "20" in str(next(result for result in results if isinstance(result, Exception)))
@pytest.mark.asyncio
async def test_stop_request_is_first_terminal_only_after_resume(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks)
occurrence_id, run_id = await occurrence(sf, runs, durable_status="running")
assert await runs.request_stop(occurrence_id, task_id="task", run_id=run_id, user_id="intruder") is False
assert await runs.request_stop(occurrence_id, task_id="task", run_id=run_id, user_id="owner") is True
assert await complete(tasks, occurrence_id, run_id) is True
stopped = await tasks.get("task", user_id="owner")
assert stopped["status"] == "paused"
assert stopped["last_error"] == f"stopped by the agent in run {run_id}"
await tasks.update("task", user_id="owner", updates={"status": "enabled", "last_error": None})
assert await complete(tasks, occurrence_id, run_id, status="failed", error="late") is False
assert (await tasks.get("task", user_id="owner"))["status"] == "enabled"
assert (await runs.list_by_task("task"))[0]["status"] == "success"
@pytest.mark.asyncio
@pytest.mark.parametrize("method", ["recover_expired_launch_claims", "mark_stale_active_runs", "reconcile_active_runs"])
async def test_restart_restores_stop_and_goal_outcome_in_same_transaction(tmp_path, database_backend, method):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks, goal_objective="report is complete")
occurrence_id, run_id = await occurrence(sf, runs, verdict=VERDICT, durable_status="running")
assert await runs.request_stop(occurrence_id, task_id="task", run_id=run_id, user_id="owner")
async with sf() as session:
durable = await session.get(RunRow, run_id)
durable.status = "success"
row = await session.get(ScheduledTaskRunRow, occurrence_id)
row.status = "launching" if method == "recover_expired_launch_claims" else "running"
await session.commit()
kwargs = {"error": "restart"}
if method != "mark_stale_active_runs":
kwargs["now"] = NOW
assert await getattr(runs, method)(**kwargs) == 1
assert (await tasks.get("task", user_id="owner"))["status"] == "paused"
recorded = (await runs.list_by_task("task"))[0]
assert recorded["status"] == "unmet"
assert recorded["goal_objective"] == "report is complete"
assert recorded["goal_verdict"] == VERDICT
assert recorded["error"] == "max_continuations"
@pytest.mark.asyncio
async def test_manual_trial_does_not_consume_limit_and_deadline_prevents_admission(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks, max_runs=2)
for suffix, trigger in [("trial", "manual"), ("first", "scheduled"), ("second", "scheduled")]:
occurrence_id, run_id = await occurrence(sf, runs, suffix=suffix, trigger=trigger)
await complete(tasks, occurrence_id, run_id)
current = await tasks.get("task", user_id="owner")
assert current["status"] == ("completed" if suffix == "second" else "enabled")
assert current["run_count"] == 3
# Reactivating a task whose cap is used up is refused at the repository.
with pytest.raises(ScheduledTaskLimitsExhausted):
await tasks.update("task", user_id="owner", updates={"status": "enabled"})
assert (await tasks.get("task", user_id="owner"))["status"] == "completed"
# A row enabled by an older writer is still completed before admission.
async with sf() as session:
(await session.get(ScheduledTaskRow, "task")).status = "enabled"
await session.commit()
assert await tasks.complete_if_ended("task", user_id="owner", now=NOW) is True
await task(tasks, "expired", end_at=NOW - timedelta(seconds=1))
assert await tasks.complete_if_ended("expired", now=NOW) is True
assert (await tasks.get("expired", user_id="owner"))["status"] == "completed"
@pytest.mark.asyncio
async def test_streak_skips_manual_external_wait_and_failure_and_notifies_once(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks, goal_objective="deliver report")
observed = []
async def observer(session, parent, row, *, events):
observed.append((row.id, events, parent.status))
tasks.set_finalization_observer(observer)
for suffix, status, trigger, error in [
("1", "unmet", "scheduled", "goal_not_met_yet"),
("trial", "unmet", "manual", "goal_not_met_yet"),
("wait", "unmet", "scheduled", "external_wait"),
("failure", "failed", "scheduled", "broken"),
("2", "unmet", "scheduled", "goal_not_met_yet"),
("3", "unmet", "scheduled", "goal_not_met_yet"),
]:
occurrence_id, run_id = await occurrence(sf, runs, suffix=suffix, trigger=trigger)
await complete(tasks, occurrence_id, run_id, status=status, error=error)
assert (await tasks.get("task", user_id="owner"))["status"] == "paused"
assert observed[-1][1] == ("run_unmet", "task_paused")
assert await complete(tasks, "occ-3", "run-3", status="unmet", error="goal_not_met_yet") is False
assert len(observed) == 6
@pytest.mark.asyncio
async def test_end_condition_wins_and_observer_failure_rolls_back(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks, max_runs=1)
occurrence_id, run_id = await occurrence(sf, runs, durable_status="running")
assert await runs.request_stop(occurrence_id, task_id="task", run_id=run_id, user_id="owner")
async def failing_observer(*args, **kwargs):
raise RuntimeError("outbox unavailable")
tasks.set_finalization_observer(failing_observer)
with pytest.raises(RuntimeError, match="outbox unavailable"):
await complete(tasks, occurrence_id, run_id)
assert (await runs.list_by_task("task"))[0]["status"] == "running"
assert (await tasks.get("task", user_id="owner"))["run_count"] == 0
tasks.set_finalization_observer(None)
await complete(tasks, occurrence_id, run_id)
assert (await tasks.get("task", user_id="owner"))["status"] == "completed"
@pytest.mark.asyncio
async def test_previous_occurrence_uses_admission_sequence_and_only_launched_history(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks)
first, run_id = await occurrence(sf, runs, suffix="first", trigger="manual")
await complete(tasks, first, run_id)
await runs.create(run_record_id="unlaunched", task_id="task", thread_id="unlaunched-thread", scheduled_for=NOW + timedelta(days=1), trigger="scheduled", status="failed")
current, _run_id = await occurrence(sf, runs, suffix="current")
previous = await runs.previous_occurrence("task", before_task_run_id=current)
assert previous["id"] == first
assert previous["thread_id"] == "thread-first"
@pytest.mark.asyncio
async def test_no_verdict_once_is_failed_and_receipt_backfill_preserves_unmet(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks, goal_objective="deliver report")
await tasks.update("task", user_id="owner", updates={"schedule_type": "once", "schedule_spec": {"run_at": NOW.isoformat()}})
occurrence_id, run_id = await occurrence(sf, runs)
await complete(tasks, occurrence_id, run_id)
assert (await tasks.get("task", user_id="owner"))["status"] == "failed"
assert await runs.update_status(occurrence_id, status="running", run_id=run_id, started_at=NOW + timedelta(seconds=1), protect_terminal=True)
assert await runs.reconcile_launched_run(occurrence_id, task_id="task", run_id=run_id, started_at=NOW)
row = (await runs.list_by_task("task"))[0]
assert row["status"] == "unmet"
assert row["error"] == "no_verdict"
assert (await tasks.get("task", user_id="owner"))["run_count"] == 1
@pytest.mark.asyncio
async def test_success_resets_unmet_streak_and_old_callback_cannot_pause_new_parent(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks, goal_objective="deliver report")
for suffix, satisfied in [("1", False), ("2", False), ("3", True), ("4", False), ("5", False)]:
occurrence_id, run_id = await occurrence(sf, runs, suffix=suffix)
verdict = dict(VERDICT, satisfied=satisfied, relied_on_assumption=satisfied)
await complete(tasks, occurrence_id, run_id, verdict=verdict)
assert (await tasks.get("task", user_id="owner"))["status"] == "enabled"
# The old result cannot be changed after it first became terminal.
assert await complete(tasks, "occ-3", "run-3", verdict=VERDICT) is False
assert (await tasks.get("task", user_id="owner"))["status"] == "enabled"
@pytest.mark.asyncio
async def test_queued_dispatch_checks_deadline_under_parent_lock(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, runs):
await task(tasks, end_at=NOW + timedelta(seconds=1))
await runs.create(run_record_id="waiting", task_id="task", thread_id="thread", scheduled_for=NOW, trigger="scheduled", status="queued")
assert await runs.claim_queued_run("waiting", lease_owner="worker", now=NOW + timedelta(seconds=2), lease_seconds=30, global_max_concurrent_runs=1) is None
assert (await tasks.get("task", user_id="owner"))["status"] == "completed"
assert (await runs.list_by_task("task"))[0]["status"] == "skipped"
@pytest.mark.asyncio
async def test_notes_bounds_and_tool_quota_excludes_terminal_and_legacy_tasks(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
for index in range(20):
await task(tasks, f"task-{index}")
await tasks.update("task-0", user_id="owner", updates={"status": "completed"})
await task(tasks, "replacement", standing_notes=["note"] * 10)
with pytest.raises(ValueError, match="10"):
await tasks.append_standing_note("replacement", user_id="owner", origin_thread_id="origin", note="extra")
with pytest.raises(ValueError, match="500"):
await tasks.append_standing_note("replacement", user_id="owner", origin_thread_id="origin", note="x" * 501)
# Existing REST callers retain their unbounded quota behavior.
await tasks.create(
task_id="legacy",
user_id="owner",
thread_id=None,
context_mode="fresh_thread_per_run",
assistant_id=None,
title="legacy",
prompt="test",
schedule_type="interval",
schedule_spec={"every_seconds": 3600},
timezone="UTC",
next_run_at=NOW,
)
@pytest.mark.asyncio
async def test_concurrent_terminal_callbacks_accept_only_one_outcome(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks)
occurrence_id, run_id = await occurrence(sf, runs)
results = await asyncio.gather(complete(tasks, occurrence_id, run_id), complete(tasks, occurrence_id, run_id, status="failed", error="competing callback"))
assert sorted(results) == [False, True]
row = (await runs.list_by_task("task"))[0]
assert row["status"] == ("success" if results[0] else "failed")
assert (await tasks.get("task", user_id="owner"))["run_count"] == 1
@pytest.mark.asyncio
async def test_postgres_owner_quota_serializes_separate_sessions():
uri = os.environ.get("TEST_POSTGRES_URI")
if not uri:
pytest.skip("requires TEST_POSTGRES_URI (real Postgres quota concurrency)")
parts = urlsplit(uri)
scheme = "postgresql+asyncpg" if parts.scheme in {"postgres", "postgresql"} else parts.scheme
query = urlencode([(key, value) for key, value in parse_qsl(parts.query, keep_blank_values=True) if key not in {"sslmode", "channel_binding"}])
uri = urlunsplit(parts._replace(scheme=scheme, query=query))
schema = f"scheduler_quota_{uuid.uuid4().hex}"
engine = create_async_engine(uri, connect_args=build_asyncpg_connect_args(schema))
try:
async with engine.begin() as conn:
await conn.execute(text(f'CREATE SCHEMA "{schema}"'))
await conn.run_sync(lambda sync: Base.metadata.create_all(sync, tables=[ScheduledTaskRow.__table__, ScheduledTaskRunRow.__table__]))
sf = async_sessionmaker(engine, expire_on_commit=False)
tasks_a, tasks_b = ScheduledTaskRepository(sf), ScheduledTaskRepository(sf)
for index in range(19):
await task(tasks_a, f"task-{index}")
results = await asyncio.gather(task(tasks_a, "a"), task(tasks_b, "b"), return_exceptions=True)
assert sum(isinstance(result, dict) for result in results) == 1
assert len(await tasks_a.list_by_origin_thread("owner", "origin")) == 20
winner = next(result["id"] for result in results if isinstance(result, dict))
await tasks_a.update(winner, user_id="owner", updates={"status": "completed"})
results = await asyncio.gather(tasks_a.update(winner, user_id="owner", updates={"status": "enabled"}, require_mutable=True), task(tasks_b, "competing-new"), return_exceptions=True)
assert sum(isinstance(result, dict) for result in results) == 1
assert type(next(result for result in results if isinstance(result, Exception))).__name__ == "ScheduledTaskQuotaExceeded"
assert sum(row["status"] in {"enabled", "running", "paused"} for row in await tasks_a.list_by_origin_thread("owner", "origin")) == 20
finally:
async with engine.begin() as conn:
await conn.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))
await engine.dispose()
@pytest.mark.asyncio
async def test_reactivation_and_creation_share_atomic_owner_quota(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
await task(tasks, "old-terminal")
await tasks.update("old-terminal", user_id="owner", updates={"status": "completed"})
for index in range(19):
await task(tasks, f"active-{index}")
results = await asyncio.gather(tasks.update("old-terminal", user_id="owner", updates={"status": "enabled"}, require_mutable=True), task(tasks, "new"), return_exceptions=True)
assert sum(isinstance(result, dict) for result in results) == 1
assert type(next(result for result in results if isinstance(result, Exception))).__name__ == "ScheduledTaskQuotaExceeded"
assert sum(row["status"] in {"enabled", "running", "paused"} for row in await tasks.list_by_origin_thread("owner", "origin")) == 20
@pytest.mark.asyncio
async def test_full_quota_blocks_terminal_reactivation_but_preserves_paused_and_legacy(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
await task(tasks, "old-terminal")
await tasks.update("old-terminal", user_id="owner", updates={"status": "completed"})
for index in range(20):
await task(tasks, f"active-{index}")
with pytest.raises(ValueError, match="20"):
await tasks.update("old-terminal", user_id="owner", updates={"status": "enabled"}, require_mutable=True)
assert (await tasks.get("old-terminal", user_id="owner"))["status"] == "completed"
await tasks.update("active-0", user_id="owner", updates={"status": "paused"})
assert (await tasks.update("active-0", user_id="owner", updates={"status": "enabled"}, require_mutable=True))["status"] == "enabled"
await tasks.create(
task_id="legacy",
user_id="owner",
thread_id=None,
context_mode="fresh_thread_per_run",
assistant_id=None,
title="legacy",
prompt="test",
schedule_type="interval",
schedule_spec={"every_seconds": 3600},
timezone="UTC",
next_run_at=NOW,
)
await tasks.update("legacy", user_id="owner", updates={"status": "completed"})
assert (await tasks.update("legacy", user_id="owner", updates={"status": "enabled"}, require_mutable=True))["status"] == "enabled"
@pytest.mark.asyncio
async def test_terminal_durable_result_wins_a_failed_takeover_race(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
await task(tasks, goal_objective="deliver report")
occurrence_id, run_id = await occurrence(sf, runs, durable_status="running")
class CompletionWinsTakeover(RunRepository):
async def claim_for_takeover(self, selected_run_id, **kwargs):
# Another worker completes between the recovery snapshot and
# takeover CAS. The real repository read observes that commit.
async with sf() as session:
row = await session.get(RunRow, selected_run_id)
row.status = "success"
row.goal_verdict = {"satisfied": True, "relied_on_assumption": False}
await session.commit()
return False
recovering = ScheduledTaskRunRepository(sf, run_repository=CompletionWinsTakeover(sf))
assert await recovering.reconcile_active_runs(error="restart", now=NOW) == 1
recorded = (await runs.list_by_task("task"))[0]
assert recorded["status"] == "success"
assert recorded["goal_verdict"]["satisfied"] is True
assert (await tasks.get("task", user_id="owner"))["run_count"] == 1
@pytest.mark.asyncio
async def test_update_preserves_goal_fresh_thread_invariant_under_lock(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
await task(tasks, goal_objective="deliver report")
before = await tasks.get("task", user_id="owner")
with pytest.raises(ValueError, match="fresh_thread_per_run"):
await tasks.update("task", user_id="owner", updates={"context_mode": "reuse_thread", "thread_id": "reused"}, require_mutable=True)
assert await tasks.get("task", user_id="owner") == before
await task(tasks, "no-goal")
updated = await tasks.update("no-goal", user_id="owner", updates={"context_mode": "reuse_thread", "thread_id": "reused"}, require_mutable=True)
assert updated["context_mode"] == "reuse_thread"
@pytest.mark.asyncio
@pytest.mark.parametrize("objective", [pytest.param("", id="empty"), pytest.param(" \t\n ", id="blank"), pytest.param("x" * 4001, id="too-long")])
async def test_create_rejects_invalid_goal_without_inserting_task(tmp_path, database_backend, objective):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
with pytest.raises(ValueError, match="Goal objective"):
await task(tasks, goal_objective=objective)
assert await tasks.list_by_origin_thread("owner", "origin") == []
@pytest.mark.asyncio
@pytest.mark.parametrize("objective", [pytest.param("", id="empty"), pytest.param(" \t\n ", id="blank"), pytest.param("x" * 4001, id="too-long")])
async def test_update_rejects_invalid_goal_without_changing_task(tmp_path, database_backend, objective):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
before = await task(tasks, goal_objective="deliver report")
with pytest.raises(ValueError, match="Goal objective"):
await tasks.update("task", user_id="owner", updates={"goal_objective": objective, "title": "changed"}, require_mutable=True)
assert await tasks.get("task", user_id="owner") == before
@pytest.mark.asyncio
@pytest.mark.parametrize("objective", [pytest.param(None, id="none"), pytest.param(" deliver\t report\n ", id="original-text"), pytest.param(" \n" + "x" * 4000 + "\t ", id="normalized-limit")])
async def test_create_and_update_preserve_valid_goal_text(tmp_path, database_backend, objective):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
created = await task(tasks, goal_objective=objective)
assert created["goal_objective"] == objective
await task(tasks, "updated", goal_objective="previous goal")
updated = await tasks.update("updated", user_id="owner", updates={"goal_objective": objective}, require_mutable=True)
assert updated["goal_objective"] == objective
assert (await tasks.get("updated", user_id="owner"))["goal_objective"] == objective
@pytest.mark.asyncio
@pytest.mark.parametrize("live_count", [19, 20])
async def test_terminal_pause_is_finished_and_takes_no_quota_slot(tmp_path, database_backend, live_count):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
await task(tasks, "terminal")
await tasks.update("terminal", user_id="owner", updates={"status": "completed"})
for index in range(live_count):
await task(tasks, f"live-{index}")
before = await tasks.get("terminal", user_id="owner")
assert await tasks.pause_with_queue_cancellation("terminal", user_id="owner", error="pause", now=NOW) == "finished"
assert await tasks.get("terminal", user_id="owner") == before
assert sum(row["status"] in {"enabled", "running", "paused"} for row in await tasks.list_by_origin_thread("owner", "origin")) == live_count
await tasks.create(
task_id="legacy",
user_id="owner",
thread_id=None,
context_mode="fresh_thread_per_run",
assistant_id=None,
title="legacy",
prompt="test",
schedule_type="interval",
schedule_spec={"every_seconds": 3600},
timezone="UTC",
next_run_at=NOW,
)
await tasks.update("legacy", user_id="owner", updates={"status": "completed"})
assert await tasks.pause_with_queue_cancellation("legacy", user_id="owner", error="legacy pause", now=NOW) == "finished"
@pytest.mark.asyncio
async def test_terminal_pause_cannot_race_a_create_out_of_its_quota_slot(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (_sf, tasks, _runs):
await task(tasks, "terminal")
await tasks.update("terminal", user_id="owner", updates={"status": "completed"})
for index in range(19):
await task(tasks, f"live-{index}")
results = await asyncio.gather(tasks.pause_with_queue_cancellation("terminal", user_id="owner", error="pause", now=NOW), task(tasks, "new"), return_exceptions=True)
assert results[0] == "finished"
assert isinstance(results[1], dict)
assert sum(row["status"] in {"enabled", "running", "paused"} for row in await tasks.list_by_origin_thread("owner", "origin")) == 20
# --- Lifecycle events (task_stopped / task_paused / task_finished) ----------------------
async def lifecycle_task(sf, tasks, runs, *, once=False, **extra):
"""The task (``once`` makes it a once task) and its originating chat, with the
scheduler's real finalization observer installed; returns each recorded call."""
from app.scheduler.service import ScheduledTaskService
await task(tasks, **extra)
if once:
await tasks.update("task", user_id="owner", updates={"schedule_type": "once", "schedule_spec": {"run_at": NOW.isoformat()}})
async with sf() as session:
session.add(ThreadMetaRow(thread_id="origin", user_id="owner"))
await session.commit()
service = ScheduledTaskService(task_repo=tasks, task_run_repo=runs, launch_run=None, poll_interval_seconds=60, lease_seconds=30, max_concurrent_runs=3)
observed = []
async def observer(session, parent, row, *, events):
observed.append((row.id if row is not None else None, events))
await service._on_finalization(session, parent, row, events=events)
for repository in (tasks, runs):
repository.set_finalization_observer(observer)
return observed
def lifecycle_calls(observed):
return [(occurrence_id, tuple(event for event in events if event.startswith("task_"))) for occurrence_id, events in observed if any(event.startswith("task_") for event in events)]
async def event_rows(sf):
async with sf() as session:
return list((await session.execute(select(ScheduledTaskEventRow).order_by(ScheduledTaskEventRow.created_at, ScheduledTaskEventRow.id))).scalars())
@pytest.mark.asyncio
async def test_agent_stop_emits_task_stopped_once(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs)
occurrence_id, run_id = await occurrence(sf, runs, durable_status="running")
assert await runs.request_stop(occurrence_id, task_id="task", run_id=run_id, user_id="owner")
assert await complete(tasks, occurrence_id, run_id) is True
assert observed == [(occurrence_id, ("run_completed", "task_stopped"))]
assert await complete(tasks, occurrence_id, run_id) is False
assert len(observed) == 1
rows = await event_rows(sf)
assert [(row.event, row.reason_code, row.anchor, row.occurrence_id, row.thread_id) for row in rows] == [("task_stopped", "agent_stop", occurrence_id, occurrence_id, "origin")]
@pytest.mark.asyncio
async def test_max_runs_completion_emits_task_finished(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, max_runs=2)
for suffix in ("1", "2"):
occurrence_id, run_id = await occurrence(sf, runs, suffix=suffix)
await complete(tasks, occurrence_id, run_id)
assert observed == [("occ-1", ("run_completed",)), ("occ-2", ("run_completed", "task_finished"))]
assert (await tasks.get("task", user_id="owner"))["status"] == "completed"
rows = await event_rows(sf)
assert [(row.event, row.reason_code, row.anchor) for row in rows] == [("task_finished", "max_runs", "occ-2")]
assert rows[0].payload_json["max_runs"] == 2
@pytest.mark.asyncio
async def test_end_condition_wins_over_agent_stop_events(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, max_runs=1)
occurrence_id, run_id = await occurrence(sf, runs, durable_status="running")
assert await runs.request_stop(occurrence_id, task_id="task", run_id=run_id, user_id="owner")
await complete(tasks, occurrence_id, run_id)
assert observed == [(occurrence_id, ("run_completed", "task_finished"))]
assert [row.event for row in await event_rows(sf)] == ["task_finished"]
@pytest.mark.asyncio
async def test_idle_end_at_finish_emits_with_end_anchor_once(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, end_at=NOW)
assert await tasks.complete_if_ended("task", user_id="owner", now=NOW + timedelta(seconds=1)) is True
assert await tasks.complete_if_ended("task", user_id="owner", now=NOW + timedelta(seconds=2)) is True
assert observed == [(None, ("task_finished",))]
rows = await event_rows(sf)
assert [(row.event, row.reason_code, row.anchor, row.occurrence_id) for row in rows] == [("task_finished", "end_at", f"end:{NOW.isoformat()}", None)]
assert (await tasks.get("task", user_id="owner"))["status"] == "completed"
@pytest.mark.asyncio
async def test_idle_max_runs_finish_then_end_time_finish_writes_two_events(tmp_path, database_backend):
"""An idle max_runs finish before the end time must not take the end-time
anchor: after a reactivation, the real end-time finish still gets its line."""
end = NOW + timedelta(hours=1)
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, end_at=end, max_runs=1)
await runs.create(run_record_id="used", task_id="task", thread_id="thread", scheduled_for=NOW, trigger="scheduled", status="queued")
async with sf() as session:
row = await session.get(ScheduledTaskRunRow, "used")
row.status, row.launch_accounted, row.finished_at = "success", True, NOW
await session.commit()
assert await tasks.complete_if_ended("task", user_id="owner", now=NOW + timedelta(seconds=1)) is True
async with sf() as session:
parent = await session.get(ScheduledTaskRow, "task")
parent.status, parent.max_runs = "enabled", 5
await session.commit()
assert await tasks.complete_if_ended("task", user_id="owner", now=end + timedelta(seconds=1)) is True
assert observed == [(None, ("task_finished",)), (None, ("task_finished",))]
rows = await event_rows(sf)
assert [(row.event, row.reason_code, row.anchor) for row in rows] == [
("task_finished", "max_runs", "seq:1"),
("task_finished", "end_at", f"end:{end.isoformat()}"),
]
@pytest.mark.asyncio
async def test_claim_time_end_skip_emits_task_finished_once(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, end_at=NOW + timedelta(seconds=1))
await runs.create(run_record_id="waiting", task_id="task", thread_id="thread", scheduled_for=NOW, trigger="scheduled", status="queued")
assert await runs.claim_queued_run("waiting", lease_owner="worker", now=NOW + timedelta(seconds=2), lease_seconds=30, global_max_concurrent_runs=1) is None
assert lifecycle_calls(observed) == [("waiting", ("task_finished",))]
assert len(observed) == 1
rows = await event_rows(sf)
assert [(row.event, row.reason_code, row.anchor) for row in rows] == [("task_finished", "end_at", "waiting")]
assert (await tasks.get("task", user_id="owner"))["status"] == "completed"
@pytest.mark.asyncio
async def test_complete_if_ended_with_queued_row_emits_once(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, end_at=NOW + timedelta(seconds=1))
await runs.create(run_record_id="waiting", task_id="task", thread_id="thread", scheduled_for=NOW, trigger="scheduled", status="queued")
assert await tasks.complete_if_ended("task", user_id="owner", now=NOW + timedelta(seconds=2)) is True
assert observed == [("waiting", ("task_finished",))]
assert [(row.event, row.anchor) for row in await event_rows(sf)] == [("task_finished", "waiting")]
assert (await runs.list_by_task("task"))[0]["status"] == "skipped"
@pytest.mark.asyncio
async def test_complete_if_ended_with_queued_manual_row_emits_idle_finish(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, end_at=NOW + timedelta(seconds=1))
await runs.create(run_record_id="trial", task_id="task", thread_id="thread", scheduled_for=NOW, trigger="manual", status="queued")
assert await tasks.complete_if_ended("task", user_id="owner", now=NOW + timedelta(seconds=2)) is True
assert observed == [(None, ("task_finished",))]
rows = await event_rows(sf)
assert [(row.event, row.anchor, row.occurrence_id) for row in rows] == [("task_finished", f"end:{(NOW + timedelta(seconds=1)).isoformat()}", None)]
# The waiting trial is left alone; only scheduled rows are skipped.
assert (await runs.list_by_task("task"))[0]["status"] == "queued"
@pytest.mark.asyncio
async def test_once_task_end_skip_stays_silent(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, once=True, end_at=NOW + timedelta(seconds=1))
await runs.create(run_record_id="waiting", task_id="task", thread_id="thread", scheduled_for=NOW, trigger="scheduled", status="queued")
assert await runs.claim_queued_run("waiting", lease_owner="worker", now=NOW + timedelta(seconds=2), lease_seconds=30, global_max_concurrent_runs=1) is None
# As in PR1: skipped -> cancelled, then the end condition marks it completed.
assert (await tasks.get("task", user_id="owner"))["status"] == "completed"
assert lifecycle_calls(observed) == []
assert await event_rows(sf) == []
@pytest.mark.asyncio
@pytest.mark.parametrize(
("status", "error", "reason"),
[("success", None, "once_done"), ("failed", "boom", "once_failed"), ("unmet", "goal_not_met_yet", "once_failed"), ("interrupted", "cancelled", None), ("skipped", None, None)],
)
async def test_once_task_finish_reasons(tmp_path, database_backend, status, error, reason):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, once=True)
occurrence_id, run_id = await occurrence(sf, runs)
assert await complete(tasks, occurrence_id, run_id, status=status, error=error) is True
rows = await event_rows(sf)
if reason is None:
assert lifecycle_calls(observed) == []
assert rows == []
else:
assert lifecycle_calls(observed) == [(occurrence_id, ("task_finished",))]
assert [(row.event, row.reason_code, row.anchor) for row in rows] == [("task_finished", reason, occurrence_id)]
@pytest.mark.asyncio
async def test_admission_time_end_emits_task_finished(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, end_at=NOW - timedelta(seconds=1))
with pytest.raises(ScheduledTaskAdmissionRejected) as rejected:
await runs.create(run_record_id="admitted", task_id="task", thread_id="thread", scheduled_for=NOW, trigger="scheduled", status="queued", coordinate_with_task=True, expected_task_user_id="owner")
assert rejected.value.reason == "ended"
assert (await tasks.get("task", user_id="owner"))["status"] == "completed"
assert observed == [(None, ("task_finished",))]
rows = await event_rows(sf)
assert [(row.event, row.reason_code, row.occurrence_id) for row in rows] == [("task_finished", "end_at", None)]
assert await runs.list_by_task("task") == []
@pytest.mark.asyncio
async def test_manual_trial_that_reaches_end_at_emits_task_finished(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs, end_at=NOW)
occurrence_id, run_id = await occurrence(sf, runs, suffix="trial", trigger="manual")
await complete(tasks, occurrence_id, run_id)
# Finalization reports the run event too; the observer drops only that for a trial.
assert observed == [(occurrence_id, ("run_completed", "task_finished"))]
assert [(row.event, row.reason_code, row.anchor) for row in await event_rows(sf)] == [("task_finished", "end_at", occurrence_id)]
assert (await tasks.get("task", user_id="owner"))["status"] == "completed"
@pytest.mark.asyncio
async def test_manual_trial_agent_stop_emits_task_stopped(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs)
occurrence_id, run_id = await occurrence(sf, runs, suffix="trial", trigger="manual", durable_status="running")
assert await runs.request_stop(occurrence_id, task_id="task", run_id=run_id, user_id="owner")
await complete(tasks, occurrence_id, run_id)
assert observed == [(occurrence_id, ("run_completed", "task_stopped"))]
assert [row.event for row in await event_rows(sf)] == ["task_stopped"]
assert (await tasks.get("task", user_id="owner"))["status"] == "paused"
@pytest.mark.asyncio
async def test_agent_stop_after_failed_run_pauses_and_says_run_failed(tmp_path, database_backend):
async with database(tmp_path, backend=database_backend) as (sf, tasks, runs):
observed = await lifecycle_task(sf, tasks, runs)
occurrence_id, run_id = await occurrence(sf, runs, durable_status="running")
assert await runs.request_stop(occurrence_id, task_id="task", run_id=run_id, user_id="owner")
await complete(tasks, occurrence_id, run_id, status="failed", error="boom")
# The transition is PR1's: a stop request pauses whatever the run outcome.
stopped = await tasks.get("task", user_id="owner")
assert stopped["status"] == "paused"
assert stopped["last_error"] == f"stopped by the agent in run {run_id}"
assert observed == [(occurrence_id, ("run_failed", "task_stopped"))]
(row,) = await event_rows(sf)
assert (row.event, row.payload_json["run_status"]) == ("task_stopped", "failed")
def test_no_inline_end_condition_completion():
"""Only finalize_occurrence and finish_task_at_end_condition finish a task.
The once-task repair in ``_associate_task_with_run`` mirrors a once run's
own outcome (not an end condition) and is the single allowed assignment.
"""
import ast
from pathlib import Path
from deerflow.persistence.scheduled_task_runs import sql as run_sql
from deerflow.persistence.scheduled_tasks import sql as task_sql
class Finder(ast.NodeVisitor):
def __init__(self):
self.stack = []
self.found = []
def _visit_function(self, node):
self.stack.append(node.name)
self.generic_visit(node)
self.stack.pop()
visit_FunctionDef = _visit_function
visit_AsyncFunctionDef = _visit_function
def visit_Assign(self, node):
targets_status = any(isinstance(target, ast.Attribute) and target.attr == "status" for target in node.targets)
if targets_status and isinstance(node.value, ast.Constant) and node.value.value == "completed":
self.found.append(self.stack[-1] if self.stack else "<module>")
self.generic_visit(node)
found = []
for module in (run_sql, task_sql):
finder = Finder()
finder.visit(ast.parse(Path(module.__file__).read_text(encoding="utf-8")))
found += [(module.__name__.rsplit(".", 2)[-2], name) for name in finder.found]
assert found == [("scheduled_task_runs", "_associate_task_with_run")]