Repository navigation
perf(usage): reduce duplicate bookkeeping during session backfill - #183186
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis PR removes duplicate deferred-repair tracking and adds repeatable usage-refresh performance measurements. Example: Cold backfill of 10,000 synthetic sessions.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR is a useful, maintainer-approved simplification with no actionable correctness findings; the earlier conflict is resolved, and normal exact-head CI remains. Priority: P3 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe usage-refresh scheduler receives transcript publications and repair requests, dispatches bounded work to existing workers, and exposes refreshed usage summaries to Gateway reports. flowchart LR
A[Transcript publications] --> B[Usage refresh queue]
C[Usage report reads] --> B
B --> D[Usage workers]
D --> E[Usage projections]
D --> B
E --> F[Gateway usage reports]
Technical reviewBest possible solution: Retain the existing queue as the sole deferred-work tracker and land the narrow deletion through the normal CI gates. Do we have a high-confidence way to reproduce the issue? Current-main source independently shows duplicate deferred-key bookkeeping; the supplied cold-worker measurements exercise its allocation cost, and no target code was executed during this review. Is this the best way to solve the issue? The smallest complete production change is the proposed queue lookup: existing enqueue operations already preserve canonical repair keys, while identity, retry, alias, and cancellation handling remain intact. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 385f80ac5fc9. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -2, Other +200. Total +198 across 3 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 25, 2026, 2:52 AM ET / 06:52 UTC (Revision 2). |
Use canonical repair keys already recorded in the pending session queue instead of retaining a second set of every deferred transcript identifier. Preserve alias, retry, publication and cancellation handling without changing token or cost totals. Production code shrinks by two lines. Extend the synthetic memory-soak harness with search and usage-report churn, keeping list RPC timing separate from its preceding label update. Validation: 22 focused refresh tests pass on base and candidate; changed files pass formatting and lint. Independent review is clean after the configured autoreview route proved unavailable.
10dbfef to
5bf8e47
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Replace the deprecated ambient loadConfig call introduced by #183186 with the awaited async config reader used by sibling benchmarks. Load the synthetic run config before profiling begins. Proof: deprecated-internal-config-api contract test fails on base and passes with this change (1 test). Focused Oxlint typechecking, format check, git diff --check, and Codex review pass. The scripts-wide typecheck cannot start with the external dependency layout.
…enclaw#183186) * perf(usage): avoid duplicate backfill remainder tracking Use canonical repair keys already recorded in the pending session queue instead of retaining a second set of every deferred transcript identifier. Preserve alias, retry, publication and cancellation handling without changing token or cost totals. Production code shrinks by two lines. Extend the synthetic memory-soak harness with search and usage-report churn, keeping list RPC timing separate from its preceding label update. Validation: 22 focused refresh tests pass on base and candidate; changed files pass formatting and lint. Independent review is clean after the configured autoreview route proved unavailable. * test(perf): measure cold session usage refresh allocation
Replace the deprecated ambient loadConfig call introduced by openclaw#183186 with the awaited async config reader used by sibling benchmarks. Load the synthetic run config before profiling begins. Proof: deprecated-internal-config-api contract test fails on base and passes with this change (1 test). Focused Oxlint typechecking, format check, git diff --check, and Codex review pass. The scripts-wide typecheck cannot start with the external dependency layout.
What Problem This Solves
Cold session-usage backfill duplicates every deferred transcript identifier in a temporary set alongside its pending queue.
User Impact
This removes a small amount of backfill allocation without changing token counts, cost arithmetic, refresh batching, or usage-report behavior.
Why This Change Was Made
The existing pending queue already records the canonical key of each deferred repair. Cleanup can consult that queue directly, so the extra remainder set and its insertions disappear. Newer repair rows retain their identity check; aliases, busy retries, and cancellation keep their existing handling. A repair whose key receives another publication remains until that queued work settles.
Refresh already uses exact transcript publications and worker checkpoints to skip unchanged sessions. Publications defer while their agent is busy and normally coalesce until a 30-second idle gap; eligible pending publications have a five-minute coalescing cap. On-demand reads flush their required work. Backfill runs in batches of 50 sessions, with contention retries backing off from 50 ms to 5 s. Startup and explicit broad invalidations still perform discovery; this change adds no cache, revision store, schema, or configuration.
Production delta: +1/-3 lines, net -2. The measurement harness also gains optional usage RPC polling and reuses its existing search/filter churn in memory-soak runs. Benchmark tooling accompanies the deletion to run the requested usage/search stress and capture cold owner allocation through real workers. Usage instructions are in the script headers.
Evidence
node scripts/run-vitest.mjs src/infra/session-cost-usage-refresh.test.ts --maxWorkers=1: 22 passed on baseline and candidate, including deferred repairs, aliases, bounded batches, busy retries, concurrent appends, and cancellation.pnpm tsgo:scriptspassed. Runtime builds passed on both revisions. The export-collision guard and both import-closure files passed (22 tests).5bf8e4784ab1bc709a4b0105bd110a6ddcf62305(the earlier measured revisions had 22).Matched Gateway stress
Both sides of the two completed pairs finished 40 cohorts / 320 turns with fresh identically generated state. Columns show baseline → candidate. Timing and GC are untraced; allocation sampling is reported separately below.
List p95 is eligible; list p99 is context only at fewer than 1,000 observations per side. Final memory follows forced GC outside the untraced window. Continuous background RPCs mean equal turn counts do not guarantee identical total work; CPU/turn and GC/turn include that background work.
Per-kind GC, RPC work, and synchronization
Major and incremental pause percentiles are contextual where their counts fall below the 200/1,000 thresholds; total GC remains eligible.
Pair 1: post-warmup releases differed by 0 ms; finish times differed by 8.71 s (0.41% solo tail).
Pair 2: post-warmup releases differed by 2 ms; finish times differed by 10.79 s (0.68% solo tail).
Successful-pair launch order was baseline/candidate, then candidate/baseline. The failed third attempt returned to baseline/candidate. The second setup originally failed before barrier release because another lane occupied its mock port; both sides were stopped and fresh fixtures used on free ports. No measured pair was discarded. The shared Mac has no supported CPU-affinity control: concurrent sides share scheduler contention.
Across the two completed pairs, GC/min improved 5.69% and GC/turn 6.21% as means of per-pair percentage changes; list p95 improved 18.05%. CPU/turn was approximately neutral (−0.72%). These are composite-workload observations, not isolated attribution. Loop p99 had mixed signs (−6.685 ms, +1.114 ms). Peak heap also had mixed signs: −22.43% then +784.42 MiB / +51.50%; mean paired peak heap increased 14.53%, and peak RSS increased 1.91%. Post-GC heap equality does not cancel the transient peak. The extra attempt and post-diagnosis follow-up failed as described below. The maintainer explicitly accepts the completed pairs under the deletion gate and classifies the later failures reproduced on both revisions as shared admission failures, not candidate regressions. The signed absolute delta divided by the mean baseline gives GC/min −5.70%, GC/turn −6.99%, CPU/turn −0.71%, loop p99 −2.62%, list p95 −20.45%, peak heap +14.42%, and peak RSS +2.25%; those are the predeclared mixed-sign gate calculations, distinct from means of per-pair percentages.
Reliability investigation
A diagnostic-only preload recorded the actual worker
admit(false)decision, without evaluating lazy inputs early or changing limits/errors. Both revisions failedsessions.usagein the usage-read singleton pool:There was no shared-compute admission on this pool. Follow-up owners:
src/gateway/server-methods/usage-session-loading.ts:150constructs the remainder batch;src/infra/session-cost-usage-worker-runtime.ts:340accounts for input bytes;packages/worker-runtime/src/worker-task-admission.ts:34rejects admission. Overview summary loading batches 256 sessions first, then the entire remainder; queued large reads can exhaust the byte budget even below the task-count cap. This demonstrates a pre-existing failure mode, not equal failure probability or exact retrospective attribution of the original uninstrumented candidate failure. Diagnostic timings do not contribute to performance acceptance.The independent reviewer accepted one final bounded untraced comparison after this diagnosis: fresh fixtures, unchanged 64-client workload and limits, synchronized warm start, a target of 40 cohorts / 320 turns. It failed on both revisions with the same RPC error after seven/eight completed cohorts. The predeclared stopping rule ended further measurement, with no replacement run. The maintainer subsequently accepted the completed pairs for this production deletion. Every completed pair and all failures remain in this record. This is a demonstrated baseline failure mode, but these runs cannot establish equal failure probability or a reliability non-regression. The usage-read admission issue is a separate follow-up; this PR changes refresh bookkeeping only.
Initial sequential measurements
Final memory is sampled after the harness's forced GC, outside the untraced diagnostics window. Untraced minor GC: 5,112 collections / 36.498 s → 4,963 / 48.765 s; major GC: 90 / 4.961 s → 87 / 6.411 s; incremental GC: 90 / 0.225 s → 87 / 0.302 s. Minor pause p95/p99: 24.830/62.718 → 39.934/77.310 ms; major p95/p99: 107.006/264.190 → 155.646/169.982 ms (context only at these tail sample counts).
The candidate took 23.1% longer with continuous polling. Equal turn counts therefore do not mean equal total RPC work. CPU/turn improved 5.1%, but GC increased 118 ms/min and 43.1 ms/turn, and eligible list p95 increased 289 ms. Lower allocation rate also coincided with slightly higher allocation per turn. These adverse measurements are retained, not dismissed as noise or hidden by a different normalizer.
Original follow-up declared before results (two completed pairs, one failed extra attempt, then the separately documented post-diagnosis failure): two concurrent untraced A/B pairs with fresh identically generated fixtures, immutable built runtimes, the same 40-cohort workload, and a synchronized post-warmup start. Swap launch order and ports for pair two. No owned builds, tests, or fixture generation during measurement. Report both GC/min and GC/turn as gates, per-method RPC counts, throughput, eligible tails, both maxima, and memory. Apply the paired relative rules and both absolute GC floors; one improved normalizer cannot cancel an adverse one. This shared Mac cannot pin CPU placement, so concurrency can couple resource contention and create unequal solo tails; those limitations remain explicit. A GC-based rejection requires the declared same-layout A/A controls; those controls do not waive a request failure. No allocation tracing is used for these timing/GC gates.
The benchmark uses synthetic 10,000-session state, 12,000 settled runs, 40 synthetic plugins, 64 WebSocket clients, eight concurrent mock-provider turns with tool calls, and sidebar/list/search/dashboard/usage churn. Timing and allocation are separate passes; traced GC is not used for timing acceptance. The shared Mac's host-sensitive timings are contextual, not a claim of isolated attribution.
Reproduce the measurements
The cold refresh uses
scripts/perf/session-cost-refresh-measure.tswith separate fresh fixtures generated byteam-shape-fixture.ts: 10,000 sessions, zero runs/projects/cron/approvals, 1 MiB transcripts, seed 967, fixed--now 1792886400000. The probe's header documents invocation. This additional tooling captures the real cold owner, because warm Gateway sampling starts after its initial backlog was queued.The Gateway fixtures contain 10,000 sessions, 12,000 settled runs, 100 cron jobs, 12 projects, and 64 MiB transcripts, with the same seed/time. Each side uses its own state directory and loopback ports. The timing command is:
The allocation pass uses the same side's post-timing state, omits
--soak-rounds, and adds--allocations --heap-sampling-interval 65536. Both passes run at least ten minutes. Main-isolate allocation sampling and GC tracing stay separate from untraced latency/GC measurements. No production Gateway was loaded or changed.Acceptance declared before measurement: remove duplicate remainder bookkeeping with unchanged usage and repair contracts; small or neutral full-Gateway results are acceptable for net production deletion. Treat shared-host timings and under-sampled tails as context; investigate controlled material regressions, not tiny percentages on noisy baselines.
Both built artifacts use base
a59c2197e14899488de553be245685a52a3d716a; the candidate adds this PR's changes. Upstream changes to unrelated Gateway paths mean these absolute stress figures must not be represented as measurements of the later rebased head. PR CI validates that final head.Current disposition: accepted for landing by the maintainer. The benchmark-harness conflict has been resolved while preserving upstream preload, cron, worktree, and filtered-page behavior. The prior head passed CI; exact-head CI is required after this rebase. The overload path remains unchanged on inspected main
8eb642293ef9917e50b504911ee93de254db2dc5; no upstream fix is claimed.