Repository navigation
fix(update): batch the package integrity drift sweep - #169599
Tsuki-hash wants to merge 11 commits into
Conversation
`createPackageIntegrityReader`'s final drift sweep re-stat'ed every observed entry strictly one at a time. On a large global install that is tens of thousands of sequential syscalls: measured on a 612 MB / ~41,900-file install, one `rootEntry()` issued 89,405 lstat calls and the sweep alone accounted for roughly half of a ~9.7 s scan. Two consequences made `openclaw update` fail on such installs: - the walk stretched well past the point where a concurrent writer could change a timestamp, and the resulting `Package rollback verification timed out` aborted an otherwise healthy update; - the longer the sweep ran, the wider the window in which an unrelated process touching the package tree turned into `retained package tree changed` and a full rollback. Bound the sweep's concurrency instead. Every entry is still re-stat'ed and a change still refuses the tree — the syscall count is unchanged and the fingerprint is byte-identical — but the batches overlap, cutting the scan from ~9.7 s to ~6.1 s on the same install. Adds `src/infra/package-update-integrity.test.ts` covering the sweep's drift refusals (mutation and disappearance after admission), budget reporting, the resource-error/mismatch distinction, and fingerprint stability.
|
🦞👀 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c9d064357f
ℹ️ 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".
Review of the previous commit found two defects in the batched sweep and its tests. This addresses both. The blanket `catch` turned every rejection into drift evidence, including `PackageIntegrityTimeoutError` and `PackageIntegrityLimitError`. That matters because `readBaseline` and activation preparation only take their directory-identity fallback for `isPackageIntegrityResourceError`: a budget exhausted inside the sweep would have been reported as `Package rollback tree changed during verification`, aborting an update that the unbatched code degraded to an incomplete-fingerprint warning. On a large or slow install that is exactly the failure this branch is meant to reduce, so the batching would have introduced a new way to hit it. `sweepForDrift` now separates the two outcomes per entry and prefers drift when a batch proves both: the tree really did change, and the operator needs the specific refusal over a resource note. The timeout tests also relied on a real 1 ms wall-clock budget, which the repository's test policy forbids and which never reached the new code path anyway. They are replaced by direct unit tests of `sweepForDrift`, which cover its classification contract deterministically: unchanged, changed, vanished, resource rethrow, and drift-beats-resource. `sweepForDrift` is exported for that purpose. Local: `package-update-swap.integrity.test.ts`, `package-update-integrity-hasher.test.ts`, `package-update-integrity.test.ts` — 41/41 passing. Measured on the same 612 MB / 41,895-file install: 89,405 lstat calls before and after, fingerprint byte-identical, 7.4 s → 5.3 s.
|
Codex review: needs maintainer review before merge. What this changesThis PR batches package-integrity metadata rechecks in groups of up to 32 entries. Example: Verify the contributor’s 612 MB npm-global installation containing 41,895 files.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR provides a useful, measured update-performance improvement that current main still lacks, with no remaining actionable correctness or security finding. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe installed updater’s integrity reader observes package files and metadata, then returns fingerprints or refusals to package activation and rollback owners. flowchart TD
A[Installed update command] --> B[Package swap owner]
B --> C[Integrity reader]
C --> D[Tree walk and file hashing]
D --> E[Batched metadata recheck]
E --> F[Fingerprint or refusal]
F --> B
Technical reviewBest possible solution: Retain the bounded scheduling improvement and existing integrity checks, with focused reader-boundary coverage. Do we have a high-confidence way to reproduce the issue? Current-main source demonstrates the sequential metadata sweep, and contributor measurements quantify its cost; no target code was executed during this review. Is this the best way to solve the issue? Bounded batching is a focused solution that preserves observations, digest encoding, deadlines, and the caller’s resource fallback. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against fada6e0812ce. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +36, Tests +243. Total +279 across 3 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
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 (10 earlier review cycles; latest 8 shown)
Reviewed October 13, 2026, 5:18 AM ET / 09:18 UTC (Revision 11). |
|
Both findings addressed in b9d0330. Thanks — the first was a real bug I introduced. P1 — Preserve deadline errors in the drift sweep Confirmed and fixed. The blanket
P1 — Drive timeout tests with a controlled clock Confirmed. The 1 ms wall-clock budgets violated the no-real-timers policy and, as you note, were consumed during traversal or hashing before the sweep — so they passed without exercising the new catch at all. I tried the fake-clock route first and it does not work here: the reader bounds its syscalls with The new tests are deterministic and cover exactly the boundary you flagged:
Verification
One thing I should flag rather than bury: I could not run |
`package-update-swap.bounds.test.ts`'s "cache during scan" case replaced the retained package's hidden lockfile when it saw the parent directory's second lstat. That counted on the drift sweep re-stat'ing entries strictly one at a time. With the sweep batched, sibling entries are re-stat'ed concurrently, so the mutation could land after the cache entry had already been observed — the sweep then saw a consistent tree, rollback was allowed to replace the launcher, and the case failed with `expected 'old launcher\n' to be 'candidate launcher\n'`. Anchor the injection on the first hashed file instead. The walk has admitted every entry by the time hashing starts and the sweep has not re-stat'ed anything yet, so this is the same point under either schedule and the entry recheck is still what catches the substitution. Local: 61/61 passing across `package-update-swap.bounds.test.ts`, `package-update-swap.integrity.test.ts`, `package-update-integrity-hasher.test.ts` and `package-update-integrity.test.ts`.
|
Addressed. Note that this review was run against 1. Preserve resource errors from the final drift sweep (P1) — fixed in
2. Replace one-millisecond timeout tests (P2) — fixed in I could not use the controlled-clock route you suggest: the reader bounds its syscalls with Instead
3. Adapt the existing drift injection to concurrent metadata reads (P2) — this one was real, and CI was right. I reproduced it locally before reading this review: The injection fired on the parent directory's second Fixed in 4. Explain the original intent of the final sweep — agreed, and this is the part I should have written down from the start. The sweep exists because 5. Real behavior proof — added to the PR body under
|
oxlint import(no-duplicates): \x27vitest\x27 was imported twice in the test file. oxlint on the three changed files: 0 warnings, 0 errors.
check-test-types-core-3 failed with TS2345: the observe() helper annotated its stats as Awaited<ReturnType<typeof fs.lstat>>, which resolves to the BigIntStats | Stats union, while sweepForDrift requires BigIntStats. Verified against test/tsconfig/tsconfig.core.test.services.json (the config that failed) plus oxlint: 0 errors. Tests: 61/61.
check-lint-core-4 failed with typescript(await-thenable) at package-update-integrity.test.ts:24: the temp-dir tracker hands back a () => void cleanup, so awaiting it is a no-op the rule rejects. Verified: oxlint 0/0 on the three changed files, tsc clean against test/tsconfig/tsconfig.core.test.services.json, tests 61/61.
|
@clawsweeper re-review The review lease issued at 06:32Z expired at 07:13Z without a durable review comment, so this looks like a lost worker rather than a completed review. Head is now
CI is green: 57 passing, 0 failing, 0 pending. The PR body now carries the |
|
🦞👀 Re-review progress:
|
Two review findings on the previous revision. Both are about tests that passed for the wrong reason. The "cache during scan" case injected its mutation on the first hashed file. The fixture visits dist before node_modules, so that callback ran before the walk had stat'ed the cache at all: the walk then recorded the symlink as the entry's original state, the sweep saw a consistent tree, and the case passed on a fingerprint difference rather than on drift detection. It would have passed with the sweep removed. Re-anchor it on the sweep's own re-stat. The walk stats each path exactly once, so a second lstat of the cache is unambiguously the sweep, and mutating before that call makes the sweep observe the substitution. That holds whether the sweep runs sequentially or in batches — mutating after it would let the sweep record the entry as unchanged. The remaining timeout case also used a real one-millisecond deadline, which assumed traversal would outlast it and could expire before reaching the sweep. Replace it with a controlled clock: performance.now is stubbed and advanced from inside the sweep's read, so the budget is spent at the chosen point instead of depending on host scheduling. This follows the pattern the bounds suite already uses. Both cases were then verified by counterexample: with the sweep neutered they fail, and with it intact they pass.
|
Both findings addressed in 1. Remaining real one-millisecond deadlineYou were right that I'd only replaced two of the three. Replaced with a controlled clock, following the bounds-suite pattern you pointed at: 2. Mutating the cache before its original observation is admittedThis was the more serious of the two, and your diagnosis was exactly right. My previous anchor fired on the first hashed file, which happens while the fixture is still walking Re-anchored on the sweep's own re-stat: the walk stats each path exactly once, so a second Counterexample verification for bothSince "the test passes" is what misled me the first time, I verified both cases by breaking the code they're supposed to cover. With and with the sweep intact, the same suites are green:
One caveat, unchanged from before: |
… sweep Two follow-ups on the previous revision. Restore the `BigIntStats` type import that the rewrite dropped while `observe()` still annotates its entries with it. The type is module-scoped rather than global, so the services test typecheck saw an unresolved name. Import it with a top-level type qualifier so nothing is emitted at runtime. The controlled-clock case also burned the budget at the wrong read. Its predicate treated any second lstat of a path as the sweep, but `rootEntry` stats the root and the tree's initial visit stats it again, so the clock advanced during traversal and the deadline expired before the sweep ran. Exclude the root, which makes the first repeat an actual sweep read. Verified by instrumenting the predicate: every burned read is now lstat call 13, which is the first read past the walk's 12, and all 12 entries are still reached — the batch covers each of them.
|
Both addressed in 1. Restored the
|
|
Merged The 31 commits that landed upstream touch Re-verified on the merged head rather than assuming the merge was inert: The unchanged caveat from before still applies: No functional change in this push — it is the upstream sync only. Still holding for a maintainer's look. |
|
Thank you @Tsuki-hash! We re-implemented this fix in #179797, which landed with you credited as co-author. Closing this one as superseded. |
The integrity reader's final drift sweep read files one at a time. It now batches 32 reads while preserving traversal-order errors; fingerprints are identical and measured sweep latency fell 59%. Supersedes #169599, thanks @Tsuki-hash. Co-authored-by: Aaron08140 <[email protected]>
The integrity reader's final drift sweep read files one at a time. It now batches 32 reads while preserving traversal-order errors; fingerprints are identical and measured sweep latency fell 59%. Supersedes openclaw#169599, thanks @Tsuki-hash. Co-authored-by: Aaron08140 <[email protected]>
What Problem This Solves
createPackageIntegrityReader's final drift sweep re-stat'ed every observed entry strictly one at a time. On a large global install that is tens of thousands of sequential syscalls, and it is most of the cost of verifying a package.Measured on a real 2026.10.1 install (612 MB, 41,895 files, 2,807 dirs, WSL2/ext4, Node 24.21.0, npm global at
~/.npm-global):rootEntry()lstat callsrootEntry()wall time859d7f4e7b8efff0…859d7f4e7b8efff0…(identical)The syscall count and the fingerprint are deliberately unchanged — this is a pure scheduling fix, not a reduction in what is verified.
Why it matters beyond the wall time: an update performs three full scans of the same package tree (
baseline,launcher, andverifyNpmRecovery). The longer each takes, the longer the run holds the tree under observation, and the more likely an unrelated process touching the package tree turns intoPackage rollback verification failed: retained package tree changedand a clean rollback — the failure signature tracked in #156112.Evidence
End-to-end update through the shipped command
Built this branch from source, installed it as the active 2026.10.2 (verified
DRIFT_SWEEP_CONCURRENCYpresent in the livedist/), then ran a real update with the patched code driving every phase:Result:
2026.10.2 (patched)→2026.10.5-beta.2, Gateway active,openclaw healthreportingevent loop: ok, andopenclaw update repairafterwards reportingintegrityDrifts: []— no drift was falsely detected across the three full scans of a 613 MB / ~42,000-file tree.Settings and data intact: the agent database snapshots above are from the live state dir, all four configured providers (deepseek, kimi, qwen, xiaomi) converged, and
doctor --lintreports only a pre-existingconfig.plaintext_secretswarning unrelated to this change.One caveat, stated plainly: my shell's command timeout sent SIGHUP into the update while it was activating, so the tail of that run was interrupted and finished via
openclaw update repair. That was my operational error, not a failure of the patch — and it usefully exercised the repair path, which completed with no integrity drift.Focused tests
pnpm test src/infra/package-update-swap.bounds.test.ts src/infra/package-update-swap.integrity.test.ts src/infra/package-update-integrity-hasher.test.ts src/infra/package-update-integrity.test.ts --maxWorkers=1tsc --noEmitreports no errors for the changed files, verified againsttest/tsconfig/tsconfig.core.test.services.json(the config CI uses for test types).Isolated measurement
Both readers invoked with a 20-minute budget against the live install:
Same syscall count, same fingerprint, 2.2 s faster on one scan.
Drift detection is not weakened
The sweep still re-stats every entry and still refuses a changed, vanished, or unreachable one.
package-update-swap.integrity.test.ts(which covers the swap's own drift refusals) passes unchanged, andpackage-update-swap.bounds.test.ts'scache during scancase — which mutates the tree mid-scan and asserts the refusal — passes after being re-anchored on a point that is unambiguous under either schedule.What I could not run:
pnpm lintdoes not complete on this machine; the script scans the whole workspace and is OOM-killed here. I verified the three changed files withoxlintdirectly (0 warnings, 0 errors) and fixed the two lint findings CI raised against earlier revisions, but a full-repo lint is unverified.Notes for reviewers
DRIFT_SWEEP_CONCURRENCY = 32is a guess at a good default; happy to tune it.sweepForDriftis exported so its error-classification contract can be tested directly. Review feedback on the first commit found that a batched sweep can spend the reader's deadline inside the sweep, and that misclassifying that as drift would abort an update the unbatched code degraded to a warning — callers only take their directory-identity fallback forisPackageIntegrityResourceError. The helper now rethrows resource errors and prefers drift when a batch proves both.