Skip to content

fix(media): avoid false failures for queued generation results - #154064

Closed
Leon-SK668 wants to merge 4 commits into
openclaw:mainfrom
Leon-SK668:leon/fix-media-pending-wait-20260921
Closed

Leon-SK668 wants to merge 4 commits into
openclaw:mainfrom
Leon-SK668:leon/fix-media-pending-wait-20260921

Conversation

@Leon-SK668

@Leon-SK668 Leon-SK668 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #151964.

What Problem This Solves

Generated media can be marked blocked after 120 seconds even when the durable session queue already owns its completion. In an isolated cron turn, retaining the requesting turn's wait can also retain the exact session lane needed by that completion: the image has finished, but the completion cannot run after the requester's model reply is released.

User Impact

Confirmed queue admission now keeps the native operation running until real delivery settles and releases the cron completion wait. It does not report queued work as delivered. Genuine permanent failure, unconfirmed handoff deadlines and existing retention handling remain intact. The shared path covers image, music and video tasks, successful generation and provider-error completion.

Known inherited limitation: a delayed outgoing-media URL may return HTTP404 after exact cron alias cleanup. The October 8 exact-head probe records this failure. The October 14 replay below passes all five checks, including immediate byte-verified HTTP download; this does not establish retained URL lifetime or real channel transport.

Why This Change Was Made

Keep durable admission and final settlement with their canonical owners. wakeMediaGenerationTaskCompletion distinguishes session_queued from an unconfirmed pending handoff. The existing native operation carries one internal completionDelivery: "queued" fact. Its retry loop applies the 120-second budget only before confirmed custody and continues observing the existing idempotent queue receipt afterward. Cron task waiting stops holding its lane only after this explicit fact; delivery or permanent failure still owns the operation's terminal outcome.

The repair replaces obsolete branch logic with current-main owners rather than recreating the old task APIs or adding a second queue. No new public task status, configuration, environment variable, protocol, SDK, database schema, lockfile or generated assets.

Owner map: native media tool → media-generate-background-completion.ts → existing durable announce/session queue → Gateway continuation runner → committed transcript. Cron admission/wait lives in attempt-async-tasks.ts; stream preparation and settlement share that wait. Existing scheduler scope, admission fences, abort/deadline rules, queue idempotency, requester identity and cleanup owners remain intact.

Existing-solutions preflight: another image/provider plugin cannot change OpenClaw's native operation and requesting-lane ownership. The maintainer's real Gateway observation in the September 25 review identifies the unresolved continuation path; the actual compiled Gateway path below exercises that path without replacing its delivery adapter.

Seven-file diff against canonical main 278d66f2459a088cd6c770a92fe30a2fa48cc226: four production files +32/-11, net +21; three existing tests +85/-2, net +83. The small production increase carries explicit custody across the existing operation and cron owners, avoiding false terminal outcomes and a circular wait. The seventh file updates the Gateway sibling expectation after successful queue custody; its actual SQLite, requester binding and lifecycle-fence assertions remain intact.

Evidence

October 14 bounded replay — same exact head, five checks passed

The unchanged held-requester harness (SHA-256 0b70d3636f3895ffae06039d70dc0f55ac3c1667e61c4808e20a0d9721efe387) ran against the existing compiled head 0e00ee3d838952d0e20bd165a0fd29b9d40003f3, tree 7a5fad5bcb88675f47fcf2e7b3e54408543ef63f, on Node 24.16.0. Source was clean before and after. The executable reports OpenClaw 2026.9.8 with that full build commit; this is not an October 14 main build.

The real Gateway held the original post-image requester for 125,323ms. Release started the completion model request 2,908ms later. Authenticated history returned exactly one assistant image attachment; the native queue had one completed row with retry count zero; the native operation succeeded; the original cron run finished ok / succeeded. The outgoing HTTP URL returned 200, 68 bytes, SHA-256 7091aaabb3c9d27a4cd4ca8254fe60af3b0a14618e223c13f7d6785f6fb8565a, equal to the generated file. All five independently recorded acceptance flags are true. The measured admitted-to-final scenario took 141.914 seconds, excluding Gateway startup and cleanup.

{
  "sourceSha": "0e00ee3d838952d0e20bd165a0fd29b9d40003f3",
  "heldMs": 125323,
  "releaseToCompletionModelMs": 2908,
  "imageProviderCalls": 1,
  "assistantAttachmentCount": 1,
  "queue": [{"status": "completed", "retryCount": 0}],
  "operationStatus": "succeeded",
  "attachmentReadback": {
    "status": 200,
    "bytes": 68,
    "sha256": "7091aaabb3c9d27a4cd4ca8254fe60af3b0a14618e223c13f7d6785f6fb8565a"
  },
  "acceptance": {
    "imageProviderCalls": true,
    "oneAssistantAttachment": true,
    "attachmentBytesMatch": true,
    "queueCompleted": true,
    "operationSucceeded": true
  }
}

Raw receipt SHA-256: 07f88d510a2a7d3b43282e6904a97409717434b5cd3a030aed696d0055e567cc. This receipt summary deliberately excludes private paths and synthetic Gateway authentication material. Only free loopback model/image HTTP peers were used; no existing service, account or channel was touched. The isolated Gateway stopped normally. The command is the same held-requester command preserved below.

This replay adds successful immediate HTTP readback to the existing queue/continuation evidence. The earlier delayed-download 404 results remain valid and retained below. No alias-retention or attachment-authorization change, new source commit, fresh CI success, scanner release, external-provider authentication or cross-channel delivery is claimed.

GitHub source-projection repair — October 13, 2026

Head unchanged: 0e00ee3d838952d0e20bd165a0fd29b9d40003f3. GitHub's PR metadata had retained the September base, reporting zero changed files while returning 3,000 unrelated files and 8,821 commits. A live current-main compare independently showed the intended seven files and four ahead commits. Re-saving the existing base: main restored the PR projection to 7 files and MERGEABLE, without retargeting the PR, modifying source or rewriting its history.

This addresses the changed-file inconsistency reported by the security-review job. Its earlier failed run is not now claimed green. The ClawSweeper complete-source hold also remains a scanner hold until the authorized review path releases it; source metadata repair is not a fresh verdict. The pr-fail-fast/aggregate run still requires an upstream Actions rerun. Leon has upstream READ access and cannot perform that rerun.

The existing candidate/base runtime receipts below keep their original hashes, observations and limits, including the media-URL 404 on both sides. No new live replay or product-code change is claimed by this maintenance.

Current exact-head acceptance and limits

Current contributor head is 0e00ee3d838952d0e20bd165a0fd29b9d40003f3, tree 7a5fad5bcb88675f47fcf2e7b3e54408543ef63f, parent 6b88940dfd53dec5f0e8505da673292334e77088. Both author and committer use Leon's company identity. All four production files are byte-identical to that parent; the only follow-up change is the existing Gateway test's pending→queued expectation.

The actual current commit was rebuilt with the same canonical private QA runtime command, exit0, 166.44 seconds wall. CLI/version, build-info and native stamps identify the current head with clean inputs. The unchanged harness below was then executed against this actual built head, 172.74 seconds wall:

MEDIA_PROOF_CHECKOUT=./154064-custody-fix node --import ./validation-main/scripts/tsx.mjs 154064-gateway-spike.mts --held

It held the original model requester 125,341ms. At120seconds the native operation remained running with queued custody. On release, the real completion model request started 2,656ms later; exactly one image provider call, one assistant attachment and one completed SQLite queue row/retry0 were observed. Native operation succeeded and original cron completed ok. Committed false failure messages, blocked operations, duplicate image calls, duplicate attachments and failed queue rows were all0. This is acceptance-green for the stated custody/continuation/false-failure repair, paired with the identical frozen-main RED below.

The independent download control still returned HTTP404/9bytes, matching frozen main. Current full probe is 4/5, PARTIAL, not all-five PASS. The unchanged all-five assertion fails; no image-download, permanent-URL, external-channel or restart claim is made. The successful harness exit is separate from this known failing control.

Current raw receipt SHA-256: 43542fc2b9f01727fd3045c77a6ed302da59f3aa10298f17d72dd3af69d52d86; sanitized summary: 9128b424109dcf3efed18a56e3a01dd301acc956d4e288d2ce311f4bbe1f899d; evidence manifest digest: 40cafad6e898f5f5494736ec06c45b2b651a075c2d9501b4d976dd6b3ac1f01a. Source/build head, source tree and tracked cleanliness match before and after the real scenario. The current summary below provides the public readback; the complete unchanged harness and prior paired evidence remain further below.

Current-head sanitized real Gateway readback
{
  "sourceSha": "0e00ee3d838952d0e20bd165a0fd29b9d40003f3",
  "sourceTree": "7a5fad5bcb88675f47fcf2e7b3e54408543ef63f",
  "sourceParents": ["6b88940dfd53dec5f0e8505da673292334e77088"],
  "buildInfo": {
    "version": "2026.9.8",
    "commit": "0e00ee3d838952d0e20bd165a0fd29b9d40003f3",
    "builtAt": "2026-10-08T11:09:41.490Z",
    "buildId": "2026.9.8-0e00ee3d8389-2026-10-08T11-09-41.490Z"
  },
  "nodeVersion": "v24.16.0",
  "sourceClean": true,
  "buildExitCode": 0,
  "heldMs": 125341,
  "releaseToCompletionModelMs": 2656,
  "imageProviderCalls": 1,
  "modelRequestsCount": 3,
  "acceptance": {
    "imageProviderCalls": true,
    "oneAssistantAttachment": true,
    "attachmentBytesMatch": false,
    "queueCompleted": true,
    "operationSucceeded": true
  },
  "repairedBehaviorPassed": true,
  "queue": [{"status": "completed", "retryCount": 0}],
  "operation": {
    "requesterSessionKey": "agent:main:cron:10cae3c9-c877-4864-a64a-df497b588f54:run:f522f0c1-9edc-4288-8752-fa71d6fbec3a",
    "status": "succeeded",
    "completionDelivery": "queued"
  },
  "assistantAttachmentCount": 1,
  "assistantText": ["Your image is ready."],
  "attachmentReadback": [{"status": 404, "bytes": 9}],
  "originalCronTerminal": [{"status": "ok", "completionStatus": "succeeded"}],
  "holdState": [
    {"label": "held-30000", "queueStatus": "pending", "operationStatus": "running", "completionDelivery": "queued"},
    {"label": "held-60000", "queueStatus": "pending", "operationStatus": "running", "completionDelivery": "queued"},
    {"label": "held-90000", "queueStatus": "pending", "operationStatus": "running", "completionDelivery": "queued"},
    {"label": "held-120000", "queueStatus": "pending", "operationStatus": "running", "completionDelivery": "queued"}
  ],
  "negativeEvidence": {
    "falseFailureTexts": [],
    "duplicateProviderCalls": false,
    "duplicateAttachments": false,
    "queueFailedRows": 0,
    "queueRetries": [0],
    "blockedOperations": 0,
    "harnessError": null,
    "cleanupError": null
  }
}

This compact readback projects the fields from the hashed full sanitized summary; it does not claim to have that summary's byte hash. No runtime functions were replaced by the inspector or the driver.

Parent-head paired acceptance retained for provenance

  • Candidate head: 6b88940dfd53dec5f0e8505da673292334e77088; reviewed tree 766116f1e658af9de090e4b186d0cc306810675f. Normal merge parents are canonical main 278d66f2459a088cd6c770a92fe30a2fa48cc226 and the previous contributor head 2d1ec3dd57dbea1f7f928d1bae44df217672b40a.
  • Exact-head guarded private QA runtime build passed, 135.1 seconds, Node24.16.0. Actual CLI version/build-info and both native build stamps identify this head, with clean inputs. This runtime-only build does not establish release-package or full declaration/type qualification.
  • Harness: external 154064-gateway-spike.mts, SHA-256 0b70d3636f3895ffae06039d70dc0f55ac3c1667e61c4808e20a0d9721efe387. It launches the selected compiled dist/index.js CLI with private state and ports, authenticates Gateway RPC, submits a real isolated cron turn, and invokes native image generation. Only the model/image HTTP peers are synthetic loopback services.
  • Authoritative readback: actual provider request counts, authenticated chat.history, independently opened read-only SQLite queue records and generated file hashes. Read-only inspector property descriptors corroborate native operation state; no owner function is replaced or invoked by that observer.
  • Final candidate held the original post-image model request for 125,388 ms. At 120 seconds, one durable queue row remained pending/retry0 and the operation remained running with queued custody. Release started the actual completion model request 2,773 ms later. The original turn committed NO_REPLY; the completion committed Your image is ready. and exactly one image attachment. One queue row completed/retry0; native operation succeeded; original cron terminal status was ok. False failure messages, duplicate image calls, duplicate attachments and blocked operations: 0.
  • The saved generated PNG is68bytes, SHA-256 7091aaabb3c9d27a4cd4ca8254fe60af3b0a14618e223c13f7d6785f6fb8565a. Its delayed outgoing Gateway URL returned 404,9bytes, so the probe's attachmentBytesMatch field is false. Four repaired-behavior flags are true; the independent all-five assertion exits1. Harness exit0 is not described as all-five acceptance-green.
  • Candidate raw receipt SHA-256 8ce1ccdae91493e3f9d4539eb900d5f48d41cfde4daf76042d4e5722c510968f; sanitized summary ea8ccbb27908fca797118bd946aa44f245b1b2d8cd9a09cfb8e5bcabef92d63f; evidence manifest digest f382ea669b8aa506f4afa8cc7069614cf1cbb43720c1b39759d53d0b2aeb85ad. Source head/tree and tracked cleanliness match before and after the real run; owned processes stop normally.

The known download limitation follows unchanged src/cron/run-continuation-cleanup.ts removing the idle exact-run alias while stable cron history retains the transcript, and unchanged src/gateway/managed-image-attachments.ts requiring transcript visibility through the attachment record's exact session key. It also reproduces on frozen main. This PR does not change attachment visibility/authorization to hide that failure.

The same final harness ran frozen main 1eb5970ff9724b88cd058bc347dee4f68dbc9612, tree 061e51c173a13ab05b89a5b108f31b888f02bf85, with exact main CLI/build provenance and clean source. The requester was held125,365ms; releasing it started the completion2,796ms later. The queue completed/retry0 and one image reached the transcript, but the operation had already acquired terminalOutcome blocked at the120second handoff deadline and an actual false retained-media failure was appended to the committed transcript. Targeted RED→GREEN: blocked operations1→0; false failure messages1→0; actual committed image count remains1. Both versions' delayed attachment URL returns404; that independent failure is not cured or counted as green. Baseline raw receipt SHA-256 4a74d97cf2908ff06268ee6716660add1475798aa50146a35c4965274a991e45, sanitized summary ed138a7e9536e7c570d04c75e3e9bf6c570e9da3cee2d4ebdbcba8802b715ad2, manifest digest f509a94ec38c131c977a79abfd4c6a8b26100f6e0a6cd4f5508399e83a2f109a.

Actual candidate proof command, from the external campaign fixture directory:

MEDIA_PROOF_CHECKOUT=./154064-custody-fix node --import ./validation-main/scripts/tsx.mjs 154064-gateway-spike.mts --held

validation-main supplies unchanged fixture helpers only. The selected checkout supplies the executable, config/runtime loading, compiled plugins, Gateway owners and native queue. No test minimal-Gateway/provider/cron bypass is enabled. Baseline selects ./154064-main-proof with the same script and arguments.

Focused tests and review

OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs src/gateway/server-restart-sentinel.media-binding.test.ts src/agents/tools/media-generate-background-shared.test.ts src/agents/embedded-agent-runner/run/attempt.async-tasks.test.ts

48/48 passed, three explicit files on the final current source, measured294.92seconds wall. Gateway10, cron9 and background media29 tests passed. This includes95.151seconds of cold Gateway worker compilation; tests are reported with total wall cost rather than describing the cold run as cheap. Tests cover all three cron media siblings, queued success and provider-error completion, existing unconfirmed deadlines, abort and permanent refusal behavior, and actual requester-binding/lifecycle/store/generation fences. Read-only scoped formatting and diff checks passed. Complete production candidate independent Codex autoreview returned findings=[], confidence0.91 on the parent; fresh independent review of the one-line Gateway change and complete seven-file context returned findings=[], confidence0.98. No production file changed between the reviews. The earlier38-test run (138.46seconds) remains parent evidence and is not renamed as this48-test run.

Previous-head upstream CI37766380938 identified the queued-versus-pending assertion now fixed here. Its unrelated main lint failure comes from main commit d8c8047cab6357591155e662fcaed3c66b896742 using forbidden Array.sort in an unmodified session-model-context test; its PR monitor also checked out the old creation base and could not find scripts/ci-pr-fail-fast.mjs. New-head required CI is evaluated separately; no unobserved result is prefilled. ClawSweeper generation37766652479 stopped before review with agent_input_scan/incomplete_source (workflow exit78), and its public acknowledgement requests maintainer investigation rather than contributor changes. That generation is not a fresh code/proof verdict.

  • Not tested: external channel delivery, real provider account/audio/video transport, retained-alias attachment URL lifetime, Gateway restart/replacement acceptance, full release-package/declaration/cross-platform checks. The image-download check above remains FAIL, distinct from the queue/cron repair evidence.

AI disclosure / sanitized agent transcript

User: “那就把这些问题都修复好吧”

AI-assisted repair: read current owners and siblings, reproduced the held-requester failure, implemented bounded custody propagation, ran focused tests and independent review, built the actual final commit and preserved both successful queue evidence and inherited download failures. No production Mac service, real channel/user message, paid provider or secret was used. Publication uses Leon's existing branch without rewriting history.

Sanitized final candidate outside readback (four repaired-behavior checks pass; download check fails)
{
  "sourceSha": "6b88940dfd53dec5f0e8505da673292334e77088",
  "sourceTree": "766116f1e658af9de090e4b186d0cc306810675f",
  "sourceParents": [
    "278d66f2459a088cd6c770a92fe30a2fa48cc226",
    "2d1ec3dd57dbea1f7f928d1bae44df217672b40a"
  ],
  "buildInfo": {
    "version": "2026.9.8",
    "commit": "6b88940dfd53dec5f0e8505da673292334e77088",
    "builtAt": "2026-10-08T10:24:40.064Z",
    "buildId": "2026.9.8-6b88940dfd53-2026-10-08T10-24-40.064Z"
  },
  "buildInfoSha256": "ebea04434710dac4f4991ad2b383ff11b1ee2795cbdabe5289d4429cb2359648",
  "harnessSha256": "0b70d3636f3895ffae06039d70dc0f55ac3c1667e61c4808e20a0d9721efe387",
  "buildCommand": "/usr/bin/env PATH=<campaign>/tools/node_modules/.bin:/usr/local/bin:/usr/bin:/bin OPENCLAW_BUILD_PRIVATE_QA=1 <campaign>/tools/node_modules/node/bin/node --import ./scripts/tsx.mjs scripts/build-all.mts qaRuntime",
  "proofCommand": "/usr/bin/env PATH=<campaign>/tools/node_modules/.bin:/usr/local/bin:/usr/bin:/bin MEDIA_PROOF_CHECKOUT=<candidate-checkout> OPENCLAW_NO_RESPAWN=1 <campaign>/tools/node_modules/node/bin/node --import ./validation-main/scripts/tsx.mjs 154064-gateway-spike.mts --held",
  "nodeVersion": "v24.16.0",
  "sourceClean": true,
  "buildExitCode": 0,
  "cliVersion": {
    "code": 0,
    "signal": null,
    "stdout": "OpenClaw 2026.9.8 (6b88940)\n",
    "stderr": "Debugger listening on ws://<loopback>/3e5202ba-08fd-4d8a-b00b-600427e3eb62\nFor help, see: https://nodejs.org/learn/getting-started/debugging\n"
  },
  "heldMs": 125388,
  "releaseToCompletionModelMs": 2773,
  "imageProviderCalls": 1,
  "modelRequestsCount": 3,
  "acceptance": {
    "imageProviderCalls": true,
    "oneAssistantAttachment": true,
    "attachmentBytesMatch": false,
    "queueCompleted": true,
    "operationSucceeded": true
  },
  "repairedBehaviorPassed": true,
  "queue": [
    {
      "status": "completed",
      "entry": {
        "id": "9ef1e2fff3533702223f5deda6f52817ca3680d84788a1fb21ba72ad4c839d54",
        "enqueuedAt": 1791455454837,
        "retryCount": 0,
        "acknowledgedAt": 1791455454837
      }
    }
  ],
  "operation": [
    {
      "runId": "tool:image_generate:4a2bf034-d779-4cb7-adbd-58a6a2ec1ff6",
      "requesterSessionKey": "agent:main:cron:898c9a60-02f8-497a-8659-9ff9678d3eaa:run:1dd4e2f6-ff0e-42c5-92fc-1910a5467998",
      "status": "succeeded",
      "completionDelivery": "queued",
      "terminalSummary": "Generated 1 image with litellm/gpt-image-2."
    }
  ],
  "assistantAttachmentCount": 1,
  "assistantText": [
    "Your image is ready."
  ],
  "attachmentReadback": [
    {
      "url": "/api/chat/media/outgoing/agent%3Amain%3Acron%3A898c9a60-02f8-497a-8659-9ff9678d3eaa%3Arun%3A1dd4e2f6-ff0e-42c5-92fc-1910a5467998/db6722f6-5caa-4625-9681-0bdda012ece3/full",
      "status": 404,
      "bytes": 9,
      "sha256": "907ba78b4545338d3539683e63ecb51cf51c10adc9dabd86e92bd52339f298b9"
    }
  ],
  "originalCronTerminal": [
    {
      "status": "ok",
      "completionStatus": "succeeded",
      "sessionKey": "agent:main:cron:898c9a60-02f8-497a-8659-9ff9678d3eaa:run:1dd4e2f6-ff0e-42c5-92fc-1910a5467998",
      "sessionId": "1dd4e2f6-ff0e-42c5-92fc-1910a5467998",
      "durationMs": 135187
    }
  ],
  "holdState": [
    {
      "label": "held-30000",
      "queueStatuses": [
        "pending"
      ],
      "operationStates": [
        {
          "status": "running",
          "completionDelivery": "queued"
        }
      ]
    },
    {
      "label": "held-60000",
      "queueStatuses": [
        "pending"
      ],
      "operationStates": [
        {
          "status": "running",
          "completionDelivery": "queued"
        }
      ]
    },
    {
      "label": "held-90000",
      "queueStatuses": [
        "pending"
      ],
      "operationStates": [
        {
          "status": "running",
          "completionDelivery": "queued"
        }
      ]
    },
    {
      "label": "held-120000",
      "queueStatuses": [
        "pending"
      ],
      "operationStates": [
        {
          "status": "running",
          "completionDelivery": "queued"
        }
      ]
    }
  ],
  "negativeEvidence": {
    "falseFailureTexts": [],
    "duplicateProviderCalls": false,
    "duplicateAttachments": false,
    "queueFailedRows": 0,
    "queueRetries": [
      0
    ],
    "blockedOperations": 0,
    "harnessError": null,
    "cleanupError": null,
    "inheritedLimitation": "Delayed outgoing media URL reads can return404 after exact cron alias cleanup; also reproduced on frozen main. This PR does not change the alias/artifact owner.",
    "unproven": [
      "External channel transport",
      "Gateway restart/replacement acceptance",
      "Full declaration/package or cross-platform lanes"
    ]
  },
  "mechanism": "Real compiled CLI/Gateway cron admission, native image tool and SQLite queue owner; free loopback model/image peers; read-only inspector property descriptors corroborate operation state."
}
Sanitized same-harness baseline outside readback (false blocked/failure reproduced; download also fails)
{
  "mode": "baseline",
  "sourceSha": "1eb5970ff9724b88cd058bc347dee4f68dbc9612",
  "sourceTree": "061e51c173a13ab05b89a5b108f31b888f02bf85",
  "sourceParents": [
    "b9533fbd155b0d0b455b23825d9e3c32f3a1eb7a"
  ],
  "buildInfo": {
    "version": "2026.9.8",
    "commit": "1eb5970ff9724b88cd058bc347dee4f68dbc9612",
    "builtAt": "2026-10-08T09:29:54.135Z",
    "buildId": "2026.9.8-1eb5970ff972-2026-10-08T09-29-54.135Z"
  },
  "buildInfoSha256": "79b3a4f17adbca58ec876c53f81399bde84d98e80f9fdc17a68ec7ef3d2f0a89",
  "harnessSha256": "0b70d3636f3895ffae06039d70dc0f55ac3c1667e61c4808e20a0d9721efe387",
  "buildCommand": "/usr/bin/env PATH=<campaign>/tools/node_modules/.bin:/usr/local/bin:/usr/bin:/bin OPENCLAW_BUILD_PRIVATE_QA=1 <campaign>/tools/node_modules/node/bin/node --import ./scripts/tsx.mjs scripts/build-all.mts qaRuntime",
  "proofCommand": "/usr/bin/env PATH=<campaign>/tools/node_modules/.bin:/usr/local/bin:/usr/bin:/bin MEDIA_PROOF_CHECKOUT=<candidate-checkout> OPENCLAW_NO_RESPAWN=1 <campaign>/tools/node_modules/node/bin/node --import ./validation-main/scripts/tsx.mjs 154064-gateway-spike.mts --held",
  "nodeVersion": "v24.16.0",
  "sourceClean": true,
  "buildExitCode": 0,
  "cliVersion": {
    "code": 0,
    "signal": null,
    "stdout": "OpenClaw 2026.9.8 (1eb5970)\n",
    "stderr": "Debugger listening on ws://<loopback>/dc39d2af-5df6-4a21-a276-894d705c372a\nFor help, see: https://nodejs.org/learn/getting-started/debugging\n"
  },
  "heldMs": 125365,
  "releaseToCompletionModelMs": 2796,
  "imageProviderCalls": 1,
  "modelRequestsCount": 3,
  "acceptance": {
    "imageProviderCalls": true,
    "oneAssistantAttachment": true,
    "attachmentBytesMatch": false,
    "queueCompleted": true,
    "operationSucceeded": false
  },
  "repairedBehaviorPassed": false,
  "baselineRedReproduced": true,
  "queue": [
    {
      "status": "completed",
      "entry": {
        "id": "dd5b2e7a89edf1c2e79845170963f81f87d30b8515065efb6a08158f72605216",
        "enqueuedAt": 1791455757963,
        "retryCount": 0,
        "acknowledgedAt": 1791455757963
      }
    }
  ],
  "operation": [
    {
      "runId": "tool:image_generate:8a8cb003-7507-4780-8a41-0529c38c7017",
      "requesterSessionKey": "agent:main:cron:55b64efa-d427-4439-af6c-e365d94bbe9e:run:92000d4a-62b2-443d-97ef-8ebab096c238",
      "status": "succeeded",
      "terminalOutcome": "blocked",
      "terminalSummary": "Required completion delivery failed before reaching the requester: media completion did not settle before the handoff deadline.\nRetained generated media:\nAttachments:\n1. type=image name=\"image-1.png\" mimeType=image/png path=\"<isolated-state>/home/.openclaw/media/tool-image-generation/image-1---0e709b1d-7805-4552-90cf-70cbf6a68272.png\""
    }
  ],
  "assistantAttachmentCount": 1,
  "assistantText": [
    "Generated media is ready, but completion delivery was not confirmed. The saved media is retained here.\nimage-1---0e709b1d-7805-4552-90cf-70cbf6a68272.png",
    "Your image is ready."
  ],
  "attachmentReadback": [
    {
      "url": "/api/chat/media/outgoing/agent%3Amain%3Acron%3A55b64efa-d427-4439-af6c-e365d94bbe9e%3Arun%3A92000d4a-62b2-443d-97ef-8ebab096c238/034acf84-68cc-4e24-9ee0-71e4c3ac78fe/full",
      "status": 404,
      "bytes": 9,
      "sha256": "907ba78b4545338d3539683e63ecb51cf51c10adc9dabd86e92bd52339f298b9"
    }
  ],
  "originalCronTerminal": [
    {
      "status": "ok",
      "completionStatus": "succeeded",
      "sessionKey": "agent:main:cron:55b64efa-d427-4439-af6c-e365d94bbe9e:run:92000d4a-62b2-443d-97ef-8ebab096c238",
      "sessionId": "92000d4a-62b2-443d-97ef-8ebab096c238",
      "durationMs": 135650
    }
  ],
  "holdState": [
    {
      "label": "held-30000",
      "queueStatuses": [
        "pending"
      ],
      "operationStates": [
        {
          "status": "running"
        }
      ]
    },
    {
      "label": "held-60000",
      "queueStatuses": [
        "pending"
      ],
      "operationStates": [
        {
          "status": "running"
        }
      ]
    },
    {
      "label": "held-90000",
      "queueStatuses": [
        "pending"
      ],
      "operationStates": [
        {
          "status": "running"
        }
      ]
    },
    {
      "label": "held-120000",
      "queueStatuses": [
        "pending"
      ],
      "operationStates": [
        {
          "status": "running"
        }
      ]
    }
  ],
  "negativeEvidence": {
    "falseFailureTexts": [
      "Generated media is ready, but completion delivery was not confirmed. The saved media is retained here.\nimage-1---0e709b1d-7805-4552-90cf-70cbf6a68272.png"
    ],
    "duplicateProviderCalls": false,
    "duplicateAttachments": false,
    "queueFailedRows": 0,
    "queueRetries": [
      0
    ],
    "blockedOperations": 1,
    "harnessError": null,
    "cleanupError": null,
    "inheritedLimitation": "Delayed outgoing media URL reads can return404 after exact cron alias cleanup; also reproduced on frozen main. This PR does not change the alias/artifact owner.",
    "unproven": [
      "External channel transport",
      "Gateway restart/replacement acceptance",
      "Full declaration/package or cross-platform lanes"
    ]
  },
  "mechanism": "Real compiled CLI/Gateway cron admission, native image tool and SQLite queue owner; free loopback model/image peers; read-only inspector property descriptors corroborate operation state."
}
Runnable external proof harness — no product assets committed

Save as 154064-gateway-spike.mts beside source checkouts validation-main, 154064-main-proof and 154064-custody-fix. The first supplies the unchanged test helpers; the latter two are the actual selected runtimes. Both runtime checkouts must have their own canonical private QA build. Select each through MEDIA_PROOF_CHECKOUT and use the command above. This is the unchanged executed script, SHA-256 0b70d3636f3895ffae06039d70dc0f55ac3c1667e61c4808e20a0d9721efe387.

The harness records its five boolean checks. Validate the stated C1/C2/C3 observations separately; its process exit0 is not an all-five PASS, and this published run explicitly retains the failed download check.

import fs from 'node:fs/promises';
import path from 'node:path';
import http from 'node:http';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { setTimeout as delay } from 'node:timers/promises';
import { DatabaseSync } from 'node:sqlite';
import { createOpenClawTestInstance } from './validation-main/test/helpers/openclaw-test-instance.ts';
import { createGatewayWsClient } from './validation-main/scripts/lib/gateway-ws-client.ts';
import { PROTOCOL_VERSION } from './validation-main/packages/gateway-protocol/src/version.ts';
import { writeOpenAiResponsesSse, writeOpenAiResponsesText } from './validation-main/test/helpers/openai-responses-sse.ts';

const campaign = path.dirname(new URL(import.meta.url).pathname);
const checkout = process.env.MEDIA_PROOF_CHECKOUT ?? path.join(campaign, '154064-main-proof');
const output = await fs.mkdtemp(path.join(campaign, '154064-proof-'));
const localGit = (args: string[]) => execFileSync('git', ['-c', 'protocol.allow=never', '-c', 'protocol.file.allow=never', '-c', 'gc.auto=0', ...args], { cwd: checkout, encoding: 'utf8' }).trim();
const buildInfoBytes = await fs.readFile(path.join(checkout, 'dist', 'build-info.json'));
const receipt: Record<string, unknown> = {
  sourceSha: localGit(['rev-parse', 'HEAD']),
  sourceTree: localGit(['rev-parse', 'HEAD^{tree}']),
  sourceParents: localGit(['show', '-s', '--format=%P', 'HEAD']).split(' '),
  initialSourceStatus: localGit(['status', '--porcelain']),
  harnessSha256: createHash('sha256').update(await fs.readFile(new URL(import.meta.url))).digest('hex'),
  buildInfo: JSON.parse(buildInfoBytes.toString()),
  buildInfoSha256: createHash('sha256').update(buildInfoBytes).digest('hex'),
  nodeVersion: process.version,
  checkout, output, modelRequests: [], snapshots: [],
};
const events: unknown[] = [];
let modelRequests = 0;
let images = 0;
let release: (() => void) | undefined;
const hold = new Promise<void>((resolve) => { release = resolve; });
const held = process.argv.includes('--held');
const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+yf7kAAAAASUVORK5CYII=';
const peer = http.createServer(async (req, res) => {
  try {
    let raw = '';
    for await (const chunk of req) raw += chunk;
    const body = JSON.parse(raw || '{}');
    if (req.url === '/v1/images/generations') {
      images += 1;
      res.writeHead(200, { 'content-type': 'application/json' });
      res.end(JSON.stringify({ data: [{ b64_json: png }] }));
      return;
    }
    if (req.url !== '/v1/responses') {
      res.writeHead(404); res.end('unhandled'); return;
    }
    modelRequests += 1;
    const index = modelRequests;
    const toolNames = (body.tools ?? []).map((tool: { name?: string; type?: string }) => tool.name ?? tool.type);
    (receipt.modelRequests as unknown[]).push({ index, at: Date.now(), input: body.input, toolNames });
    console.log(JSON.stringify({ stage: 'model-request', index, toolNames }));
    await fs.writeFile(path.join(output, 'model-requests.json'), JSON.stringify(receipt.modelRequests, null, 2));
    if (index === 1) {
      const args = JSON.stringify({ prompt: 'A tiny proof image', model: 'litellm/gpt-image-2', count: 1 });
      const item = { type: 'function_call', id: 'fc_image_proof', call_id: 'call_image_proof', name: 'image_generate', arguments: args };
      writeOpenAiResponsesSse(res, [
        { type: 'response.output_item.added', item: { ...item, arguments: '' } },
        { type: 'response.function_call_arguments.delta', delta: args },
        { type: 'response.output_item.done', item },
        { type: 'response.completed', response: { id: 'resp_image_proof', status: 'completed', output: [item], usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } },
      ]);
      return;
    }
    if (index === 2 && held && images > 0) await hold;
    writeOpenAiResponsesText(res, { text: index === 2 ? 'NO_REPLY' : 'Your image is ready.', messageId: `msg_${index}`, responseId: `resp_${index}` });
  } catch (error) {
    res.writeHead(500); res.end(String(error));
  }
});
await new Promise<void>((resolve) => peer.listen(0, '127.0.0.1', resolve));
const peerPort = (peer.address() as { port: number }).port;
const model = { id: 'proof', name: 'proof', api: 'openai-responses', agentRuntime: { id: 'openclaw' }, reasoning: false, input: ['text'], contextWindow: 128000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } };
const instance = await createOpenClawTestInstance({
  name: 'media-requester-settlement', cwd: checkout,
  entrypoint: ['--inspect=127.0.0.1:0', 'dist/index.js'],
  startTimeoutMs: 240000,
  env: { OPENCLAW_TEST_MINIMAL_GATEWAY: undefined, OPENCLAW_SKIP_PROVIDERS: undefined, OPENCLAW_SKIP_CRON: undefined, VITEST: undefined, OPENCLAW_NO_RESPAWN: '1' },
  config: {
    gateway: { controlUi: { enabled: false } },
    agents: { defaults: { model: { primary: 'proof/proof' }, models: { 'proof/proof': { agentRuntime: { id: 'openclaw' } } }, mediaModels: { image: { primary: 'litellm/gpt-image-2' } }, heartbeat: { every: '0m' }, skills: [], skipBootstrap: true, timeoutSeconds: 300 } },
    tools: { profile: 'full', allow: ['image_generate'], codeMode: false, toolSearch: false },
    models: { mode: 'merge', providers: {
      proof: { baseUrl: `http://127.0.0.1:${peerPort}/v1`, apiKey: 'proof-local-free', api: 'openai-responses', agentRuntime: { id: 'openclaw' }, request: { allowPrivateNetwork: true }, models: [model] },
      litellm: { baseUrl: `http://127.0.0.1:${peerPort}/v1`, apiKey: 'proof-local-free', api: 'openai-completions', models: [] },
    } },
    plugins: { allow: ['litellm', 'image-generation-core'], entries: { litellm: { enabled: true } } },
    cron: { enabled: true },
  },
});
let client: ReturnType<typeof createGatewayWsClient> | undefined;
let inspector: WebSocket | undefined;
let inspectorId = 0;
async function inspectorRead(method: string, params: Record<string, unknown>) {
  if (!inspector) {
    const endpoint = /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[^\s]+)/.exec(instance.logs())?.[1];
    if (!endpoint) throw new Error('Owned Gateway inspector endpoint unavailable');
    inspector = new WebSocket(endpoint);
    await new Promise<void>((resolve, reject) => { inspector!.addEventListener('open', () => resolve(), { once: true }); inspector!.addEventListener('error', reject, { once: true }); });
  }
  const id = ++inspectorId;
  const observed = new Promise<Record<string, any>>((resolve, reject) => {
    const timer = setTimeout(() => { inspector!.removeEventListener('message', receive); reject(new Error('Read-only native operation observation timed out')); }, 5000);
    const receive = (event: MessageEvent) => {
      const message = JSON.parse(String(event.data));
      if (message.id !== id) return;
      clearTimeout(timer); inspector!.removeEventListener('message', receive);
      if (message.error || message.result?.exceptionDetails) reject(new Error(JSON.stringify(message)));
      else resolve(message.result);
    };
    inspector!.addEventListener('message', receive);
  });
  inspector.send(JSON.stringify({ id, method, params }));
  return observed;
}
async function observeOperations() {
  // Property inspection observes retained owner state without calling owner functions.
  const root = await inspectorRead('Runtime.evaluate', { expression: 'globalThis', timeout: 5000 });
  const globals = await inspectorRead('Runtime.getProperties', { objectId: root.result.objectId, ownProperties: true });
  const state = globals.result.find((field: { name: string }) => field.name === 'Symbol(openclaw.mediaGenerationOperations)');
  if (!state) return [];
  const fields = await inspectorRead('Runtime.getProperties', { objectId: state.value.objectId, ownProperties: true });
  const operations = fields.result.find((field: { name: string }) => field.name === 'operations');
  const map = await inspectorRead('Runtime.getProperties', { objectId: operations.value.objectId, ownProperties: true });
  const entries = map.internalProperties.find((field: { name: string }) => field.name === '[[Entries]]');
  const list = await inspectorRead('Runtime.getProperties', { objectId: entries.value.objectId, ownProperties: true });
  const observed: Record<string, unknown>[] = [];
  for (const entry of list.result.filter((field: { name: string }) => /^\d+$/.test(field.name))) {
    const pair = await inspectorRead('Runtime.getProperties', { objectId: entry.value.objectId, ownProperties: true });
    const value = pair.result.find((field: { name: string }) => field.name === 'value');
    const operation = await inspectorRead('Runtime.getProperties', { objectId: value.value.objectId, ownProperties: true });
    observed.push(Object.fromEntries(operation.result.map((field: { name: string; value?: { value?: unknown } }) => [field.name, field.value?.value])));
  }
  return observed;
}
async function save(label = 'snapshot', observe = true) {
  const snapshot: Record<string, unknown> = { label, at: Date.now() };
  if (observe) {
  try {
    const db = new DatabaseSync(path.join(instance.stateDir, 'state', 'openclaw.sqlite'), { readOnly: true });
    try {
      receipt.queue = snapshot.queue = db.prepare("SELECT * FROM delivery_queue_entries WHERE queue_name = 'session'").all();
      for (const row of receipt.queue as { entry_json: string }[]) {
        const entry = JSON.parse(row.entry_json);
        if (entry.expectedMediaUrls?.length) {
          receipt.expectedMediaUrls = entry.expectedMediaUrls;
          receipt.expectedMediaHashes = await Promise.all(entry.expectedMediaUrls.map(async (file: string) => ({ file, sha256: createHash('sha256').update(await fs.readFile(file)).digest('hex') })));
        }
      }
    }
    finally { db.close(); }
  } catch (error) { snapshot.queueReadError = String(error); }
  try {
    const db = new DatabaseSync(path.join(instance.stateDir, 'agents', 'main', 'agent', 'openclaw-agent.sqlite'), { readOnly: true });
    try { receipt.sessions = snapshot.sessions = db.prepare('SELECT session_key, current_session_id, entry_json FROM session_nodes').all(); }
    finally { db.close(); }
  } catch (error) { snapshot.sessionsReadError = String(error); }
  try { receipt.operations = snapshot.operations = await observeOperations(); }
  catch (error) { snapshot.operationReadError = String(error); }
  (receipt.snapshots as unknown[]).push(snapshot);
  }
  await fs.writeFile(path.join(output, 'receipt.json'), JSON.stringify({ ...receipt, images, modelRequestsCount: modelRequests, events }, null, 2));
  await fs.writeFile(path.join(output, 'gateway.log'), instance.logs());
}
async function waitUntil(label: string, check: () => boolean, ms = 180000) { const start = Date.now(); while (!check()) { if (Date.now() - start > ms) throw new Error(`timeout ${label}`); await delay(100); } }
try {
  console.log(JSON.stringify({ stage: 'starting', output }));
  receipt.cliVersion = await instance.cli(['--version'], { timeoutMs: 45000 });
  await instance.startGateway();
  console.log(JSON.stringify({ stage: 'gateway-ready', url: instance.url }));
  client = createGatewayWsClient({ url: instance.url, onEvent: (event) => events.push(event) });
  await client.waitOpen();
  async function rpc(method: string, params: unknown) {
    const result = await client!.request(method, params, 45000);
    if (!result.ok) throw new Error(`${method}: ${JSON.stringify(result.error)}`);
    return result.payload as Record<string, unknown>;
  }
  await rpc('connect', { minProtocol: PROTOCOL_VERSION, maxProtocol: PROTOCOL_VERSION, client: { id: 'gateway-client', version: '1.0.0', platform: process.platform, mode: 'backend' }, role: 'operator', scopes: ['operator.admin', 'operator.read', 'operator.write'], caps: [], auth: { token: instance.gatewayToken } });
  const job = await rpc('cron.add', { name: 'media requester settlement proof', enabled: true, schedule: { kind: 'every', everyMs: 3600000 }, sessionTarget: 'isolated', wakeMode: 'next-heartbeat', payload: { kind: 'agentTurn', message: 'Generate a tiny image, then end this turn with NO_REPLY.', timeoutSeconds: 300, lightContext: true, toolsAllow: ['image_generate'] }, delivery: { mode: 'none' } });
  receipt.job = job;
  receipt.run = await rpc('cron.run', { id: job.id, mode: 'force' });
  console.log(JSON.stringify({ stage: 'cron-admitted', jobId: job.id, run: receipt.run }));
  await save('cron-admitted');
  await waitUntil('post-image model request', () => modelRequests >= 2 && images === 1);
  receipt.imageReadyAt = Date.now();
  console.log(JSON.stringify({ stage: 'image-ready-requester-held', held, images }));
  await save('image-ready');
  if (held) {
    const holdStart = Date.now();
    let nextSnapshot = 30000;
    while (Date.now() - holdStart < 125000) { await delay(1000); if (Date.now() - holdStart >= nextSnapshot) { await save(`held-${nextSnapshot}`); console.log(JSON.stringify({ stage: 'holding', elapsedMs: Date.now() - holdStart })); nextSnapshot += 30000; } }
  }
  await save('before-release');
  receipt.releasedAt = Date.now(); release?.();
  await waitUntil('completion model request', () => modelRequests >= 3, 90000);
  await delay(3000);
  receipt.completionObserved = true;
  await save('completion-model-observed');
  const hasSettledCompletion = () => {
    const rows = receipt.queue as Record<string, unknown>[] | undefined;
    const operations = receipt.operations as Record<string, unknown>[] | undefined;
    return Boolean(rows?.length && rows.every((row) => row.status === 'completed' || row.status === 'failed') && operations?.length && operations.every((operation) => operation.status === 'succeeded' || operation.status === 'failed'));
  };
  const settlementDeadline = Date.now() + 45000;
  while (!hasSettledCompletion()) {
    if (Date.now() >= settlementDeadline) throw new Error('timeout queue and media operation terminal readback');
    await delay(250);
    await save('terminal-settlement');
  }
  const operations = receipt.operations as { requesterSessionKey?: string }[] | undefined;
  const sessionKey = operations?.[0]?.requesterSessionKey;
  if (sessionKey) {
    const historyKey = sessionKey.includes(':run:') ? sessionKey.slice(0, sessionKey.lastIndexOf(':run:')) : sessionKey;
    receipt.historySessionKey = historyKey;
    receipt.history = await rpc('chat.history', { sessionKey: historyKey, limit: 100, maxChars: 50000 });
  }
  const queue = receipt.queue as Record<string, unknown>[] | undefined;
  const media = queue?.flatMap((row) => {
    const payload = typeof row.entry_json === 'string' ? JSON.parse(row.entry_json) : {};
    return payload.expectedMediaUrls ?? [];
  }) ?? [];
  if (media.length) receipt.expectedMediaHashes = await Promise.all(media.map(async (file: string) => ({ file, sha256: createHash('sha256').update(await fs.readFile(file)).digest('hex') })));
  const messages = (receipt.history as { messages?: Record<string, unknown>[] } | undefined)?.messages ?? [];
  const attachments = messages.filter((message) => message.role === 'assistant').flatMap((message) => {
    const blocks = Array.isArray(message.displayContent) ? message.displayContent : Array.isArray(message.content) ? message.content : [];
    return blocks.filter((block) => ['image', 'audio', 'video', 'attachment'].includes(block.type));
  });
  receipt.assistantAttachments = attachments;
  receipt.attachmentReadback = await Promise.all(attachments.map(async (attachment: { url?: string }) => {
    const response = await fetch(`${instance.url.replace('ws:', 'http:')}${attachment.url}`, { headers: { authorization: `Bearer ${instance.gatewayToken}` } });
    const bytes = Buffer.from(await response.arrayBuffer());
    const sha256 = createHash('sha256').update(bytes).digest('hex');
    if (response.ok) await fs.writeFile(path.join(output, `attachment-${sha256}.png`), bytes);
    return { url: attachment.url, status: response.status, bytes: bytes.length, sha256 };
  }));
  const readback = receipt.attachmentReadback as { status: number; sha256: string }[];
  const expectedHashes = receipt.expectedMediaHashes as { sha256: string }[] | undefined;
  const terminalOperations = receipt.operations as Record<string, unknown>[] | undefined;
  receipt.acceptance = { imageProviderCalls: images === 1, oneAssistantAttachment: attachments.length === 1, attachmentBytesMatch: readback.length === 1 && readback[0].status === 200 && readback[0].sha256 === expectedHashes?.[0]?.sha256, queueCompleted: queue?.length === 1 && queue[0].status === 'completed', operationSucceeded: terminalOperations?.length === 1 && terminalOperations.every((operation) => operation.status === 'succeeded' && operation.terminalOutcome !== 'blocked') };
  await save('final');
} catch (error) {
  receipt.error = String(error); console.error(String(error)); await save('failure'); process.exitCode = 1;
} finally {
  release?.(); client?.close(); inspector?.close();
  await instance.cleanup().catch(async (error) => { receipt.cleanupError = String(error); await save('cleanup-error', false); });
  await new Promise<void>((resolve) => peer.close(() => resolve()));
  receipt.finalSourceStatus = localGit(['status', '--porcelain']);
  receipt.finalSourceSha = localGit(['rev-parse', 'HEAD']);
  receipt.finalSourceTree = localGit(['rev-parse', 'HEAD^{tree}']);
  await save('cleaned-up', false);
  console.log(JSON.stringify({ stage: 'receipt', output, completionObserved: receipt.completionObserved, error: receipt.error }));
}

@clawsweeper

clawsweeper Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review blocked

Automated review did not run, so no review verdict was produced.

Reason: ClawSweeper could not verify the complete source for this revision.

Automatic review is on hold, including after source changes. Request a fresh re-review after resolving the failure; maintainers can also release the hold through an intentional scanner-policy update.

Next step: No contributor action is requested. Maintainers should inspect the linked workflow run.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL labels Sep 20, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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 20, 2026
@clawsweeper

clawsweeper Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head 2d1ec3dd57dbea1f7f928d1bae44df217672b40a, but the PR head is now 0e00ee3d838952d0e20bd165a0fd29b9d40003f3. Its old verdict and PR readiness labels are no longer current.

Next step
Run or wait for a fresh ClawSweeper review on the current PR head.

Review history (4 earlier review cycles)
  • reviewed 2026-09-20T20:59:09.568Z sha 27b793b :: needs maintainer review before merge. :: none
  • reviewed 2026-09-21T02:41:54.435Z sha 2d1ec3d :: needs maintainer review before merge. :: none
  • reviewed 2026-09-27T10:05:26.655Z sha 2d1ec3d :: needs real behavior proof before merge. :: [P1] Settle queued media after the requesting Gateway turn ends
  • reviewed 2026-10-02T21:32:28.017Z sha 2d1ec3d :: needs real behavior proof before merge. :: none

Integrate the diagnosed upstream CI owner fixes. Preserve terminal task writes across compatible runtime replacement, bound retirement receipt retries, and retain the existing unconfirmed cron handoff contract.
@raffareis

Copy link
Copy Markdown

Confirming this reproduces on a live gateway and flagging a second-order effect the issue text does not cover.

Environment: OpenClaw 2026.9.5, Linux/Docker, WhatsApp (Baileys) channel, claude-cli runtime, requester is a real one-to-one DM. Two image_generate tasks hit the 120 s deadline with the requesting session active and were recorded blocked — and the same generated image was delivered to the user 2–5 times. Full log evidence is in #151964 (comment posted today).

The part that may be worth a test case beyond the cron scenario: the false blocked terminal feeds media retention, and the retained media is then re-handed to the agent as a protected [Generated media delivery retry] follow-up asking it to redeliver — while the durable queue, which already owns that delivery, is draining and replaying the same payload (in our case amplified by No active WhatsApp Web listener retries on the channel side). So the user-visible failure mode on a chat channel is duplicate media, not a wrong ledger entry.

Not a request to change the design — just suggesting that "queued completion never redelivers what the queue already owns" is worth asserting explicitly, since a more obedient completion turn than mine would turn the false failure into yet another copy. Happy to hand over redacted logs and the two task records if they help.

For what it's worth, this is the scenario that motivated the comment: the user complained about the repeated image before anyone looked at the task ledger, so the ledger error was the less visible half of the bug.

@obviyus

obviyus commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

Thanks @Leon-SK668 for preserving queue custody rather than marking pending work successful. I compared this with #152114 and exercised this candidate with current main merged locally, through a real Gateway isolated cron turn and a controllable local image provider (no paid provider).

The task/status part works, but I cannot land this for #151964 yet because the requester-lane delivery case still does not complete:

  • Baseline main e2d2e9fdb86: hold the requester's post-image-tool model response, finish the image, and wait 125 seconds. Status stays Generated media; delivering completion, then becomes terminal blocked with Image generation completion wake failed after successful generation. Releasing the requester produces a lane-wait diagnostic with activeAhead=1 and waitedMs=125896.
  • This candidate (2d1ec3dd57db, with the same main merged locally): after 125 seconds the media task correctly remains running with Media task finished; completion queued, and there is no false failure. Release the requester response: its assistant NO_REPLY with stopReason=stop is committed to the transcript, but no completion model request or image delivery follows during the next 90 seconds. The retained SQLite queue row remains pending, retry_count=0; both the cron run and media task remain running. Gateway shutdown still reports one embedded run. The completion provider was not held in this scenario.
  • Idle-requester control on the candidate: exactly one byte-verified PNG delivered in 1.503 seconds, then the task settles successfully.
  • Focused pending-wake, shared lifecycle, and status suites: 85 tests passed.

This is a real-entry-point gap that the manually composed command-lane test does not cover. The requester must be able to release its lane after its final model response while the queue retains completion custody. I have not merged or closed either PR. Baseline also exposes a later admitted-run failure after releasing the lane; that should not be mistaken for successful image delivery.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed 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 removed the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Oct 2, 2026
@Leon-SK668
Leon-SK668 requested a review from a team as a code owner October 8, 2026 10:52
@openclaw-barnacle openclaw-barnacle Bot removed the agents Agent runtime and tooling label Oct 8, 2026
@clawsweeper clawsweeper Bot removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 9, 2026
@steipete

Copy link
Copy Markdown
Contributor

Thank you for this fix. The same problem (#151964) was resolved on main by #172637 (ff9985c). It keeps queued media completions alive past the 120 s handoff, releases the requesting lane, and gives the model explicit "end this turn" guidance from action=status, with regressions for image, music and video. Since main already carries an equivalent fix, I'm closing this as superseded. Your analysis and repro helped confirm the shape of the fix.

@steipete steipete closed this Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High-priority user-facing bug, regression, or broken workflow. size: XL

Projects

None yet

4 participants