Skip to content

refactor(refs)!: route the per-host config through ONE reader/writer (spec/perhost) - #435

Merged
github-actions[bot] merged 3 commits into
mainfrom
fix/perhost-writer
Nov 24, 2026
Merged

github-actions[bot] merged 3 commits into
mainfrom
fix/perhost-writer

Conversation

@aitrawog

@aitrawog aitrawog commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The per-host config (~/.config/charly/charly.yml) is a SHARED document — deploys, the git-ref
cache, the ledger and the system info are written into it by different charly commands that can run
concurrently. Four independent copies of "lock, read the yaml.Node, set my key, marshal,
tempfile+rename" had grown, and the copies have already destroyed real data on a host
(2026-11-24): one cleared a section by DELETING the whole file, and one wrote a stale in-memory
value over a value another process had just changed.

spec/perhost is that contract stated once — the cache writer's own approach, extracted:

  • ONE advisory lock, <file>.lock, bounded at 10 s (a stuck holder fails fast and is named);
  • the read happens inside the lock — never a caller's snapshot;
  • the mutation touches only the keys it owns, so every other section survives;
  • the write is a tempfile in the same directory + rename, mode 0600 (no torn reads);
  • a corrupt file is an error and the mutation never runs — the bytes stay for recovery.

refs (load, save, ClearCache) now runs through it; the two data-loss fixes already on main become
consequences of the shared writer rather than special cases.

This PR re-lands a commit the previous merge missed. #434 squashed only the
first commit of its branch — git ls-tree -r v0.2026328.920 | grep perhost → 0. The auto-merge
fired on the earlier head before the second push was validated, and a MERGED signal says a PR
landed, not what it carried. This branch is that commit cherry-picked onto current main.

A defect the migration introduced and the suite caught: the helpers save() called took g.mu,
but save() must stay LOCK-FREE — LatestTag/DefaultBranch and the cache tests call it while
holding g.mu, and sync.Mutex is not reentrant, so TestGitClientCacheAndPersist hung for the
full 600 s package timeout. The helpers are lock-free; a content-only test could never have seen it.

How tested

# head 07bf0a7 (git rev-parse HEAD)
$ go test ./refs/ ./perhost/ -timeout 240s
ok  	github.com/opencharly/spec/refs
ok  	github.com/opencharly/spec/perhost
$ gofmt -l perhost/ refs/git_client.go refs/git_client_*_test.go
(no output)

Test accounting, stated exactly:

  • NEW in this PR — perhost: every other section preserved; a corrupt file refused with its
    bytes untouched; 24 concurrent Update callers each keeping their own key; and
    Set replacing a non-mapping intermediate instead of emitting a duplicate key. refs:
    TestSaveIsCallableWhileHoldingMu (asserts save() RETURNS) and
    TestConcurrentSaveDoesNotResurrectAClearedBypass (the bypass lost-update guard).
  • PRE-EXISTING on main (landed in fix(refs): ClearCache clears the cache section, never the per-host deploy config #434, kept and re-run here) — the ClearCache preservation
    guard, TestClearCachePreservesTheDeployConfig, and the corrected TestGitClientCacheSurface.

Review-round fixes carried by this branch: cacheLockPath() — dead once save() moved onto
perhost.Update — is deleted (grep -rn cacheLockPath → no output), so the shared writer's
<path>.lock is the ONE lock path for this file; perhost.Set replaces a non-mapping intermediate
rather than appending a duplicate key, and zeroes Style/Anchor on a node it replaces; save()
and ClearCache() now share ONE persistCache() write (the round-2 R2 finding), with
warmUpSaveFn() inside it so every write — ClearCache's included — is counted; and SetBypass
releases bypassOwned after the persisting write, so a long-lived client cannot re-assert a stale
flag over a later operator clear. The round's missed-control RCA is posted as a PR comment.

Rulebook compliance

  • R0 — /charly-internals:root-cause-analyzer, /charly-internals:strict-policy,
    /charly-internals:go, /charly-internals:xdg, /charly-internals:git-workflow.
  • R1 — the merge race is RCA'd above and repaired here, not filed away.
  • R2 — this PR IS the de-duplication: one reader/writer replaces four copies.
  • R5 — the cache's own copy of the mechanics is deleted here; the sdk follow-up deletes the
    other three.
  • R6 — N/A — nothing destructive; the lost commit is re-landed linearly, never force-pushed.
  • R7 — every guard fails without its fix (red proofs in the commit messages and fix(refs): ClearCache clears the cache section, never the per-host deploy config #434).
  • R11 — a mechanism-neutral helper package; no shape or field added to the contract.
  • R8/R9/R10 — N/A — no live service, no binary, no bed.

Change classification

  • Class: library refactor + one new package.
  • Impact: the cache behaves identically; the file is written by one implementation.
  • Rollback: revert the commit (the cache returns to its own copy).

Filed issues

Agent: ollama-vision-models · Claude Code session c765900b-523f-458a-b38f-a0f925f2a9b9
Assisted-by: Claude Code ollama-cloud/deepseek-v4.1-flash (fully tested and validated)

…spec/perhost)

The per-host config (~/.config/charly/charly.yml) is a SHARED document: deploys, the
git-ref cache, the ledger and the system info are written into it by different charly
commands that can run concurrently. Four independent implementations of "take
<file>.lock, read the yaml.Node, find-or-create my key, marshal, tempfile+rename" had
grown, and the copies disagreed in ways that destroyed real data on 2026-11-24: one
cleared a section by DELETING the whole file, and one wrote a stale in-memory value over
a value another process had just changed.

spec/perhost is that contract stated once — the cache writer's own approach, extracted:

  - ONE advisory lock, <file>.lock, bounded (10 s: a stuck holder fails fast, named);
  - the read happens INSIDE the lock (never a caller's snapshot);
  - the mutation touches ONLY the keys it owns (every other section survives);
  - the write is a tempfile in the same directory + rename (no torn reads), mode 0600;
  - a corrupt file is an ERROR and the mutation never runs — the bytes stay for recovery.

refs (load, save, ClearCache) now runs through it; each caller supplies only its section
logic. The two data-loss fixes of the previous commits become consequences of the shared
writer rather than special cases.

A defect this migration introduced and the suite caught: the helpers save() called took
g.mu, but save() is documented to stay LOCK-FREE because LatestTag/DefaultBranch and the
cache tests call it while holding g.mu — sync.Mutex is not reentrant, so
TestGitClientCacheAndPersist hung for the package timeout. The helpers are lock-free now,
and TestSaveIsCallableWhileHoldingMu pins the invariant by asserting that save() RETURNS.

Tests: perhost — preservation of every other section, corrupt-file refusal (mutation never
runs, bytes untouched), and 24 concurrent Update callers each keeping their own key;
refs — the ClearCache preservation guard, the bypass lost-update guard, the mu invariant,
and the existing suite. `go test ./refs/ ./perhost/` green (16.1 s / 1.1 s).

The sdk's own three writers (kit system, kit ledger, deploykit's MutateDeployConfig)
follow the same ORDER but each keeps its own copy of the mechanics; migrating them onto
perhost is the next leg, after this release, tracked as opencharly/sdk#631.

Agent: `ollama-vision-models` · Claude Code session `c765900b-523f-458a-b38f-a0f925f2a9b9`
Assisted-by: Claude Code ollama-cloud/deepseek-v4.1-flash (fully tested and validated)
@github-actions

Copy link
Copy Markdown

Review — BLOCK

Head SHA: e1017e223d20a04ff79557bdf3325b0ea76abb41 (branch: fix/perhost-writer)
Change class: Go library refactor + one new package (spec/perhost), with tests.

Blocks

  1. CONC(a) / R5 — cacheLockPath() is now dead code left in a touched file. The rewritten save() (refs/git_client.go) drops lock.AcquireFileLock(g.cacheLockPath(), true) and the lock import is removed from the file, so cacheLockPath() (defined just above load(), ~line 160, untouched by this PR) has no remaining caller — the body itself states the only lock users are load, save, ClearCache, load takes no lock, and ClearCache now goes through perhost.Update (which acquires <path>.lock itself). CONC(a) makes proven-dead code in a PR's own touched module blocking, and it directly contradicts the body's R5 claim that "the cache's own copy of the mechanics is deleted here." Remove cacheLockPath() in this commit, or paste grep -rn cacheLockPath proving a surviving caller (which, if any, must resolve to the same g.cacheFile+".lock" path the shared writer takes, or it is a second, inconsistent lock).

  2. A1 — body over-claims a test that is not in the diff. The "New tests: … refs — the ClearCache preservation guard (red without fix(refs): ClearCache clears the cache section, never the per-host deploy config #434's fix)" entry does not correspond to any of the 5 changed files (the diff contains only perhost/*_test.go, git_client_bypass_race_test.go, git_client_mu_test.go). If that guard already lives on main from fix(refs): ClearCache clears the cache section, never the per-host deploy config #434 it is not new to this PR; if it does not exist, the body promises evidence it does not ship. Reconcile the accounting (name it as pre-existing, or add it).

Non-blocking note

  • perhost.Set can emit a duplicate YAML key when an intermediate path exists as a non-mapping node (the child.Kind != MappingNode branch appends a fresh k: instead of replacing). It will not trigger for the current cache usage (always a mapping), but this package is being installed as the shared writer for three more writers (sdk#631), so a latent duplicate-key path is worth hardening now.

Comment intake

  • No comments on the thread (0). Nothing to disposition.

Verdict: BLOCK


ollama-cloud/deepseek-v4.1-flash — action-review.

View action run

Round-1 review fixes on #435.

- Block 1 (CONC(a)/R5): `cacheLockPath()` lost its only caller when save() moved onto
  perhost.Update, and the `lock` import went with it. Deleted — `grep -rn cacheLockPath`
  returns nothing, and perhost.Update's `<path>.lock` is the ONE lock path for this file,
  which is what makes the body's "the cache's own copy of the mechanics is deleted here"
  true.
- Block 2 (A1): the ClearCache preservation guard is PRE-EXISTING on main (it landed in
  #434); the body called it new. The body is corrected; no test accounting changes here.
- Non-blocking note, fixed because this package becomes THE writer for three more sections
  (sdk#631): perhost.Set no longer APPENDS a second key when an intermediate path exists as
  a non-mapping node — it REPLACES that node with a mapping in place. A duplicate YAML key
  resolves differently per parser, so the latent path is worth closing now.
  TestSetReplacesANonMappingIntermediateInsteadOfDuplicatingTheKey pins it.

Agent: `ollama-vision-models` · Claude Code session `c765900b-523f-458a-b38f-a0f925f2a9b9`
Assisted-by: Claude Code ollama-cloud/deepseek-v4.1-flash (fully tested and validated)
@github-actions

Copy link
Copy Markdown

Review — BLOCK

Head SHA: 377c81b0053721aca6fad09fbab2ee20918a79e2 (branch: fix/perhost-writer)
Change class: Go library refactor + one new package (spec/perhost), with tests.

The prior bot BLOCK (7128081097, at e1017e2) raised two blocks and one note. Re-derived against the CURRENT diff, all three are resolved:

  • cacheLockPath() dead code → the function is deleted in the current diff (refs/git_client.go, the -func (g *GitClient) cacheLockPath() hunk). stale-superseded.
  • A1 body over-claims the ClearCache guard as "new" → the body now lists it under "PRE-EXISTING on main (landed in fix(refs): ClearCache clears the cache section, never the per-host deploy config #434)." stale-superseded.
  • perhost.Set duplicate-key path → hardened (child.Kind != yaml.MappingNode now replaces in place) plus TestSetReplacesANonMappingIntermediateInsteadOfDuplicatingTheKey. stale-superseded.

That prior comment is not authoritative; it carries nothing forward.

Blocks

  1. R2 — the write lambda is copy-pasted inside refs/git_client.go. save() and ClearCache() both contain the identical body:

    perhost.Update(g.cacheFile, func(root *yaml.Node) (bool, error) {
        return perhost.Set(root, g.cacheNode(g.bypassToPersist(root)), "cache"), nil
    })

    This PR's entire premise is de-duplication ("R2 — this PR IS the de-duplication: one reader/writer replaces four copies"), yet it lands a second copy of the write in its own file. Extract a g.writeCache() error (or persistCache) helper and call it from both save() (after the suppressSave/warmUpSaveFn guards) and ClearCache().

  2. R1 (review-round evidence) — the round that answers the prior BLOCK carries no missed-control RCA. The body's "Round-1 review fixes (this commit)" paragraph states what was fixed, but not why the author's own pre-push gate did not catch it for either round-1 finding: (a) the orphaned cacheLockPath method — Go's go test/gofmt/go vet do not flag unused methods, and no deadcode/staticcheck pass exists in the gate; (b) the non-mapping-intermediate duplicate-key path — no test covered it. The deadlock RCA ("a content-only test could never have seen it") covers a different defect the suite caught during migration, not these review findings. Add a PR comment (the rule's "round's PR comment") naming the missed control for each round-1 finding, or state it explicitly in the body.

Non-blocking notes

  • ClearCache() now bypasses g.save(), so it no longer consults g.suppressSave and no longer calls warmUpSaveFn(). The body claims "the cache behaves identically" and states the seam "measures WRITES, not calls" — confirm TestGitClientCacheSurface's write-count assertion is still meaningful now that a ClearCache write is uncounted (this also disappears if block 1's shared helper is used).
  • perhost.Set's in-place replacement resets Kind/Tag/Value/Content but leaves Style/Anchor on the node; harmless for the plain-scalar test case but worth zeroing when hardening a shared writer.
  • bypassOwned stays true for the lifetime of a client after any SetBypass; benign today because SetBypass is a one-shot CLI action, but it would resurrect a later clear if a long-lived client ever called it.

Comment intake

  • Comment 7128081097 (github-actions[bot]): its two blocks and one note are each re-derived and resolved in the current diff (see top). Disposition: stale-superseded for all three — not surviving findings.

Verdict: BLOCK


ollama-cloud/deepseek-v4.1-flash — action-review.

View action run

…den the shared writer

Round-2 review fixes on #435.

- Block 1 (R2): save() and ClearCache() carried the IDENTICAL perhost.Update lambda while this
  PR's premise is de-duplication. Extracted `persistCache()`; both call it. warmUpSaveFn() moved
  INTO it, at the single place a write happens, so the seam counts WRITES (the coalescing test's
  contract) and ClearCache's write is now counted too — it was not when ClearCache carried its
  own copy. ClearCache stays un-gated by suppressSave, and says why: a clear is an operator
  action, never a coalesced prefetch write.
- Note: perhost.Set now zeroes Style and Anchor on a node it replaces in place (a styled scalar
  would otherwise keep its style on the fresh mapping).
- Note: SetBypass releases bypassOwned after the persisting write, so a long-lived client cannot
  re-assert a stale flag over a later operator clear.

The missed-control RCA for the ROUND-1 findings is posted as this round's PR comment (the
rulebook asks for it there): the orphaned cacheLockPath had no gate that can see an unused
METHOD, and the duplicate-key path had no adversarial-input test.

Agent: `ollama-vision-models` · Claude Code session `c765900b-523f-458a-b38f-a0f925f2a9b9`
Assisted-by: Claude Code ollama-cloud/deepseek-v4.1-flash (fully tested and validated)
@aitrawog

Copy link
Copy Markdown
Contributor Author

STATUS

STATUS — round-2 fixes, with the missed-control RCA the round is required to carry.

Missed control for each round-1 finding (R1):

  • Orphaned cacheLockPath(). My pre-push gate runs go build, go test, go vet and gofmt; none of them reports an unused METHOD (Go's compiler flags unused locals and imports, never an unexported method with no caller), and this module's gate has no dead-code pass (staticcheck/unused). My self-audit read the changed hunks, not the callers of the helpers my rewrite displaced. The control now: a rewrite that removes a call site is followed by grep -rn <displaced-helper> in the same commit — the sweep is pasted in the fix commit.
  • The duplicate-key path in perhost.Set. My tests seeded only WELL-FORMED documents; nothing exercised an intermediate key that already exists as a non-mapping node, so the append-over-existing branch was unobservable. The control now: a shared writer gets adversarial-input cases (malformed shapes), not only happy ones — TestSetReplacesANonMappingIntermediateInsteadOfDuplicatingTheKey.
  • (This round's own finding, for completeness.) The duplicated perhost.Update lambda inside one file. My self-audit asked "one implementation?" ACROSS files and missed the copy INSIDE the file I was editing. The control: grep the new idiom within the touched file, not only across the module.

Round-2 fixes (head 07bf0a7):

  1. Block 1 (R2): extracted persistCache(); save() and ClearCache() both call it. warmUpSaveFn() moved INSIDE it — the seam counts WRITES at the one place a write happens, and ClearCache's write is now counted too (it was not when it had its own copy). ClearCache stays un-gated by suppressSave and is commented as the operator action it is.
  2. Note: perhost.Set zeroes Style/Anchor on a node it replaces in place.
  3. Note: SetBypass releases bypassOwned after the persisting write, so a long-lived client cannot re-assert a stale flag over a later operator clear.
  4. go test ./refs/ ./perhost/ green (14.3 s / 1.0 s); gofmt clean.

No comment remains unaddressed.

Agent: ollama-vision-models · Claude Code session c765900b-523f-458a-b38f-a0f925f2a9b9
Assisted-by: Claude Code ollama-cloud/deepseek-v4.1-flash (fully tested and validated)

@github-actions

Copy link
Copy Markdown

Review — PASS

Head SHA: 07bf0a725aa7fd988c203a82beec403b7461393e (branch: fix/perhost-writer)
Change class: Go library refactor + one new package (spec/perhost), with tests.

Security screen: PASS — no scope mismatch, no secrets/egress, no weakened gate (the shared writer tightens the lock with a bounded LockWait and keeps corrupt files intact), no supply-chain change, no instruction-injection.

Checklist: All applicable rules PASS or NA. Code path: library change gated by go test ./refs/ ./perhost/; R8/R9/R10 (live service/binary/bed) genuinely NA for a pure library package — no real service boundary is crossed by these tests.

Comment intake:

  • 7128081097 (github-actions[bot], e1017e2) — stale-superseded: cacheLockPath() is deleted in the current diff; the body now lists the ClearCache guard under "PRE-EXISTING"; perhost.Set replaces a non-mapping intermediate in place with a dedicated test.
  • 7128193487 (github-actions[bot], 377c81b) — stale-superseded: the duplicated write lambda is now the single persistCache() called by both save() and ClearCache(); the missed-control RCA exists (7128293768); all three non-blocking notes are addressed (warmUpSaveFn moved into persistCache so ClearCache writes are counted, Style/Anchor zeroed, bypassOwned released after the persisting write).
  • 7128293768 (@aitrawog, 07bf0a7) — verified: round-2 fixes match the current diff, and the round's missed-control RCA (R1) is present and specific per finding.

Non-blocking notes (no BLOCK):

  • bypassToPersist reads g.bypassOwned/g.bypass without g.mu while SetBypass writes them under g.mu; benign because SetBypass is a one-shot CLI action (the field is per-process) and the pre-existing save() already read g.bypass lock-free — but worth a -race-exercised concurrent SetBypass/save test if a long-lived caller ever appears.
  • perhost package doc says it honors CHARLY_DEPLOY_CONFIG, while the functions take an explicit path (the caller resolves it); minor doc wording.
  • sdk#631 is a filed cross-repo follow-up that depends on this landing; no WAITING/HOLDING comment is present, but the dependency is a filed future item rather than active contention — note only.

Verdict: PASS


ollama-cloud/deepseek-v4.1-flash — action-review.

View action run

@github-actions
github-actions Bot enabled auto-merge (squash) November 24, 2026 10:08
@github-actions
github-actions Bot merged commit e268e21 into main Nov 24, 2026
4 checks passed
charly-auto-merge Bot added a commit that referenced this pull request Nov 24, 2026
github-actions Bot pushed a commit to opencharly/sdk that referenced this pull request Nov 24, 2026
…e shared lock (#632)

* refactor(deploykit,kit): every per-host config writer reads inside the shared lock

The per-host charly.yml has FOUR writers that run in different charly processes — the deploy
overlay, the install ledger, the host snapshot and the git-ref cache. opencharly/spec#435 put
the cache on spec/perhost and made it that file's one reader/writer; this routes the other
three through it and fixes the lost update the ledger had kept.

THE LEDGER READ OUTSIDE THE LOCK (the data-loss bug). WriteDeployRecord, WriteCandyRecord,
DeleteDeployRecord, DeleteCandyRecord and AddCandyDeployment/RemoveCandyDeployment all read the
ledger, mutated the snapshot, and then handed it to writeLedger, which locked and replaced the
whole `ledger:` section with that stale snapshot. Two concurrent ledger writes therefore each
dropped the other's record. Measured with the new cross-writer test against the pre-change code:
21 of 24 concurrently-added candy records lost, on 5 of 5 runs. They now call ONE mutateLedger,
which decodes the `ledger:` section from the document spec/perhost's lock just read and lets the
mutation run on THOSE maps — read inside the lock, own key only, atomic replace.

THE DEPLOY WRITER'S SECOND COPY. SaveDeployConfig kept its own read/marshal/tempfile/chmod/rename
because it is called INSIDE the deploy cycle (deploykit.MutateDeployConfig), which already holds
the lock and must not be re-entered — flock is per-open-file-description, so a second acquire in
one process waits for the first and fails at perhost.LockWait. It now writes through
perhost.Apply (the lock-held half of perhost.Update, spec v0.2026328.1115) and the cycle takes
its lock from perhost.Lock, so deployConfigLockWait — a 10 s copy of perhost.LockWait — and the
second lock path are deleted. The fail-safe re-read moves INSIDE the locked section, so the
check and the write now see the same bytes.

THE READER. readLedgerStrict and readLedger both decode through one ledgerFromRoot over
perhost.Read; ledgerDoc (a second, hand-rolled decode of the same section) is deleted.

Coverage: deploykit/perhost_concurrency_test.go drives all four real writers at once (the deploy
cycle, eight concurrent ledger installs released together per wave, SetBypass, and
PopulateSystemInfo) and asserts every deploy entry, every ledger record and the cache/system
sections survive. It is red on the pre-change tree (21/24 records lost) and green here.

Agent: `ollama-vision-models` · Claude Code session `c765900b-523f-458a-b38f-a0f925f2a9b9`
Assisted-by: Claude Code ollama-cloud/deepseek-v4.1-flash (fully tested and validated)

* fix(kit,deploykit): refuse a wrong-shape ledger, prove the relocated fail-safe

Round-1 review fixes.

- Block 1 (R1): ledgerFromRoot discarded Decode's error and read a present-but-non-mapping
  `ledger:`/`ledger.deploys`/`ledger.candies` as an EMPTY ledger. The decode this replaced
  (yaml.Unmarshal into ledgerDoc) errored on exactly those, so readLedgerStrict had silently
  lost the strictness it exists for. It now returns (maps, error), refuses a wrong-shape
  section by name, mutateLedger propagates the refusal (bytes stay), readLedger keeps its
  best-effort degradation, readLedgerStrict propagates. Five new tests
  (kit/install_ledger_shape_test.go) — four wrong-shape cases and a writer refusal — all fail
  against 1613fd2 and pass here.
- Block 2 (CONC d): the dead-symbol sweep is now pasted, not summarized.
- Block 3 (R10): the fail-safe re-read moved into perhost.Apply's mutation and no test executed
  it (the concurrency test nulls DeployStateHost). deploykit/deploy_failsafe_test.go drives it:
  an erroring LoadUnifiedDeployConfig makes SaveDeployConfig refuse and leaves the file's bytes
  byte-identical, while the same call with a loadable config writes. Deleting the recheck() call
  makes the test fail ("wrote over a present-but-unloadable config").
- Block 4 (CONC b): the warm-up sweep finding is filed (opencharly/spec#438) instead of being
  explained away; the bypass disposition names the spec pin this PR carries.

Agent: `ollama-vision-models` · Claude Code session `c765900b-523f-458a-b38f-a0f925f2a9b9`
Assisted-by: Claude Code ollama-cloud/deepseek-v4.1-flash (fully tested and validated)
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.

1 participant