Skip to content

fix(logging): keep logs.tail cost proportional to the window - #172885

Merged
steipete merged 1 commit into
mainfrom
fix/logs-tail-window-cost
Oct 15, 2026
Merged

steipete merged 1 commit into
mainfrom
fix/logs-tail-window-cost

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Related: #172507

What Problem This Solves

Fixes: the Control UI Logs page slows down and stalls the Gateway as the day's log file grows. Every 2-second poll rescanned the whole log file and re-redacted the tail without its fast path. On a 79 MB log, each poll took about 350–475 ms of Gateway main-thread time.

User Impact

User impact: leaving the Logs page open costs a few milliseconds per poll no matter how large the daily log is. Gateway responsiveness no longer gets worse over the day. Redaction output is unchanged.

Why This Change Was Made

  • PEM context scan. Finding out whether a PEM block was open at the window start meant scanning backwards until a BEGIN/END delimiter turned up. Normal logs have none, so each call read the file back to byte 0. logs.tail now caches one anchor: the last complete-record cursor plus whether a PEM block is open there, keyed by file, device and inode. The backward scan stops at the anchor, and the state is carried forward across the window with the existing delimiter scanner. Incremental polls therefore read only new bytes.
    • The anchor is dropped on rotation, on truncation below the anchor, on a file switch, and on an inode change between stat and open.
    • The interface stays generic, so log-tail does not special-case PEM.
  • redactSensitiveLines regression. Since the 10.3 redaction rewrite this was about 3x slower than v2026.10.1. Normalizing the PEM pattern built a new pattern array. The transport redactor only uses its built-in prefilter when it gets the exact default array, so the copy turned the prefilter off. The default array is now passed back when the patterns match it one for one.
  • Accepted tradeoffs (also noted in a code comment):
    • The first call per file per process still scans back once.
    • An in-place rewrite that keeps the same inode and a size at or above the anchor offset would reuse stale state. Logs only append and rotate by file, so this is accepted.

Evidence

  • Benchmark: a real 8.8 MB Gateway JSON log and a 79 MB concatenation of it. Calls use readConfiguredLogTail({limit:500,maxBytes:250000}), then 10 incremental polls that each append 32 records. Three interleaved runs on a loaded host:

    File Metric origin/main this PR
    79 MB incremental poll, median 348–475 ms 2.5–5.3 ms
    79 MB max event-loop delay during polls 38–119 ms 2–5 ms
    8.8 MB incremental poll, median 31–144 ms 2.1–5 ms
    79 MB cold call (still one full scan) 430–713 ms 334–655 ms
  • redactSensitiveLines on a real 250 KB, 370-line tail, 30 runs, median thread CPU: v2026.10.1 25.5 ms, main 95.6 ms, this PR 46.0 ms.

    • CPU profile on main: RegExp exec at 47.6% self time and visitRedactMatches at 72.9% total. visitRedactMatches drops to 0.8% after the fix.
    • Output hash on the real tail is identical across all three versions, and 5,744 synthetic comparisons are byte-identical.
  • Regression tests at the readConfiguredLogTail boundary:

    • a PEM block opened before the window is still redacted on cold and incremental calls
    • a block closed before the window does not cause over-redaction
    • openers on filtered-out lines
    • partial delimiters split across polls
    • rotation, truncation and empty-poll invalidation
    • switching to another file
    • rotation between stat and open
  • Local commands: pnpm test src/logging/redact*.test.ts src/logging/log-tail*.test.ts src/logging/logger-redaction-behavior.test.ts src/logging/diagnostic-support-redaction.test.ts src/logging/redacting-stream.test.ts (180 passed), pnpm tsgo, oxfmt, git diff --check.

  • CI: the checks-ui-e2e failures are inherited from main at that time, not caused by this PR.

    • Failing tests: session-management.sidebar "nests spawned sessions", session-management.promotion, and sidebar-agent-first geometry.
    • The same sidebar and promotion tests fail in unrelated PR runs from the same window: 38705646809 and 38704530691.
    • The UI bundle imports only src/logging/redact-patterns.ts, which this PR does not change.

@clawsweeper

clawsweeper Bot commented Oct 15, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T17:12:09.469590Z 9a3d765 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.

@github-actions

github-actions Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 9a3d765b5c38e9474c1803e904ad35bb18569ebb
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/logging/redact-pattern-runtime.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/logging/redact-pem.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/logging/redact.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added 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 Oct 15, 2026
@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR caches complete-record PEM context between log polls and restores the default redaction prefilter.

Example: Incremental polling of a 79 MB Gateway log after appending 32 records.

  • Before: The supplied benchmark reports median polls of 348–475 ms because each poll scans retained history.
  • After: The supplied benchmark reports 2.5–5.3 ms polls using cached context.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused, source-consistent optimization with useful owner-boundary measurements; supplied evidence does not exercise the shipped entry point.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; its body reports direct-reader benchmarks on real Gateway logs, identical output comparisons, and boundary tests, but supplies no shipped CLI or RPC capture.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Opening or following Gateway logs increasingly stalls other Gateway work as the daily log grows.
Reason: The maintainer-authored change addresses measured overhead without adding configuration, changing persisted data, or expanding the public API.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a verified logging performance problem with maintainer-approved scope, and source review found no definite introduced bug.

Priority: P1
Reviewed head: ada13befa4fbf8003c18feb8ca247e598b588fda

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not show a shipped logs.tail RPC or CLI performance run, or base-failing results for the added cache-preservation tests.
Agent review details

How this fits together

The shared log-tail reader reads configured raw log files, selects complete records, applies credential redaction, and returns lines with byte cursors to Gateway RPC, CLI, and diagnostic consumers.

flowchart LR
A[Raw Gateway log] --> B[Log tail reader]
C[Cursor and window limits] --> B
D[Process context anchor] --> B
B --> E[Record and batch redaction]
E --> F[Lines and byte cursor]
F --> G[Gateway CLI and diagnostics]
Loading

Technical review

Best possible solution:

Retain the shared reader optimization while preserving complete-record cursors and existing egress masking.

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

Current-main source scans backward to byte zero when no PEM delimiter resolves context and loses default-array identity during normalization; the body supplies comparative benchmarks, but this review executed no target code.

Is this the best way to solve the issue?

The optimization stays within the existing reader and matcher owners, preserves masking and cursor contracts, and uses a bounded process cache with explicitly accepted invalidation limits.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Backward PEM-context reconstruction changes intended behavior with a stated reason (fe3b289: Reconstruct prior context so selection and cursor cuts cannot expose a PEM body whose opener is outside the returned window.)
  • Per-record PEM normalization keeps the original intent (084f82d: Keep partial PEM context at batch scope while independently masking raw JSON records.)
  • Complete-record cursor settlement keeps the original intent (c676593: Advance only through bytes actually consumed so concurrent truncation and regrowth cannot silently skip appended records.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +86, Tests +135. Total +221 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 113 27 +86
Tests 1 136 1 +135
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 249 28 +221

Labels

Label changes:

  • add P1: Repeated log polling performs growing main-thread work in a reported Gateway-stall investigation, with substantial measured steady-state cost.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P1: Repeated log polling performs growing main-thread work in a reported Gateway-stall investigation, with substantial measured steady-state cost.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • 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.

Reviewed October 15, 2026, 3:29 AM ET / 07:29 UTC.

@steipete
steipete force-pushed the fix/logs-tail-window-cost branch from ada13be to 051ea25 Compare October 15, 2026 16:00

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 051ea251ea

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/logging/log-tail.ts
Comment on lines +303 to +309
redactionAnchor = {
file,
dev: contextStat.dev,
ino: contextStat.ino,
offset: cursor,
states,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Retain anchors for concurrent tail cursors

When two Control UI clients poll the same growing log at different times, both start an interval at cursor C; the first request publishes C′ here, so the second request rejects the sole cached anchor because C′ is greater than its contextStart C and falls back to scanning from byte zero. Since every request overwrites this single slot, one client can repeat the full-file scan every two seconds, preserving the Gateway stalls this change is intended to remove. The Gateway exposes this function process-wide to every logs.tail client (src/gateway/server-methods/logs.ts:15), while each Logs page polls independently (ui/src/pages/logs/logs-page.tsx:36,83), so retain usable anchors for multiple cursor offsets rather than only the latest one.

AGENTS.md reference: AGENTS.md:L74-L74

Useful? React with 👍 / 👎.

Cache the PEM open/closed state at the last returned cursor per (file, dev, ino)
so incremental polls scan only new bytes instead of walking back to byte 0, and
restore default-pattern identity in redactSensitiveLines so the transport
redactor's prefilter applies again.

Refs #172507
@steipete
steipete force-pushed the fix/logs-tail-window-cost branch from 051ea25 to 9a3d765 Compare October 15, 2026 17:08
@steipete
steipete enabled auto-merge (squash) October 15, 2026 17:30
@steipete
steipete merged commit 1541902 into main Oct 15, 2026
128 checks passed
@steipete
steipete deleted the fix/logs-tail-window-cost branch October 15, 2026 17:36
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

RomneyDa pushed a commit that referenced this pull request Oct 16, 2026
Cache the PEM open/closed state at the last returned cursor per (file, dev, ino)
so incremental polls scan only new bytes instead of walking back to byte 0, and
restore default-pattern identity in redactSensitiveLines so the transport
redactor's prefilter applies again.

Refs #172507

(cherry picked from commit 1541902)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…w#172885)

Cache the PEM open/closed state at the last returned cursor per (file, dev, ino)
so incremental polls scan only new bytes instead of walking back to byte 0, and
restore default-pattern identity in redactSensitiveLines so the transport
redactor's prefilter applies again.

Refs openclaw#172507
RomneyDa pushed a commit that referenced this pull request Oct 27, 2026
Cache the PEM open/closed state at the last returned cursor per (file, dev, ino)
so incremental polls scan only new bytes instead of walking back to byte 0, and
restore default-pattern identity in redactSensitiveLines so the transport
redactor's prefilter applies again.

Refs #172507

(cherry picked from commit 1541902)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: M 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