Skip to content

fix(gateway): bound audit and Codex backlogs - #126154

Merged
steipete merged 3 commits into
mainfrom
steipete/zen-cannon-bb37af
Aug 19, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/zen-cannon-bb37af

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Follow-up to #126033 and #126073.

What Problem This Solves

Fixes two independent backlog owners exposed by a live Linux Gateway soak on deployed commit fa62fccb867f315bf4282cfc67066d5d878c598a: transient database is locked audit failures during concurrent tool-heavy turns, and process memory high-water pressure while large Codex output bursts were draining.

The same Gateway process reached RSS 3.42 GiB / heap 2.88 GiB and later similar peaks, then repeatedly drained by roughly 1.5+ GiB. One observed drain moved heap from 4.11 GiB to 2.22 GiB in about 13 minutes. That evidence identifies an unbounded-but-drainable backlog, not a proven permanent leak.

Why This Change Was Made

Audit persistence previously ran in a Worker with its own JavaScript realm and module cache, so it opened a second physical DatabaseSync for the shared global state database. This change removes that Worker and its build/release surface, then uses a bounded process-owned structuredClone queue that drains through the process-canonical SQLite connection. Audit attempts use a reusable connection-local timeout scope, fail fast at timeout 0, retry transient contention asynchronously with bounded 25 ms to 1 s backoff, and emit one sustained audit-specific warning. Corruption, schema, and external-ownership failures remain terminal. Retention now deletes deterministic 1,024-row batches until settled.

Separately, Codex notification projection added one setImmediate per notification even though the keyed turn router already serializes projection and the physical client already owns receive-time rate-limit merging. Exact Codex rust-v0.147.0 source permits each stdout and stderr reader to emit up to 10,000 output-delta events using 8,192-byte read buffers for one native shell command. Removing the redundant yield lets that authoritative serialized queue drain directly without dropping output or changing limits.

Alternatives were rejected because a transport-specific retry or larger SQLite timeout would preserve duplicate connection ownership, while output dropping or heap-threshold changes would hide rather than remove the notification backlog.

Production LOC is +537/-400 (net +137), tests +298/-48 (net +250), docs +27/-21 (net +6), and tooling +0/-3. The positive production delta is the reusable fail-fast cold-open/contention boundary; the audit writer itself deletes the Worker and duplicate connection owner.

There is no SQLite schema-version change and no Gateway protocol-version change. No live Gateway was restarted or reconfigured. #126073 independently removed idle ingress write amplification and composes with this repair.

User Impact

Gateway audit persistence no longer creates a competing SQLite writer, transient lock contention stays off the agent hot path, and bounded retention avoids oversized cleanup transactions. Codex tool-output bursts drain in order without one macrotask per notification, reducing avoidable process-memory high-water pressure while preserving output and turn ordering.

Release-note context: fixes transient audit SQLite lock failures and drainable process-memory pressure during concurrent tool-heavy Gateway turns.

Evidence

Pre-fix owner regressions failed for the intended reasons:

  • canonical PRAGMA data_version: expected 2, received 3 because the Worker committed on another connection
  • bounded retention: expected 1,024 deleted rows, but all 1,025 were deleted
  • Codex burst: expected 128 notifications handled before the first macrotask, received 0

Post-fix local proof:

  • focused owner/sibling suite: 10 files, 169 tests passed
  • post-rebase owner/sibling plus shared ingress composition suite: 11 files, 195 tests passed across 4 Vitest shards
  • node scripts/check-changed.mjs: all selected gates passed
  • pnpm build: passed
  • pnpm check:docs: passed with 0 broken links
  • git diff --check: passed
  • exact uncommitted patch Codex autoreview: clean, no accepted/actionable findings
  • rebase onto current origin/main: stable patch ID unchanged; current main includes fix(channels): stop idle ingress retention writes #126073

Known gap: there has not yet been a post-fix live deployment or soak. Exact-head CI, deterministic owner regressions, and the repo-native Testbox/prepare gate are the landing proof.

Live Gateway SQLite lock failures and process heap pressure exposed two
independent queue owners. Route best-effort audit persistence through the
canonical shared-state connection with bounded contention retries, and remove
the per-notification Codex yield so the keyed turn queue can drain directly.

Follow-up to #126033 and #126073.
@clawsweeper

clawsweeper Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete
steipete marked this pull request as ready for review August 19, 2026 03:31
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts labels Aug 19, 2026
@steipete
steipete requested a review from a team as a code owner August 19, 2026 03:31
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 19, 2026
@clawsweeper

clawsweeper Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 19, 2026, 12:17 AM ET / 04:17 UTC.

ClawSweeper review

What this changes

This PR replaces the audit Worker with a bounded process-owned SQLite queue and removes a per-notification scheduling yield from Codex output projection.

Regression provenance

Possible regression — suspected (reproduction; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

Keep open for maintainer proof review. The audit ownership refactor is source-backed, but the cited upstream Codex runtime contract could not be directly inspected and no after-fix Gateway soak is available.

Priority: P1
Reviewed head: b428281f6151b51127768c6a71d612899684d91b
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The repair is focused and regression-covered, but merge confidence is limited by unavailable upstream-contract inspection and no after-fix soak.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer PR has deterministic regression evidence; the missing after-fix soak is a maintainer proof decision rather than an external-contributor proof gate.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer PR has deterministic regression evidence; the missing after-fix soak is a maintainer proof decision rather than an external-contributor proof gate.
Evidence reviewed 5 items Audit owner boundary: The proposed writer queues cloned audit requests and drains them through the process-owned state-database path with zero-timeout contention retries.
Current main behavior: Current main still uses a Worker that opens its own audit persistence realm, so this PR is not obsolete.
Local serialization boundary: The Codex turn router serializes notifications through one promise tail, supporting review of the removed extra yield within OpenClaw itself.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs src/audit/audit-event-writer.test.ts extensions/codex/src/app-server/run-attempt.notification-burst.test.ts

Result: PASS (completed)

node scripts/run-vitest.mjs src/audit/audit-event-writer.test.ts extensions/codex/src/app-server/run-attempt.notification-burst.test.ts
runner@runnervmzvulz:/tmp/clawsweeper-live-proof-126154-sgKbd8/target$ node scripts/run-vitest.mjs src/audit/audit-event-writer.test.ts extensions/codex/src/app
-server/run-attempt.notification-burst.test.ts
node scripts/run-vitest.mjs src/audit/audit-event-writer.test.ts extensions/codex/src/app-server/run-attempt.notification-burst.test.ts
[test] starting test/vitest/vitest.unit.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-126154-sgKbd8/target

 ✓  unit  src/audit/audit-event-writer.test.ts (11 tests) 5598ms
     ✓ keeps progress absent while disabled and routes enabled progress off audit_events  366ms
     ✓ keeps a cold owner open nonblocking under a held write lock  368ms
     ✓ keeps the shared queue nonblocking under a held write lock and flushes before stop  379ms
     ✓ reports sustained lock contention once while backing off retries  2714ms
     ✓ prunes expired identity contexts before preserving exact-envelope conflicts  379ms
     ✓ keeps schema and insert failures off the admission path  451ms
     ✓ keeps malformed, serialization, and key failures nonblocking and redaction-safe  327ms

 Test Files  1 passed (1)
      Tests  11 passed (11)
   Start at  04:18:49
   Duration  9.19s (transform 2.54s, setup 1.00s, import 2.22s, tests 5.60s, environment 0ms)

[test] starting test/vitest/vitest.extension-codex.config.ts




























Assertions:

  • PASS expect_output: Test Files

How this fits together

Gateway audit admission records best-effort activity through the shared state database, while the Codex plugin serializes app-server notifications into each agent turn’s projected output. Both paths handle asynchronous work during active runs.

flowchart LR
  A[Gateway activity] --> B[Audit admission]
  B --> C[Bounded audit queue]
  C --> D[Shared state database]
  E[Codex output notifications] --> F[Serialized turn router]
  F --> G[Notification projection]
  G --> H[Agent output]
Loading

Decision needed

Question Recommendation
Should this availability-sensitive repair land on deterministic owner regressions and CI alone, or wait for direct upstream Codex-contract inspection plus an after-fix isolated Gateway soak? Require the missing proof: Inspect the cited Codex source and attach redacted after-fix Gateway contention and output-drain evidence before landing.

Why: The PR explicitly grounds its Codex change in an upstream runtime contract and identifies a live soak as the source of the reported failures, neither of which is fully verifiable from this checkout.

Before merge

  • Resolve merge risk (P1) - The PR’s Codex throughput rationale depends on an upstream runtime claim that could not be directly inspected because the required sibling checkout is unavailable.
  • Resolve merge risk (P1) - The PR reports no after-fix isolated Gateway soak for the contention and sustained-output paths.
  • Resolve merge risk (P2) - Production code is net +137 lines for a bug fix; retain that growth only where the canonical shared-connection and temporary-timeout boundary cannot be absorbed into an existing owner.
  • Complete next step (P2) - This protected maintainer-authored PR needs a maintainer choice on the remaining contract and soak proof before merge.
Agent review details

Security

None.

PR surface

Source +137, Tests +251, Docs +6, Other -3. Total +391 across 29 files.

View PR surface stats
Area Files Added Removed Net
Source 15 537 400 +137
Tests 8 299 48 +251
Docs 3 27 21 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 3 0 3 -3
Total 29 863 472 +391

Review metrics

Metric Value Why it matters
Production versus test LOC production +537/-400 (net +137); tests +298/-48 (net +250) The Worker removal is offset by queue, timeout, and cold-open logic, making the net production growth material to this bug-fix review.

Stored data model

Persistent data-model change detected: database schema: src/audit/message-delivery-progress-store.test.ts, database schema: src/infra/sqlite-busy-timeout.test.ts, migration/backfill/repair: src/state/openclaw-state-db-open.ts, serialized state: src/infra/state-database-coordinator.ts, serialized state: src/state/openclaw-state-db-open.ts, serialized state: src/state/openclaw-state-db.ts, and 4 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Add runtime proof before merge (recommended)
    Capture redacted after-fix contention and sustained-output evidence, then verify the exact upstream Codex emission contract.
  2. Accept the proof gap
    A maintainer may intentionally land based on the focused regressions and CI without an after-fix soak.

Technical review

Best possible solution:

Retain the single process-owned audit writer path, verify the exact Codex upstream contract, and add redacted after-fix Gateway evidence before landing; collapse any remaining timeout/opening duplication into the state-database owner where possible.

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

Yes from source: current main’s audit writer creates a separate Worker-backed persistence path, and this PR adds focused contention and burst regressions; no after-fix live Gateway reproduction was supplied.

Is this the best way to solve the issue?

Unclear: using the process-owned shared-state connection is a coherent owner-boundary repair, but the Codex scheduling premise remains unverified against the upstream runtime cited by the PR.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: The PR addresses observed Gateway lock contention and output-backlog pressure during active agent work.
  • merge-risk: 🚨 availability: It changes shared SQLite write handling and high-volume Codex notification draining.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer PR has deterministic regression evidence; the missing after-fix soak is a maintainer proof decision rather than an external-contributor proof gate.

Evidence

What I checked:

  • Audit owner boundary: The proposed writer queues cloned audit requests and drains them through the process-owned state-database path with zero-timeout contention retries. (src/audit/audit-event-writer.ts:83, b428281f6151)
  • Current main behavior: Current main still uses a Worker that opens its own audit persistence realm, so this PR is not obsolete. (src/audit/audit-event-writer.ts:1, 8c3b3c6ea8d3)
  • Local serialization boundary: The Codex turn router serializes notifications through one promise tail, supporting review of the removed extra yield within OpenClaw itself. (extensions/codex/src/app-server/turn-router.ts:505, b428281f6151)
  • Upstream Codex contract unavailable: The PR body expressly relies on exact upstream Codex output-emission behavior, but ../codex is absent and the checkout could not retrieve missing objects because DNS resolution failed; this prevents the required direct contract check.
  • History attribution: The shallow checkout attributes the currently reviewed audit writer lines to the checked-out head; deeper feature history could not be retrieved. (src/audit/audit-event-writer.ts:84, b428281f6151)

Likely related people:

  • steipete: Authored the checked-out head and the merged related ingress-retention repair; shallow history prevents a broader ownership attribution. (role: recent merged adjacent contributor; confidence: medium; commits: b428281f6151, cc273e6eeab7; files: src/audit/audit-event-writer.ts, extensions/codex/src/app-server/run-attempt.notification-burst.test.ts)

Rank-up moves

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

  • Inspect the exact Codex source version cited by the PR.
  • Add redacted after-fix Gateway soak or production-boundary trace evidence.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-19T03:37:59.401Z sha 7779122 :: needs maintainer review before merge. :: none

@steipete

Copy link
Copy Markdown
Contributor Author

Landing proof for b428281f6151b51127768c6a71d612899684d91b.

The pre-fix owner regressions failed for the intended reasons: the canonical PRAGMA data_version observed a second physical connection commit (expected 2, received 3), retention deleted all 1,025 rows instead of one 1,024-row batch, and the Codex burst handled 0 of 128 notifications before the first macrotask.

Final proof:

  • node scripts/run-vitest.mjs src/audit/audit-event-writer.test.ts src/audit/audit-events.test.ts src/audit/message-delivery-progress-store.test.ts src/infra/sqlite-busy-timeout.test.ts src/infra/sqlite-transaction.test.ts src/state/openclaw-state-ownership.test.ts extensions/codex/src/app-server/run-attempt.notification-burst.test.ts extensions/codex/src/app-server/client-runtime.test.ts extensions/codex/src/app-server/run-attempt.usage-limits.test.ts extensions/codex/src/app-server/turn-router.test.ts src/channels/message/ingress-monitor.test.ts — 11 files, 195 tests, 4 shards passed.
  • pnpm check:architecture — passed after adding the required narrow raw-SQL contract annotation to the cold-open schema probe.
  • node scripts/run-vitest.mjs test/vitest-projects-config.test.ts extensions/codex/src/app-server/run-attempt.notification-burst.test.ts — 19 tests, 2 shards passed; the new regression is registered in the full-suite ownership map.
  • node scripts/check-changed.mjs — selected gates passed.
  • pnpm build — passed.
  • pnpm check:docs — passed with 0 broken links.
  • git diff --check — passed.
  • AGENTS_HOME="$HOME/.claude" "$HOME/.claude/skills/autoreview/scripts/autoreview" --mode branch --base origin/main — final full-bundle Codex autoreview clean; TruffleHog clean; no accepted/actionable findings.
  • Exact-head CI: https://github.com/openclaw/openclaw/actions/runs/32214925282 — completed successfully; the repo-native exact-head watcher returned GREEN.

The live Linux Gateway soak that motivated the repair observed transient audit lock failures and drainable process-memory high-water pressure. The same process reached RSS 3.42 GiB / heap 2.88 GiB and later drained roughly 1.5+ GiB; one observed heap drain was 4.11 GiB to 2.22 GiB in about 13 minutes. This is evidence of an unbounded-but-drainable backlog, not a proven permanent leak.

ClawSweeper rank-up moves:

  • Fulfilled: directly inspected exact upstream Codex rust-v0.147.0 (be6e8eac029b183056b7e4402879f15d2c85f61b). exec.rs defines 8,192-byte reads and a 10,000-delta cap; the separate stdout/stderr read_output calls each maintain that cap, and bespoke_event_handling.rs forwards those deltas to app-server clients.
  • Intentionally skipped: no post-fix live deployment/soak. This work order forbids touching, restarting, or reconfiguring the live Gateway, and no post-fix deployed artifact exists yet. Exact-head CI, deterministic owner regressions, direct dependency inspection, clean final autoreview, and the native Testbox/prepare gate are the landing proof.

Final LOC: production +537/-400 (net +137), tests +299/-48 (net +251), docs +27/-21 (net +6), tooling +0/-3. The production growth is the reusable fail-fast cold-open and connection-local contention boundary; the audit writer itself deletes the Worker and duplicate connection owner. There is no schema-version or protocol-version change, and no live Gateway was restarted or reconfigured.

@steipete
steipete merged commit 5564671 into main Aug 19, 2026
222 of 223 checks passed
@steipete
steipete deleted the steipete/zen-cannon-bb37af branch August 19, 2026 04:44
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 20, 2026
* fix(gateway): bound audit and Codex backlogs

Live Gateway SQLite lock failures and process heap pressure exposed two
independent queue owners. Route best-effort audit persistence through the
canonical shared-state connection with bounded contention retries, and remove
the per-notification Codex yield so the keyed turn queue can drain directly.

Follow-up to openclaw#126033 and openclaw#126073.

* fix(gateway): annotate raw SQLite cold-open probe

* test(codex): register notification burst shard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: codex gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant