Skip to content

fix(logging): keep file logging from blocking Gateway requests - #197586

Merged
steipete merged 7 commits into
mainfrom
fix/gateway-file-log-worker
Nov 12, 2026
Merged

steipete merged 7 commits into
mainfrom
fix/gateway-file-log-worker

Conversation

@steipete

@steipete steipete commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: a stalled filesystem lookup during Gateway logging can block its main thread, delaying requests and liveness checks.

User Impact

File logging now performs preparation, admission, rotation and append in one lazy worker. FIFO ordering, graceful drain and best-effort errors remain; forced process-exit rescue retains its explicit synchronous contract.

Default logging also stops tslog's automatic synchronous source-map probes. Raw callsite metadata remains, and the dependency's existing TSLOG_SOURCE_MAPS override still enables diagnostic mapping. This adds no OpenClaw configuration option.

Why This Change Was Made

The existing asynchronous append helper still used synchronous lstat/fstat admission. Moving the entire filesystem operation to the existing worker infrastructure preserves its security checks and rotation ordering without adding metadata caches or replacing the dependency's admission policy. Existing worker threads write directly, avoiding recursive logger workers. A deployed worker process still has a main thread and uses the same lazy logger worker; its sealed deployment, runtime mapping and archive inventory now include that entry.

The tradeoff is one lazy worker: cold synthetic measurements added a median 49.3 MiB of process RSS. First settled log latency under a busy host was 996 ms median (176–1837 ms); this measures isolated logger construction and its first write, not whole Gateway boot. Warm total CPU increased about 5 ms per observed 23-batch minute. Production core grows by 173 lines because no complete filesystem owner previously existed.

Evidence

On macOS Node 26.12.1, the same warmed, steady-state 23-settled-batch workload reproduces 69 main-thread synchronous Node fs API calls for normal logging and 381 with rotation; both become zero. These are API counters, not kernel syscall counts. Cold module-loader calls are excluded from this count claim. Separate A/A controls, five interleaved timing and allocation windows, and five independent worker cold starts are retained. Exactly one worker serves repeated targets; allocation measurements cover the main isolate only. Host load and A/A wall differences preclude a wall-speed claim.

The actual default-environment Node main-thread regression fails on the parent and passes with the fix. It checks rotation, persisted tail, raw callsites, explicit diagnostic opt-in, first-target failure/recovery, lifecycle drain and existing-worker recursion. Existing logger consumers, browser-import tests, type/lint/format/runtime guards, unused-file checks and the full private-QA runtime build pass. Codex independent review found no actionable P0–P2 issues.

The affected real-Gateway Control UI file passes all four compatibility cases (its fixture silences file logging; it is not the logging I/O proof). Its two cross-agent cases also failed on the exact parent: the test expected both agents while leaving the page scoped to the default agent. The fixture now selects All agents through the public picker and preserves every owner/reset assertion. The missing precondition originated in #128803 (source-history attribution); the parent failures remain recorded.

The actual-main-thread regression also passes on Linux Node 26.12.1. Its counter and the maintained benchmark exclude unavailable non-callable exports such as Linux lchmodSync, while preserving all callable-method and native-realpath instrumentation. The macOS timing/allocation evidence is unchanged: only count windows install wrappers.

The extracted portable archive regression failed before the packaging correction: flush settled after an append warning, but the expected log file was missing. The repaired archive persists the record through the same worker owner and sealed filesystem bootstrap. The added test/support proof is exactly 193 net lines: 147 initial proof lines, three for Linux callable-export filtering, and 43 for the portable regression plus its required bundle fixture.

Portable validation passes 104 tooling assertions, 22 bundle-owner tests and two browser-import tests. One native-mode fixture initially refused the external scratch volume’s unsafe ancestor permissions; its isolated replay passes using the normal private test temp directory, with no safety-policy change. Core/tooling types, lint and format pass. An earlier local test-line ratchet reproduced the exact main parent’s 27-line overage (introduced by #197543, commit 3b13df5). That historical failure remains recorded. After the required current-main conflict integration, the supported ratchet passes with 193 net added lines under main’s fixed 400-line per-PR allowance and zero allocation credit. This PR’s obsolete allocation was removed; no allowance was added to absorb the earlier main regression.

CI also caught an overbroad native PR-wrapper inventory entry: portable deployment bootstraps are not native wrapper imports. Removing that one entry keeps the sealed deployment/archive registrations intact and restores both wrapper import-closure checks (red before removal, green after). No product source or test behavior changed.

Native merge admission found a later conflict when another worker was added at the same private build-entry list position. The integration preserves both secretFileRead and fileLog; logger runtime, portable bootstrap/archive and UI fixture bytes remain unchanged. Both workers’ build graphs, shared-chunk exclusion and package inventory pass (four focused cases), and fresh Codex review is clean. The prior native attempt aborted before dispatch; the integrated head requires fresh CI and final-head review.

The final bookkeeping-only commit removes the obsolete allocation after main introduced its fixed per-PR test budget. The narrow budget check passes with 193 added lines and zero credit; independent Codex review is clean. Runtime and test source remain unchanged.

Move complete file preparation, rotation and append units into one lazy worker while preserving FIFO, graceful drain, best-effort failures and explicit forced-exit rescue. Default existing tslog source-map probing off without overriding an explicit diagnostic policy; retain raw callsites.

Observed steady-state synchronous calls fall from 69 to zero per 23 settled batches, and from 381 to zero with rotation. Preserve independent A/A CPU, allocation and cold-worker cost evidence. Repair the affected cross-agent UI fixture by selecting All agents through its public picker; exact parent reproduces the missing-scope failure and all four cases pass after correction.
@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts size: L labels Nov 12, 2026
Integrate main at 3b13df5 and preserve both exact standalone entries in the Knip conflict. Logger runtime, regression, UI fixture, docs, benchmark and build registration bytes remain identical to the reviewed candidate; worker lifecycle context is unchanged. Independent Codex review and targeted formatting/diff validation passed.
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 12, 2026
@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR moves ordinary file-log filesystem work into a lazy worker and disables implicit source-map probes while preserving diagnostic opt-in.

Example: The reported macOS Node 26 workload writes 23 settled logging batches with rotation.

  • Before: Logging performs 381 synchronous filesystem API calls on the main thread.
  • After: The reported count becomes zero as filesystem work runs in the logging worker.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation has meaningful production-path regression coverage and no definite code findings, while the required shipped-behavior evidence remains incomplete.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A filesystem lookup during file logging can stall Gateway requests and liveness checks.
Reason: The source confirms the problem, and the maintainer-authored direction explicitly accepts the worker's measured resource costs.

Merge readiness

✅ Ready for maintainer review

This PR addresses a current Gateway stall path and retains meaningful unique work; no definite correctness or security regression was found.

Priority: P2
Reviewed head: 50c0e5680f0a6d5df7e6f3200d5b959ddc5e091a

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Publish redacted output from the shipped Gateway exercising file logging and rotation while requests remain responsive, including the changed default after upgrading from the latest stable release.
Agent review details

How this fits together

Gateway log records enter the existing bounded FIFO transport, which dispatches filesystem operations to one worker and produces rotated JSONL files or best-effort warnings.

flowchart LR
  A[Gateway logging] --> B[JSONL serialization]
  B --> C[Bounded FIFO transport]
  C --> D[Lazy logging worker]
  D --> E[Guarded filesystem operations]
  E --> F[Log files and archives]
  C --> G[Forced exit rescue]
  G --> E
Loading

Technical review

Best possible solution:

Retain the existing FIFO transport and guarded filesystem contract while using the shared worker infrastructure for ordinary logging I/O.

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

Current-main logging and pinned fs-safe source establish synchronous filesystem work on the Gateway thread; the author reports baseline failures and after-fix counters, but this read-only review ran no target code.

Is this the best way to solve the issue?

The change fixes the owning filesystem boundary without duplicating admission policy or adding caches; its worker entry modules serve distinct build and deployment boundaries.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4eb318d5eea7.

Provenance checked

  • Asynchronous transport and worker placement changes intended behavior with a stated reason (1cbbda1: The earlier repair deliberately chose an in-process flusher to avoid worker wiring costs; this PR explains why remaining synchronous admission now warrants isolation.)
  • Batching, ordering and forced-exit rescue keeps the original intent (ce30057: Bounded batches reduce shutdown filesystem operations while preserving record boundaries and avoiding replay of issued writes.)
  • Bounded log-directory creation keeps the original intent (ce3b88c: Nonrecursive bounded creation prevents an infinite mkdir loop on a deleted but mounted temporary directory.)
  • tslog source-map policy changes intended behavior with a stated reason (d13f07b: The tslog 5 migration retained dependency defaults; this PR documents disabling synchronous diagnostic probes by default while preserving explicit overrides.)
  • Cross-agent usage browser fixture keeps the original intent (fix(usage): preserve agent ownership for matching session IDs #128803: The fixture protects independent ownership for equal session IDs across agents; selecting All agents restores its required scope without weakening assertions.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Current main retains blocking logging operations: Fetched main still prepares directories synchronously in the logger and rotates files synchronously in the transport; the central repair is not implemented there. (src/logging/logger.ts:518, 4eb318d5eea7)
  • Introduced worker cutover: The introduced diff retains the queue owner, relocates directory preparation and rotation, and uses the existing writer-worker pool and lifecycle registry. (src/logging/logger-file-worker.ts:13, 50c0e5680f0a)
  • Previous packaging finding resolved: The deploy manifest, sealed runtime mapping, archive inventory and bootstrap include file-log.worker; the relocated-archive regression checks persisted contents. These logging bytes remain unchanged from the previous reviewed head. (test/scripts/worker-deploy-build-plugin.test.ts:234, 50c0e5680f0a)
  • Existing design and accepted worker cost: perf(logging): flush file transport asynchronously off the request path #114769 deliberately preferred an in-process flusher; this maintainer-authored PR explains the remaining synchronous admission calls and explicitly records the lazy worker's 49.3 MiB median RSS cost and cold-write latency. (src/logging/logger-file-transport.ts:213, 1cbbda18c390)
  • Pinned dependency confirms synchronous admission: The patch directly imports appendRegularFile from this dependency; version 0.27.1 performs synchronous lstat/fstat identity checks inside its asynchronous append, confirming the stated cause while preserving its guarded append contract. (src/regular-file.ts:294, ea225ba262cf)
  • Pinned source-map override contract: The patch changes behavior governed by tslog 5.4.0; its source checks TSLOG_SOURCE_MAPS on every resolution and recognizes off, false and 0, so the nullish default preserves explicit diagnostic settings. (src/env/sourceMap.node.ts:499, 332e0fd003cf)

Likely related people:

  • Peter Steinberger: Raw commit 1cbbda1 adds src/logging/logger-file-transport.ts:282 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1cbbda18c390; files: src/logging/logger-file-transport.ts)
  • Alix-007: Raw commit 4b65ebd adds src/logging/logger-file-transport.ts:110 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4b65ebd2280b; files: src/logging/logger-file-transport.ts)

PR surface

Source +173, Tests +193, Docs +9, Other +141. Total +516 across 19 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 8 289 116 +173
Tests 6 193 0 +193
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 4 141 0 +141
Total 19 632 116 +516

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit. Replaced prior rating: 🦐 gold shrimp.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.

Label justifications:

  • P2: Synchronous file-log operations can delay Gateway requests and liveness checks, but the submission does not establish an urgent widespread outage.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit. Replaced prior rating: 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-11-12T06:28:20.390Z sha 0e20bf7 :: needs changes before merge. :: [P2] Ship the logging worker in portable worker bundles
  • reviewed 2026-11-12T07:15:25.357Z sha 9a03c5c :: needs maintainer review before merge. :: none
  • reviewed 2026-11-12T07:49:54.003Z sha 0186f3a :: needs maintainer review before merge. :: none

Reviewed November 12, 2026, 4:16 AM ET / 09:16 UTC (Revision 4).

Count callable Sync exports while excluding unavailable lchmodSync on Linux. Preserve native realpath instrumentation, descriptor restoration and counter-free timing/allocation windows. Actual-main-thread regression passes on Linux Node26 and macOS; no production or workload change.
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed both items from the review of 0e20bf7:

  1. Portable logging is included at every owning boundary: src/infra/runtime-process-manifest.ts:470 builds the sealed entry and line 518 registers its runtime mapping; src/shared/worker-bundle-hash.ts:23 includes it in the transferred archive. src/worker/worker-deploy-file-log.ts:1 applies the existing sealed filesystem bootstrap before the same logging worker. The distinction is deliberate: a portable worker process has a main thread and uses this pool; existing worker threads retain the direct filesystem unit to prevent recursive worker creation. test/scripts/worker-deploy-build-plugin.test.ts:234 extracts the real archive, writes and flushes a log, checks its persisted contents and drains the owner. It failed before this correction with append failure and a missing file, and passes after it. The affected portable/bundle tests, including native-asset rejection, pass. No synchronous fallback was added.
  2. The reported conflict was resolved by integrating main 3b13df5 in 68cf192, preserving both neighboring Knip entries. The subsequent portable repair is 9a03c5c. The branch and body now include the final source and proof; fresh independent Codex review found no actionable P0–P2 issue.

The four UI E2E cases are compatibility proof only because their fixture silences file logging. Actual logging is covered by the main-thread process regression, the extracted portable artifact regression, and the retained local Gateway measurement. The exact main parent's 27-line test-ratchet regression is documented separately; this PR funds its full 193-line test delta.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete marked this pull request as ready for review November 12, 2026 07:09
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T09:14:22.680436Z 50c0e56 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 12, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The final CI repair removes one unnecessary native PR-wrapper inventory entry in 0186f3a. Both reported wrapper import-closure failures reproduce before the removal and pass after it; fresh independent Codex review is clean. Portable deploy bootstraps are not imports of the native PR wrapper, so the corrected wrapper inventory retains the ordinary logger worker without pulling in the sealed deployment graph.

The two prior review items remain resolved on this head:

  1. src/infra/runtime-process-manifest.ts:470 and line 518, src/shared/worker-bundle-hash.ts:23, and src/worker/worker-deploy-file-log.ts:1 still build, map, archive and bootstrap the same logger worker. The extracted-artifact persistence regression at test/scripts/worker-deploy-build-plugin.test.ts:234 remains unchanged and passing.
  2. The merge-conflict correction is retained; the published branch includes main 3b13df5 and the portable repair. No product source changed in this final wrapper-only correction.

The body includes the corrected proof and the separately attributed main test-line regression.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 12, 2026
@clawsweeper clawsweeper Bot added 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 12, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The current-main conflict is resolved in ebad47c. Native admission stopped before sending a merge request when main added another worker at the same build-entry list position. scripts/lib/runtime-process-core-build-entries.mts:52 now retains both secretFileRead and fileLog.

The prior numbered items remain resolved:

  1. src/infra/runtime-process-manifest.ts:476 and line528 retain the deploy/sealed entries; src/shared/worker-bundle-hash.ts:23 retains the archive entry; src/worker/worker-deploy-file-log.ts:1 retains the sealed bootstrap. Those logger runtime/portable bytes are unchanged from the cleared 0186 head; extracted-archive proof remains qualified.
  2. scripts/lib/runtime-process-core-build-entries.mts:51 and line52 preserve both workers and resolve the new merge conflict. Both workers’ build graphs, shared-chunk exclusion and package inventory pass all four focused cases. Fresh independent Codex review is clean.

Final head 50c0e5680f0a6d5df7e6f3200d5b959ddc5e091a also removes the obsolete allocation record. The integrated test-line ratchet passes with 193 added lines under the fixed 400-line allowance and zero allocation credit; the mechanical cleanup has a separate clean Codex review. The earlier exact-parent deficit remains documented as historical evidence. The main sealed-entry factory change preserves the logger’s sibling file-log.worker.mjs result; its new filename lookup falls back for this existing mapping. No logger behavior, configuration or schema changed during integration.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 12, 2026
@steipete
steipete merged commit 5358d05 into main Nov 12, 2026
168 of 171 checks passed
@steipete
steipete deleted the fix/gateway-file-log-worker branch November 12, 2026 10:42
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 13, 2026
…law#197586)

* fix(logging): isolate runtime file work from Gateway requests

Move complete file preparation, rotation and append units into one lazy worker while preserving FIFO, graceful drain, best-effort failures and explicit forced-exit rescue. Default existing tslog source-map probing off without overriding an explicit diagnostic policy; retain raw callsites.

Observed steady-state synchronous calls fall from 69 to zero per 23 settled batches, and from 381 to zero with rotation. Preserve independent A/A CPU, allocation and cold-worker cost evidence. Repair the affected cross-agent UI fixture by selecting All agents through its public picker; exact parent reproduces the missing-scope failure and all four cases pass after correction.

* test(logging): preserve filesystem counters on Linux

Count callable Sync exports while excluding unavailable lchmodSync on Linux. Preserve native realpath instrumentation, descriptor restoration and counter-free timing/allocation windows. Actual-main-thread regression passes on Linux Node26 and macOS; no production or workload change.

* fix(logging): include file worker in portable archives

* fix(logging): keep portable bootstrap out of PR wrapper

* chore(logging): remove obsolete test allocation
tideclaw-bot added a commit that referenced this pull request Nov 24, 2026
Worker threads already perform file logging directly. Route them to the loaded filesystem owner before importing the main-thread writer pool. An in-place update can replace the old hashed chunk before a worker isolate first flushes during SIGTERM, putting final log writes at risk. Keep one lazy main-thread writer as in #197586, and inject the owning transport flush to remove the reverse import.

Relocated package: existing filter caught the post-SIGTERM logger-worker chunk on 9e93dae and returned no matches on the fix (1,085 probe entries; positive control passed). The fixed CLI exited zero and persisted the final shutdown log record. Runtime build, tarball validation, bootstrap import budgets, both cycle checks, focused logger tests and the isolated real-Node logger fixture passed.

Co-authored-by: RomneyDa <[email protected]>
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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L 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