Skip to content

perf(logging): flush file transport asynchronously off the request path - #114769

Merged
steipete merged 7 commits into
mainfrom
perf/gateway-async-log-transport
Jul 27, 2026
Merged

steipete merged 7 commits into
mainfrom
perf/gateway-async-log-transport

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Every gateway ws response slower than DEFAULT_WS_SLOW_MS (50ms) emits a [ws] ⇄ res log line whose file transport does JSON.stringify + a redactSensitiveText regex sweep + fs.statSync rotation accounting + a blocking appendRegularFileSync — all on the event loop. Under bursts this is a positive feedback loop: each slow response's sync append pushes concurrent responses over 50ms, which then also pay it.

Why This Change Was Made

Production perf campaign on team.openclaw.ai: the sync file append is pure event-loop stall on the hottest logging path, amplifying exactly when the gateway is busiest.

User Impact

Log file writes no longer stall request handling. No change to log content, redaction, format, thresholds, or console/TTY transports — only when bytes hit disk:

  • Bounded 4,096-record circular queue with a single ordered async flush loop; overflow drops oldest and writes exactly one dropped-count marker (never silent).
  • Rotation accounting moved into the flusher (per flush, not per record).
  • Graceful exits await the queue; forced exits synchronously drain everything not yet submitted. Named tradeoff: one already-issued async append is not replayed on abrupt forced exit (avoids duplicate/interleaved JSONL), so at most that single in-flight record can be lost.

An earlier iteration used a worker thread; it was deliberately simplified to this in-process flusher — the IPC/lifecycle/build wiring wasn't paying rent.

Evidence

  • 19 test files / 273 tests pass, including new regressions: queue-order + byte-identical output vs the sync path, overflow marker semantics, exit-drain via the exit-hook seam, rotation at the size boundary.
  • Targeted oxlint, git diff --check; Blacksmith Testbox pnpm format + pnpm tsgo:core (run 30309359392).
  • Codex autoreview clean after fixing two findings. DEFAULT_WS_SLOW_MS unchanged.

@steipete
steipete marked this pull request as ready for review July 27, 2026 22:08
@openclaw-barnacle openclaw-barnacle Bot added cli CLI command changes size: L maintainer Maintainer-authored PR labels Jul 27, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 27, 2026
@clawsweeper

clawsweeper Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 27, 2026, 7:29 PM ET / 23:29 UTC.

ClawSweeper review

What this changes

Replaces synchronous JSONL file-log appends with a bounded ordered asynchronous queue, adds shutdown draining, and updates logging tests to wait for queued writes.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 8 items remain

Keep this PR open for maintainer review. The asynchronous transport addresses a credible gateway hot-path stall, but the branch also adds a public plugin-SDK callable for process shutdown and deliberately changes file-log durability under overload and bounded shutdown; those contracts need an owner decision and real after-fix behavior proof before merge.

Priority: P2
Reviewed head: 87ea9bed86d85885841c3b29d193f179fa92c500
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The performance idea and targeted tests are useful, but the unresolved SDK-boundary defect and absence of real behavior proof keep this PR below merge-ready quality.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The PR reports tests and Testbox checks, but no redacted after-fix live output, terminal recording, runtime logs, or artifact demonstrates ordered file output and graceful/forced shutdown behavior in a real setup. 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 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The PR reports tests and Testbox checks, but no redacted after-fix live output, terminal recording, runtime logs, or artifact demonstrates ordered file output and graceful/forced shutdown behavior in a real setup. 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 5 items Async transport and explicit loss policy: The proposed transport introduces a 4,096-record queue, an asynchronous append loop, overflow tracking, and process-exit handling; the PR body explicitly permits dropped records under overflow and up to one in-flight record on abrupt forced exit.
Public SDK-surface growth: The branch raises both plugin SDK surface budgets by one and records the reason as the logger file-transport flush used for graceful shutdown drains. That makes a core process-lifecycle concern externally callable rather than keeping it behind a core-owned boundary.
Shutdown path depends on public flush helper: The gateway signal path imports the logger flush helper and waits up to four seconds before exiting, so the new API and timeout behavior affect graceful gateway shutdown rather than test-only behavior.
Findings 1 actionable finding [P1] Keep shutdown flushing out of the plugin SDK
Security None None.

How this fits together

Gateway request tracing and other runtime paths emit structured logs through the shared logger. This change moves file-backed JSONL writes off those request paths, then coordinates flushing during gateway shutdown so queued records reach the configured log file.

flowchart LR
  A[Gateway and runtime events] --> B[Shared structured logger]
  B --> C[Bounded file-log queue]
  C --> D[Ordered async file writer]
  D --> E[Rotated JSONL log files]
  F[Graceful gateway shutdown] --> G[Flush timeout decision]
  G --> C
  G --> H[Process exit]
Loading

Decision needed

Question Recommendation
Should OpenClaw accept bounded asynchronous file logging that can drop records during overload or after the graceful-shutdown timeout, and if so should its drain remain a core-only lifecycle capability rather than a plugin SDK API? Approve a core-only transport: Move the drain behind a core lifecycle seam, retain the bounded transport, and document the approved overload and shutdown-loss behavior.

Why: The performance benefit is plausible, but the acceptable durability tradeoff and the permanence of a plugin-visible shutdown control are operational product contracts rather than mechanical implementation details.

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The PR reports tests and Testbox checks, but no redacted after-fix live output, terminal recording, runtime logs, or artifact demonstrates ordered file output and graceful/forced shutdown behavior in a real setup. 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.
  • Keep shutdown flushing out of the plugin SDK (P1) - This change raises the public plugin-SDK budget for flushLogger, but the only production caller is the core gateway signal path. Exposing process-exit coordination as a plugin API creates a permanent external lifecycle contract and conflicts with the core-owned lifecycle boundary; move the drain to an internal/core seam unless maintainers explicitly approve this SDK API.
  • Resolve merge risk (P1) - Merging changes file-log durability from synchronous append semantics to bounded asynchronous delivery: records can be dropped during sustained overload, and graceful shutdown proceeds after four seconds even if the queue has not settled.
  • Resolve merge risk (P1) - The new flushLogger callable is recorded as plugin SDK surface growth even though its purpose is core process lifecycle management, creating a broader external contract than the gateway shutdown path needs.
  • Complete next step (P2) - A maintainer must choose the file-log durability policy and whether a plugin-visible shutdown API is acceptable; this is not a safe mechanical repair dispatch.
  • Improve patch quality - Move logger draining to a core-owned lifecycle boundary or obtain explicit approval for the plugin SDK contract.
  • Improve patch quality - Attach redacted live terminal output or a recording showing non-blocking request-path logging, ordered output, and both shutdown paths; redact endpoints, IP addresses, and credentials.

Findings

  • [P1] Keep shutdown flushing out of the plugin SDK — scripts/plugin-sdk-surface-report.mjs:188
Agent review details

Security

None.

PR surface

Source +309, Tests +189, Generated 0, Other +2. Total +500 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 4 378 69 +309
Tests 13 231 42 +189
Docs 0 0 0 0
Config 0 0 0 0
Generated 1 1 1 0
Other 1 4 2 +2
Total 19 614 114 +500

Review metrics

Metric Value Why it matters
Plugin SDK callable 1 added The branch increases the public plugin SDK budget for a logger flush operation used by gateway shutdown, expanding an external compatibility surface.

Merge-risk options

Maintainer options:

  1. Keep lifecycle draining internal (recommended)
    Replace the new plugin-SDK callable with a core-owned shutdown seam and add focused coverage showing the gateway exit path still drains it.
  2. Approve the operational tradeoff
    Explicitly accept bounded queue loss and the four-second graceful-exit cutoff as the file-log durability contract before merging.
  3. Pause pending durability direction
    Do not land the transport if maintainers require synchronous-equivalent file-log durability under overload and shutdown.

Technical review

Best possible solution:

Keep flushing and timeout coordination in a core-owned lifecycle boundary, make the overload and shutdown-durability policy explicitly approved, then attach redacted live evidence showing ordered output and the graceful/forced shutdown behavior.

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

Not applicable as a conventional bug reproduction: this is a performance and lifecycle refactor, and the PR does not attach a current real-world before/after run demonstrating the claimed request-path improvement.

Is this the best way to solve the issue?

No, not yet. The asynchronous transport is a plausible approach, but publishing its shutdown drain through the plugin SDK is not the narrowest owner boundary and the durability tradeoff needs explicit approval.

Full review comments:

  • [P1] Keep shutdown flushing out of the plugin SDK — scripts/plugin-sdk-surface-report.mjs:188
    This change raises the public plugin-SDK budget for flushLogger, but the only production caller is the core gateway signal path. Exposing process-exit coordination as a plugin API creates a permanent external lifecycle contract and conflicts with the core-owned lifecycle boundary; move the drain to an internal/core seam unless maintainers explicitly approve this SDK API.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.91

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 1755087bca79.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded gateway logging performance refactor with meaningful operational consequences but no demonstrated active user outage.
  • merge-risk: 🚨 compatibility: A new plugin SDK callable and changed file-log delivery semantics can become an external lifecycle and upgrade contract.
  • merge-risk: 🚨 availability: The flush timeout and bounded queue can affect shutdown completion and logging behavior during a busy gateway period.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR reports tests and Testbox checks, but no redacted after-fix live output, terminal recording, runtime logs, or artifact demonstrates ordered file output and graceful/forced shutdown behavior in a real setup. 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:

  • Async transport and explicit loss policy: The proposed transport introduces a 4,096-record queue, an asynchronous append loop, overflow tracking, and process-exit handling; the PR body explicitly permits dropped records under overflow and up to one in-flight record on abrupt forced exit. (src/logging/logger-file-transport.ts:20, 87ea9bed86d8)
  • Public SDK-surface growth: The branch raises both plugin SDK surface budgets by one and records the reason as the logger file-transport flush used for graceful shutdown drains. That makes a core process-lifecycle concern externally callable rather than keeping it behind a core-owned boundary. (scripts/plugin-sdk-surface-report.mjs:185, 87ea9bed86d8)
  • Shutdown path depends on public flush helper: The gateway signal path imports the logger flush helper and waits up to four seconds before exiting, so the new API and timeout behavior affect graceful gateway shutdown rather than test-only behavior. (src/cli/gateway-cli/run-loop.ts:18, 87ea9bed86d8)
  • Prior review continuity: The latest completed ClawSweeper cycle already identified keeping the logger drain out of the plugin SDK as a P1 concern. The current branch still records the additional public callable in the SDK budget update, so that blocker remains unresolved. (scripts/plugin-sdk-surface-report.mjs:188, 87ea9bed86d8)
  • Proof status: The PR body reports focused tests, formatting, type checks, and an autoreview, but it does not provide a redacted after-fix live run, terminal capture, runtime log, or recording that demonstrates request-path behavior and shutdown draining in a real setup.

Likely related people:

  • steipete: Authored the seven commits in this PR, including the follow-up revisions that added shutdown-drain coverage and recorded the public surface increase. (role: recent area contributor; confidence: medium; commits: 0f6f18475666, a60d4e8606b2, e1ba59652d9f; files: src/logging/logger-file-transport.ts, src/logging/logger.ts, src/cli/gateway-cli/run-loop.ts)

Rating scale

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

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

Workflow

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

History

Review history (4 earlier review cycles)
  • reviewed 2026-07-27T22:12:56.505Z sha 0f6f184 :: needs real behavior proof before merge. :: [P1] Preserve or explicitly approve file-log durability
  • reviewed 2026-07-27T22:25:44.372Z sha a60d4e8 :: needs real behavior proof before merge. :: [P1] Resolve file-log durability before queuing appends
  • reviewed 2026-07-27T22:36:13.768Z sha 7bf5f6c :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-27T22:48:03.724Z sha e1ba596 :: needs real behavior proof before merge. :: [P1] Keep the logger drain out of the plugin SDK

- +1 public export/callable budget with annotation: logger file-transport
  flush for graceful shutdown drains; regenerate SDK API baseline
- three tests that read the log file right after logging now drain the
  async file transport first (flushLogger) instead of racing the flusher
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts commands Command implementations agents Agent runtime and tooling labels Jul 27, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 27, 2026
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Jul 27, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 27, 2026
@steipete
steipete merged commit 1cbbda1 into main Jul 27, 2026
124 of 126 checks passed
@steipete
steipete deleted the perf/gateway-async-log-transport branch July 27, 2026 23:40
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 28, 2026
…th (openclaw#114769)

* perf(logging): flush file transport asynchronously off the request path

* fix(ci): record flushLogger surface growth and drain before log reads

- +1 public export/callable budget with annotation: logger file-transport
  flush for graceful shutdown drains; regenerate SDK API baseline
- three tests that read the log file right after logging now drain the
  async file transport first (flushLogger) instead of racing the flusher

* test: drain async log transport before reading talk and request-trace logs

* test: drain async log transport in CLI logger file tests

* test: drop unused withTempDirSync import
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: L 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