Skip to content

fix(gateway): keep uncommitted generated media while its session run is live - #119764

Merged
Takhoffman merged 1 commit into
openclaw:mainfrom
yetval:fix/managed-media-transient-ttl-active-run
Aug 6, 2026
Merged

Takhoffman merged 1 commit into
openclaw:mainfrom
yetval:fix/managed-media-transient-ttl-active-run

Conversation

@yetval

@yetval yetval commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

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: null and retentionClass: "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: the chat.history handler 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 (main 7b8bba26c9539eb631a56ea65c2ff22771b2d0db): the transient branch of cleanupManagedOutgoingMediaRecords decides deletion from age alone.

} else if (!entry.cleanupPending) {
  const createdAtMs = Date.parse(record.createdAt);
  shouldDelete = Number.isFinite(createdAtMs) && nowMs - createdAtMs >= transientMaxAgeMs;
}

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. attachManagedOutgoingMediaToMessage then discards the boolean from attachManagedImageRecordToMessage, so the reaped record surfaces as a dead URL instead of a failure.

Fix

cleanupManagedOutgoingMediaRecords accepts a hasActiveSessionRun probe and skips the transient-age reap while the record's session still has a registered chat run.

} else if (!entry.cleanupPending) {
  const createdAtMs = Date.parse(record.createdAt);
  shouldDelete =
    Number.isFinite(createdAtMs) &&
    nowMs - createdAtMs >= transientMaxAgeMs &&
    params?.hasActiveSessionRun?.(record.sessionKey, record.agentId?.trim() || undefined) !==
      true;
}

Both GC entry points supply the probe from the gateway's registered chat-run map via a new hasRegisteredChatRunForSessionKey helper in src/gateway/server-methods/session-active-runs.ts: scheduleChatHistoryManagedMediaCleanup (chat.history sweep) and the maintenance sweep default in src/gateway/server-maintenance.ts. The helper deliberately counts every registered chatAbortControllers entry rather than the visible-run projection: clearTrackedActiveRun flips projectSessionActive to 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-dispatch finally. For global records 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 (claimManagedImageRecordCleanupIfCurrent refuses 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 entering media/outgoing was 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.
  • New regression tests: retains an aged transient record while its session still has an active run (also proves the later attach promotes the record) and reaps an aged transient record once its session has no active run in src/gateway/managed-image-attachments.test.ts; registered-run matching in src/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.json and -p test/tsconfig/tsconfig.core.test.json clean.

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:

# BEFORE (pristine main 7b8bba26c95)
{
  "liveRunSession": {
    "blockUrl": "/api/chat/media/outgoing/agent%3Amain%3Aproof-live-run/520bb03a-079b-421f-9ecd-ef81cc994083/full",
    "recordSurvivedGcDuringActiveRun": false,
    "fileSurvivedGcDuringActiveRun": false,
    "finalizeAttachEffective": false,
    "retentionClassAfterFinalize": null
  },
  "idleSession": {
    "agedTransientReapedWithNoRun": true
  }
}
# AFTER (this patch, identical inputs)
{
  "liveRunSession": {
    "blockUrl": "/api/chat/media/outgoing/agent%3Amain%3Aproof-live-run/3ad892bf-07c3-4b3f-aebe-ce5132973d2e/full",
    "recordSurvivedGcDuringActiveRun": true,
    "fileSurvivedGcDuringActiveRun": true,
    "finalizeAttachEffective": true,
    "retentionClassAfterFinalize": "history"
  },
  "idleSession": {
    "agedTransientReapedWithNoRun": true
  }
}

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.

…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.
@yetval
yetval marked this pull request as ready for review August 5, 2026 22:26
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Aug 5, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P1 High-priority user-facing bug, regression, or broken workflow. labels Aug 5, 2026
@clawsweeper

clawsweeper Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 5, 2026, 6:32 PM ET / 22:32 UTC.

ClawSweeper review

What this changes

The PR keeps uncommitted generated chat media until its registered gateway run finishes, preventing cleanup from leaving finalized messages with dead media URLs.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep 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
Reviewed head: 150b2851bc3c000084d105172c64b68373890a6d

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A narrowly scoped owner-boundary fix with direct source tracing, focused regression coverage, and convincing real-pipeline before/after evidence.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body shows before/after terminal output from real SQLite-backed managed media, on-disk files, registered run state, history cleanup, and final attachment; the idle-control record still expires.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body shows before/after terminal output from real SQLite-backed managed media, on-disk files, registered run state, history cleanup, and final attachment; the idle-control record still expires.
Evidence reviewed 7 items Current-main failure path: Current main reaps a transient managed-media record solely after its 15-minute age threshold, while creation precedes transcript attachment and the later wrapper does not surface a failed attachment.
Cleanup-owner repair: The patch keeps the age-based transient deletion rule in the cleanup owner and adds only the injected fact needed to defer deletion when the owning run remains registered.
Both cleanup entry points use the same fact: The chat-history sweep and hourly maintenance default each supply the registered-run predicate; source search found no other production callers of the managed outgoing cleanup function.
Findings None None.
Security None None.

How this fits together

Gateway 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]
Loading

Before merge

  • Resolve merge risk (P1) - Exact-head CI was still in progress in the supplied snapshot, so normal merge gating remains outstanding.
  • Complete next step (P2) - No repair lane is needed because source review found no discrete defect; await the normal exact-head CI gate.
Agent review details

Security

None.

PR surface

Source +41, Tests +100. Total +141 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 44 3 +41
Tests 2 102 2 +100
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 146 5 +141

Review metrics

Metric Value Why it matters
Production versus test delta production +44/-3; tests +102/-2 The production growth is limited to the missing run-liveness ownership boundary and both production callers; regression coverage is substantially larger.

Stored data model

Persistent data-model change detected: serialized state: src/gateway/server-methods/session-active-runs.test.ts, serialized state: src/gateway/server-methods/session-active-runs.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    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.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best 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.

Labels

Label changes:

  • add P1: A long-running gateway turn can finalize a message whose generated media was silently deleted, leaving users with a permanently dead URL.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body shows before/after terminal output from real SQLite-backed managed media, on-disk files, registered run state, history cleanup, and final attachment; the idle-control record still expires.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body shows before/after terminal output from real SQLite-backed managed media, on-disk files, registered run state, history cleanup, and final attachment; the idle-control record still expires.

Label justifications:

  • P1: A long-running gateway turn can finalize a message whose generated media was silently deleted, leaving users with a permanently dead URL.
  • 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 (terminal): The PR body shows before/after terminal output from real SQLite-backed managed media, on-disk files, registered run state, history cleanup, and final attachment; the idle-control record still expires.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body shows before/after terminal output from real SQLite-backed managed media, on-disk files, registered run state, history cleanup, and final attachment; the idle-control record still expires.

Evidence

What I checked:

  • Current-main failure path: Current main reaps a transient managed-media record solely after its 15-minute age threshold, while creation precedes transcript attachment and the later wrapper does not surface a failed attachment. (src/gateway/managed-image-attachments.ts:675, 6d2ba0d5622f)
  • Cleanup-owner repair: The patch keeps the age-based transient deletion rule in the cleanup owner and adds only the injected fact needed to defer deletion when the owning run remains registered. (src/gateway/managed-image-attachments.ts:676, 150b2851bc3c)
  • Both cleanup entry points use the same fact: The chat-history sweep and hourly maintenance default each supply the registered-run predicate; source search found no other production callers of the managed outgoing cleanup function. (src/gateway/server-maintenance.ts:331, 150b2851bc3c)
  • Registration spans finalization: The helper intentionally counts registered entries even after visible activity is cleared, and the chat-send lifecycle retains its abort registration until post-dispatch finalization and cleanup complete. (src/gateway/server-methods/session-active-runs.ts:64, 150b2851bc3c)
  • Regression coverage and real behavior proof: The added tests retain an aged live-run record through cleanup and promote it on attachment, while still reaping an idle record; the PR body reports matching before/after output using real SQLite storage, on-disk media, history cleanup, registration, and attachment. (src/gateway/managed-image-attachments.test.ts:1933, 150b2851bc3c)
  • Current area provenance: Blame attributes the current cleanup and caller-era code to this current-checkout commit, making its author the strongest available recent routing owner; partial history does not establish an introducing PR. (src/gateway/managed-image-attachments.ts:675, 6269be70c55f)

Likely related people:

  • steipete: Current-checkout blame attributes the central cleanup-era source to this author; the lifecycle boundary is also in the same recent gateway area. (role: recent managed-media cleanup and gateway-lifecycle contributor; confidence: high; commits: 6269be70c55f; files: src/gateway/managed-image-attachments.ts, src/gateway/server-maintenance.ts, src/gateway/chat-abort.ts)
  • he-yufeng: Authored the merged managed-outgoing cleanup lifecycle work in fix(media): keep the ttl sweep out of the managed outgoing tree #119127, which is complementary rather than a replacement. (role: adjacent managed-media lifecycle contributor; confidence: medium; commits: cd709e4a3a18; files: src/gateway/managed-image-attachments.ts, src/gateway/server-maintenance.ts)

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.

@Takhoffman Takhoffman self-assigned this Aug 6, 2026
@Takhoffman
Takhoffman merged commit b3fbe6f into openclaw:main Aug 6, 2026
186 of 189 checks passed
@Takhoffman

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 6, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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.

2 participants