Skip to content

fix(update): batch the package integrity drift sweep - #169599

Closed
Tsuki-hash wants to merge 11 commits into
openclaw:mainfrom
Tsuki-hash:fix/package-integrity-drift-sweep-batching
Closed

Tsuki-hash wants to merge 11 commits into
openclaw:mainfrom
Tsuki-hash:fix/package-integrity-drift-sweep-batching

Conversation

@Tsuki-hash

@Tsuki-hash Tsuki-hash commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

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):

before after
rootEntry() lstat calls 89,405 89,405 (unchanged)
rootEntry() wall time ~9.7 s ~5.3 s (-45%)
fingerprint 859d7f4e7b8efff0… 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, and verifyNpmRecovery). 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 into Package rollback verification failed: retained package tree changed and 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_CONCURRENCY present in the live dist/), then ran a real update with the patched code driving every phase:

$ openclaw update --yes --tag beta
candidate-state-snapshot: shared database snapshot ... 1662/1662 pages, 0.063 seconds
candidate-state-snapshot: agent database snapshot ... 2205/2205 pages, 0.147 seconds
candidate-doctor:        doctor --fix --non-interactive --no-workspace-suggestions
candidate-doctor-lint:   doctor --lint --json --severity-min error
candidate-config:        config validate --json
candidate-plugins:       plugins list --json
candidate-recovery:      --check
candidate-gateway-startup: gateway run
candidate-state-cleanup: removed disposable temporary copy

Result: 2026.10.2 (patched) → 2026.10.5-beta.2, Gateway active, openclaw health reporting event loop: ok, and openclaw update repair afterwards reporting integrityDrifts: [] — 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 --lint reports only a pre-existing config.plaintext_secrets warning 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=1

Test Files  4 passed (4)
     Tests  61 passed (61)

tsc --noEmit reports no errors for the changed files, verified against test/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:

{"label":"installed-2026.10.1 (before)","ok":true,"elapsedMs":7428,"lstatCalls":89405,"opendirCalls":2807,"version":"2026.10.1","digest":"859d7f4e7b8efff0"}
{"label":"patched-source (after)","ok":true,"elapsedMs":5258,"lstatCalls":89405,"opendirCalls":2807,"version":"2026.10.1","digest":"859d7f4e7b8efff0"}

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, and package-update-swap.bounds.test.ts's cache during scan case — 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 lint does not complete on this machine; the script scans the whole workspace and is OOM-killed here. I verified the three changed files with oxlint directly (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 = 32 is a guess at a good default; happy to tune it.
  • sweepForDrift is 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 for isPackageIntegrityResourceError. The helper now rethrows resource errors and prefers drift when a batch proves both.
  • A deeper fix — reusing the baseline fingerprint for the restore verification instead of scanning the same tree a third time — looked attractive but is a much larger change with real correctness implications, so I left it alone deliberately.

`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.
@clawsweeper

clawsweeper Bot commented Oct 12, 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 12, 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-12T04:16:53.658376Z c9d0643 PR opened
ℹ️ 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.

@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: 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".

Comment thread src/infra/package-update-integrity.ts Resolved
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 12, 2026
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.
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: The supplied reader measurement took 7,428 ms with 89,405 lstat calls.
  • After: The patched reader took 5,258 ms with the same call count and reported fingerprint.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, behavior-proven optimization with no actionable defect; redundant tests keep the patch below A.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied WSL2/ext4 evidence exercises the patched installed integrity reader through openclaw update and subsequent repair, reports a healthy Gateway, and pairs reader measurements with unchanged calls and fingerprints; the update’s tail was interrupted by shell SIGHUP, so uninterrupted completion is not claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large npm installations spend avoidable time verifying package metadata during updates.
Reason: The standalone scheduling improvement has measured value and preserves the verification contract; it does not claim to resolve the broader linked issue.

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
Reviewed head: b6d518750b279d42b9755299f78746ac33f195a7

Before merge

None.

Findings

None.

Tests

  • Low-value test src/infra/package-update-integrity.test.ts: Remove the duplicate unchanged, changed, and vanished-entry helper cases in favor of the existing reader-boundary cases, and keep the sweep private; retain distinct error-precedence coverage at that boundary.
  • Low-value test src/infra/package-update-integrity.test.ts: Remove the repeated-walk fingerprint self-comparison: both expected and actual values come from the same implementation, while the bounds suite already supplies an independent persisted-digest oracle.
Agent review details

How this fits together

The 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
Loading

Technical review

Best 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

  • Final retained-tree metadata sweep keeps the original intent (c8c03f9: Reject altered recovery material before restoration and verify package identity and contents rather than version alone.)
  • Serial sweep following worker hashing changes intended behavior with a stated reason (68c31fd: Parallelize file hashing while preserving ordered digests, metadata verification, limits, and refusal behavior.)
  • Mid-scan cache substitution test keeps the original intent (36bd762: Consolidate retained update coverage during the low-value test cleanup; this PR preserves the refusal assertion with a schedule-independent injection point.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced scheduling change: The pinned introduced diff replaces the sequential final sweep with bounded batches, retains the existing metadata comparison, and preserves resource-error classification. (src/infra/package-update-integrity.ts:196, b6d518750b27)
  • Current main still uses the sequential sweep: Current main awaits each observed entry’s lstat separately; the earlier worker-hashing optimization does not implement this scheduling change. (src/infra/package-update-integrity.ts:571, fada6e0812ce)
  • Existing resource fallback remains reachable: The swap owner accepts only classified resource failures for its directory-identity fallback; the new sweep rethrows those errors rather than converting them to drift. (src/infra/package-update-swap.ts:288, b6d518750b27)
  • Original verification purpose: fix(update): verify restored npm package tree #136329 introduced retained-tree verification to reject changed recovery material; its creation blob includes the final metadata sweep, which this PR preserves. (src/infra/package-update-integrity.ts:196, c8c03f90d734)
  • Supplied real update evidence: The complete PR body reports a patched installed driver running openclaw update, completing through repair after a shell SIGHUP, with healthy Gateway output and reader measurements showing unchanged syscall counts and fingerprints. (b6d518750b27)
  • Prior findings resolved: The head restores BigIntStats typing, advances the controlled clock on a non-root sweep read, and substitutes the hidden cache before its second lstat; the reviewed files are unchanged from the previous completed review. (src/infra/package-update-integrity.test.ts:174, b6d518750b27)

Likely related people:

  • Peter Steinberger: Raw commit 5cf24af adds src/infra/package-update-integrity.ts:130 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5cf24affb0c1; files: src/infra/package-update-integrity.ts)
  • Jason (Json): Raw commit c8c03f9 adds src/infra/package-update-integrity.ts:20 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c8c03f90d734; files: src/infra/package-update-integrity.ts)
  • Patrick Schiller: Raw commit d5c2462 adds src/infra/package-update-integrity.ts:585 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: d5c246249673; files: src/infra/package-update-integrity.ts)

PR surface

Source +36, Tests +243. Total +279 across 3 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 46 10 +36
Tests 2 248 5 +243
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 294 15 +279

Review metrics

Metric Value Why it matters
Production versus test LOC Production +46/-10; tests +248/-5 Bounded batching and error classification justify the production growth; duplicate helper tests and a fingerprint self-comparison inflate the test addition.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The measured optimization shortens package verification on large installations without establishing an urgent current-main regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Consolidate duplicate helper coverage at the reader boundary, keep the sweep private, and remove the fingerprint self-comparison.

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.

History

Review history (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-12T05:24:07.959Z sha 32d2479 :: needs real behavior proof before merge. :: [P2] Replace the remaining one-millisecond timeout test | [P2] Mutate the cache only after its observation is admitted
  • reviewed 2026-10-12T06:16:55.259Z sha b6b2c37 :: needs real behavior proof before merge. :: [P2] Replace the remaining one-millisecond timeout test | [P2] Mutate the cache only after its observation is admitted
  • reviewed 2026-10-12T07:19:43.407Z sha 869ffe7 :: needs real behavior proof before merge. :: [P2] Replace the remaining one-millisecond timeout test | [P2] Mutate the cache only after its observation is admitted
  • reviewed 2026-10-12T08:55:41.037Z sha 869ffe7 :: needs real behavior proof before merge. :: [P2] Replace the remaining one-millisecond timeout test | [P2] Mutate the cache only after its observation is admitted
  • reviewed 2026-10-13T02:06:49.264Z sha 869ffe7 :: needs changes before merge. :: [P2] Replace the remaining real one-millisecond deadline | [P2] Mutate the cache after its original observation is admitted
  • reviewed 2026-10-13T06:25:13.960Z sha 6f5f057 :: needs changes before merge. :: [P2] Restore the BigIntStats type import | [P2] Advance the controlled clock at an actual sweep read
  • reviewed 2026-10-13T06:48:33.559Z sha 680698c :: needs maintainer review before merge. :: none
  • reviewed 2026-10-13T08:20:19.022Z sha ff67c7b :: needs maintainer review before merge. :: none

Reviewed October 13, 2026, 5:18 AM ET / 09:18 UTC (Revision 11).

@Tsuki-hash

Copy link
Copy Markdown
Contributor Author

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 catch did swallow PackageIntegrityTimeoutError and PackageIntegrityLimitError into a generic drift refusal, and since readBaseline / activation preparation only take their identity fallback for isPackageIntegrityResourceError, a budget spent inside the sweep would abort the update instead of degrading to the incomplete-fingerprint warning. That is precisely the failure class this branch targets, so the batching would have added a new way to reach it.

sweepForDrift now classifies each entry separately and rethrows the resource error, while still preferring drift when a batch proves both.

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 performance.now(), which vi.useFakeTimers({ toFake: [...] }) does not cover (nothing in the repo fakes performance), and advancing it after the reader is constructed is too late because the deadline is captured at construction. Rather than mock performance.now globally — which the policy discourages and which made every unrelated test in the file fail — I exported sweepForDrift and tested its classification contract directly.

The new tests are deterministic and cover exactly the boundary you flagged:

  • unchanged tree → resolves
  • changed entry → drift refusal
  • vanished entry → drift refusal
  • PackageIntegrityTimeoutError / PackageIntegrityLimitError → rethrown as-is, not reclassified
  • drift and resource failure in the same batch → drift wins

Verification

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 (859d7f4e7b8efff0…), 7.4 s → 5.3 s.

One thing I should flag rather than bury: I could not run pnpm lint to completion on this machine (the script scans the whole workspace and gets OOM-killed), so lint is unverified. tsc --noEmit reports no errors for the two changed files.

`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`.
@Tsuki-hash

Copy link
Copy Markdown
Contributor Author

Addressed. Note that this review was run against d2ff5e51aafd, which is not on this branch — the head is now da833981. Items 1 and 2 were already fixed in b9d03300 before this review landed; item 3 was a genuine failure I reproduced locally and have now fixed.

1. Preserve resource errors from the final drift sweep (P1) — fixed in b9d03300, before this review.

sweepForDrift now classifies each entry separately: isPackageIntegrityResourceError rejections are collected and rethrown as-is, while drift still wins when a batch proves both. The old blanket catch {} really did turn a budget exhausted inside the sweep into Package rollback tree changed during verification, which would have aborted an update the unbatched code degraded to a warning — a regression I introduced with the batching, so thank you for catching it.

2. Replace one-millisecond timeout tests (P2) — fixed in b9d03300.

I could not use the controlled-clock route you suggest: the reader bounds its syscalls with performance.now(), which vi.useFakeTimers({ toFake: [...] }) does not cover (nothing in this repo fakes performance), and advancing it after construction is too late because the deadline is captured at construction. Mocking performance.now globally broke every other test in the file.

Instead sweepForDrift is exported and its classification contract is tested directly — deterministically, with no clock and no host-timing dependence:

  • unchanged tree → resolves
  • changed entry → drift refusal
  • vanished entry → drift refusal
  • PackageIntegrityTimeoutError / PackageIntegrityLimitError → rethrown, not reclassified
  • drift and resource failure in the same batch → drift wins

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:

× npm rollback content diagnostics > verifies retained bytes after cache during scan
  → expected 'old launcher\n' to be 'candidate launcher\n'

The injection fired on the parent directory's second lstat, which only identified a point in the sweep while the sweep was strictly sequential. Under batching the siblings 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 and rollback replaced the launcher.

Fixed in da833981 by anchoring the injection on the first hashed file: the walk has admitted every entry by the time hashing starts and the sweep has not re-stat'ed anything yet, so it is the same point under either schedule and the entry recheck is still what catches the substitution. The pre-restoration refusal assertion is retained.

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 hashFile only proves a file was stable across its own read. A file the walk stat'ed early and something else rewrote later is invisible to hashFile, and the sweep is the only pass that re-examines already-admitted entries. That is why I kept it and batched it rather than deleting it — my first attempt did delete it, and a test I wrote then proved the deletion lost real detection, which is what pushed me to the batching approach.

5. Real behavior proof — added to the PR body under ## Evidence: the focused test run (61/61), the before/after measurement with matching syscall counts and fingerprint, and an explicit statement of what I could not verify. pnpm lint does not complete on this machine (whole-workspace scan is OOM-killed), so lint is unverified and I have said so rather than implying it passed.

@clawsweeper re-review

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 12, 2026
Tsuki-hash and others added 4 commits October 12, 2026 13:17
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.
@Tsuki-hash

Copy link
Copy Markdown
Contributor Author

@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 96d0c2fb, which is 7 commits ahead of the d2ff5e51aafd revision the last completed review was run against. Since that review:

  • the P1 resource-error misclassification in the drift sweep is fixed (b9d03300)
  • the 1 ms wall-clock timeout tests are replaced with direct unit tests of sweepForDrift's classification contract (b9d03300)
  • the cache during scan drift injection is re-anchored so it is deterministic under batching, which fixes the package-update-swap.bounds.test.ts failure the review predicted (da833981)
  • the TS2345 and await-thenable CI failures are fixed (b6b2c37e, 96d0c2fb)

CI is green: 57 passing, 0 failing, 0 pending. The PR body now carries the What Problem This Solves and Evidence sections the context check requires.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 13, 2026
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.
@Tsuki-hash

Copy link
Copy Markdown
Contributor Author

Both findings addressed in 6f5f0578. Thanks for catching these — the second one in particular was a test that passed for the wrong reason.

1. Remaining real one-millisecond deadline

You were right that I'd only replaced two of the three. package-update-integrity.test.ts still had a case constructing the reader with a 1 ms budget and asserting the traversal outlasted it — host-scheduling dependent, and it could expire before ever reaching the sweep.

Replaced with a controlled clock, following the bounds-suite pattern you pointed at: performance.now is stubbed and advanced from inside the sweep's own lstat, so the budget is spent at the chosen point rather than whenever the host happens to schedule it. The case now asserts PackageIntegrityTimeoutError, that isPackageIntegrityResourceError holds for it, and — the part that matters for the batching — that the message is not the generic tree changed refusal.

2. Mutating the cache before its original observation is admitted

This 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 dist — before node_modules/.package-lock.json has been stat'ed at all. The walk then recorded the symlink as that entry's original state, the sweep saw a consistent tree, and the case passed on a fingerprint difference. It would have passed with the sweep deleted.

Re-anchored 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 substituting before that call makes the sweep observe the change. Mutating after it would let the sweep record the entry as unchanged — which is the failure mode you described. This holds whether the sweep runs sequentially or in batches, so the case now genuinely covers the recheck rather than the fixture's shape.

Counterexample verification for both

Since "the test passes" is what misled me the first time, I verified both cases by breaking the code they're supposed to cover. With sweepForDrift temporarily stubbed out:

Tests  7 failed | 20 passed (27)
  → promise resolved "undefined" instead of rejecting          (x3)
  → promise resolved "{ kind: 'directory', ... }" instead of rejecting  (x2)
  → expected +0 to be 1 // Object.is equality                  (cache during scan)

and with the sweep intact, the same suites are green:

Test Files  4 passed (4)
     Tests  61 passed (61)

oxlint on both changed files reports 0 warnings and 0 errors.

One caveat, unchanged from before: pnpm lint still does not complete on this machine — the script scans the whole workspace and gets OOM-killed here, so a full-repo lint remains unverified. CI's own lint job is green for these files.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 13, 2026
… 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.
@Tsuki-hash

Copy link
Copy Markdown
Contributor Author

Both addressed in 680698c8. And the second one was the same class of mistake I made before — a test that passes without testing what it claims — so I instrumented it rather than trusting the green result.

1. Restored the BigIntStats type import

Correct, and my fault for dropping it in the rewrite while observe() still annotated its entries with it. Restored as a top-level import type so nothing is emitted at runtime — oxlint flags the inline-specifier form as leaving a side-effect import behind, which is what it reported once I put it back.

2. Clock was burning during traversal, not in the sweep

Also correct. I instrumented the actual lstat sequence instead of reasoning about it, and rootEntry does stat the root twice before the tree's first visit — so my "second lstat of a path is the sweep" predicate fired on read 2 of 6 and the deadline expired mid-traversal. The case was passing for the wrong reason again.

The measured sequence for a small fixture is:

walk:  root  root  dist  a.js  b.js  package.json     (6 reads)
sweep: root  dist  a.js  b.js  package.json           (5 reads)

Excluding the root from the predicate makes the first repeat the sweep's own re-stat. Instrumenting the fixed predicate confirms it:

burned at call 13  dist
burned at call 13  file-0.js
burned at call 13  file-1.js
... (all 12 fixture entries)

Call 13 is the first read past the walk's 12, and every entry is still reached — so the batch covers each of them and the budget is spent on a genuine sweep read, not on traversal.

Verification

Test Files  4 passed (4)
     Tests  61 passed (61)

oxlint on both changed files: 0 warnings, 0 errors.

On the type error you flagged: I could not run the project typecheck — tsc --noEmit -p test/tsconfig/tsconfig.core.test.services.json is OOM-killed on this machine, which is also why the missing import slipped through in the first place. What I did instead was type the changed file directly with --strict --target es2023: 0 errors in package-update-integrity.test.ts. That run does emit ~13,900 unrelated errors from packages/agent-core under a bare command-line invocation, so it is not a substitute for CI's typecheck job — but the specific unresolved name you reported is gone, and CI's services test typecheck will be the real confirmation.

Counterexample from the previous commit still holds: with sweepForDrift stubbed out, these cases fail; with it intact they pass.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 13, 2026
@Tsuki-hash

Copy link
Copy Markdown
Contributor Author

Merged upstream/main into this branch to keep it current while it waits for a maintainer. New head is b6d518750, and the branch is now level with upstream main (0 behind, 11 ahead).

The 31 commits that landed upstream touch ui/, src/process/, src/gateway/, src/config/ and a handful of other package-update-* files, but none of the three files in this PR, so the merge was conflict-free and the diff is unchanged from ff67c7b94:

 src/infra/package-update-integrity.test.ts   | 240 +++++++++++++++++++++++++++
 src/infra/package-update-integrity.ts        |  56 ++++--
 src/infra/package-update-swap.bounds.test.ts |  13 +-
 3 files changed, 294 insertions(+), 15 deletions(-)

Re-verified on the merged head rather than assuming the merge was inert:

$ node scripts/run-vitest.mjs run \
    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
Test Files  4 passed (4)
     Tests  61 passed (61)
$ npx oxlint src/infra/package-update-integrity.ts \
               src/infra/package-update-integrity.test.ts \
               src/infra/package-update-swap.bounds.test.ts
Found 0 warnings and 0 errors.

The unchanged caveat from before still applies: pnpm lint does not complete on this machine, because the whole-workspace scan is OOM-killed here. I have not verified a full-repo lint, and CI's lint jobs remain the real confirmation.

No functional change in this push — it is the upstream sync only. Still holding for a maintainer's look.

@steipete

Copy link
Copy Markdown
Contributor

Thank you @Tsuki-hash! We re-implemented this fix in #179797, which landed with you credited as co-author. Closing this one as superseded.

steipete added a commit that referenced this pull request Oct 21, 2026
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]>
@steipete steipete closed this Oct 21, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 22, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

2 participants