Skip to content

fix(harness): reclaim the promoted config cache when its last leaf releases - #225

Merged
pdettori merged 4 commits into
rossoctl:mainfrom
pdettori:fix/216-config-cache-outlives-leaf
Sep 5, 2026
Merged

pdettori merged 4 commits into
rossoctl:mainfrom
pdettori:fix/216-config-cache-outlives-leaf

Conversation

@pdettori

@pdettori pdettori commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

Fixes #216.

The bug

The overlay materialises a promoted bundle into a digest-keyed cache in the shared pool sandbox and nothing ever removed it. buildCleanupScript (harness/src/converge.ts:44) takes down the leaf worktree; the config-overlay teardown removed only the per-leaf symlink. Its own doc comment stated the intent outright — "The shared cache is immutable and outlives every leaf."

So /workspace/.sh-config/sha256-<digest>/ stayed on disk indefinitely, world-readable, holding the promoted CLAUDE.md and memory/. A later leaf dispatched with no configRef could lease the same sandbox, explore the filesystem, and answer from a sibling's workflow — measured in #216 with a ticket id and a sandbox token it had been told nothing about.

Two consequences: spec §2 goal 6 ("absent a promoted bundle, harness behavior is unchanged") was true in the harness process but not observably true, since every tool call runs in the sandbox; and bare-leaf behavior became dependent on unrelated earlier promotions, so any A/B with a bare control was silently invalid on a warm pool.

The fix

Refcount the cache. Each leaf registers an empty file under /workspace/.sh-config/.refs/<digest>/; the release drops it and tears the cache down once none remain.

Three details that are load-bearing rather than stylistic:

  • The ref is registered before the presence check, both inside one flock. Otherwise a leaf could read hit and have the directory deleted beneath its symlink by a concurrent release, running the turn with silently-absent configuration — the plausible-but-wrong-work failure this design exists to prevent (spec §4.4). buildCacheProbeScript is renamed buildCacheAcquireScript because it now mutates.
  • The release restores write permission before rm -rf. ADR-0031's chmod -R a-w clears the write bit on the cache's directories too, and a directory needs write permission on itself to unlink its entries. The populate script's EXIT trap already does this for the same reason.
  • Teardown keys on the overlay having been attempted, not having succeeded. The ref is claimed by the overlay's first exec, so a partial failure (truncated transfer, failed populate) would otherwise leak one and pin that digest's cache forever — reinstating the bug inside the code meant to fix it. overlayCreated: boolean becomes overlayDigest: string | undefined, set before the call.

The refs tree is dot-prefixed so the sha256-* globs that enumerate cached bundles skip it, and sits beside the cache rather than inside it, since chmod -R a-w leaves nowhere writable within. Both flock'd sections sweep refs older than 24h, so a harness pod dying mid-leaf cannot pin a cache forever; the window is far longer than any turn, so it cannot evict a live leaf's ref.

Trade-off this accepts

Concurrent fan-out still transfers a bundle once — that is spec §4.5's actual claim, and those leaves hold refs simultaneously. Reuse across separate dispatches is given up: one arriving after the pool has gone idle re-transfers the bundle. This is recorded in the spec, ADR-0031 and the demo's "Notes and limits" rather than left as folklore.

Concurrent cross-leaf visibility remains an accepted non-goal (P2 §9, one trust domain; Kata isolation is P3/#48). What this closes is the narrower claim: a promoted bundle no longer survives the leaf that brought it.

The demo now proves the fix instead of working around it

The rm -rf /workspace/.sh-config/sha256-* purge before the bare control arm is gone. Reintroducing it would clean up after a teardown regression and hide it, so the script asserts emptiness (naming the offending pods on failure) and its own test pins the absence of an rm.

The "bundle materialised on the filesystem" check had to move: it read the cache after Run B returned, which now correctly finds nothing, so it would have had to be downgraded to trusting the model's prose. Run B is dispatched in the background and the check watches for the bundle to appear underneath it — same single dispatch, no extra model call. The reclaim is asserted once the run finishes, so the demo shows both halves of the invariant.

Review follow-ups (96e09fc)

Three non-blocking findings, all verified before changing anything:

  • prom_file leaked. The script declares promote_log/repromote_log empty before cleanup() — because set -u aborts the EXIT trap on an unset name — and removes them inside it. prom_file did neither. Now declared and removed alongside them; confirmed the trap completes and removes the file with the declaration, and aborts without it.
  • The walkthrough's cache listing was not .refs-blind, while configRefsDir's comment claimed the docs enumerate through a sha256-* glob. A concurrent leaf or a stale ref made it print a filename, and the callout below tells the reader that means a bug to report — the wrong bug. Listing scoped; comment now states that the dot prefix hides refs from a glob but not from an unscoped find.
  • The 3d poll loop was unbounded, so a dispatch writing nothing at all spun forever. Bounded in both directions like the scripted equivalent.

One correction to the suggested diff: scoping needs sh -c, as the script's own check at line 300 does. A bare kubectl exec -- find /workspace/.sh-config/sha256-* sends the glob literally — it matches nothing locally, so bash leaves it alone — and remote find then reports nothing whether or not a bundle is cached, converting an emptiness check into one that always passes. Verified in a container: literal glob finds 0 files with a bundle present; sh -c form finds the bundle's files and no refs.

Footer phrasing changed to Assisted-By. Note the PR Description Attribution section cited isn't in this repo's CLAUDE.md — it has only Commit Attribution — but the Assisted-By preference there clearly extends to this, so it is applied rather than argued.

Verification

Gate Result
make lint pass
make typecheck pass
make test pass — harness 385 passed / 2 files skipped; all suites green
deploy/knative/tests/demo-promoted-workflow.test.sh PASS
shellcheck -x -S warning (the CI gate severity) pass

The unit tests assert script text, which cannot catch a wrong rm or a permission bug. So the generated scripts were also executed against a scratch tree in a container as a non-root uid — root bypasses the directory write bit, which would let the removal succeed even with the chmod missing and pass a broken implementation. 22/22 behavioural checks: cache survives a sibling's release, dies with the last ref, .refs invisible to the sha256-* glob, re-acquire is a clean cold miss, executable bits survive the round trip, double release idempotent.

Negative control: stripping chmod -R u+w leaves the cache in place, confirming that line is load-bearing and the positive result is not vacuous.

Not covered here: the flock race under genuine concurrency, and the whole path against a real pooled sandbox. The demo's two new assertions are that evidence and have been reasoned about, not run — they need a warm cluster.

Assisted-By: Claude Code

…leases

The digest-keyed cache the overlay materialises in the shared pool sandbox had
no teardown: buildCleanupScript removed only the leaf worktree, and cleaning up
the per-leaf symlink left /workspace/.sh-config/<digest>/ on disk indefinitely,
world-readable, holding the promoted CLAUDE.md and memory/. A later leaf
dispatched with NO configRef could lease the same sandbox, explore the
filesystem and answer from a sibling's workflow -- measured, with a ticket id
and a token it had been told nothing about.

That makes spec §2 goal 6 ("absent a promoted bundle, harness behavior is
unchanged") true in the harness process but not observably true, since every
tool call runs in the sandbox. It also made bare-leaf behavior depend on
unrelated earlier promotions, so any A/B with a bare control was silently
invalid on a warm pool.

Refcount the cache instead. Each leaf registers an empty file under
/workspace/.sh-config/.refs/<digest>/ and the release drops it, tearing the
cache down once none remain. Both halves run under the per-pod flock the
populate path already uses, and the ref is registered BEFORE the presence
check -- otherwise a leaf could read `hit` and have the directory deleted
beneath its symlink by a concurrent release, running the turn unconfigured.
The refs tree is dot-prefixed so the `sha256-*` globs that enumerate cached
bundles skip it, and it sits beside the cache rather than inside it, because
ADR-0031's `chmod -R a-w` leaves nowhere writable within.

Teardown keys on the overlay having been ATTEMPTED, not having succeeded:
the ref is claimed by the overlay's first exec, so a partial failure would
otherwise leak one and pin that digest's cache forever -- reinstating the bug
in the code meant to fix it.

Concurrent fan-out still transfers a bundle once (spec §4.5). Reuse across
separate dispatches is given up deliberately: one arriving after the pool has
gone idle re-transfers.

Verified beyond the script-shape unit tests by executing the generated scripts
as a non-root uid -- a sibling's release leaves the cache intact, the last one
removes it, and stripping the `chmod -R u+w` makes the removal fail, so that
line is load-bearing rather than defensive.

Fixes rossoctl#216

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
The demo used to `rm -rf /workspace/.sh-config/sha256-*` before the bare
control arm, because the cache outlived its leaf and a warm pool made that
control silently invalid (rossoctl#216). Now that the cache is refcounted the purge is
not just unnecessary, it is harmful: an rm here cleans up after a teardown
regression and hides it, and the control's honesty goes back to depending on
this script rather than on the harness. So assert emptiness, name the offending
pods when it fails, and pin the ABSENCE of an rm in the script's own test.

The filesystem check for the materialised bundle had to move. It read the cache
after Run B returned, which now correctly finds nothing, so it would have had
to be downgraded to trusting the model's prose. Run B is dispatched in the
background instead and the check watches for the bundle to appear underneath it
-- same single dispatch, no extra model call. The reclaim is then asserted once
the run finishes, so the demo shows both halves of the invariant rather than
standing in for one of them.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Three documents asserted the invariant this fix reverses. Spec §4.5's
"Two-level placement" described the shared cache as populated once and never
reclaimed; ADR-0031 spoke to write-protection (`chmod -R a-w`) as though that
covered promoted memory reaching a shared volume, when write-protection is not
lifetime and the two were conflated; and the demo walkthrough told readers to
purge the cache by hand, with a "Notes and limits" entry tracking rossoctl#216 as open.

All three now describe the refcounted lifetime, including the cost it accepts:
no reuse across separate dispatches. The demo's 3a verifies emptiness rather
than forcing it, and 3d dispatches in the background so the bundle can be
observed while it legitimately exists -- reading that path after the run now
finds nothing, which the section says explicitly and then demonstrates.

Concurrent cross-leaf visibility stays an accepted non-goal (P2 §9; Kata
isolation is P3/rossoctl#48). What rossoctl#216 closed is narrower and is stated as such: a
promoted bundle no longer survives the leaf that brought it.

The superseded wording in docs/plans/ is left alone -- a plan records what was
planned, not what the code does now.

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

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the refcount protocol end to end rather than only reading the diff. No blocking issues — the mechanism is sound and the parts the description calls load-bearing genuinely are.

What I verified beyond the diff:

  • hit implies a complete cache. buildCachePopulateScript on main takes the same /workspace/.sh-config.lock and lands the tree via an atomic mv "$TMP" "$DIR", so the acquire's [ -d "$DIR" ] under that lock can never observe a half-populated directory.
  • No digest mismatch between acquire and release. Both are env.configRef (run-leaf.ts:475 and :479), so the release targets the cache the acquire claimed. The new test pinning DIR=/REFS= in the release script covers this.
  • The converge path cannot leak refs. configRef and overlayConfig are reachable only from runPromptLeaf (run-leaf.ts:299, :447, :477), so there is no second path that overlays a bundle and tears down via cleanupWorkspace without dropping a ref. Worth stating explicitly, since a ref leak there would reinstate #216 for that digest.
  • The demo's reclaim assertion is not racing teardown. The cleanup exec is awaited in runPromptLeaf's finally, which resolves before the HTTP response is produced — so it has completed by the time wait "$prom_pid" returns. The assertion is ordered by construction, not by luck.
  • The background-poll window is not tight. On a cold miss the file appears with the atomic mv and stays for the whole model turn; on a warm cache it is there immediately. The 240-iteration bound plus kill -0 exceeds curl --max-time 240 either way.

Three non-blocking findings inline: a temp file that escapes the script's own EXIT-trap convention, and a docs command whose scope contradicts the invariant configRefsDir's comment claims the docs uphold.

One nit outside the diff: the PR description footer reads Generated with Claude Code. The hub repo's CLAUDE.md ("PR Description Attribution") asks for Assisted-By: Claude Code and rules out "Generated with" phrasing — the three commits already get this right.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (harness src + tests), Shell (demo + demo test), Docs (ADR, spec, demo walkthrough)
Agent/IDE config (.claude/.vscode): none
Commits: 3 commits, all signed off, all using Assisted-By:
CI status: passing (12/12)

Posted as a COMMENT rather than an APPROVE only because GitHub does not permit approving one's own pull request; there are no blocking findings.

# -- which is what this demo used to do -- would now always find nothing, and the mechanical check
# below would have to be downgraded to trusting the model's words. So watch for the bundle to appear
# underneath the run instead. Same single dispatch either way: no extra model call.
prom_file="$(mktemp)"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — prom_file is never cleaned up.

The script already has a convention for exactly this: promote_log and repromote_log are declared at lines 72-73 before cleanup() — with a comment explaining that set -u would abort the EXIT trap on an unset name — and are removed inside it. prom_file does neither, so it leaks a temp file on every run, and on any early exit between here and the cat at line 356.

 # near lines 72-73, beside the other trap-visible temp files
 promote_log=""
 repromote_log=""
+prom_file=""

...and add it to the rm -f in cleanup(). Worth following the existing pattern rather than a local trap, since the comment there records why the declaration has to precede the trap.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 96e09fc, following the existing convention rather than a local trap: prom_file="" beside promote_log/repromote_log at the top, and added to the rm -f in cleanup().

Verified both halves of the reason the convention exists, in a container: with the declaration the trap runs to completion and the file is gone; without it set -u aborts the trap before it prints anything. So the comment at lines 70-71 is describing a real failure, not a theoretical one.

Comment thread docs/demos/promoted-workflow-demo.md Outdated
```bash
# The leaf may have leased ANY pool sandbox, so ask the pool rather than guessing a pod.
export POOL=$(kubectl get pods -n $NS -l 'sh.kagenti.io/sandbox-pool=default' -o name | sed 's|pod/||')
for p in $POOL; do kubectl exec -n $NS "$p" -- find /workspace/.sh-config -type f 2>/dev/null; done \

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — this command is not .refs-blind, but the code comment says the docs are.

find /workspace/.sh-config -type f will also print .refs/sha256-<digest>/<runId> whenever a ref file exists. Meanwhile configRefsDir's rationale in config-overlay.ts:17-18 — and the unit test that pins it — states that "the demo and the docs both enumerate cached bundles with ls -1d /workspace/.sh-config/sha256-*". That is true of demo-promoted-workflow.sh, but not of this command.

It matters because a stale ref (a harness pod that died mid-leaf, up to REF_STALE_MINUTES = 24h) or a concurrent leaf makes this print a filename, and the callout immediately below tells the reader that "If the command above prints file names, that is a bug to report, not a step to repeat." So the reader is pointed at the wrong bug.

Either scope the command:

for p in $POOL; do kubectl exec -n $NS "$p" -- find /workspace/.sh-config/sha256-* -type f 2>/dev/null; done \
  | sed 's|.*/sha256-[0-9a-f]*/||'

or narrow the claim in the configRefsDir comment (and the test comment) to the demo script alone. The dot prefix is still load-bearing either way — this is about the comment describing something the doc does not actually do.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 96e09fc. Confirmed the premise first — an unscoped find /workspace/.sh-config -type f does list .refs/<digest>/<runId>, so with a stale or concurrent ref the reader was being pointed at the wrong bug.

Took the scope-the-command option, since that keeps both enumerations consistent and the comment true. One correction to the suggested diff, though: it needs sh -c, the way the script's own check at line 300 does it. As written, kubectl exec -- find /workspace/.sh-config/sha256-* -type f has the glob expanded by the local shell, where the path does not exist — bash leaves it literal with nullglob off — so remote find gets a literal sha256-*, matches nothing, and prints nothing whether or not a bundle is cached. That turns the emptiness check into one that always passes, which is the same class of false green the surrounding code is careful about.

Measured in a container with a bundle and a ref both present:

unscoped find            -> lists the ref file      (premise holds)
scoped via sh -c         -> 1 bundle file, 0 refs   (correct)
literal unexpanded glob  -> 0 files                 (silently empty)

Also narrowed the configRefsDir comment and its test comment: they now say the enumeration is glob-scoped and add that the dot prefix does not hide refs from an unscoped find, which is what made the doc drift possible.

Comment thread docs/demos/promoted-workflow-demo.md Outdated
prompt:"Write the ship note for the auth timeout fix.", configRef:$c}')" \
$BASE/runs > /tmp/overlay-run.json &

until [ -s /tmp/overlay-run.json ]; do

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — unbounded loop in a copy-paste walkthrough.

If the background curl writes nothing — wrong host header, service not up, $BASE unset — /tmp/overlay-run.json stays empty and this spins forever. The equivalent loop in demo-promoted-workflow.sh is bounded in both directions (for _ in $(seq 1 240) plus kill -0 "$prom_pid" || break, lines 339 and 350).

Something like for _ in $(seq 1 240); do ... [ -s /tmp/overlay-run.json ] && break; sleep 1; done would match. Minor, but this walkthrough is otherwise meticulous about exactly this class of "the command lies to you" failure.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 96e09fc — bounded in both directions to match demo-promoted-workflow.sh: for _ in $(seq 1 240) with [ -s /tmp/overlay-run.json ] && break after the inner poll, so it also stops once the run has written its result rather than only on timeout.

…listing

Three findings from review of rossoctl#216's fix, none blocking.

`prom_file` escaped the script's own temp-file convention: `promote_log` and
`repromote_log` are declared empty before `cleanup()` -- because `set -u` would
abort the EXIT trap on an unset name -- and removed inside it. `prom_file` did
neither, leaking a temp file on every run and on any early exit before the
`cat`. Declared and removed alongside them now. Verified both halves: the trap
completes and removes the file with the declaration present, and aborts without
it, which is the reason the convention exists.

The walkthrough's `find /workspace/.sh-config -type f` was not `.refs`-blind,
while `configRefsDir`'s rationale claimed the docs enumerate cached bundles
through a `sha256-*` glob. A concurrent leaf or a stale ref (up to
REF_STALE_MINUTES) therefore made that command print a filename, and the callout
below it tells the reader a filename is a bug to report -- pointing at the wrong
bug. The listing is scoped to `sha256-*` now, and the comment says plainly that
the dot prefix hides refs from a glob but not from an unscoped find.

Scoping needs `sh -c` so the glob expands in the POD, matching how the script's
own check at line 300 does it. Passing `sha256-*` as a bare kubectl argument
sends it literally -- it does not match locally, so bash leaves it alone -- and
remote `find` then reports nothing whether or not a bundle is cached, which
would have turned an emptiness check into one that always passes.

The background-poll loop in 3d was unbounded, so a dispatch that writes nothing
at all (wrong Host header, unset `$BASE`) spun forever. Bounded in both
directions like the scripted equivalent: 240 iterations, and an early break once
the run has written its result.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori merged commit 8ce52ee into rossoctl:main Sep 5, 2026
12 checks passed
@pdettori
pdettori deleted the fix/216-config-cache-outlives-leaf branch September 5, 2026 15:48
pdettori added a commit to pdettori/moca that referenced this pull request Nov 16, 2026
Sixteen ADRs still said Proposed although their decisions are in code
on main. Each status line now names the merged PRs that implemented it
and the date the core landed (format of ADR-0042), and notes what is
still owed where only part is built:

- 0028 (rossoctl#170, rossoctl#201, rossoctl#340; its KEDA transport removed by ADR-0041)
- 0029 (rossoctl#171), 0030 (rossoctl#214), 0031 (rossoctl#214, rossoctl#225)
- 0032 (rossoctl#249, rossoctl#350, as amended by MI1)
- 0035 (rossoctl#251; ADR-0048 adds lease mode beside it)
- 0036 (rossoctl#347), 0038 (rossoctl#458), 0039 (rossoctl#467), 0040 (rossoctl#481)
- 0043 (rossoctl#560, rossoctl#588, rossoctl#600, rossoctl#615), 0044 (rossoctl#563), 0045 (rossoctl#620)
- 0046 (phase 1: rossoctl#630, rossoctl#641, rossoctl#646; phase 2 owed)
- 0047 (M1 and M3: rossoctl#704, rossoctl#713, rossoctl#717, rossoctl#765; M2 owed)
- 0048 (rossoctl#706, rossoctl#763, rossoctl#802, rossoctl#808, rossoctl#814; off by default until the
  security review's lease sections are signed off)

The README index follows, and its 0033 row, which still said Proposed
after rossoctl#249 accepted the ADR, is corrected.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Promoted config cache outlives its leaf in the shared pool sandbox, so a configRef-less leaf can answer from it

1 participant