Skip to content

fix(runtime-host): reap stale Runtime Host control directories - #5268

Closed
Yx01-me wants to merge 13 commits into
apache:mainfrom
Yx01-me:codex/runtime-host-control-directory-reaping
Closed

Yx01-me wants to merge 13 commits into
apache:mainfrom
Yx01-me:codex/runtime-host-control-directory-reaping

Conversation

@Yx01-me

@Yx01-me Yx01-me commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #4712

Verification

AI use

Select exactly one:

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope:

Checklist

  • Tests cover the change and fail without it
  • Lint, format, typecheck and the affected suites pass locally

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No

@github-actions github-actions Bot added the effort/XL Under 2500 readable lines label Sep 13, 2026
@Yx01-me
Yx01-me force-pushed the codex/runtime-host-control-directory-reaping branch from b65178f to c335c86 Compare September 13, 2026 19:14

@hqhq1025 hqhq1025 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.

Technical NO-GO: one P1 and one P2 remain on this head.

The change adds bounded stale-control-directory reclamation, separates the durable owner lock, retries public Artifact writer acquisition across directory replacement, and schedules a background sweep after Host startup. The reclamation boundary currently includes durable access/plugin state, and cleanup also removes the parent needed by the existing candidate-startup diagnostic path.

Validation: npm run build:test, full typecheck, lint, format check, ASF headers, and git diff --check passed. Storage tests passed 1101 with 13 skipped. Runtime Host tests reported 1581 passed, 13 skipped, and 2 failed: the credential-reconnect failure described inline is attributable to this change; the other is the unchanged managed Bash sandbox integration, and this runner rejects both unshare and bwrap. GitHub has no hosted checks for this head. The PR is currently conflicting with main 0d4a6ba5f48de6807ab96d6b5aad3635cc6a1f57 in packages/runtime-host/src/__tests__/host-kernel.test.ts. Native Windows/macOS cleanup behavior was not exercised.

Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

| undefined;
if (access === 'write') {
try {
const result = await quarantineRootControlDirectory({

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] Preserve durable access and plugin state across normal Host shutdown

This now quarantines the entire per-root control directory whenever a write owner closes. That directory is not only an endpoint/diagnostic cache: openRuntimeHostAccessAuthority(owner.controlDirectory) stores credential hashes, revocations, collaboration grants, and approved requests in runtime-host-access.json, while the plugin composition and trusted package stores are also rooted there and explicitly document their data as durable. On this exact head, the unchanged production test an authenticated WebSocket Client reconnects after service restart to canonical state fails deterministically with credential_rejected; a real owner/access-authority restart probe likewise authenticated before owner.close(), observed the control directory removed, and could no longer authenticate after reopening. Thus every graceful Host restart invalidates remote clients and discards installed plugin state. Please move disposable registration/diagnostic artifacts into a dedicated subtree, or move the durable stores outside the directory before reclaiming it.

rootId: capabilityRecord.rootId,
heldOwnerHandle: compatibilityHandle,
});
if (result.kind === 'quarantined') quarantined = result;

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.

[P2] Keep the startup diagnostic writable after owner cleanup

For failures after ownership is acquired, startInteractiveRuntimeHostCandidate() first calls owner.close() and only then does candidate-entry.ts call writeCandidateStartupDiagnostic(). With this new whole-directory quarantine, the diagnostic parent no longer exists, and the writer opens its temporary file without recreating that parent. A production-path probe using the real candidate starter with a throwing composition factory produced startup_diagnostic_io_failed/ENOENT, and the subsequent diagnostic read returned undefined. The existing entrypoint test covers a failure before owner acquisition, so it does not catch this ordering. Preserve or recreate the diagnostic location after cleanup, write the diagnostic before reclaiming the directory, or place diagnostics outside the reclaimed namespace.

@hqhq1025 hqhq1025 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.

Technical GO: I found no remaining P0-P3 issue on this head.

The two prior findings are fixed. Root-control quarantine now re-checks the directory contents before and after claim allocation and skips the entire directory when any durable or unknown entry is present, so access credentials, revocations, plugin composition/packages, and future state survive owner close and later sweeps. The Candidate diagnostic writer also recreates and validates its private parent before the atomic write, so a startup failure after owner cleanup remains observable.

I re-ran the production paths rather than relying only on the new unit assertions: authenticated WebSocket credential reuse survived five complete Host close/restart cycles, and the real detached Candidate failure path preserved its startup diagnostic in three consecutive runs. The root-authority stress suite, including the real SIGKILL tombstone recovery, passed 53 tests with 2 platform/benchmark skips; the full Host-kernel file passed 82 with 1 benchmark skip.

Validation also passed build:test, full typecheck/lint/format, ASF headers, Windows inventory, git diff --check, Storage 1264 passed / 14 skipped, focused Storage 59/65 and Runtime Host 25/25, and the hosted test and windows_recovery jobs. The head cleanly merges with current main ea990cab7ffa768dc1a574b539f73a83f8faabb8.

Two unrelated local-suite caveats remain. Without suppressing Node's SQLite ExperimentalWarning, one unchanged Storage child-process test treats that warning as an error; with NODE_NO_WARNINGS=1, the full package passes. Runtime Host reports 1922 passed / 20 skipped / 1 failed / 6 cancelled: the unchanged managed-Bash sandbox test fails because this runner rejects both unshare and bwrap, and the unchanged resumable-peer-stream file reproduces the six cancellations alone. Native Windows/macOS cleanup behavior was not independently exercised.

Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

@Astro-Han Astro-Han 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.

Review focus: reaping safety

Targeted review of the destructive path only (root-authority.ts, candidate.ts, artifact-writer-lock.ts, tests). I did not read the benchmark/perf scaffolding or the full test file line by line.

Liveness is proven by locks, not by mtime — this is the right call

quarantineRootControlDirectory (packages/storage/src/root-authority.ts:1163) requires non-blocking exclusive acquisition of both owner.lock and .maka-artifact-writer.lock, then re-validates directory dev/ino (:1207), both lock handle/path identities, and the disposable-entry set again immediately before the rename (:1219-1225). The mtime < graceMs check (:765) is only a skip optimization, never the liveness proof. That means:

  • SIGKILL/crash, suspended laptops, clock skew and backwards clocks cannot cause a live host to be reaped — the OS lock is what gates deletion.
  • Same-process reaping is safe too: fs-native-extensions uses flock on darwin, F_OFD_SETLK on Linux and LockFileEx on Windows (node_modules/fs-native-extensions/src/{apple,linux,win32}.c), all of which conflict across distinct fds/handles, so the reaper cannot steal its own host's owner.lock. The in-process test does not reap an active write owner confirms busy.
  • I confirmed in acquireStateRootLock (:1006-1126) that the compatibility owner.lock handle is held for the whole owner lifetime and only released in close(), so "live host ⇒ lock held" actually holds. The two-lock split is necessary and correctly covers the standalone Artifact Writer case.

No path traversal / over-broad deletion

Entry names must match ROOT_ID_PATTERN (^[a-f0-9]{64}$, :757), plus a parse(controlDirectory).dir !== controlRoot guard (:1171); claim directories must match a strict UUIDv4 pattern and be direct children of .reap (:1313, isReapClaimName :1393); symlinked control roots/candidates are rejected (sameFilesystemIdentity checks isSymbolicLink), and nested symlinks are unlinked rather than followed (:1384). state-root-owners/ is never touched. Tests cover all of these, including rejects a symlinked reap namespace without deleting outside it and the foreign-lock symlink case.

Durable state is protected in the conservative direction

containsOnlyDisposableRootControlEntries (:1247) is an exact-name allowlist. I cross-checked every writer into the control dir: runtime-host-access.json (access-credential-store.ts), plugin-composition-v2.json, plugin-packages-v2/, plugin-generations-v1/, plugin-data/ are all not allowlisted, so those directories are now preserved rather than deleted. Good — unknown/future entries fail safe too. Worth stating explicitly in the PR description, though: hosts that opened an access authority (candidate.ts:141, before scheduleRootControlDirectoryReaper) now leave a permanent directory, so the leak is only fixed for hosts that never wrote durable state. That matches the doc's follow-up list, just worth being loud about.

Partial deletion leaves a resumable, isolated state

The original <rootId> path is never recursively deleted — only the rename target is, under .claim.lock, with a claim-identity guard before every step. A successor owner rebuilt at <rootId> is a different inode and is not touched (tested by rename isolation preserves a new owner created before old-claim deletion and a successor process reaps a SIGKILL tombstone without deleting a rebuilt owner, which is effectively a cross-process live-owner test: the parent holds the owner while a child reaper sweeps with graceMs: 0).

Findings

1. Startup race: a host starting while the reaper quarantines that exact rootId fails with invalid_lock_artifact (low severity, traced not reproduced).
tryAcquireStableRootLock re-asserts the lock path identity after taking the lock (:1143). Interleaving: reaper reads the stale dir mtime (:765) → host calls prepareStorageRootControlDirectory then open('<rootId>/owner.lock', 'a+') (creating the file, refreshing the dir mtime) → reaper opens that same inode, tryLocks it (still free), completes quarantine and renames the dir → host's tryLock then succeeds on the now-detached inode and the post-lock assertStableLockArtifact sees ENOENT → invalid_lock_artifact, and acquireStateRootLock:1039 releases both locks and rethrows, so the candidate start fails. A relaunch recovers (the durable lock is released), but the error is misleading and the reaper runs precisely when hosts are starting (candidate.ts:166, setImmediate after ready).
Cheap mitigation: re-apply the freshness check immediately before the rename (re-lstat the source dir at :1219 and require Date.now() - mtimeMs >= graceMs) — a host that just created owner.lock has refreshed that mtime, which closes most of the window. Optionally retry the control-dir owner.lock acquisition once on invalid_lock_artifact in acquireStateRootLock.

2. nit — the grace window is re-applied to .reap claims using the claim's own mtime, which deletion refreshes (:738). A tombstone that exceeds the 500 ms / 1024-entry budget is not retried at the next host startup as the doc claims, but 24 h later — and every partial pass resets that clock (removeClaimContents mutates the claim directory). Claims are already serialized by .claim.lock, so the grace check buys no safety there; exempting .reap/* from graceMs (or using birthtime/ctime) would make "resume at a later Host startup" actually true.

3. nit — rmdir(child) at :1382 does not tolerate ENOTEMPTY. If anything reappears inside a tombstoned subtree between the opendir scan and the rmdir, the whole claim is abandoned as failed and retried a full grace window later (compounded by #2). Treating ENOTEMPTY as a re-queue of that subtree would be more robust.

4. nit — the claim handle is released twice. removeRootControlClaim closes heldClaimHandle at :1345, then the caller closes it again in the finally (:783, and root-authority.ts:1096 in the shutdown path). Harmless today (FileHandle.fd is -1 after close and both helpers swallow errors), but the ownership is ambiguous — one owner would be clearer.

5. nit — reapStaleRootControlDirectories returns only the first budget batch and summary is reset at every boundary (:657-700). The name reads like a full sweep, so busy/failed totals silently depend on where the 500 ms default cuts the scan. Production (candidate.ts:72) correctly uses the generator; only the naming/API shape is confusing. Consider aggregating across batches or renaming to …FirstBatch.

6. nit — packages/runtime-host/src/__tests__/host-kernel.test.ts:20 is the only import in packages/runtime-host from another package's build output (../../../storage/dist/__tests__/fixtures/isolated-control-home.js). That makes the runtime-host suite depend on @maka/storage being compiled first, and it is invisible to workspace tooling. If the --import preload really must be a .js file, a short comment on that constraint would help.

Test coverage for "must not delete a live host"

Adequate, and I checked it is the lock that is exercised rather than the grace period: does not reap an active write owner, keeps active readers and Artifact writers out of stale-directory reaping, allows only one of two process reapers to claim a stale directory, rename isolation preserves a new owner created before old-claim deletion, revalidates lock identity after claim allocation before rename, claim deletion unlinks nested symlinks without following their targets, plus preserves durable access and plugin state on close and during a later sweep. One gap worth noting: no test drives finding #1's interleaving (a starting host vs. a reaper paused inside quarantineRootControlDirectory) — the existing rename mocks pause after the rename, not between open(owner.lock) and rename.

Also verified: the Windows inventory arithmetic is consistent (9 new rows; portable-candidate 32→40, platform-contract 36→37, total 95→104) and the test titles quoted in docs/windows-test-inventory.md match the new test() names; the doc's stated protocol matches the implementation step for step; zh-CN-only docs are consistent with existing docs/architecture practice.

No blocking safety issues from me — the double-exclusive-lock + rename-into-claim + identity-revalidation design holds up. The one item I'd like an answer on before merge is finding #1.

@hqhq1025 hqhq1025 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.

Review of exact head 2eea6ee02be48e8b6d87024602ca6d55fa20eae9.

This series adds stale Runtime Host control-directory reaping, preserves durable control state, rebuilds startup-diagnostic parents, and adds a bounded retry for a directory renamed after owner.lock was opened. The previously reported persistence and diagnostic-loss issues remain fixed, but the new retry still leaves one reachable startup race, so this head is not ready to merge.

Validation on this head: clean npm ci; npm run build:test; storage root-authority tests (51 passed, 6 skipped); Runtime Host kernel/startup-diagnostic tests (87 passed, 1 skipped); full typecheck, lint, format, ASF headers, Windows test inventory, and git diff --check. Hosted test and windows_recovery are green. Against current main 8d5a3cac3504c36cb1849b060153b58188e2c7b2, the merge tree conflicts in generated docs/windows-test-inventory.md. Native Windows/macOS behavior was not exercised locally.

Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

Comment thread packages/storage/src/root-authority.ts Outdated
if (
attempt !== 0 ||
!(error instanceof StorageRootAuthorityError) ||
error.code !== 'invalid_lock_artifact'

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.

[P2] Retry when the reaper removes the directory before open

This condition only retries invalid_lock_artifact, which is produced when the compatibility lock was opened and then renamed before its identity check. A second reachable ordering remains: prepareStorageRootControlDirectory() returns, the reaper quarantines and deletes that disposable directory, and only then this owner tries to open owner.lock. In that case open() raises ENOENT, tryAcquireStableRootLock() wraps it as lock_failed, and this branch rethrows instead of recreating the directory and retrying.

I reproduced that ordering on this exact head by running the real reaper immediately before the candidate owner-lock open: the reaper reported reaped: 1, then tryAcquireInteractiveRootOwner() failed with lock_failed and cause code ENOENT. The added regression pauses only after open() returns, so it cannot cover this window. Please include expected missing-path failure around the prepare/open pair in the bounded retry, and add a test where reaping finishes before open().

@me2seeks me2seeks 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.

Automated review notice: This comment was posted by an automated review agent operated by me2seeks make. It is not an independent human review and does not replace one.

Summary

Reaps stale Runtime Host control directories: bounded by a 24h grace (ROOT_CONTROL_REAP_GRACE_MS), 1,024-entry scan cap, 500ms duration budget, and a .claim.lock with 3 claim retries, moving stale directories into a .reap namespace instead of deleting in place. ROOT_ID_PATTERN (^[a-f0-9]{64}$) validates identities before any filesystem mutation, and prepareRootControlDirectoryForDiagnostic recreates the private diagnostic parent after a failed Candidate releases its owner. The issue (failed/abandoned control directories accumulating and colliding with fresh Candidates) is real, the reaper is conservative (budget-exhaustion reported in the summary, busy/skipped/failed distinguished), and a zh-CN architecture doc plus the Windows test inventory are updated in step. CI test and windows_recovery green.

Findings

  1. [P3] ROOT_CONTROL_REAP_MAX_DURATION_MS = 500 bounds the whole scan+move loop; on a very slow filesystem (network-mounted control root) a single rename could exceed the remaining budget mid-sequence, leaving a directory half-moved into .reap with its claim lock intact — recovered on the next reap pass by design, but worth confirming a test exercises a mid-loop budget cut rather than only the clean path.
  2. [P3] 24h grace is global; a Host that restarts daily with rotating identities will keep ~2 days of directories — fine, but the doc should state the disk-growth bound (24h × worst-case creation rate) for operators.

Verdict

merge-ready — conservative, budgeted, well-validated reaping with honest summary accounting; two P3 robustness notes only.

@hqhq1025 hqhq1025 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.

Reviewed exact head 72d10fbab8d29099de4b91072bf755a088bbd68a. I found no remaining P0-P3 issues.

This follow-up closes the previously reported owner-acquisition race. packages/storage/src/root-authority.ts:1029-1051 now treats a missing compatibility-lock path like the existing post-open identity race and retries once while the durable root lock is still held. The regression at packages/storage/src/__tests__/root-authority.test.ts:988-1041 pauses immediately before the real owner.lock open, runs the production reaper to remove the prepared directory, then verifies that acquisition recreates the directory and succeeds. This exercises the ordering that previously surfaced as lock_failed with an ENOENT cause.

I also rechecked the broader change: conservative stale control-directory discovery/reaping, persistent-entry preservation, artifact-writer compatibility locks, Candidate startup serialization, and startup-diagnostic recreation. The earlier persistence and diagnostic fixes remain intact.

Validation on Node 24.18.1: clean install, build:test, full typecheck, lint, format, ASF headers, Windows inventory, and git diff --check; Storage completed 1,556 pass / 14 skip, root-authority completed 52 pass / 6 skip, and focused Runtime Host tests completed 87 pass / 1 skip. Hosted test and windows_recovery are green. The PR is 11 commits ahead / 7 behind current main 2f32205528a4436783c800715261d4b6e286023d, and the merge tree 838b14a58bb9ef78c6e0c6addc9e336bf6b86f0f is conflict-free.

Not independently verified: native Windows/macOS execution, power-loss/fsync fault injection, or packaged Electron startup behavior.

Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

@Astro-Han Astro-Han 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.

Review at 72d10fba. The deletion logic is sound. Liveness is decided by locks, not PIDs: the reaper holds both the exclusive owner.lock and the artifact-writer lock through the rename. It re-checks directory and lock identity before renaming, keeps anything that is not on the disposable list, skips symlinked or junction candidates, and resumes interrupted claims on a later sweep. We found no way for it to remove a live Host's directory. The compatibility-lock race is fixed and covered by the new test. root-authority.test passes locally: 52 pass / 6 skip by default, and 56 pass / 2 skip with MAKA_STORAGE_STRESS=1.

P2: a Candidate can lose the election when no Host exists. The new retry at acquireStateRootLock only covers a thrown error (missing path or invalid lock artifact). If a concurrent stale-directory sweep is holding that directory's owner.lock, which it takes with tryAcquireStableRootLock(..., 'write') without the durable root lock, then tryAcquireStableRootLock returns undefined instead of throwing.

The Candidate then releases the durable lock and returns undefined, which becomes {kind:'loser'} and exit code 2 even though no owner exists. This is rare, because it needs a directory older than 24h plus a concurrent start. When it happens, connect-or-spawn loses a backoff cycle, and the CLI retire path can fail.

Possible fixes:

  • While the exclusive durable lock is held, retry briefly when the compatibility lock is busy.
  • Have the reaper take (or try) the durable root lock first and skip roots where it is held.

P3s are inline.

Automated review (Claude lineage, posted from the Astro-Han account). No approval implied.

(!isMissingPathError(error) &&
(!(error instanceof StorageRootAuthorityError) ||
error.code !== 'invalid_lock_artifact'))
) {

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.

P2 (see the review body): this retry handles thrown errors only. If the reaper is holding owner.lock, the attempt returns undefined, which falls through to the !compatibilityHandle branch below and makes this Candidate a loser while no Host owns the root.

join(claimDirectory, ROOT_CONTROL_CLAIM_LOCK),
'write',
);
if (!claimHandle) return { kind: 'busy' };

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.

P3: when the rename fails later in this block (EPERM/EBUSY/ENOENT), the .reap/<uuid> claim directory is left behind until its 24h grace period expires. The design notes say the rename always fails on Windows, so a claim leaks on every sweep and every owner close there. The unlink + rmdir cleanup used in the skipped branch just below would work here too.

name === 'registration.json' ||
name === 'bundle-imports-v1' ||
/^registration\.json\.\d+\.[0-9a-f-]{36}\.tmp$/u.test(name) ||
/^startup-diagnostic(?:\.[0-9a-f-]{36})?\.json(?:\.\d+\.[0-9a-f-]{36}\.tmp)?$/u.test(name) ||

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.

P3: because startup-diagnostic*.json is now on the disposable list, and owner close triggers a reap, any write-owner acquire and close removes the saved startup diagnostic. CLI idle probes do this too. Before this change the file survived until it was explicitly cleared. Is that intended?

@Astro-Han Astro-Han 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.

Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

Review of exact head b8cfd381. The previous review head was 72d10fba. The new merge from main (5da004cd) adds nothing to the PR diff. The real change is b8cfd381.

Earlier findings:

  • Astro-Han P2 (a Candidate loses the election while a reaper holds owner.lock) is fixed, with a bounded wait. acquireStateRootLock now retries a busy compatibility lock 4 times at 25ms while it holds the durable lock (root-authority.ts:1036-1048). The single replacement retry is unchanged and the loop is bounded. A legacy owner that knows only owner.lock still wins after about 100ms. Two owners still cannot emerge, because the durable lock is held throughout.
  • Astro-Han P3 (claim leak when rename fails) is fixed. On ENOENT/EBUSY/EPERM the empty claim is removed (:1283-1286, :1357-1364). These codes match what libuv returns on native Windows, so the "safe but does not reclaim" Windows mode no longer leaves a .reap/<uuid> on every sweep and every close.
  • Astro-Han P3 (startup diagnostic deleted by owner close) is answered: the design doc now defines it as an attempt-scoped handoff. That matches the attempt-scoped readers in connect-or-spawn.ts, so I consider it resolved.
  • The earlier durable-state, diagnostic-parent and ENOENT-before-open fixes are unchanged and their tests pass.

I re-checked the destructive path at this head and found no way to remove a live Host's directory. Liveness comes from OS locks, not PIDs. Directory and lock identity are re-checked after claim allocation and before the rename. Durable or unknown entries cause a skip. Symlinks are never followed, and the control namespace is private to the user. The PR has no protocol epoch change.

I found no P0-P2 issues. Two P3 notes are inline.

Validation: the hosted test and windows_recovery jobs are green. The head merges cleanly with current main 7c90bac2d. Locally on Node 22: build:test passed. Storage root-authority: 55 pass / 6 skip, or 59 pass / 2 skip with MAKA_STORAGE_STRESS=1. The three new tests passed 10/10 repeated runs. Runtime Host host-kernel + startup-diagnostic: 87 pass / 1 skip. The Windows inventory is current, and Storage lint, format and typecheck are clean. Not verified: native Windows/macOS execution, or real cross-process timing of the busy window.

// Holding the durable lock rules out a current owner, but a reaper can
// briefly hold the compatibility lock while it quarantines stale state.
// Bound the wait so an older owner that only knows this lock still wins.
if (busyRetries >= ROOT_CONTROL_COMPATIBILITY_LOCK_BUSY_RETRIES) break;

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.

P3: this retry window (4 x 25ms) is a timing heuristic, and nothing on the reaper side keeps it within that window. The reaper holds owner.lock across about 15 awaited fs operations (:1225-1282), in another Host process that runs the sweep right after its own startup (candidate.ts:91). Event-loop or threadpool queueing, or a slow home directory, can push that past 100ms. The Candidate then still exits as a loser while no owner exists. That is very unlikely, since the same root must be more than 24h stale and the timing must collide. Still, a matching bound in the reaper would turn this window into a guarantee. For example, record the time when owner.lock is acquired, and return busy (removing the empty claim) before the rename once more than about 50ms has passed. A debug log when busy retries run out would also help diagnose the residual case.

await removeEmptyRootControlReapClaim(claimDirectory, claimHandle);
return isMissingPathError(error) ? { kind: 'skipped' } : { kind: 'busy' };
}
await closeReapLock(claimHandle);

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.

P3 (minor): the cleanup now covers rename ENOENT/EBUSY/EPERM. This branch, though, still closes the lock and rethrows without removing the empty .reap/<uuid>/.claim.lock. That happens for invalid_lock_artifact from assertDirectoryIdentity / assertStableLockArtifact, and !claimHandle at :1259 has the same effect. These paths realistically need external tampering, and the 24h claim sweep collects them. A best-effort removeEmptyRootControlReapClaim here, which must not mask the original error, would make the doc statement at line 140 true for every path.

@github-actions github-actions Bot added the stale No qualifying activity within the lifecycle policy window label Nov 3, 2026
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

This pull request has had no new commits for 30 days and has been marked stale. It will be closed in 7 days unless a new commit is pushed.

Comments do not reset this timer: only a new commit does. If the pull request is intentionally long-lived, a maintainer can apply the pinned label.

@github-actions

Copy link
Copy Markdown

This pull request has been closed because it received no new commits during the 7-day grace period. This is not a judgement on the merit of the change; it only keeps the review queue aligned with work that is actively in flight.

The branch and review history are preserved. Push a new commit and reopen the pull request whenever the work is ready to continue.

@github-actions github-actions Bot closed this Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/XL Under 2500 readable lines stale No qualifying activity within the lifecycle policy window

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(runtime-host): reap stale Runtime Host control directories

4 participants