Skip to content

Fix: Replay the usage ring beside live traffic, not before it - #1519

Merged
huang195 merged 4 commits into
rossoctl:mainfrom
huang195:fix/usage-replay-background
Oct 27, 2026
Merged

huang195 merged 4 commits into
rossoctl:mainfrom
huang195:fix/usage-replay-background

Conversation

@huang195

@huang195 huang195 commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Problem

The startup usage replay ran before any listener, so /healthz waited for it.

  • It has been growing: 0.15s–4.55s over 20 restarts from 10-10 to 10-23.
  • On 2026-10-27 it hit its 5s budget on both restarts. Launch to healthy took 13.6s and 6.4s.
  • agentop setup waits 15s for health. It ran out, so make dev-install rolled back.

Two things make it slow, measured on a copy of a real archive:

  • launchd's ProcessType=Background: 1.1s at normal priority, 3.1–4.1s under taskpolicy -b.
  • It decodes content it then discards: JSON decoding is ~95% of the read; messages and tool results are 75% of each event's bytes, and ReplayCopy drops them straight away.

Fix

Run the replay beside live traffic, not before it.

  • archive.ReplaySources takes the segment list before any listener starts. A process never appends to a segment it did not open, so nothing live traffic records is read back and counted twice.
  • usage.Aggregator.BeginReplay returns a private ring to feed. The time-ordered feed then keeps eviction and request pairing as they were.
  • FinishReplay merges it with the existing mergeRing. It first applies every clear, delete and rename the live ring took meanwhile, so an erased session stays erased.
  • The budget is 60s now, since it no longer delays readiness. Still all or nothing.

User-visible change: for a few seconds after a restart, LAST 1H counts only live traffic, then fills in.

Verification

Scratch Cortex on 49600–49604, a copy of a real archive, under taskpolicy -b:

Before After
launch → /healthz 6.4s / 13.6s (replay timed out) 0.47s
LAST 1H empty 0 at health, 525 requests 3.9s later

New tests:

  • Live traffic recorded during the replay counts once.
  • A delete, clear or rename during the replay holds after the merge.
  • The merge sums in every ring and keeps the session cap.
  • startUsageReplay returns at once and merges later.

The first two were checked by mutation: each fails when the guard it covers is removed. core, cmd/cortex and cmd/agentop pass with -race; vet and gofmt are clean.

Not in this PR

  • Dropping ProcessType=Background from the plist. It throttles every request, not only startup. Commit 0d936d2 added it with no stated reason.
  • A replay-only decode that skips message bodies, about 3–4× faster. Not needed once the replay no longer blocks readiness.
  • The archive open itself still blocks startup. It took 6s once on 10-27, and 0.4–1.5s on every other restart.

Assisted-By: Claude (Anthropic AI) [email protected]

Summary by CodeRabbit

  • Performance
    • The proxy now starts serving without waiting for session archive replay to finish. Replay runs alongside live traffic, covering the previous six hours, with a one-minute time limit.
  • Accuracy
    • Replayed usage is merged with live activity while preserving clears, deletions, and renames made during replay.
    • If replay exceeds its time limit or encounters an error, usage windows include traffic recorded since startup.

The startup replay of the session archive into the usage ring ran
before any listener, so /healthz waited for it — up to its 5s budget.
On a loaded laptop it reached that budget on both restarts of
2026-10-27, and agentop setup's 15s health wait expired and rolled the
install back.

The replay now starts before the listeners and finishes beside them:

- archive.ReplaySources takes the segment list before any listener
  starts. A process never appends to a segment it did not open, so
  nothing live traffic records is read back and counted twice.
- usage.Aggregator.BeginReplay hands out a private ring to feed, so
  the time-ordered feed keeps eviction and request pairing as they were.
- FinishReplay merges it with mergeRing, first applying every clear,
  delete and rename the live ring took meanwhile, so an erased session
  does not come back.

The budget is 60s now: it no longer delays readiness.

Measured on a copy of a real archive under taskpolicy -b (launchd's
Background ProcessType): healthy after 0.47s; the replay merged 3.9s
later with 525 requests in LAST 1H.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
@huang195
huang195 requested a review from a team as a code owner October 27, 2026 17:37
@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 1 minute.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: adc6f44e-8732-47c7-a592-163fd78fa4df
Commits

Reviewing files that changed from the base of the PR and between 09a4aa0 and e659f34.

Files selected for processing: 3
  • cmd/cortex/archive_replay_test.go
  • core/session/archive/replay.go
  • docs/laptop-service.md

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d3d97bd4-d391-4cc2-8535-c3bc3b0ab06c
Commits

Reviewing files that changed from the base of the PR and between 4a9d05a and 09a4aa0.

Files selected for processing: 15
  • CLAUDE.md
  • cmd/agentop/local_endpoint.go
  • cmd/agentop/local_endpoint_test.go
  • cmd/cortex/archive.go
  • cmd/cortex/archive_replay_test.go
  • cmd/cortex/main.go
  • core/cost/usage/cleared.go
  • core/cost/usage/deleted.go
  • core/cost/usage/rekey.go
  • core/cost/usage/replay.go
  • core/cost/usage/replay_test.go
  • core/cost/usage/usage.go
  • core/session/archive/replay.go
  • core/session/archive/replay_bench_test.go
  • docs/laptop-service.md

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Walkthrough

Archive usage replay now starts alongside live traffic instead of delaying listener startup. It reads a snapshot of archive segments into a private usage ring, then merges the results while preserving live clears, deletes, and renames. The replay budget is 60 seconds.

Changes: Archive usage replay

Layer / File(s) Summary
Snapshot and read archive sources
core/session/archive/replay.go, core/session/archive/replay_bench_test.go
ReplaySet snapshots eligible segments and reads events from that snapshot. ReplaySince delegates to these methods.
Track and merge private usage replay
core/cost/usage/*.go, cmd/cortex/archive_replay_test.go
The aggregator records live clears, deletes, and renames during replay. On completion, it merges replayed totals and session rings into live usage while enforcing the session cap. Tests cover the merge and concurrent live changes.
Run replay alongside startup traffic
cmd/cortex/archive.go, cmd/cortex/main.go, cmd/cortex/archive_replay_test.go, cmd/agentop/local_endpoint.go, cmd/agentop/local_endpoint_test.go, CLAUDE.md, docs/laptop-service.md
Startup snapshots archive sources and runs replay asynchronously with a 60-second budget. It merges on success and abandons replay on error. Tests and documentation describe the updated flow.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Cortex as cmd/cortex
  participant Archive
  participant ReplaySet
  participant Aggregator
  Cortex->>Archive: ReplaySources(last six hours)
  Cortex->>Aggregator: BeginReplay()
  Cortex->>ReplaySet: Read(ctx, callback)
  Cortex->>Aggregator: FinishReplay(private ring) on success
Loading

Possibly related issues

  • Issue 1497: The change keeps replayed usage consistent with live clears, deletes, renames, and concurrent traffic.
  • Issue 964: The change replays archived usage after restart and merges it with live usage.

Suggested reviewers: cwiklik, esnible, alan-cha

Merge Risk: Low · previous review 09a4a

The change is mergeable with awareness that a session renamed during replay may temporarily show too little historical usage.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: running usage replay alongside live traffic instead of delaying startup.
Docstring Coverage Passed Docstring coverage is 92.86% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviv…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 92.86% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 14 functions across 13 files. (2 skipped: 2 unsupported.)

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Fixes review: the double-count test used a session with no archived segment, so it passed even if the archive reopened an old segment
Fixes review: Read's comment said a segment erased mid-read lost nothing, but the totals an erase keeps come up short; now a shortcut comment naming that limit
Files:
- cmd/cortex/archive_replay_test.go
- core/session/archive/replay.go

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Fixes review: laptop-service.md's restart paragraph said the proxy replays the archive (up to 5s) before it serves, which the background replay made false
Files:
- docs/laptop-service.md

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Fixes review: the rewritten restart line ran past the paragraph's wrap
Files:
- docs/laptop-service.md

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>

@evaline-ju evaline-ju 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.

Moves the startup usage-ring replay off the readiness path. Correctness hinges on three things: segment list is taken before any listener starts; the replay feeds a private aggregator; the live aggregator logs clears, deletes and renames until FinishReplay applies them before merging.

Independent verification:

  • Mutation check: stubbed out FinishReplay's op-replay loop → TestStartUsageReplay_AnEraseOrRenameMeanwhileHolds fails on all three subtests (delete/clear/rename) as the PR body claims. Restored, passes.
  • Tried a second mutation (moving set := arch.ReplaySources(...) to after store.Append + store.Close) and the test still passed — suggesting the archive's publish/close timing happens to leave the live turn out of the index at that moment too, so the test's safety margin is wider than its comment ("the set must not") implies. Not a bug.

Diff is well-scoped, the replaying/replayOps field pair is written only under a.mu, and the user-visible change (empty-then-fills LAST 1H for a few seconds) is called out in docs.

Assisted-By: Claude (Anthropic AI) [email protected]

@huang195
huang195 merged commit 5fc927d into rossoctl:main Oct 27, 2026
29 checks passed
@huang195
huang195 deleted the fix/usage-replay-background branch October 27, 2026 18:58
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants