Skip to content

improve: reduce Gateway blocking during image delivery - #159348

Merged
steipete merged 4 commits into
mainfrom
codex/managed-media-worker-custody-20260927
Sep 27, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/managed-media-worker-custody-20260927

Conversation

@steipete

@steipete steipete commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Image delivery still performs metadata writes on the Gateway event loop even though its metadata reads already use a worker.

User Impact

Creating, promoting, and cleaning up managed images no longer performs database work on the Gateway thread. Chat publication waits for its accepted media work, preserving attachment availability and cleanup ordering. No schema, migration, retention, configuration, or operator change is required; existing update behavior remains unchanged.

Why This Change Was Made

Move insertion, message-commit promotion, cleanup claims, and claimed deletion into the existing shared-state worker and transaction owner. Promotion reserves its records before yielding so cleanup cannot overtake accepted work. Both transcript owners join completion before publication or release, and chat, injected messages, internal replies, cron, heartbeat, and restart delivery move onto that contract together. The old synchronous and later-attachment paths are removed.

The asynchronous boundary needs explicit custody: the original descriptor and metadata row settle together, native commit receipts reconcile lost ordinary replies, and uncertain or retired-store outcomes retain bytes without accepting a stale result. The existing admission record supplies a stable coordination key for ordering, never authorization. The added production code carries these custody and settlement guarantees through the existing storage owner.

Stored-data compatibility

The stored image-record types, selected columns, row serializer, row decoder, and equality behavior are unchanged from the base revision. Worker commands and completion callbacks change only execution and publication ordering; they do not change database columns, schema version, transcript bytes, or retention. The existing real record-store suite passes all eight cases, including every-field round-trip and close/reopen persistence. No new migration or Doctor action is needed. This resolves the review renderer’s path-based compatibility item; the review itself also confirms that the stored-data representation is unchanged.

Evidence

  • The existing real image-create entry records 14 host data-SQL observer events before and zero after. These hooks count preparation and execution, not fourteen distinct statements. The original negative control fails; the candidate preserves the stored image and metadata. This is an event-loop boundary measurement, not a production latency benchmark.
  • 383 focused cases across 17 files cover worker transactions, commit-receipt recovery, cleanup races, partial promotion, retired authority, descriptor replacement, and publication settlement. Connection-local trigger fixtures were replaced with the existing native commit-admission control so faults reach the actual worker transaction; assertions remain intact.
  • The real isolated WebSocket flow creates an explicit non-main dashboard session, sends a message, observes publication, and reads the persisted title while dispatch is held. Its existing case passes in 3.258 s; supported-wrapper wall is 78.21 s (78.799 s including the supervisor), with normal fixture retirement and all descendants joined.
  • Core production types, all ten affected test type graphs, typed lint, formatting, import cycles, line limits, assertion safety, and database/media/schema guards pass. A complete independent P0–P2 review inspected 72 source datasets across five passes with no findings. Current-head CI passes: 155 jobs succeeded and 19 were skipped, with no failures. No full build was run because this does not alter Gateway lazy-loading or bundled-plugin artifact boundaries.

Fourteen added cases took 13.905 s combined case-body time in focused --maxWorkers=1 runs. Individual body times are 0.687/3.163 s for record ordering and receipts; 2.366/0.768/0.848/0.763/1.541/1.428 s for custody outcomes; 0.050/0.048/0.051 s for transcript completion; 0.959/0.611 s for injected-message publication; and 0.622 s for restart publication. The new custody file occupied 74.49 s including cold transform/setup in its Vitest cell. Multi-file wrapper walls are not represented as standalone per-file costs. The successful final hosted Gateway-methods job passed 1,335 tests across 68 files (one skipped) in 153.68 s; its repaired directive fixture passed all 225 cases with 8.028 s summed case-body time. Those are group/body costs, not standalone file wall times, and that job does not contain the 14 new cases. These tests use actual worker settlement because an in-process helper test cannot prove the commit/cleanup boundary.

The first public-flow attempt reached its unchanged 600 s external budget without a test-body result while an owned thread was observed waiting on Btrfs allocation. Its namespace/resource claim and receipt remain retained. After completed task-cache cleanup and a healthy filesystem preflight, one recovery run passed with unchanged assertions and timeout. An internal-source suite also reported a fork-termination warning after all eleven cases passed; its supervisor joined every descendant, but the warning's cause is not claimed fixed. Earlier fixture/type corrections and their original failures remain recorded in the task evidence.

The first hosted run failed in src/media/local-media-path.windows.test.ts: image ingestion passed its assertions, but the fixture tried to remove openclaw.sqlite after only synchronous handle close and Windows returned EBUSY. The fixture now awaits the existing scoped session-state cleanup owner before deleting its directory; the redundant global synchronous teardown is removed. Nine existing cleanup and real worker-custody cases pass in 65.232 s wrapper wall. Native Windows CI on commit 765f5bf6 then passed the ingestion and awaited cleanup case in 741 ms, and its media group passed 9/9 cases in 13.80 s. The job was later cancelled during another group after an independent dependency-check failure; this is case/group evidence, not a whole-job pass. The owning core-test-infra type graph, one-file typed lint, formatting, and diff checks pass. No test assertions, retries, or production behavior changed in this repair.

The dependency check then found two kernel exports whose production callers were removed by this cutover. Those details are now private; the two synchronous publication observers use the existing typed command dispatcher. All 26 existing cases in the affected files pass in 96.608 s supervised wall. Both exact pnpm deadcode:full scans, production types, both owning test type graphs, typed lint, formatting and diff checks pass. Fresh independent review found no actionable P0–P2 issue in the three-file repair. No new tests, runtime behavior, stored representation, dependency or schema changes were introduced. The repaired source is included in the successful final CI run below.

The next hosted run exposed 18 outgoing-image assertions in chat.directive-tags.test.ts: its canned saveMediaBuffer returned a pathname without production's descriptor custody, so delivery correctly rejected the fake resource. The original binding-owned reply case reproduced the failure locally in 38.138 s supervised wall. The six-line fixture repair forwards every argument to the real save function for outgoing originals and keeps the existing inbound fixtures and assertions. All 225 existing cases then passed in 43.001 s supervised wall (40.05 s Vitest), including the 18 hosted failures. The owning Gateway-methods type graph passes in 42.640 s; typed lint, formatting, and diff checks also pass. A fresh independent P0–P2 review of the fixture and seven complete storage/custody owners found no actionable issue. No production change or new test was needed. The repaired fixture is included in the successful final CI run below.

CI on 2f38b8c4 then encountered an inherited UI lint regression in index.tree-snapshots.test.ts, introduced by main commit 8cea9e99. PR #159394 fixed that exact map/spread violation; its owning lint, UI shards, and CI gate passed. This branch is refreshed onto aad795bf containing that fix, with the complete reviewed patch byte-identical and no overlapping main changes in its 65 paths. Fresh CI on head 1e5e6540 passed: run 36295083109, with 155 successful jobs, 19 skips, and no failures. The earlier failed run remains a distinct result. The current-head ClawSweeper review is published and has no correctness or security findings.

@clawsweeper

clawsweeper Bot commented Sep 27, 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: XL labels Sep 27, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. labels Sep 27, 2026
@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 27, 2026, 12:49 AM ET / 04:49 UTC (Revision 4).

ClawSweeper review

What this changes

The branch moves managed-image metadata writes into OpenClaw’s shared-state worker and waits for accepted media work before publishing affected transcript messages.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR open. Current main and the latest release still perform managed-image metadata writes on the Gateway thread. The prior upgrade concern is resolved by the unchanged stored-row representation, and this review found no introduced blocking defect.

Priority: P2
Reviewed head: 1e5e654070b13b6c392fa7153e3ce912add3f903

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The worker cutover has concrete real-boundary observations, focused race coverage, and no verified correctness blocker, though it spans several publication paths.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured PR body reports a real image-create run through the Gateway media owner with 14 host SQL events before and zero after while retaining the file and metadata, plus an isolated WebSocket publication run; worker fault tests supplement those observations. Pinned source comparison shows no stored-row contract change, so no data-model migration is needed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured PR body reports a real image-create run through the Gateway media owner with 14 host SQL events before and zero after while retaining the file and metadata, plus an isolated WebSocket publication run; worker fault tests supplement those observations. Pinned source comparison shows no stored-row contract change, so no data-model migration is needed.
Evidence reviewed 8 items Current main still writes synchronously: The current-main store calls the shared-state write transaction directly for managed-image insertion; the latest release has the same path.
Latest-release check: Release v2026.9.6 still contains the synchronous insertion and promotion path, so the central change has not shipped.
Introduced worker boundary: The introduced store reserves per-attachment ordering and dispatches mutations through the shared-state worker; its kernel performs the synchronous transaction inside that worker.
Findings None None.
Security None None.

How this fits together

The Gateway receives media from agent replies, saves original files and metadata in shared state, then publishes transcript messages. Clients use those messages to request the attachments.

flowchart LR
  A[Agent media reply] --> B[Gateway media preparation]
  B --> C[Original file custody]
  B --> D[Shared-state worker]
  D --> E[Committed metadata]
  C --> F[Transcript publication]
  E --> F
  F --> G[Client attachment download]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +457, Tests +781, Docs +10. Total +1248 across 65 files.

View PR surface stats
Area Files Added Removed Net
Source 25 787 330 +457
Tests 39 893 112 +781
Docs 1 13 3 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 65 1693 445 +1248

Review metrics

Metric Value Why it matters
Main-thread SQL observations 14 before, 0 after The reported image-create measurement directly targets the event-loop work this PR removes; it is not a latency benchmark.
Production versus test lines production +787/-330; tests and test support +893/-112 The net production growth supports worker transaction custody and publication settlement, as explained in the PR body.

Stored data model

Persistent data-model change detected: serialized state: src/cron/isolated-agent/current-session-completion.ts, serialized state: src/gateway/internal-source-reply-persistence.ts, serialized state: src/gateway/server-methods/chat-send-commentary-media.ts, unknown-data-model-change: src/gateway/internal-source-reply-persistence.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep shared SQLite as the single metadata owner and require settled promotion before clients can observe a managed attachment.

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

Yes. Current main visibly executes managed-image writes synchronously, and the PR reports a real image-create observer run measuring that boundary; this read-only review did not execute it.

Is this the best way to solve the issue?

Yes. The patch uses the existing shared-state worker and transcript completion owner while preserving the stored record format, which is a maintainable boundary for this work.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4c3181e2386c.

Labels

Label changes:

  • add merge-risk: 🚨 message-delivery: The changed metadata-promotion and transcript-publication ordering is attachment-delivery sensitive, even though focused proof covers its known races.

Label justifications:

  • P2: This is a bounded Gateway performance and reliability improvement without evidence of an urgent user-facing outage.
  • merge-risk: 🚨 message-delivery: The changed metadata-promotion and transcript-publication ordering is attachment-delivery sensitive, even though focused proof covers its known races.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured PR body reports a real image-create run through the Gateway media owner with 14 host SQL events before and zero after while retaining the file and metadata, plus an isolated WebSocket publication run; worker fault tests supplement those observations. Pinned source comparison shows no stored-row contract change, so no data-model migration is needed.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured PR body reports a real image-create run through the Gateway media owner with 14 host SQL events before and zero after while retaining the file and metadata, plus an isolated WebSocket publication run; worker fault tests supplement those observations. Pinned source comparison shows no stored-row contract change, so no data-model migration is needed.

Evidence

What I checked:

  • Current main still writes synchronously: The current-main store calls the shared-state write transaction directly for managed-image insertion; the latest release has the same path. (src/gateway/managed-image-record-store.ts:84, 4c3181e2386c)
  • Latest-release check: Release v2026.9.6 still contains the synchronous insertion and promotion path, so the central change has not shipped. (src/gateway/managed-image-record-store.ts:84, eb377ac59e6c)
  • Introduced worker boundary: The introduced store reserves per-attachment ordering and dispatches mutations through the shared-state worker; its kernel performs the synchronous transaction inside that worker. (src/gateway/managed-image-record-store.ts:75, 1e5e654070b1)
  • Stored representation unchanged: The image-record fields, selected columns, row serializer, row decoder, and equality function match the pinned base; added types describe worker commands. No schema or migration file is introduced. (src/gateway/managed-image-record-store.kernel.ts:27, 1e5e654070b1)
  • Authority and custody coverage: The new worker-custody cases exercise revoked channel authority, database retirement, file replacement, and lost worker replies through the real state worker and file owner. (src/gateway/managed-image-attachments.worker-custody.test.ts:114, 1e5e654070b1)
  • Reported real-boundary observations: The captured PR body reports an image-create run with 14 main-thread SQL observer events before and zero after, preserving file and row, plus an isolated WebSocket session-publication run. These are contributor-reported observations, not executions performed in this read-only review. (1e5e654070b1)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Mitchell Etzel: 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 (3 earlier review cycles)
  • reviewed September 26, 2026, 10:55 PM ET / September 27, 2026, 02:55 UTC sha unknown :: blocked before merge. :: none
  • reviewed 2026-09-27T03:10:08.522Z sha 765f5bf :: needs maintainer review before merge. :: none
  • reviewed 2026-09-27T04:24:44.160Z sha 2f38b8c4d164b2e66d129bf717d6a449a9973996 :: blocked before merge. :: none

@steipete
steipete force-pushed the codex/managed-media-worker-custody-20260927 branch from 2f38b8c to 1e5e654 Compare September 27, 2026 04:42
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Sep 27, 2026
@steipete
steipete merged commit 40d84ae into main Sep 27, 2026
245 checks passed
@steipete
steipete deleted the codex/managed-media-worker-custody-20260927 branch September 27, 2026 05:08
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
* perf(gateway): move managed media writes off the event loop

* test(media): await worker cleanup in Windows fixture

* refactor(media): keep worker kernel details private

* test(media): use native custody for outgoing chat fixtures
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 merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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