Repository navigation
[perf] agent: answer a wait group with one query - #455
Conversation
kunkunblueberry
left a comment
There was a problem hiding this comment.
REQUEST CHANGES ef4471c Refs #449
job wait --allsilently loses jobs. Once every selected job has settled,job_statesselects an empty set and returns{"jobs": [], "completed": 0, "failed": 0}with exit code 0. With one already-failedjob in the project,job wait --allexits 0, whilejob wait <that-id>correctly exits 1. A job that fails while the agent is still waiting also disappears, so the agent is told everything succeeded.job_statesre-selects by "not terminal" on every poll instead of holding the wait group it started with.- The same path drops the failure reason:
deliveryis thorough, but a dropped job carries noerrorDetails, norecovery, and never reaches thefailedcount. gateway.executeruns the newread_onlycheck before thetryblock.arguments.get('type')raisesAttributeErrorfor non-dict arguments andTypeErrorfor an unhashabletypesuch as{"type": ["job.status"]}, so both escape the gateway'sToolResulterror contract. On 6a41c57 both inputs return a normalinvalid_inputerror. This is a regression introduced by this tip.gateway.close()still cancelscanvas.statuswaits but notjob.status: an in-flight 100 s window blocks turn teardown. Measured 5.7 s of blockedclose()withwaitSeconds=6; a 300 s window blocks proportionally longer. Stopping a turn now waits out the poll window.job.statusallowswaitSecondsup to 300, but the agent CLI socket timeout is 120 s (cli.py:180), so aWAIT_WINDOW=100request plus a snapshot read can exceed the transport limit.project show --summaryprints reference and editor-document counts but not their identities. After removing per-command--helpdiscovery, the agent can no longer obtain a reference ID to callreference.update/reference.remove.capabilitiesis described as replacing per-command--help, but it covers only the 32 types derived fromCOMMAND_MODELS. It omits 28 commands the agent uses every turn, includingjob wait,job show,video create,canvas add-material,canvas text *,project show,query,model list/show/availability,asset import,timeline import/export/default-font, andvoice list/create/delete. As shipped it cannot replace discovery, and the PR description claims that it can.
Ran:
pytest tests/test_agent_gateway.py tests/test_creation_canvas_service.pyon ef4471c: 47 passed, 1 skippedpytest tests/test_cli.pyon ef4471c: 3 failed, 31 passed. The 3 failures (test_voice_create_sends_private_fields_in_multipart_to_api,test_parser_error_shows_specific_command_help[plain|color]) needfontTools, which is absent from this local environment, and they fail identically on 6a41c57. Baseline environment gap, not this tip.- Release checks green on ef4471c (full tip SHA), all with this head SHA:
checks / python,static,frontend,browser (assistant|isolated|voice),checks,tests,route, CodeQL - Reproduced the first four findings with real
CreationProjects+CreationCanvasseeded jobs and a realToolGateway; the gateway behaviour was cross-checked against 6a41c57 to separate regression from pre-existing behaviour
Not run:
npm test/npm run buildlocally; the diff touches backend code and the generated contract only- Real provider generation; everything above used local seeded jobs and doubles
Non-blocking: the title says [perf] while the label is type:feat, and the tip adds both a new job.status query type and a capabilities command. Pick one type: reading per CONTRIBUTING. The PR body is English and Refs #449 is the right link, since #449 remains an open RFC. No UI change, so no demo is needed here.
The --all semantics deserve attention first: reducing avoidable calls is the point of #449, and an empty answer in the most common case (every job already finished) teaches the agent that a failed run succeeded.
ef4471c to
e6e5482
Compare
|
Re-reviewed at e6e5482. The rebase moved the tip, but this pull request's content is byte-identical to ef4471c: same 12 files, same +690/-32, and All seven findings are still present at e6e5482. Line numbers are from this tip:
Separately, the body now conflicts with #449's T1 evidence (issuecomment-7092098846). That analysis pins
Still open from my previous review and unaddressed here: the title says Not changed by this re-review: I have not run this tip locally; the seven findings are confirmed by reading e6e5482's code plus reproductions I ran at ef4471c on identical content. I have not merged, force-pushed, or dismissed any check. |
The agent waited for generation one job at a time. Each poll spawned a CLI process, read the whole project snapshot and emitted its own tool record, so the traced run in ThinkFlowLab#449 spent 968 waits and 954 status queries on 15 jobs. job.status answers up to 50 jobs from a single snapshot and can wait server side for terminal states. One call now covers a whole wait group, and a long wait costs one process per 100 s window instead of one per second. Accepted receipts hand back a single job wait command for every job they started, and read-only queries no longer take the turn's execution slot, so waiting does not block the other work in the same turn. Discovery no longer costs one process per command: capabilities summarizes all 32 commands with their required fields in one call, and project show --summary returns identities and revisions instead of every record body. scripts/bench_agent_polling.py measures the same fixture before and after: 14 jobs in one tick cost 180.6 ms and 14 snapshot reads, or 14.0 ms and 1 read; per-command help costs 33 calls, 30.1 s and 110 KB, while capabilities costs 1 call, 1.0 s and 7 KB.
) `job wait --all` re-read the set of unfinished jobs on every poll, so each job disappeared from the answer as soon as it settled. A job that failed while the caller waited was dropped from the report instead of being counted as failed: the caller was told nothing went wrong, and `errorDetails`, `recovery` and the non-zero exit code never reached it. The wait group is now resolved once, when the wait starts, and the server keeps reporting that same group. A wait with nothing to wait for answers `jobs: []` with a `note` naming where final job status can be read, instead of an empty answer that reads like every job succeeded. Three further defects on the same path: - The read-only check in `ToolGateway.execute` ran before argument validation, so `{"type": ["job.status"]}` raised `TypeError` and a non-mapping raised `AttributeError` out of the tool call instead of returning a tool error. The check now tolerates any argument shape and only skips the execution lock for a query whose type is a known read-only string. - `ToolGateway.close` cancelled a pending `canvas.status` wait but not a `job.status` one, so stopping a turn waited out the whole poll window. - A `job wait` window of 100 s had to fit inside the agent socket read timeout of 120 s together with the snapshot read that answers it. The window is now 60 s and the socket timeout is derived from it, with a test for the invariant. `capabilities` claimed to replace per-command `--help` but only described the 32 commands built from a command model, omitting 24 registered commands including `job wait`, `job show`, `query`, `project show`, `model *`, `asset import`, `canvas text *`, `timeline *` and `voice *`. It now also describes the registered parser, so discovery cannot fall behind the commands that exist. `project show --summary` gained `references` and `editorDocuments` identities: `reference.update`, `reference.remove` and `editor.save` need those IDs, and dropping them made the summary the one read that could not start an edit. Refs ThinkFlowLab#449
e6e5482 to
354644e
Compare
|
Fixed all seven findings in 1 + 2 — 3 — 4 — 5 — wait window vs socket timeout. 6 — 7 — Regression, re-measured on this headA CLI-level task replay (
Worst single call before was Tests on this head:
|
kunkunblueberry
left a comment
There was a problem hiding this comment.
All seven findings are fixed and I verified each against the code at this tip, not from the description. Reproductions below used real CreationProjects + CreationCanvas seeded jobs and a real ToolGateway.
- Fixed.
CreationCanvas.unfinished_jobsresolves the group once andwait_jobspolls a frozengroup. I made both queued jobs settle during the wait; the answer still named both, counted them, and exited 1:
completed: 0, failed: 2, note: "These jobs did not succeed; errorDetails names the cause..."
An empty project now answers withnote: "No job in this project is still running. project show --summary lists every job and its final status."instead of a silent success. - Fixed. Settled jobs stay in the report with
errorDetails,recovery,resumeAllowedandcancelRequested, as the run above shows. - Fixed.
_read_only()guards onisinstance, so the check can no longer leave the error contract. All three shapes return aToolResulterror instead of raising:{'type': ['job.status']}→Unsupported query type ...;'not-a-dict'→command: Input should be a valid dictionary;['job.status']→ same. - Fixed.
WAITING_QUERIESincludesjob.statusandclose()cancels both. Measured:close()finished within 1 s with a 300 sjob.statuswait in flight (was 5.7 s of blocking atwaitSeconds=6before). - Fixed.
WAIT_WINDOW = 60,SOCKET_TIMEOUT = 120, and the socket uses the derived value, so a window plus its snapshot read fits. The invariant is asserted in the suite. - Fixed.
summarizenow listsreferences(id, revision, targetSpecId, binding, role, order, active) andeditorDocuments(id, revision, kind, title), soreference.update/reference.remove/editor.saveare reachable. - Fixed.
capabilitiesmerges the registered parser with the typed models: 56 commands, includingjob wait,job show,project show,query,model *,asset import,video create,canvas text *,timeline *,voice *. Only the deliberately hiddencapabilities,serve,dev,desktopremain out.
Two things for a follow-up, neither blocking this PR:
- The pull request description is now stale against its own code. It still says "server waits up to 100 s per window" (
WAIT_WINDOW = 60), "capabilities (32 commands)" (56), and keeps the table row "a 15 min wait spawns ~900 processes ... the same wait spawns 9 processes". #449's T1 evidence (issuecomment-7092098846) states: "The 954 status requests must not be reported as 954 CLI process launches." This is a claim-accuracy problem in the text, not a code defect, and I am not holding the tip for it. Please correct the description before merge so the record matches what ships. - The title says
[perf]while the label istype:feat; the tip adds ajob.statusquery type and acapabilitiescommand.
Ran:
pytest tests/test_agent_gateway.py tests/test_creation_canvas_service.pyon 354644e: 50 passed, 1 skippedpytest tests/test_cli.pyon 354644e: 37 passed, 3 failed. The 3 failures needfontTools, absent from this local environment, and fail identically on main. Baseline environment gap, not this tip.- My own reproductions of all seven findings against real services at this tip, plus the frozen-group mid-wait scenario quoted above
- Release checks green on 354644e (full tip SHA), every run carrying this head SHA:
checks / python,static,frontend,browser (assistant|isolated|voice),checks,tests,route, CodeQL
Not run:
npm test/npm run buildlocally; the diff is backend code plus the generated contract- Real provider generation; everything above used seeded jobs and doubles
Coordinator: ping after this Reviewer PASS and green CI on 354644e. This skill does not merge.
|
Description corrected to match what shipped. All three points were checked against the merged tip
The title/label mismatch is still open: |
…y discovery, and surface wait outcomes (#449) (#681) * [test] bench: measure job waits, job show and tool-event folding Extend scripts/bench_agent_polling.py for #449 T1 so a change to the wait and query paths can be compared with its base under identical inputs. - --source measures another source tree (for example a worktree of the base commit); the script and its fixtures stay the same on both sides. - Fixtures are built once per configuration (nodes, commits, waiting and finished jobs, workspace projects) and copied per run. - wait: idle windows (cold and warm), unrelated saves during a window, a job settling in process and from another process, and an already settled job. Records snapshot and head reads, CPU, catalog lock hold time, detection latency and whether the answer matches a fresh read. - show: job show for a succeeded job through the real agent gateway and over HTTP, including a held execution lock; records calls, bytes, snapshot reads and an output digest. - events: one turn with many tool events through the API. - --summarize prints n, P50 and P90 (nearest rank) for one or two files. The default scenario keeps its previous output. No model or provider is called. * [perf] canvas: copy a waited project's snapshot only after a commit job.status and canvas.status waits poll every half second, and every tick deep-copied the whole project snapshot inside the catalog lock. That lock is shared across threads and processes with lease renewal, saves, job checkpoints and change polling, so an idle 60-second wait held it for about 2.4 s on a 200-node project. CommitLog.snapshot_if_changed runs the same recovery, lookup and head validation as snapshot() in one lock acquisition and copies the snapshot only when the head differs from the one the caller already has. Every job, result and canvas change is a commit with a new head, and the job and item views read nothing but the snapshot, so an unchanged head leaves the previous view current. Because the head and snapshot come from one acquisition, a commit between them cannot be missed; journal recovery, blocked projects and a rewritten head are reported on the same tick as before. Each tick still takes the catalog lock exactly once. snapshot(), head(), job_states() and item_status() are unchanged; the waits reuse their view computation through _job_views and _item_view. Measured with scripts/bench_agent_polling.py on macOS (base b834c01): a 5-second idle wait now copies the snapshot once instead of 11 times; wait CPU falls from 220 to 54 ms and catalog-lock hold from 198 to 35 ms on a 200-node project, and from 483 to 79 ms at 1,000 nodes. Terminal states are reported as quickly as before, in process and from another process, and every returned state matched a fresh read. * [perf] cli: report job show delivery from job.status, not a project read job show and query job.get read the whole project after a succeeded job to work out which canvas items show its asset. In agent mode that was a read_project call: every record plus the model catalog, and, unlike read-only queries, it waited for the turn's execution slot behind any write in progress. job wait already reports delivery from job.status. job show now asks job.status for the one job and takes its delivery, so both commands report delivery through the same server-side code. The fields and their values are unchanged; the previous client-side computation is kept in the test as the reference for adopted, candidate, material-bound and material-override deliveries. Errors propagate as before; generation jobs are never removed, so the second query cannot miss a job the first one found. Measured with scripts/bench_agent_polling.py --scenario show (200-node project): agent-mode response bytes fall from 140,085 to 2,660, HTTP from 125,435 to 2,486, and with a write holding the execution slot for 2 s job show answers in 54 ms instead of 2,034 ms. Output digests match the base commit at 50, 200 and 1,000 nodes. * [perf] assistant: index a turn's tool records by call ID Each tool event looked up its record with a linear search and replaced it with list.index, so folding a turn's events was quadratic on the API event loop. The face-replacement trace in #449 had about 1,200 calls in one turn; a CLI wait loop can produce thousands of events. Keep a call ID to position map beside the records. Records are only appended or replaced in place, so positions never move; order, statuses and each call's first textOffset are unchanged. A test folds interleaved updates for 3 and 2,500 calls and compares the saved records with the previous linear fold. Measured with scripts/bench_agent_polling.py --scenario events through the API, alternating with the base commit: one turn with 2,500 calls takes 609 ms instead of 803 ms and with 5,000 calls 1,298 ms instead of 2,054 ms (P50, n=10 each); saved tool records are identical. * [bugfix] agent: give every runtime the same command discovery rule The system prompt asks for one opendirector capabilities call and no per-command --help. The per-turn execution context of the native runtimes (OpenCode, Codex, Claude) and of JiuwenSwarm still said to discover commands with opendirector --help and each command's --help, so a turn received both instructions. Per-command help probing was the discovery cost #455 measured at 33 calls before capabilities existed. Both contexts now use CLI_DISCOVERY, defined beside SYSTEM with the same rule. The fake harnesses of the native and JiuwenSwarm runtime tests assert the actual prompt they receive asks for capabilities once and never for opendirector --help; the same tests fail against the base commit. Human terminal usage still documents --help. This removes the conflicting instruction only. Whether a model now issues fewer discovery calls needs a real-model run, which this change does not include. * [test] trace: reconcile job wait records with the #449 statistics Issue #449 published counts for the DeepSeek face-replacement trace (954 complete job.get records, 59 distinct responses, 895 repeats, 9,662,495 result bytes, 14 project reads after successful jobs). Later changes need the same numbers computed the same way. scripts/trace_job_queries.py applies the published selection rules to a trace archive (read in memory and checked against its SHA-256) or its deepseek.jsonl, labels each completed CLI record as a project change, a necessary wait, an avoidable repeat or a delivery read, and lists each job's status changes. --check-published fails with every number it could not reproduce. Its snapshot estimate for head-gated waits is labelled as a model, not a measurement. The tests use a synthetic trace; the real trace is not in the repository and has not been run here. * [feat] agent: record what each job and canvas wait observed A tool record's status is the outcome of the call. A job.status window that returns while jobs are still running is a successful call, so it is saved as complete; in the #449 trace 939 complete job queries were for queued or running jobs, and the record alone could not tell a settled wait from a timed-out window. The CLI transport now saves waitOutcome beside a successful job.status or canvas.status record: whether the wait settled, and the job status counts or the item status it saw. status keeps its meaning and nothing in the interface reads the new field yet: how the execution record should show an unsettled wait is decision 1 of the RFC. trace_job_queries.py counts settled and unsettled recorded waits when a trace has the field. ChatTool declares the optional field; there is no user-visible text. * [feat] assistant: show waits that returned before their jobs finished The execution record counted every complete call as done. A job.status window that returned while its jobs were still running is a complete call, so the #449 trace showed 939 such queries as finished work. A complete record whose waitOutcome is unsettled now reads "Not finished" (未结束), is left out of the done count, and the summaries add "N returned before jobs finished" (N 次返回时任务未结束). Calls that did not complete keep their status, and records saved before waitOutcome existed read as before. Both strings are added in zh-CN and en-US. This is a proposal for decision 1 of RFC #449; the maintainers may prefer another presentation of the same recorded outcome. Checked with unit tests and, in the browser, both languages on the reply fixture: summaries, per-record labels, no cross-language leak, and no overflow at a 320 px panel width. assistant_wait_outcome.mjs repeats those checks for the gate lane; Playwright is not installed locally, so the script itself has not been run here. * [refactor] agent: share discovery rule, deduplicate snapshot read, and trim inline comments (#449) * [test] assistant: verify waitOutcome SSE streaming and persistence; drop unused import (#449) * [test] browser: close nested tool group and wait for visible status in assistant_wait_outcome (#449)
Refs #449.
The agent waited for generation one job at a time: the traced run in #449 spent 968
job waitCLI calls and 954job.getstatus requests to follow 15 jobs. Those 954 requests produced only 59 distinct answers for the same job IDs — 895 of them (93.8%) repeated an answer already recorded for that job — and the recorded result strings came to about 9.66 MB. Discovery had the same shape: the SYSTEM prompt told the agent to probe--helpper command, so it spent 15 separate bash calls on probing before doing any creative work.This change removes the per-job and per-command loops while keeping the business semantics: same commands, same reads, same receipts.
What changed
job wait JOBpollsjob.getfor one jobjob wait JOB.../job wait --alluses the newjob.statusquery: one snapshot answers up to 50 jobsWAIT_WINDOW = 60, withSOCKET_TIMEOUT = 120derived from it), so the same 15 min wait is 15 callsjob.status,job.get,object.get,canvas.statusanswer without the execution slot; writes still serializenext.commandshad onejob waitper accepted jobjob waitcommand carrying every job IDopendirector --helpplus one--helpper command, one call each; the bench spent 33 CLI calls on the 32 typed commands aloneopendirector capabilities(56 commands — the 32 typed command models plus the 24 that exist only in the parser — with summaries and required fields);--help-fieldonly for a field whose shape is unclearproject showreturns every record bodyproject show --summaryreturns identities, revisions and statuses; the full snapshot stays the defaultjob waitreturned one job and its deliverydeliveryin the same batched answerMeasured
scripts/bench_agent_polling.pybuilds a 200-item / 600-commit project with 14 unfinished jobs and times both paths.project showpayload (same fixture)End to end against a real API process (
job waitwith 14 IDs): 1.02 s and one call, versus 0.94 s perjob showfor the same coverage.These are server calls, snapshot reads, payload sizes and CLI calls. They are not counts of CLI process launches per polling iteration: one
job waitprocess loops internally, and the 954job.getrequests above were issued from insidejob waitcalls rather than one process each.Behaviour changes
job waittakes one or more job IDs or--all, and prints{"jobs": [...], "completed": n, "failed": n}, adding"timeout": trueand exit code 2 when the window closes. Interrupted and cancelled jobs still exit 1, as before, and each terminal job carries thedeliverythe previous output exposed.job.statusis a new query type in the creation contract, so the generated schema andsrc/contracts/generated.tsare regenerated.Validation
pytest: 2884 passed, 105 skipped.npm test: 952 passed;npm run buildsucceeds.check:i18n,check:browser-manifest,check:browser-localeclean; no user-visible copy changed.any/all/timeout waiting, multi-ID and--allCLI waits with distinct exit codes, summary identity coverage with a payload at most a quarter of the full snapshot, the capabilities digest, and that a read-only query answers while a write holds the execution slot. The wait window and its derived socket timeout are asserted as an invariant, so a window can never outlast the read that answers it.Not in this PR
The remaining causes in #449 need separate changes: a native tool channel instead of one CLI process per action (R1), event-driven canvas sync instead of a full
/canvasrefresh per tool event (R4), poll aggregation instead of one record per poll (R5), preview pipeline (R8), and the TTFA/TTC instrumentation (T5) that this measurement should feed into.