Repository navigation
fix(gateway): keep uncommitted generated media while its session run is live - #119764
Conversation
…is live Generated assistant media is stored with a null messageId and a transient retention class until the assistant turn commits its transcript message and attaches the record. The managed outgoing media GC reaped transient records purely by age, so any turn still in flight past the 15 minute TTL had its media records and files deleted before finalization; the later attach is silently ineffective and the committed message keeps a permanently dead media URL. Cleanup now accepts a hasActiveSessionRun probe and skips the transient age reap while the owning session still has a registered chat run. Both GC entry points, the chat.history sweep and the maintenance sweep, supply the probe from the gateway's registered chat run map, which spans admission through finalization. Sessions without a live run keep the existing TTL behavior.
|
Codex review: needs maintainer review before merge. Reviewed August 5, 2026, 6:32 PM ET / 22:32 UTC. ClawSweeper reviewWhat this changesThe PR keeps uncommitted generated chat media until its registered gateway run finishes, preventing cleanup from leaving finalized messages with dead media URLs. Merge readinessKeep open: this is a focused cleanup-owner repair with no actionable correctness finding. The supplied before/after production-function proof and current source support the bug and repair; await exact-head CI completion. Likely related people: steipete (recent cleanup/lifecycle owner, high confidence) and he-yufeng (adjacent managed-media lifecycle contributor, medium confidence). Priority: P1 Review scores
Verification
How this fits togetherGateway chat replies store generated media as transient SQLite-backed records before attaching them to a finalized transcript message. Gateway history and maintenance cleanup delete expired media, so they must retain a record while the run that can attach it is still registered. flowchart LR
A[Assistant generates media] --> B[Transient media record]
B --> C[Gateway cleanup sweep]
D[Registered chat run] --> E{Run still registered?}
C --> E
E -->|yes| F[Retain for finalization]
E -->|no and expired| G[Delete record and file]
F --> H[Attach to transcript message]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +41, Tests +100. Total +141 across 6 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the retention decision in managed-media cleanup, inject registered-run state only at its two gateway callers, and land after exact-head CI completes. Do we have a high-confidence way to reproduce the issue? Yes. The PR provides a concrete current-main-equivalent reproduction using real managed-media persistence, a registered chat run, history cleanup, and final attachment; the aged live-run record is deleted before the patch and retained after it. Is this the best way to solve the issue? Yes. The cleanup owner owns destructive retention, while the gateway callers inject the one lifecycle fact it cannot own; moving the check to attachment would only detect deletion after the file is already gone. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 6d2ba0d5622f. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
|
Merged via squash.
|
…is live (openclaw#119764) …is live Generated assistant media is stored with a null messageId and a transient retention class until the assistant turn commits its transcript message and attaches the record. The managed outgoing media GC reaped transient records purely by age, so any turn still in flight past the 15 minute TTL had its media records and files deleted before finalization; the later attach is silently ineffective and the committed message keeps a permanently dead media URL. Cleanup now accepts a hasActiveSessionRun probe and skips the transient age reap while the owning session still has a registered chat run. Both GC entry points, the chat.history sweep and the maintenance sweep, supply the probe from the gateway's registered chat run map, which spans admission through finalization. Sessions without a live run keep the existing TTL behavior. Co-authored-by: Tak Hoffman <[email protected]>
Summary
Generated assistant media (images, audio, video) in gateway chat replies is deleted by the managed outgoing media GC while the assistant turn that generated it is still running. The media record is created with
messageId: nullandretentionClass: "transient", and only promoted when finalization commits the transcript message and attaches it. The GC reaps transient records purely by age with a 15 minute TTL, so any turn that stays in flight past the TTL (slow generation, queued turn, delayed provider response, blocked finalization) has its records and files deleted before the attach runs. The attach ignores the persistence result, so finalization succeeds anyway and the committed assistant message keeps a permanently dead media URL. Both GC entry points are automatic: thechat.historyhandler schedules a session-scoped sweep every time a client opens the chat, and the gateway maintenance lifecycle runs an unscoped sweep on a timer.Root cause
src/gateway/managed-image-attachments.ts(main7b8bba26c9539eb631a56ea65c2ff22771b2d0db): the transient branch ofcleanupManagedOutgoingMediaRecordsdecides deletion from age alone.The transient state means "an in-flight turn has not committed its message yet", but the GC has no way to know whether that turn is still alive, so it treats every aged transient record as an orphan.
attachManagedOutgoingMediaToMessagethen discards the boolean fromattachManagedImageRecordToMessage, so the reaped record surfaces as a dead URL instead of a failure.Fix
cleanupManagedOutgoingMediaRecordsaccepts ahasActiveSessionRunprobe and skips the transient-age reap while the record's session still has a registered chat run.Both GC entry points supply the probe from the gateway's registered chat-run map via a new
hasRegisteredChatRunForSessionKeyhelper insrc/gateway/server-methods/session-active-runs.ts:scheduleChatHistoryManagedMediaCleanup(chat.history sweep) and the maintenance sweep default insrc/gateway/server-maintenance.ts. The helper deliberately counts every registeredchatAbortControllersentry rather than the visible-run projection:clearTrackedActiveRunflipsprojectSessionActiveto false as soon as the agent loop emits its terminal event, which is exactly when post-dispatch finalization (transcript append plus attach) is still running, while the registration itself spans admission through the post-dispatchfinally. Forglobalrecords it matches per agent and retains conservatively when either side has no explicit agent id.Why this is the right boundary
The retention rule ("a transient record may only be reaped once no live turn can still attach it") belongs to the cleanup owner, so it is expressed inside
cleanupManagedOutgoingMediaRecords; the run registry is per-server request state the cleanup module cannot reach, so callers inject the one missing fact as a probe. Both production callers are wired in this change, so no GC path can reintroduce the reap. The short create-to-attach race was already safe (claimManagedImageRecordCleanupIfCurrentrefuses to claim a row a concurrent attach updated); this change closes the long window the claim guard cannot see. Sessions without a live run keep the exact TTL behavior, including crashed-run orphans, which reap on the next sweep after the stale run entry expires out of the map (the maintenance loop already prunes expired entries). The aged-orphan file sweep is intentionally untouched: files gain a record in the same tick they are saved, so a live turn's files are never recordless long enough to age out. Sibling surfaces: open PR #117266 (mine) protects committed records referenced by inactive transcript branches in the same file but does not touch the transient branch or these lines; the generic attachment sweep enteringmedia/outgoingwas already fixed by #119127. Making the attach result fail finalization instead was rejected: at attach time the file is already gone, so the only correct fix is to not delete it while the turn is live.Two accepted tradeoffs, named so they are decisions rather than oversights. First, transient records that will never be attached (finalization paths that build a second content set or fail before attach) are now retained for as long as their session stays continuously busy across sweeps; cleanup is deferred to the first sweep that finds the session idle, not lost, so a busy session accumulates only until its next quiet moment. Second, the probe compares the record's stored session key against registered run keys verbatim; a run re-registered under a different key form after a gateway restart is not matched and the record falls back to the pre-fix TTL, which is correct there because the interrupted finalization can no longer attach it.
Verification
node scripts/run-vitest.mjs src/gateway/server-maintenance.test.ts src/gateway/server-methods/session-active-runs.test.ts src/gateway/managed-image-attachments.test.ts src/gateway/managed-image-record-store.test.ts- 4 files, 137 tests passed.retains an aged transient record while its session still has an active run(also proves the later attach promotes the record) andreaps an aged transient record once its session has no active runinsrc/gateway/managed-image-attachments.test.ts; registered-run matching insrc/gateway/server-methods/session-active-runs.test.ts. With the four production files reverted to pristine main the new tests fail (aged transient record reaped, helper export missing); with the patch they pass.node scripts/run-oxlint.mjs <changed files>clean;oxfmt --check <changed files>clean.node scripts/run-tsgo.mjs -p tsconfig.core.jsonand-p test/tsconfig/tsconfig.core.test.jsonclean.Real behavior proof
Behavior addressed: generated assistant media is deleted by the automatic managed-media GC while the assistant turn is still running, so the finalized message keeps a permanently dead media URL.
Real environment tested: the real gateway managed-media pipeline on pristine main 7b8bba2 (all four production files byte-identical through the rebased base 6d2ba0d) and on the patched tree with identical inputs, in an isolated OPENCLAW_STATE_DIR: real createManagedOutgoingMediaBlocks persistence (shared SQLite state DB plus on-disk media store), a real chat run registered through registerChatAbortController, the real chat.history GC entry scheduleChatHistoryManagedMediaCleanup, and the real attachManagedOutgoingMediaToMessage finalization call. Nothing was stubbed; record creation ran under a clock shifted back 16 minutes so the records aged past the 15 minute transient TTL, exactly the state a 16 minute old generation leaves behind.
Exact steps or command run after this patch:
node --import tsx managed-media-live-run-proof.mjs(script drives the production functions above for two sessions: one with a registered live run, one idle)Evidence after fix:
Observed result after fix: with a registered run the aged record and its file survive the sweep and the finalization attach promotes the record to history with the committed message id, while the idle session's aged transient record is still reaped on the unchanged TTL.
What was not tested: no end-to-end gateway server with a real provider holding a turn open past 15 minutes of wall clock; the maintenance-sweep wiring was exercised through the same probe rather than a live hourly timer.