Skip to content

refactor(acp): persist parent-stream diagnostic batches through the agent writer - #164454

Merged
steipete merged 3 commits into
mainfrom
dbasync/acpdiag
Oct 3, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/acpdiag

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

ACP parent-stream diagnostic flushes execute SQLite transactions on the Gateway caller thread. Moving them asynchronously also needs explicit shutdown settlement and must not replay a batch whose commit outcome is unknown.

Why This Change Was Made

Bind a typed diagnostic adapter to the canonical per-agent writer. Capture the child, run, and physical database before yielding; serialize diagnostics before dispatch; allocate sequence numbers and insert each ordered batch in one synchronous worker transaction with current transaction/commit grants.

The relay keeps its 256-event pending buffer, flush thresholds, retry backoff, and warning bounds, with one batch in flight. Only confirmed rollback or canonical pre-execution refusal can retry. Disposal seals admission synchronously and joins accepted persistence through the existing Gateway resource host before database transports close. Run-ID replacement installs the next relay immediately, without waiting for diagnostic cleanup.

User Impact

No schema, retention, durability, configuration, SDK surface, or update migration changes. Diagnostic failures remain isolated from child execution and parent progress. The superseded synchronous writer is removed; all runtime callers use the worker-backed recorder. There are no retained host SQL authority reads in this lane.

Production diff: +298 / -109 / net +189 (407 changed lines), excluding tests, docs, and test routing. Static inventory: T1 1,233 → 1,230, with no classification override and zero new OPENCLAW_* names. Proof base: 4ab382220e2cca1deedb2c2549982f91c0fb5c64.

Evidence

  • Real relay boundary: zero caller-thread prepare/exec calls and 100 ordered durable events. The same regression failed on the original source at caller-thread BEGIN IMMEDIATE (32.07 s wall).
  • Real server.close() order: 101 accepted/buffered events persist before database teardown; events after the close prelude are refused. One Gateway boot; 96.71 s file duration / 48.00 s test time on the loaded host. This real lifecycle boundary cannot be established by the cheaper store or mocked relay tests.
  • Recorder, boundary, relay, spawn, and archive suites: 95 tests passed, pnpm test <five files> --maxWorkers=1, 228.21 s wall. Recorder file 10.04 s, archive file 90.58 s, three agent files together 94.30 s. Covers FIFO, captured inputs, malformed diagnostics, atomic rollback, native error details, unknown-outcome non-replay, disposal settlement, and immediate relay replacement.
  • Required import/build-graph proof: test/scripts/runtime-process-build-graph.test.ts, src/auto-reply/reply/get-reply.imports.test.ts, src/worker/worker.runtime-imports.test.ts, and test/scripts/eager-import-closure.test.ts: 31 tests passed. Group durations: 7.03 s, 10.61 s, and 54.50 s. The compiled-wrapper inventory is closed; the new adapter is registered in the runtime-process build inventory.
  • Existing two-file baseline: 31 tests passed in 72.59 s wall. The first attempt overlapped initial setup artifact generation and failed before tests; setup was joined before the successful baseline.
  • Database worker ratchet against the pinned base: passed (29.53 s wall). Madge: 0 cycles (45.11 s wall).
  • After type-aware lint corrections, the 37 affected recorder/boundary/relay tests passed again in 565.57 s wall (most time was compiled-worker preparation under filesystem load). Targeted type-aware lint passed in 21.16 s; scripts lint passed in 190.98 s.
  • Gateway runtime build (pnpm build qaRuntime): passed, 537.88 s wall, including artifact-lock wait; actual build phases took 123.3 s. The broader full build completed package and main JavaScript compilation but was intentionally stopped during unrelated bundled-plugin declaration generation. No full-build pass is claimed.
  • Fresh Codex autoreview through P2: clean. Its initial relay-replacement finding was fixed and independently re-reviewed.
  • Registry latest and beta both resolve to 2026.9.8; the released SDK does not export the removed diagnostic writer or relay handle.

Released-SDK comparison obtained: pnpm plugin-sdk:api:diff -- --base v2026.9.8 --head 5d3fb7a898880adbaa2e048e06febe0651ecec5d produced a checked report and evidence JSON after using a realpath-resolved TMPDIR and RUNNER_TEMP. Base commit: fc23bc864e4553c2d215e479eeec47b67a0bf943; report digest: c7d46b0bc9f01609c049a2947042b5040635ea76dedff6b557ca56f0108c195f. The release-to-head report includes existing mainline SDK drift (8 removed subpaths, 1 added, 2,219 affected exports), not a claim of a globally unchanged SDK. This PR changes no src/plugin-sdk, api.runtime, package export, or documented SDK subpath surface. The removed recorder and changed relay handle are internal-only; none of the changed ACP symbols appears in the report, so this patch requires no released-signature compatibility adapter.

node scripts/check-changed.mjs --base 4ab382220e2cca1deedb2c2549982f91c0fb5c64 -- src/agents/subagents/spawn/acp-parent-stream-store.sqlite.ts src/agents/subagents/spawn/acp-spawn-parent-stream.test.ts passed after the lint corrections (2344.08 s wall), including core and all 27 test type graphs, targeted core lint, and every selected static guard. pnpm lint:scripts also passed, covering the routing inventories. The initial whole-PR check found only the corrected unbound callback and floating test disposal errors; its unchanged-file lint evidence and earlier checks are retained. The corrections are committed in 8f951b3594105ca35f53e65f3e0471c5fedf882c; fresh P2 review of the resulting source is clean. The corrected-head CI relay-boundary test took 0.488 s; the local wall times above are not CI measurements. Other individual test durations were not separately extracted from the shared CI shards.

Overlap: #164269 is incidental normalization cleanup in the relay; #162433 is the explicitly deferred umbrella ownership draft. This change uses minimal persistence/lifecycle hunks and does not adopt either restructuring. No competing diagnostic persistence migration was found.

Landing repairs and CI attribution

5d3fb7a898880adbaa2e048e06febe0651ecec5d addresses both actionable ClawSweeper findings. The relay replaces an ordinary flush timer when establishing rollback backoff, including when traffic arrives during a pending write. Its existing retry test now fails on the unfixed source (expected one write, observed two before the retry deadline) and passes with the fix. The new ACP adapter is also registered in the scanner's existing fixed-protocol family; the worker loader requires the exact bindSqliteWorkerBackend export.

All 32 relay tests pass (523.20 s command wall time; 321.33 s Vitest file duration, dominated by worker compilation on the loaded host), and all 54 export-name guard tests pass (8.55 s command wall time). The export-name collision guard passes. Fresh Codex autoreview through P2 is clean for the complete staged candidate. The PR-body template heading failure was corrected.

Initial CI run 37144854704 had the PR-caused export registration failure and a separate inherited Linux Doctor/NOCOW teardown failure: src/flows/doctor-health.nocow.test.ts, “joins Doctor's inspection child and database handles before rewriting both stores,” fails while releasing an agent lease under offline maintenance. The same failure and stack occur on main in job 111264313536. This PR does not change that test, Doctor maintenance, or lease/lifecycle owners. An isolated local Node 24.21 container completed all requested repetitions after remote capacity failures. Doctor reproduces the same CI failure 5/5 on the PR head, 5/5 on the merge base, and 5/5 on CI main 7e3ba7f. No CI rerun was sent.

Final-head boundary confirmation: hosted CI observed 100 ordered diagnostic events with zero caller-thread SQL (acp-parent-stream.worker-boundary.test.ts, 488 ms). The real Gateway close regression passed again locally on 5d3fb7a8: 101 accepted events remained durable after all database transports closed, while the late event was refused (241.93 s command wall / 183.24 s Vitest / 56.79 s test). ClawSweeper completed the corrected head at 2026-10-03 19:15 UTC with no actionable correctness findings; its only remaining item was the now-obtained SDK report.

The corrected-head CI run 37146925267 passed source contracts and all other selected jobs except two Node roots and their aggregate gate; no jobs were cancelled. Besides Doctor/NOCOW, the snapshot-diagnostics assertion failed on CI's synthetic merge 0373aa48d9c12bbd9c7798fb1b7fa7296037a1d9. Its base, main 7e3ba7f (#162258), introduced the exact aggregate error text that omits filesystem guidance when snapshot cleanup also fails. That message is absent from this PR head and its merge base, and the test does not reach the ACP worker. Independent execution on current main fe6414a23399eb97b40af76e2ba2cc70b28ba5bc reproduced the exact snapshot assertion, aggregate message, and errcode=778 in all five runs. The relevant test, snapshot, retirement, and formatting sources are identical between CI baseline 7e3ba7f and that main checkout. The Linux comparison matrix is complete: snapshot diagnostics passes 5/5 on the PR head and 5/5 on the merge base, then fails with the exact CI assertion and message 5/5 on CI main 7e3ba7f. All 30 runs were single-file invocations with --maxWorkers=1; the container used fresh pinned public checkouts and no host credentials. Both failed CI roots are independently attributed to main in untouched files, and are retained as failures in the native admin evidence rather than relabeled as green.

…gent writer

Move durable diagnostic sequence allocation and ordered batch insertion into the canonical per-agent worker. Retain bounded relay buffering, confirmed-refusal retries, unknown-outcome non-replay, and accepted settlement through Gateway close. Keep run-ID relay replacement immediate.
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L labels Oct 3, 2026
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 4:27 PM ET / 20:27 UTC (Revision 6).

ClawSweeper review

What this changes

Moves ACP child-agent stream diagnostics into the existing agent database writer and joins accepted writes during Gateway shutdown.

Merge readiness

✅ Ready for maintainer review

This work remains necessary on current main. Both earlier findings are resolved, and the updated evidence addresses the previous comparison request; no new actionable patch defect was found.

Priority: P2
Reviewed head: 5d3fb7a898880adbaa2e048e06febe0651ecec5d

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Strong production-boundary proof supports a coherent owner-preserving cutover, and both prior defects are repaired.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded final-head execution exercises the real relay and database worker with 100 ordered durable events and zero caller-thread SQL, plus real Gateway shutdown with an injected writer hold, 101 durable events, and late-event refusal. Inspected harnesses match those claims. Existing row fields, sequence allocation, serialization, deletion relationships, and schema remain unchanged; no stored-data model migration is introduced.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded final-head execution exercises the real relay and database worker with 100 ordered durable events and zero caller-thread SQL, plus real Gateway shutdown with an injected writer hold, 101 durable events, and late-event refusal. Inspected harnesses match those claims. Existing row fields, sequence allocation, serialization, deletion relationships, and schema remain unchanged; no stored-data model migration is introduced.
Evidence reviewed 8 items Current main still uses synchronous persistence: Fetched main retains recordAcpParentStreamEvents, which allocates sequences and inserts diagnostic batches through runOpenClawAgentWriteTransaction on the caller thread. The requested worker cutover is therefore still useful.
Captured target and canonical writer: The recorder captures the existing physical database before yielding, snapshots serialized events before queue admission, and dispatches through the existing agent worker store with execution.assertCurrent. The worker preserves the existing row fields and performs sequence allocation plus insertion in one synchronous transaction with transaction and commit admission.
Shutdown settlement through existing ownership: Disposal synchronously seals event admission, joins the active batch and remaining buffer, drains accepted work, and closes the recorder. Its completion is registered with the existing SDK resource host, which Gateway close drains before agent database retirement.
Findings None None.
Security None None.

How this fits together

The ACP parent-stream relay receives child-agent runtime events and sends progress to the parent conversation. Its diagnostic recorder separately stores ordered events in the child’s agent database.

flowchart TD
  A[Child runtime events] --> B[Parent stream relay]
  B --> C[Parent progress]
  B --> D[Bounded diagnostic buffer]
  D --> E[Agent writer admission]
  E --> F[Atomic ordered database batch]
  G[Gateway shutdown] --> B
  G --> H[Join accepted persistence]
  H --> F
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +189, Tests +361, Docs +10, Other +1. Total +561 across 16 files.

View PR surface stats
Area Files Added Removed Net
Source 5 298 109 +189
Tests 9 435 74 +361
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 16 744 183 +561

Review metrics

Metric Value Why it matters
Production versus test growth production net +189 lines; tests and test support net +459 lines Production growth is justified by the typed worker adapter and explicit persistence settlement; tests cover distinct FIFO, rollback, transport, and shutdown contracts.

Technical review

Best possible solution:

Keep diagnostic persistence under the canonical agent writer, preserving bounded buffering, atomic ordering, conservative retry, and shutdown settlement.

Do we have a high-confidence way to reproduce the issue?

Yes, source establishes that current-main relay flushes enter a synchronous SQLite transaction; the supplied boundary regression reports failure on the original caller-thread BEGIN IMMEDIATE. This review performed source inspection only.

Is this the best way to solve the issue?

Yes, reusing the existing agent writer and Gateway resource host is a focused cutover that preserves the storage format and avoids a competing persistence owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 28a6f71449aa.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded internal persistence improvement with relevant correctness proof and no demonstrated urgent user-facing regression.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded final-head execution exercises the real relay and database worker with 100 ordered durable events and zero caller-thread SQL, plus real Gateway shutdown with an injected writer hold, 101 durable events, and late-event refusal. Inspected harnesses match those claims. Existing row fields, sequence allocation, serialization, deletion relationships, and schema remain unchanged; no stored-data model migration is introduced.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded final-head execution exercises the real relay and database worker with 100 ordered durable events and zero caller-thread SQL, plus real Gateway shutdown with an injected writer hold, 101 durable events, and late-event refusal. Inspected harnesses match those claims. Existing row fields, sequence allocation, serialization, deletion relationships, and schema remain unchanged; no stored-data model migration is introduced.

Evidence

What I checked:

  • Current main still uses synchronous persistence: Fetched main retains recordAcpParentStreamEvents, which allocates sequences and inserts diagnostic batches through runOpenClawAgentWriteTransaction on the caller thread. The requested worker cutover is therefore still useful. (src/agents/subagents/spawn/acp-parent-stream-store.sqlite.ts:20, 28a6f71449aa)
  • Captured target and canonical writer: The recorder captures the existing physical database before yielding, snapshots serialized events before queue admission, and dispatches through the existing agent worker store with execution.assertCurrent. The worker preserves the existing row fields and performs sequence allocation plus insertion in one synchronous transaction with transaction and commit admission. (src/agents/subagents/spawn/acp-parent-stream-store.sqlite.ts:30, 5d3fb7a89888)
  • Shutdown settlement through existing ownership: Disposal synchronously seals event admission, joins the active batch and remaining buffer, drains accepted work, and closes the recorder. Its completion is registered with the existing SDK resource host, which Gateway close drains before agent database retirement. (src/agents/subagents/spawn/acp-spawn-parent-stream.ts:564, 5d3fb7a89888)
  • Production boundary proof: Inspected harnesses exercise the actual relay and database worker, plus real server.close() with an injected writer hold and a fresh database connection after teardown. The captured PR body reports final-head observations of 100 ordered events with zero caller-thread SQL and 101 durable shutdown events with late-event refusal. These scenarios directly cover the changed production path; no tests were executed during this review. (src/gateway/server-close.acp-diagnostics.test.ts:16, 5d3fb7a89888)
  • Previous findings and compatibility evidence: The current relay clears an existing flush timer before establishing rollback backoff, and the export scanner registers the new worker in its fixed-protocol family. The captured body records the obtained v2026.9.8 SDK comparison, digest c7d46b0bc9f01609c049a2947042b5040635ea76dedff6b557ca56f0108c195f, and distinguishes unrelated mainline SDK drift from this internal change. Captured source revision: 008cd99456caca6d8601a77c31c92b870fd4df6bd931bb272383099fcdf61f58. (scripts/check-export-name-collisions.mts:713, 5d3fb7a89888)
  • Updated inherited-failure comparison: The captured body now reports the complete Linux matrix: Doctor/NOCOW fails 5/5 on head, merge base, and CI main; snapshot diagnostics passes 5/5 on head and merge base and fails 5/5 on CI main. Live job metadata confirms two failed Node roots and their aggregate, with no cancellations. This addresses the prior comparison request without relabeling CI as passing. Raw log retrieval was blocked at results-receiver.actions.githubusercontent.com, so this review did not independently inspect those failure logs; native landing must validate any exception through its existing evidence owner. (5d3fb7a89888)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-03T18:41:29.106Z sha 8f951b3 :: blocked before merge. :: [P2] Replace the ordinary flush timer when scheduling a retry
  • reviewed 2026-10-03T18:46:37.740Z sha 8f951b3 :: blocked before merge. :: [P2] Replace the ordinary flush timer when scheduling a retry | [P2] Register the worker in the fixed-protocol export registry
  • reviewed 2026-10-03T19:15:16.221Z sha 5d3fb7a :: needs changes before merge. :: none
  • reviewed 2026-10-03T19:51:10.090Z sha 5d3fb7a :: needs maintainer review before merge. :: none
  • reviewed 2026-10-03T20:13:19.214Z sha 5d3fb7a :: needs changes before merge. :: none

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 3, 2026
Keep rollback backoff intact when diagnostic events arrive during an in-flight write. Register the ACP adapter under the loader-required worker export contract. The deferred-write regression fails before the timer fix; all 32 relay tests and 54 export guard tests pass. P2 review is clean.
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 3, 2026
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 3, 2026
@steipete
steipete merged commit 930bd38 into main Oct 3, 2026
181 of 185 checks passed
@steipete
steipete deleted the dbasync/acpdiag branch October 3, 2026 20:39
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…gent writer (openclaw#164454)

* refactor(acp): persist parent-stream diagnostic batches through the agent writer

Move durable diagnostic sequence allocation and ordered batch insertion into the canonical per-agent worker. Retain bounded relay buffering, confirmed-refusal retries, unknown-outcome non-replay, and accepted settlement through Gateway close. Keep run-ID relay replacement immediate.

* fix(acp): retain source guard binding and await relay test cleanup

* fix(acp): preserve diagnostic retry backoff and register worker

Keep rollback backoff intact when diagnostic events arrive during an in-flight write. Register the ACP adapter under the loader-required worker export contract. The deferred-write regression fails before the timer fix; all 32 relay tests and 54 export guard tests pass. P2 review is clean.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. scripts Repository scripts size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant