Skip to content

fix(gateway): unify HTTP media stream ownership - #117000

Merged
steipete merged 1 commit into
mainfrom
codex/wave3-gateway-http-stream-lifecycle
Jul 31, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/wave3-gateway-http-stream-lifecycle

Conversation

@steipete

@steipete steipete commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway assistant-media and managed outgoing-media responses duplicated ownership of opened file descriptors. Disconnect cleanup could close the same FileHandle twice, and managed playback transcoding could leave a real descriptor open when transcoding rejected or a replacement descriptor was opened after the response had already ended.

Why This Change Was Made

Descriptor ownership belongs at the existing shared gateway byte-response boundary. This change replaces duplicated route-specific teardown with one bounded lifecycle owner, transfers streaming ownership to FileHandle.createReadStream({ autoClose: true }), and starts managed-media cleanup ownership immediately after opening the descriptor. Production code gets smaller: 88 lines added, 89 removed; net -1.

User Impact

  • Interrupted assistant-media and managed outgoing-media requests close their underlying descriptors exactly once.
  • Playback-transcode failures and already-ended replacement responses no longer leak an opened descriptor.
  • Existing full-response, partial-range, conditional request, empty-response, and HEAD behavior remains covered and unchanged.
  • No authentication, gateway protocol, configuration/defaults, public SDK, persistent state/SQLite, provider, or channel contracts change.

Evidence

Distinct root causes

  1. Duplicate close ownership on disconnect. Both sibling routes explicitly closed a FileHandle after destroying its FileHandle-backed ReadStream. Personally inspected Node's internal/fs/streams: FileHandleOperations.close at lines 87–96 and ReadStream.prototype._destroy at lines 300–311 show stream teardown already closes the same handle. A real TCP disconnect using an 8 MiB response reproduced 2 FileHandle.close calls before; 1 after, with the descriptor closed (fd=-1) in both cases.
  2. Missing early descriptor ownership across playback transcoding. Managed media opened the original descriptor before awaiting resolvePlaybackTranscode(...), leaving rejection outside cleanup ownership. A transcoded replacement opened after response termination also missed the already-emitted close event. Focused regressions spy on the actual handle and verify fd=-1 after both paths.

Exact immutable candidate and focused remote proof

$ CI=true OPENCLAW_TESTBOX=1 OPENCLAW_TESTBOX_REMOTE_RUN=1 \
    node scripts/run-oxlint-shards.mjs --only=core --threads=8
[oxlint:core] finished
exit 0
  • Exact-head focused proof:
$ CI=1 OPENCLAW_TESTBOX=1 OPENCLAW_TESTBOX_REMOTE_RUN=1 \
    OPENCLAW_VITEST_MAX_WORKERS=2 pnpm test \
    src/gateway/http-byte-range.test.ts \
    src/gateway/managed-image-attachments.test.ts \
    src/gateway/control-ui.http.test.ts
src/gateway/control-ui.http.test.ts             116 passed
src/gateway/http-byte-range.test.ts               20 passed
src/gateway/managed-image-attachments.test.ts     68 passed
Test Files  3 passed
Tests       204 passed, 0 failed
exit 0
  • Redacted real 8 MiB TCP client-disconnect proof:
{
  "head": "3bb199292b9a57610ce0b5e579026adbe9601216",
  "payloadBytes": 8388608,
  "before": { "closeCalls": 2, "destroyed": true, "readableEnded": false, "fd": -1 },
  "after": { "closeCalls": 1, "destroyed": true, "readableEnded": false, "fd": -1 }
}
  • The exact-head owner suite includes real descriptor regressions for the three requested behaviors: disconnect closes the descriptor exactly once, playback-transcode rejection closes the opened descriptor, and an already-ended response immediately closes its replacement descriptor.
  • All five previous hosted lint findings were corrected at their owners with no suppression: redundant assignment, two inconsistent async returns, a discarded ternary expression, and an imprecise test spy type.
  • git diff --check, targeted formatting, exact-head full core lint, and all 204 owner tests passed.

Independent full-branch autoreview

A genuine independent structured Codex gpt-5.6-sol review at high reasoning inspected the complete current candidate 3bb199292b9a57610ce0b5e579026adbe9601216, with real TruffleHog 3.96.0 and an explicit P3 threshold: zero P0/P1/P2/P3 findings, verdict “patch is correct”, confidence 0.93. A separate strict owner/caller/Node-contract review also reported no actionable findings.

An earlier review correctly identified the already-ended replacement-descriptor race as P2; it was fixed at the canonical owner and covered by a real descriptor regression. Its separate provisional P1 inference about Node stream ownership was disproved by inspecting the actual Node implementation and observing the real TCP descriptor behavior; explicit autoClose: true makes ownership unambiguous.

Changed files

  • src/gateway/control-ui.ts
  • src/gateway/http-byte-range.ts
  • src/gateway/http-byte-range.test.ts
  • src/gateway/managed-image-attachments.ts
  • src/gateway/managed-image-attachments.test.ts

ClawSweeper rank-up moves

  1. Attach redacted focused current-head test or live-output evidence for disconnect, transcode rejection, and an already-ended replacement response — addressed. The current immutable head, full core-lint output, exact 204-test output, exact workflow URL, real TCP before/after JSON, and all three descriptor regression behaviors are documented above.
  2. Let protected maintainer review decide after current required checks complete — addressed. Required hosted checks on the exact current head are green; this PR is submitted through the repository-native maintainer review, prepare, and merge workflow rather than bypassing its protected owner decision.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Jul 31, 2026
@steipete
steipete marked this pull request as ready for review July 31, 2026 19:27
@steipete
steipete force-pushed the codex/wave3-gateway-http-stream-lifecycle branch from 8cd701d to 3bb1992 Compare July 31, 2026 19:44
@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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 31, 2026
@clawsweeper

clawsweeper Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 31, 2026, 3:49 PM ET / 19:49 UTC.

ClawSweeper review

What this changes

The PR moves assistant-media and managed outgoing-media HTTP responses to one shared gateway helper that owns the opened file descriptor through streaming, disconnect, error, and no-body paths.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 5 items remain

Keep this PR open for protected maintainer review. Current main still has two route-specific file-handle cleanup implementations, while the proposed shared gateway byte-stream owner directly addresses that duplicated lifecycle boundary; the remaining blocker is proof tied to the current force-pushed head, not a source-proven patch defect.

Priority: P2
Reviewed head: 3bb199292b9a57610ce0b5e579026adbe9601216
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The shared-owner design is focused and source-supported, but real behavior proof has not been refreshed for the current force-pushed head.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The PR body contains relevant real TCP-disconnect and remote focused-test evidence, but it identifies candidate 8cd701d7823676717ce123549c955a821b448e61 while the current head is 3bb1992; add redacted current-head terminal, workflow, or runtime output before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The PR body contains relevant real TCP-disconnect and remote focused-test evidence, but it identifies candidate 8cd701d7823676717ce123549c955a821b448e61 while the current head is 3bb1992; add redacted current-head terminal, workflow, or runtime output before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current duplication remains on main: Current main separately creates FileHandle-backed read streams with autoClose disabled and separately closes their handles from stream and response events in both media routes; the proposed owner-boundary consolidation is therefore still necessary.
Sibling managed-media path: The managed outgoing-media route repeats the same explicit stream-end, stream-close, stream-error, and response-close cleanup pattern, so a shared byte-response owner covers the common invariant rather than only one reported route.
Node stream ownership contract: The locally installed Node fs/promises type contract documents that FileHandle.createReadStream defaults autoClose to true and closes the descriptor automatically on error or end; this supports making the stream the sole descriptor owner after creation.
Findings None None.
Security None None.

How this fits together

The Gateway serves verified local assistant and managed outgoing media over HTTP, including byte ranges and playback-transcoded replacements. Each route opens a trusted file handle, computes a response plan, streams bytes to the client, and must release the descriptor exactly once when the response finishes or disconnects.

flowchart LR
  A[Assistant or managed media request] --> B[Open verified local file]
  B --> C[Shared byte-stream lifecycle owner]
  C --> D[Range and conditional response plan]
  D --> E[File-backed read stream]
  E --> F[HTTP client response]
  F --> G[Finish, error, or disconnect cleanup]
Loading

Decision needed

Question Recommendation
Should the protected maintainer review accept this shared gateway descriptor owner after the contributor supplies focused proof for head 3bb1992? Require refreshed exact-head proof: Request redacted terminal or workflow output for the current head covering disconnect, playback-transcode rejection, and a replacement opened after response completion.

Why: The architectural direction is sound from the available source and Node contract evidence, but the only cited live proof is tied to an earlier unavailable candidate and the protected label requires explicit human handling.

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The PR body contains relevant real TCP-disconnect and remote focused-test evidence, but it identifies candidate 8cd701d7823676717ce123549c955a821b448e61 while the current head is 3bb1992; add redacted current-head terminal, workflow, or runtime output before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - The available real-behavior proof names an earlier candidate commit rather than the current force-pushed head, so it does not yet establish the current branch's exact lifecycle behavior.
  • Resolve merge risk (P1) - The maintainer label is protected review context; a human should confirm the canonical ownership boundary after the current-head proof and required checks complete.
  • Complete next step (P2) - No mechanical repair is identified; a protected maintainer should review the shared ownership boundary after current-head proof is refreshed.
Agent review details

Security

None.

PR surface

Source -1, Tests +152. Total +151 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 88 89 -1
Tests 2 155 3 +152
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 243 92 +151

Review metrics

Metric Value Why it matters
Shared lifecycle boundary 2 media-serving routes proposed to use 1 shared byte-stream owner The consolidation removes duplicated descriptor-release policy from sibling HTTP routes, so both routes need current-head lifecycle proof.

Stored data model

Persistent data-model change detected: serialized state: src/gateway/http-byte-range.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Refresh lifecycle proof before merge (recommended)
    Run the focused gateway lifecycle tests and demonstrate the real disconnect/transcode paths on the current head so descriptor cleanup is verified against the branch that will merge.
  2. Accept the proof gap intentionally
    A maintainer may accept the prior candidate evidence only after confirming the force-pushed head did not change the relevant stream-owner behavior.

Technical review

Best possible solution:

Keep one shared byte-stream lifecycle owner at the gateway response boundary, preserve verified-handle streaming and byte-response behavior, and attach focused current-head disconnect, transcode-rejection, and already-ended-response proof before merge.

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

Yes, at source level: current main has both routes disable stream auto-close and independently close the same opened handle on stream and response lifecycle events. The PR body also describes a focused TCP-disconnect reproduction, but that run is not yet tied to the current head.

Is this the best way to solve the issue?

Yes in principle: descriptor ownership belongs at the shared byte-response boundary because both routes implement the same stream lifecycle and Node's FileHandle stream contract owns closure when auto-close is enabled. The final merge decision should wait for exact-head proof rather than introduce another route-specific cleanup path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8b5871e1b703.

Labels

Label justifications:

  • P2: This is a bounded Gateway reliability repair affecting HTTP media cleanup, with no evidence of a current crash loop, data loss, or wider emergency.
  • merge-risk: 🚨 availability: The patch changes resource ownership on response completion, stream errors, and client disconnects, where a lifecycle regression could stall or fail media requests.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body contains relevant real TCP-disconnect and remote focused-test evidence, but it identifies candidate 8cd701d7823676717ce123549c955a821b448e61 while the current head is 3bb1992; add redacted current-head terminal, workflow, or runtime output before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current duplication remains on main: Current main separately creates FileHandle-backed read streams with autoClose disabled and separately closes their handles from stream and response events in both media routes; the proposed owner-boundary consolidation is therefore still necessary. (src/gateway/control-ui.ts:751, 9e626c38370e)
  • Sibling managed-media path: The managed outgoing-media route repeats the same explicit stream-end, stream-close, stream-error, and response-close cleanup pattern, so a shared byte-response owner covers the common invariant rather than only one reported route. (src/gateway/managed-image-attachments.ts:1535, 9e626c38370e)
  • Node stream ownership contract: The locally installed Node fs/promises type contract documents that FileHandle.createReadStream defaults autoClose to true and closes the descriptor automatically on error or end; this supports making the stream the sole descriptor owner after creation.
  • Current-head evidence gap: The PR body identifies focused proof for candidate 8cd701d7823676717ce123549c955a821b448e61, but the live head supplied for review is 3bb1992 after a force-push. The partial clone has the head commit metadata but could not hydrate its promised blobs or the earlier proof candidate because github.com DNS was unavailable. (3bb199292b9a)
  • Feature-history routing: The current byte-range owner was most recently changed by the conditional-media ETag repair, and file history/shortlog show Peter Steinberger as the dominant contributor across all three affected gateway files, with Vincent Koc as an adjacent contributor. (src/gateway/http-byte-range.ts:84, d8b30b7a7f55)
  • Release/main status: The supplied latest release is v2026.7.1 at 2d2ddc4; current main is 9e626c3 and contains the still-duplicated lifecycle code, so this PR is neither implemented nor superseded on main. (src/gateway/http-byte-range.ts:1, 9e626c38370e)

Likely related people:

  • steipete: Peter Steinberger authored the current PR, the recent conditional-media ETag repair, and the clear majority of historical changes across the three affected Gateway files. (role: dominant recent contributor and proposed lifecycle owner; confidence: high; commits: 3bb199292b9a, d8b30b7a7f55; files: src/gateway/http-byte-range.ts, src/gateway/control-ui.ts, src/gateway/managed-image-attachments.ts)
  • Vincent Koc: Repository shortlog and file history show repeated contributions around the affected Gateway/media paths, making Vincent a useful secondary routing contact. (role: adjacent recent area contributor; confidence: medium; commits: abd8a46b0a52; files: src/gateway/control-ui.ts, src/gateway/managed-image-attachments.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Attach redacted focused current-head test or live-output evidence for disconnect, transcode rejection, and an already-ended replacement response.
  • Let the protected maintainer review decide after the current required checks complete.

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.

@steipete
steipete merged commit f47542c into main Jul 31, 2026
135 of 141 checks passed
@steipete
steipete deleted the codex/wave3-gateway-http-stream-lifecycle branch July 31, 2026 21:17
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Jul 31, 2026
* origin/main: (22 commits)
  fix(cron): preserve lazy ownership and bounded notification lifetimes (#117018)
  fix: live updater no-op restarts healthy gateways (#117038)
  fix(bedrock): release streaming clients (#117039)
  fix(google): restore canonical Gemini and Vertex provider invariants (#117042)
  fix(channels): preserve accepted LINE and Mattermost delivery (#117024)
  fix(feishu): unify truthful delivery and media ownership (#117023)
  fix(ui): isolate gateway observer lifecycles (#117017)
  fix(tui): keep reset transitions isolated from stale input (#116873)
  fix(gateway): centralize streamed media descriptor ownership (#117000)
  feat(plugins): externalize OpenCode provider (#117035)
  fix(onboarding): restore skill dependency consent (#116644)
  fix(streaming): preserve incomplete bracket tails in final replies (#116983)
  fix: allow slower gateway readiness after updates (#117032)
  fix(plugin-state): avoid shared SQLite corruption when CLI starts during gateway runtime (#113204)
  fix(cli): keep config file output raw under JSON logging (#116968)
  fix(ai): malformed Anthropic stream frames expose raw event payloads (#116938)
  fix(qa): authenticate actual scenario execution evidence (#117004)
  feat(plugins): externalize NovitaAI provider (#117007)
  fix(text): preserve fenced tool markers in visible-text sanitizer (#116939) (#116971)
  fix(channels): reset metadata memos with plugin lifecycle (#117005)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant