diff --git a/docs/architecture/tla/HistoryStoreCache.ReadersStayBlind.cfg b/docs/architecture/tla/HistoryStoreCache.ReadersStayBlind.cfg new file mode 100644 index 0000000000..e2eb81520c --- /dev/null +++ b/docs/architecture/tla/HistoryStoreCache.ReadersStayBlind.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "ReadersStayBlind" +INVARIANTS TypeOK HostRecordIsItsOwnBaseline PeerTitleCopiesIntoHost PeerFieldSurvivesStaleSave PeerUpdateReachesReaders PublishedSaveKeepsPeerField +CHECK_DEADLOCK FALSE + diff --git a/docs/architecture/tla/HistoryStoreCache.RefreshAdopts.cfg b/docs/architecture/tla/HistoryStoreCache.RefreshAdopts.cfg new file mode 100644 index 0000000000..5966a712db --- /dev/null +++ b/docs/architecture/tla/HistoryStoreCache.RefreshAdopts.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "RefreshAdopts" +INVARIANTS TypeOK HostRecordIsItsOwnBaseline PeerFieldSurvivesStaleSave PublishedSaveKeepsPeerField +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/HistoryStoreCache.RefreshEvicts.cfg b/docs/architecture/tla/HistoryStoreCache.RefreshEvicts.cfg new file mode 100644 index 0000000000..250fa177bf --- /dev/null +++ b/docs/architecture/tla/HistoryStoreCache.RefreshEvicts.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "RefreshEvicts" +INVARIANTS TypeOK HostRecordIsItsOwnBaseline PeerTitleCopiesIntoHost PeerFieldSurvivesStaleSave PublishedSaveKeepsPeerField +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/HistoryStoreCache.SettleAdopts.cfg b/docs/architecture/tla/HistoryStoreCache.SettleAdopts.cfg new file mode 100644 index 0000000000..c0eaaa2a58 --- /dev/null +++ b/docs/architecture/tla/HistoryStoreCache.SettleAdopts.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "SettleAdopts" +INVARIANTS TypeOK HostRecordIsItsOwnBaseline PeerFieldSurvivesStaleSave PublishedSaveKeepsPeerField +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/HistoryStoreCache.ViewSaveDisputedFromCache.cfg b/docs/architecture/tla/HistoryStoreCache.ViewSaveDisputedFromCache.cfg new file mode 100644 index 0000000000..693170a97d --- /dev/null +++ b/docs/architecture/tla/HistoryStoreCache.ViewSaveDisputedFromCache.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "ViewSaveDisputedFromCache" +INVARIANTS TypeOK HostRecordIsItsOwnBaseline PeerTitleCopiesIntoHost PeerFieldSurvivesStaleSave PeerUpdateReachesReaders PublishedSaveKeepsPeerField DisputedSaveKeepsPostScanPeerField +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/HistoryStoreCache.ViewSaveFromCache.cfg b/docs/architecture/tla/HistoryStoreCache.ViewSaveFromCache.cfg new file mode 100644 index 0000000000..fa16be5a26 --- /dev/null +++ b/docs/architecture/tla/HistoryStoreCache.ViewSaveFromCache.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "ViewSaveFromCache" +INVARIANTS TypeOK HostRecordIsItsOwnBaseline PeerTitleCopiesIntoHost PeerFieldSurvivesStaleSave PeerUpdateReachesReaders PublishedSaveKeepsPeerField +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/HistoryStoreCache.cfg b/docs/architecture/tla/HistoryStoreCache.cfg new file mode 100644 index 0000000000..cbddd5bd79 --- /dev/null +++ b/docs/architecture/tla/HistoryStoreCache.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "Fixed" +INVARIANTS TypeOK HostRecordIsItsOwnBaseline PeerTitleCopiesIntoHost PeerFieldSurvivesStaleSave PeerUpdateReachesReaders PublishedSaveKeepsPeerField DisputedSaveKeepsPostScanPeerField +CHECK_DEADLOCK FALSE + diff --git a/docs/architecture/tla/HistoryStoreCache.tla b/docs/architecture/tla/HistoryStoreCache.tla new file mode 100644 index 0000000000..e6efc2ba61 --- /dev/null +++ b/docs/architecture/tla/HistoryStoreCache.tla @@ -0,0 +1,377 @@ +---- MODULE HistoryStoreCache ---- +\* Models the per-host cache of TaskHistoryStore (src/core/task-persistence/TaskHistoryStore.ts). +\* Source: the other host saves a field and sets the auto title on the same record. Sink: reconcile +\* writes the cache, the settle path of setAutoTitleIfAbsent copies a field, and upsert reads the +\* cache to build the delta of its next save. Production starts a reconcile from the file watcher +\* 500 ms after a write event, so a reconcile can land inside another host's write sequence. +\* Failure: the watcher reconcile replaced a record this host held with the peer record. The host's +\* next save then diffed against the peer record, so this host's older field value went back out over +\* the peer value. CI job 144242012101 on PR 1321 shows it on Windows, where the check is slow enough +\* for the debounce to land inside it. One task file is shared by two extension hosts. +\* Invariant HostRecordIsItsOwnBaseline: after a skipped auto title settles, the host cache still +\* holds the field this host wrote. That cache is what the next write delta is measured against. +\* Invariant PeerTitleCopiesIntoHost: the settle copies the peer auto title into the host cache. +\* Invariant PeerFieldSurvivesStaleSave: the host save after the settle keeps the peer field on disk. +\* Modes: Fixed - reconcile adds a record the host lacks and keeps a record it holds. RefreshAdopts - +\* reconcile replaces a record the host holds. RefreshEvicts - the watcher sees the file gone during a +\* rename, the entry is dropped, and the settle then adopts the peer record it read. SettleAdopts - +\* the settle copies the whole peer record instead of only the auto title. +\* Expect: Fixed holds all three invariants. RefreshAdopts, RefreshEvicts and SettleAdopts each fail +\* HostRecordIsItsOwnBaseline and PeerFieldSurvivesStaleSave. PeerTitleCopiesIntoHost is expected to +\* hold in every mode: the fix copies the peer title, and no sabotage removes that copy. +\* Not modeled: task ids, the record lock, the mtime skip that decides when a reconcile re-reads, the +\* peer cache, record creation and removal, and every field but the two the failure needs. +\* Result: Fixed holds all three invariants in 11 states. Each run takes 1.5 to 2.4 seconds, java start +\* included. RefreshAdopts fails HostRecordIsItsOwnBaseline in 17 states and PeerFieldSurvivesStaleSave +\* in 14 states, and holds PeerTitleCopiesIntoHost in 25 states: adopting the peer record does not lose +\* the peer title, so the title half is not what breaks. RefreshEvicts fails all three: HostRecordIs +\* ItsOwnBaseline and PeerTitleCopiesIntoHost in 18 states and PeerFieldSurvivesStaleSave in 25 states. +\* The extra failure was not expected. Dropping the live entry leaves the host holding no record after +\* a settle, which is the third observable: the host read returns nothing until a later scan adds it. +\* SettleAdopts fails HostRecordIsItsOwnBaseline in 8 states and PeerFieldSurvivesStaleSave in 12 states +\* and holds PeerTitleCopiesIntoHost in 14 states. check.sh runs the four configs and exits 0. +\* Replay: the RefreshAdopts trace (host save, peer save, peer title, reconcile, settle) is the failing +\* row on the parent code. Run with the parent file it fails at the cache read; run with this change it +\* passes. The scratch probe showed the same values with a 700 ms wait for the real watcher debounce. +\* Review: 0 covered, 1 added, 0 gap. Added: CI job 144242012101 (PR 1321, run 47103197306). No review +\* thread exists for it yet, so the run id stands in place of a thread id in the commit message body. +\* Near model: scripts/check-task-store-concurrency.ts offers a refresh that replaces a whole host cache +\* with the disk record, so it encodes the pre-change rule and no invariant of it pins this baseline. +\* Cost: 20 TLC runs in all: 12 per-invariant runs, then two check.sh runs of four configs each. +\* Each run takes 0.8 to 3.8 seconds, java start included. +\* Agent time is not measured. +\* Property test: src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts, the +\* row "keeps this host's own record as the baseline when a reconciliation runs around it". +\* Second change (PR 1321, review thread 4793464968): get() and getAll() read the host cache, so a +\* reconcile that kept this host's record also kept the record it read away from every reader. A +\* history reader then reported this host's field after the file already carried the peer field. +\* Invariant PeerUpdateReachesReaders: after a reconcile read a peer field beside a record this host +\* holds, a host read reports the peer field. The host read falls back to the cache only after this +\* host saved, settled or re-based, which is the save baseline the next delta is measured against. +\* Mode ReadersStayBlind: the scan keeps the cache, which is the baseline rule, but the readers keep +\* reading the cache. That is the code before this change and the sabotage for the new invariant. +\* Expect: Fixed holds PeerUpdateReachesReaders with the three older invariants. ReadersStayBlind +\* fails PeerUpdateReachesReaders and holds the other three, which isolates the reader half from the +\* baseline half. The three older sabotage modes keep their verdicts; RefreshEvicts now fails the new +\* invariant too, because dropping the live entry leaves the reader view empty while scannedPeerField +\* is set. SettleAdopts is not expected to touch the new invariant. +\* Not modeled for this change: the mtime skip that decides when a scan re-reads, task ids, and the +\* delete path that drops a reader view. One record and one reader view are enough to show the order. +\* Result (second change): Fixed holds PeerUpdateReachesReaders with the three older invariants in 22 +\* states. ReadersStayBlind fails PeerUpdateReachesReaders in 6 states and holds the other three, so +\* the counterexample is the reader half alone: HostSave, then PeerSave, then Reconcile. RefreshEvicts +\* fails the new invariant in 7 states too: the scan drops the live entry, so a reader has nothing to +\* report while the witness that a peer field was scanned is still set. That extra failure was not +\* expected. RefreshAdopts and SettleAdopts hold the new invariant, as expected, because both publish +\* what the scan read. check.sh runs the five configs: HistoryStoreCache.cfg passes and the four +\* variants fail, and the script exits 0. +\* The per-invariant state counts of the first change moved after the two new state variables joined +\* the state: RefreshAdopts 17 to 18 (the stale-save count stayed 14), RefreshEvicts 18 to 20, 18 to 20 +\* and 25 to 27, and SettleAdopts 8 to 11 and 12 to 19. Every verdict stayed where the first change +\* recorded it. +\* Cost (second change): 30 TLC runs - 25 per-invariant runs over the five modes, four probe runs and +\* four bisection runs while diagnosing a TLC quirk, then one check.sh run of the five configs. A +\* per-invariant run takes 0.8 to 1.1 seconds and a five-config check.sh run 5.2 seconds, java start +\* included; the eight diagnosis runs took 0.2 to 1.1 seconds each. TLC once reported "Successor state +\* is not assigned" for an action that assigns a variable the empty tuple inside IF ... THEN ... ELSE; +\* writing the two assignments inside the branches fixed it. That +\* is a tool report, not a finding about the store. Agent time is not measured. +\* Property test (second change): src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts, five rows +\* inside describe("reconcile()"). "publishes a peer record to the readers after a scan without +\* re-basing the save baseline" is the trace above: the scan reads the peer record, the reader reports +\* it, the cache does not. "drops the published record when a later scan finds the file equal to the +\* baseline" covers the Reconcile-equal branch that clears the reader view. "lets a forced refresh +\* re-base the record a plain scan had only published" covers the forced mode writing the baseline. +\* "stops applying a published record to the list once this host writes its own" and "stops answering a +\* single read from a published record once this host writes its own" cover the reader view stopping +\* when the baseline object is gone. All five are red on the parent file and green here. Four sabotage +\* runs pin them line by line: deleting the drop leaves a row red, dropping the forced-refresh test from +\* the branch choice leaves one red, forcing the list guard reds one, and forcing the read guard reds +\* two. The replay matches the model trace: the scan reads the peer record, the reader reports it, the +\* cache does not. +\* Review ratchet (second change): 1 covered, 1 added, 0 gap. PR 1321 thread 4793464968 is added: +\* the first version of this spec had no reader view, so it could not express the finding. The +\* baseline half of the same thread was covered by HostRecordIsItsOwnBaseline on the first version. +\* Third change (PR #2846, review thread 4804929990): get() and getAll() return the record a scan +\* read from disk, but the save baseline stayed the older cached record, so upsertCore built its +\* delta against that cache. A caller that read a peer-updated record, changed one unrelated field, +\* and saved wrote the peer's values back over a newer peer write - the thread's pendingAction A, B, +\* C example. Before the reader view existed the scan made the published record the baseline, so a +\* save from that record excluded the peer's field and the overwrite did not occur. +\* Action PeerSave2: the peer writes a second field value after the scan published the first. +\* Action ViewSave: a reader spreads the published record, changes its own title, and saves; the +\* save diffs the reader view, so the published field is unchanged by the caller and does not ride +\* the delta over the newer peer value. Invariant PublishedSaveKeepsPeerField: after such a save +\* the newer peer field is still on disk. Mode ViewSaveFromCache: the save diffs the stale cache +\* baseline and writes the published field back over the newer peer value - the code before the fix +\* and the sabotage for the new invariant. +\* Guards: ViewSave needs ~saved, ~settled and ~viewSaved, and StaleSave gains ~viewSaved, so one +\* save observable fires per trace. PeerUpdateReachesReaders gains ~viewSaved: a save from the +\* reader view replaces the reader view with what was written, so the publish half of that +\* invariant is checked only on traces without such a save. Its equality also widens from "peer" +\* to any peer value: PeerSave2 moves the field to "peer2" while the scanned flag stays set, so +\* the old body would fail on a trace where the peer wrote twice before the next scan. +\* ReadersStayBlind still fails the widened body - its reader holds "own". PeerFieldSurvivesStaleSave's +\* consequent widens the same way for the same reason; the four sabotaged modes still fail it. +\* PeerSave's guard also requires the field to be outside the peer2 family: a later first-value write +\* would revert the field PublishedSaveKeepsPeerField pins, and the peer's second value is the one +\* the post-save scenario keeps writing. HostRecordIsItsOwnBaseline's pin stops at a reader-view save: +\* that save replaces the cache with what was written, and the written record is the new baseline. +\* Expect: Fixed holds all six invariants. ViewSaveFromCache fails PublishedSaveKeepsPeerField and +\* holds the other five, which isolates the save-baseline half from the reader half. ReadersStayBlind, +\* RefreshAdopts, RefreshEvicts and SettleAdopts keep their recorded verdicts and hold the new +\* invariant: ViewSave needs a published reader view and a second peer value, and the view-base +\* branch keeps the peer field whatever the mode. +\* Not modeled for this change: task ids, the record lock, the mtime skip, the peer cache, record +\* creation and removal, and every field but the two the failure needs. One record, one reader view +\* and two peer field values are enough to show the order. +\* Result (third change): Fixed holds all six invariants in 64 states. ViewSaveFromCache fails +\* PublishedSaveKeepsPeerField in 11 states and holds the other five - the per-invariant runs confirm +\* it - so the counterexample is the save-baseline half alone: HostSave, PeerSave, PeerSave2, +\* Reconcile, then a save spread from the published record writes the published field back over the +\* newer peer value. ReadersStayBlind, RefreshAdopts, RefreshEvicts and SettleAdopts keep their +\* recorded verdicts (7, 19, 31 and 15 distinct states) and hold the new invariant. Four failures +\* were model-only, found by the model rather than the review: PeerSave2 made the old "= peer" bodies +\* of PeerUpdateReachesReaders and PeerFieldSurvivesStaleSave fail, a settle after a reader-view save +\* made HostRecordIsItsOwnBaseline fail, and a first-value peer write after ViewSave made +\* PublishedSaveKeepsPeerField fail; the Guards paragraph above records each widening or guard. +\* check.sh runs the six configs: HistoryStoreCache.cfg passes and the five variants fail, and the +\* script exits 0. +\* Review ratchet (third change): 1 covered, 1 added, 0 gap. PR #2846 thread 4804929990: the +\* baseline half (the save baseline stays this host's record) is covered by +\* HostRecordIsItsOwnBaseline; the reader-save half is added as PublishedSaveKeepsPeerField, because +\* the first version of this spec had no save-from-the-reader-view action and could not express it. +\* Property test (third change): src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts, the +\* row "keeps a newer peer field when a save spreads the published record" inside describe("reconcile()"), +\* red on the parent file and green here. The two stale-save rows now assert the persisted disk +\* status, and the safeWriteJson mock honors the merge callback so the rows exercise the real merge. +\* Cost (third change): 16 TLC runs - five check.sh runs (four while diagnosing the four model-only +\* failures, one green), five manual runs to read each violation trace, six per-invariant runs over +\* ViewSaveFromCache. A manual or per-invariant run takes under a second and a six-config check.sh +\* run about six seconds, java start included. Agent time is not measured. +\* Fourth change (PR #2846, CR walkthrough row "Persistence Integrity = ERROR (lost-update)"): +\* saveBaseline collapsed the whole save onto the cache baseline as soon as one key disputed, so a +\* save disputing one field also carried the reader view's values for the fields the caller never +\* touched and wrote them over the peer's post-scan values. The fix prices the delta per key against +\* the reader view: saveDelta keeps a key only when the incoming value differs from the view and, +\* while the view disagrees with the cache, also differs from the cache. +\* Model: PeerSave2 now moves the title beside the field (the peer's post-scan write touches both), +\* ViewSaveDisputed spreads the published record and disputes the field to "peer3" while leaving the +\* title at the published value, and DisputedSaveKeepsPostScanPeerField pins that the post-scan title +\* survives the save. PublishedSaveKeepsPeerField is now scoped to saves whose title is "own" (the +\* ViewSave shape) so the disputed save does not falsify it, and PeerTitle is gated on ~viewSaved so +\* a peer auto title written after a save cannot read as the save having lost the title. Per-config +\* state counts moved with that scoping: 90/7/20/35/16/10/11. +\* Expect: Fixed holds all seven invariants; ViewSaveDisputedFromCache (the collapse rule) fails +\* DisputedSaveKeepsPostScanPeerField and holds the other six. +\* Result: Fixed passes in 90 distinct states; ViewSaveDisputedFromCache fails +\* DisputedSaveKeepsPostScanPeerField in 10 states - the collapse writes the view's title back over +\* the peer's post-scan "peer2" title - and holds the other six; the five older variants keep their +\* fail verdicts with moved counts. check.sh exits 0 over the seven configs. +\* Review ratchet (fourth change): 1 covered, 1 added, 1 gap. Covered: PublishedSaveKeepsPeerField +\* (third change, thread 4804929990) covers the view-base half of the same save path. Added: +\* DisputedSaveKeepsPostScanPeerField for the CR walkthrough lost-update row (no thread id yet, the +\* row text stands in). Gap: the stale-snapshot clause of saveDelta (a key whose incoming value still +\* equals the cache baseline drops out) is not modeled - the spec has no pre-publish snapshot variable. +\* Property test (fourth change): TaskHistoryStore.spec.ts, describe("save against the reader view +\* (lost-update defense)"): the get() row and the getAll() row are red on the parent file (saveBaseline) +\* with "peer summary" vs "peer summary 2" and green here; the stale-snapshot row pins the published +\* record against a pre-publish save. Negative control: stashing TaskHistoryStore.ts fails the two +\* rows and leaves 50 passing. +\* Cost (fourth change): 9 TLC runs - three check.sh runs over seven configs (first six-config shape, +\* two scoped reruns after model fixes), three per-config traces (Fixed violation, PeerTitle leak, +\* discriminator check), four edit-and-rerun cycles. A check.sh run is about six seconds, java start +\* included. Agent time is not measured. + + +CONSTANT Mode + +VARIABLE hostCache, hostRead, scannedPeerField, disk, hostSnap, settled, saved, viewSaved +vars == <> + +\* "own" is the value this host wrote. "peer" and "peer2" are the values the other host wrote, in +\* scan order. "none" is unset. +FieldVals == {"own", "peer", "peer2", "peer3", "none"} +Record == [field: FieldVals, title: FieldVals] +NoRecord == <<>> + +TypeOK == /\ hostCache \in Record \cup {NoRecord} /\ hostRead \in Record \cup {NoRecord} + /\ disk \in Record \cup {NoRecord} /\ hostSnap \in Record \cup {NoRecord} + /\ scannedPeerField \in BOOLEAN /\ settled \in BOOLEAN /\ saved \in BOOLEAN + /\ viewSaved \in BOOLEAN + +Init == /\ hostCache = NoRecord /\ hostRead = NoRecord /\ scannedPeerField = FALSE + /\ disk = NoRecord /\ hostSnap = NoRecord /\ settled = FALSE /\ saved = FALSE + /\ viewSaved = FALSE + +\* This host saves its own field value. Its cache and the snapshot it holds both read "own" after. +HostSave == + /\ hostSnap = NoRecord + /\ disk' = [field |-> "own", title |-> "none"] + /\ hostCache' = [field |-> "own", title |-> "none"] + /\ hostSnap' = [field |-> "own", title |-> "none"] + /\ hostRead' = [field |-> "own", title |-> "none"] + /\ UNCHANGED <> + +\* The other host saves its field value onto the same record. Its own cache is not a variable: only +\* the shared file and this host's cache enter the invariants. The first-value write happens only +\* from a clean field: once the peer wrote its second value the field stays in the peer2 family, so +\* a save from the reader view is not later reverted by a first-value write. +PeerSave == + /\ disk # NoRecord + /\ disk.field # "peer" + /\ disk.field # "peer2" + /\ disk' = [field |-> "peer", title |-> disk.title] + /\ UNCHANGED <> + +\* The other host writes a second field value after a scan published the first. The reader view +\* keeps the published value until the next scan, a settle or a save replaces it. +PeerSave2 == + /\ disk # NoRecord + /\ disk.field # "peer2" + /\ disk' = [field |-> "peer2", title |-> "peer2"] + /\ UNCHANGED <> + +\* The other host sets the auto title. A settle by this host then reads it and skips its own write. +PeerTitle == + /\ disk # NoRecord + /\ disk.title # "peer" + /\ ~viewSaved + /\ disk' = [field |-> disk.field, title |-> "peer"] + /\ UNCHANGED <> + +\* A reconcile scans the task directory. It adopts a record this host lacks in every mode, and it +\* publishes what it read to the reader view. ReadersStayBlind is the code before the second change: +\* the cache keeps this host's record, and a reader still reads the cache. +Reconcile == + /\ disk # NoRecord + /\ ( /\ Mode = "RefreshAdopts" + /\ hostCache' = disk + /\ hostRead' = disk + \/ /\ Mode = "RefreshEvicts" + /\ IF hostCache # NoRecord + THEN /\ hostCache' = NoRecord + /\ hostRead' = NoRecord + ELSE /\ hostCache' = disk + /\ hostRead' = disk + \/ /\ Mode = "ReadersStayBlind" + /\ IF hostCache = NoRecord THEN hostCache' = disk ELSE UNCHANGED hostCache + /\ hostRead' = IF hostCache = NoRecord THEN disk ELSE hostCache + \/ /\ (Mode = "Fixed" \/ Mode = "SettleAdopts" \/ Mode = "ViewSaveFromCache") + /\ IF hostCache = NoRecord THEN hostCache' = disk ELSE UNCHANGED hostCache + /\ hostRead' = disk + ) + /\ scannedPeerField' = IF disk.field = "peer" THEN TRUE ELSE scannedPeerField + /\ UNCHANGED <> + +\* The settle path of setAutoTitleIfAbsent: the record carries a peer auto title, so this host skips +\* its write and copies only auto title into its cache. With nothing cached it adopts what it read. +Settle == + /\ hostSnap # NoRecord + /\ disk # NoRecord + /\ disk.title = "peer" + /\ ~settled + /\ hostCache' = IF hostCache = NoRecord THEN disk + ELSE IF Mode = "SettleAdopts" THEN disk + ELSE [hostCache EXCEPT !.title = disk.title] + /\ hostRead' = hostCache' + /\ scannedPeerField' = FALSE + /\ settled' = TRUE + /\ UNCHANGED <> + +\* This host saves the snapshot it took before the peer write. A delta holds a field only when the +\* snapshot differs from this host's cache, so a cache that keeps its own value writes nothing back. +StaleSave == + /\ hostSnap # NoRecord + /\ disk # NoRecord + /\ disk.field = "peer" + /\ ~saved + /\ ~viewSaved + /\ disk' = IF hostCache # NoRecord /\ hostSnap.field # hostCache.field + THEN [disk EXCEPT !.field = hostSnap.field] + ELSE disk + /\ hostCache' = disk' + /\ hostRead' = disk' + /\ scannedPeerField' = FALSE + /\ saved' = TRUE + /\ UNCHANGED <> + +\* A reader spreads the record the scan published, changes its own title, and saves. The save diffs +\* the reader view: the published field is unchanged by the caller, so it does not ride the delta +\* over the peer value written after the scan. ViewSaveFromCache is the code before that fix: the +\* save diffs the stale cache baseline and writes the published field back over the newer peer value. +ViewSave == + /\ hostRead # NoRecord + /\ disk # NoRecord + /\ disk.field = "peer2" + /\ ~saved + /\ ~settled + /\ ~viewSaved + /\ disk' = IF Mode = "ViewSaveFromCache" + THEN [disk EXCEPT !.field = hostRead.field, !.title = "own"] + ELSE [disk EXCEPT !.title = "own"] + /\ hostCache' = disk' + /\ hostRead' = disk' + /\ scannedPeerField' = scannedPeerField + /\ viewSaved' = TRUE + /\ UNCHANGED <> + +\* A reader spreads the published record, contends its own field to "none" and leaves the title at +\* the published value. The per-key delta carries only the contended field, so the title the peer +\* moved after the scan stays on disk. ViewSaveDisputedFromCache is the collapse rule: one disputed +\* key sends the whole delta against the stale cache baseline, so the untouched title rides the +\* scan-time published value back over the newer peer value. +ViewSaveDisputed == + /\ hostRead # NoRecord + /\ disk # NoRecord + /\ disk.field = "peer2" + /\ disk.title = "peer2" + /\ ~saved + /\ ~settled + /\ ~viewSaved + /\ disk' = IF Mode = "ViewSaveDisputedFromCache" + THEN [disk EXCEPT !.field = "peer3", !.title = hostRead.title] + ELSE [disk EXCEPT !.field = "peer3"] + /\ hostCache' = disk' + /\ hostRead' = disk' + /\ scannedPeerField' = scannedPeerField + /\ viewSaved' = TRUE + /\ UNCHANGED <> + +Next == HostSave \/ PeerSave \/ PeerSave2 \/ PeerTitle \/ Reconcile \/ Settle \/ StaleSave \/ ViewSave \/ ViewSaveDisputed + +Spec == Init /\ [][Next]_vars + +\* Half one of the policy: the cache a later delta is measured against keeps this host's value. +\* A save from the reader view replaces the cache with what was written, and that record is the new +\* baseline - its field is what PublishedSaveKeepsPeerField pins - so the pin stops at that save. +HostRecordIsItsOwnBaseline == + IF settled /\ ~saved /\ ~viewSaved THEN hostCache # NoRecord /\ hostCache.field = "own" ELSE TRUE + +\* Half two: skipping the write must not lose the peer auto title. +PeerTitleCopiesIntoHost == + IF settled /\ ~saved THEN hostCache # NoRecord /\ hostCache.title = "peer" ELSE TRUE + +\* The consequence: saving the stale snapshot must not put this host's old value back on disk. The +\* field stays a peer value, whichever the peer wrote last: PeerSave2 can move it after the stale +\* save, and the sabotaged modes still fail - their stale save writes "own" back. +PeerFieldSurvivesStaleSave == IF saved THEN disk # NoRecord /\ disk.field # "own" /\ disk.field # "none" ELSE TRUE + +\* The reader half of the second change: what the scan read must reach a host read, and it may fall +\* back to this host's record only when this host saved or settled, which replaces the reader view. +PeerUpdateReachesReaders == + IF scannedPeerField /\ ~viewSaved + THEN hostRead # NoRecord /\ hostRead.field # "own" /\ hostRead.field # "none" + ELSE TRUE + +\* The save-baseline half of the third change: a save spread from the published record keeps the +\* newer peer field on disk instead of writing the published value back over it. +PublishedSaveKeepsPeerField == (viewSaved /\ disk.title = "own") => (disk # NoRecord /\ disk.field = "peer2") + +\* The fourth change: a disputed save carries only the keys the caller changed, so a save that +\* contends one field keeps the title the peer moved after the scan instead of writing the +\* scan-time published value back over it. +DisputedSaveKeepsPostScanPeerField == + (viewSaved /\ disk.field = "peer3") => (disk.title = "peer2") + +==== diff --git a/src/core/task-persistence/TaskHistoryStore.ts b/src/core/task-persistence/TaskHistoryStore.ts index e0bb54998c..63c953c846 100644 --- a/src/core/task-persistence/TaskHistoryStore.ts +++ b/src/core/task-persistence/TaskHistoryStore.ts @@ -73,6 +73,13 @@ interface DelegationRepairIntent { */ type AutoTitleDiskRead = { kind: "found"; item: HistoryItem } | { kind: "missing" } | { kind: "unreadable" } +/** + * A record a reconciliation read from disk beside the record this host already held. `baseline` + * is the cache entry the read was taken beside, so the entry stops applying as soon as this host + * writes, evicts or re-bases its own record. + */ +type RefreshedRecord = { baseline: HistoryItem; item: HistoryItem } + export interface TaskHistoryStoreOptions { /** * Optional callback invoked inside the write lock after each mutation @@ -86,6 +93,18 @@ export class TaskHistoryStore { private readonly globalStoragePath: string private readonly onWrite?: (items: HistoryItem[]) => Promise private cache: Map = new Map() + /** + * What the last reconciliation read from disk for a task this host already held. A reader gets + * this record while the entry still names the live cache entry, so a peer update reaches the + * history readers after the fs.watch or periodic reconciliation without the scan moving the peer + * record into `cache` - that entry is the baseline the next save from this host diffs against. + * invalidate(), invalidateAll() and reconcile({ forceRefresh: true }) remain the ways a peer + * record becomes this host's baseline. An entry is removed when the task's cache entry is + * removed - delete(), deleteMany(), a reconcile eviction, the auto-title settle of a missing + * record, invalidate() - and invalidateAll() clears the whole map, so the map tracks live tasks + * instead of growing past them. + */ + private refreshedRecords: Map = new Map() private taskFileMtimes: Map = new Map() private writeLock: Promise = Promise.resolve() private fsWatcher: fsSync.FSWatcher | null = null @@ -169,16 +188,37 @@ export class TaskHistoryStore { /** * Get a single history item by task ID. + * + * After a reconciliation this is the record the scan read from disk, even though the scan left + * this host's own record in `cache` as the save baseline; see `refreshedRecords`. */ get(taskId: string): HistoryItem | undefined { - return this.cache.get(taskId) + return this.readView(taskId) + } + + /** + * The record a reader sees for `taskId`: the published record while its entry still names the + * live cache entry, otherwise the cache itself. `get`, `getAll` and the save delta in + * `upsertCore` all answer from this one place. + */ + private readView(taskId: string): HistoryItem | undefined { + const refreshed = this.refreshedRecords.get(taskId) + return refreshed && refreshed.baseline === this.cache.get(taskId) ? refreshed.item : this.cache.get(taskId) } /** * Get all history items, sorted by timestamp descending (newest first). + * + * Reports the same view `get` does, so the history list `ClineProvider` posts is not held at a + * record a peer host has already replaced. */ getAll(): HistoryItem[] { - return Array.from(this.cache.values()).sort((a, b) => b.ts - a.ts) + const items: HistoryItem[] = [] + for (const taskId of this.cache.keys()) { + const view = this.readView(taskId) + if (view !== undefined) items.push(view) + } + return items.sort((a, b) => b.ts - a.ts) } /** @@ -238,7 +278,12 @@ export class TaskHistoryStore { // Merge: preserve existing metadata unless explicitly overwritten const merged = existing ? { ...existing, ...item } : item - const delta = existing ? this.buildDelta(item.id, existing, item) : { ...item } + // The delta is priced per key against the reader view (the record get()/getAll() publish): + // fields the caller left at the view never ride the delta over a newer peer record on + // disk. A key whose incoming value still carries the cache baseline - a stale snapshot + // taken before the publish - keeps the cache baseline and drops out, so the peer's newer + // record survives the stale save. + const delta = existing ? { id: item.id, ...this.saveDelta(item.id, existing, item) } : { ...item } let written: HistoryItem try { written = await this.writeTaskFile(merged, delta) @@ -279,6 +324,7 @@ export class TaskHistoryStore { async delete(taskId: string): Promise { return this.withLock(async () => { this.cache.delete(taskId) + this.refreshedRecords.delete(taskId) this.taskFileMtimes.delete(taskId) // Remove per-task file (best-effort) @@ -309,6 +355,7 @@ export class TaskHistoryStore { return this.withLock(async () => { for (const taskId of taskIds) { this.cache.delete(taskId) + this.refreshedRecords.delete(taskId) this.taskFileMtimes.delete(taskId) // Remove per-task file (best-effort) @@ -336,6 +383,11 @@ export class TaskHistoryStore { * * - Tasks on disk but missing from cache: read and add * - Tasks in cache but missing from disk: remove + * + * - Tasks on disk whose record differs from one this host already holds: the record this host + * holds stays the save baseline, and the record this scan read becomes what `get()` and + * `getAll()` report, so a peer's completed status reaches the history readers without the scan + * re-basing the delta a later save from this host diffs against. */ async reconcile(options: { forceRefresh?: boolean } = {}): Promise { // Run through the write lock to prevent interleaving with upsert/delete @@ -377,8 +429,27 @@ export class TaskHistoryStore { if (item?.id === taskId) { const previous = this.cache.get(taskId) this.taskFileMtimes.set(taskId, mtimeMs) + // The cached record is the baseline this host's next save diffs against: a + // caller holds a snapshot of it, and swapping in a peer's whole record here + // would make that stale snapshot write this host's old fields back over the + // peer's newer ones - the same stale-save stomp that autoTitle settlement + // avoids by copying only autoTitle. A task this host has never held is added + // from disk, a task whose file is gone is evicted below, and a peer's field + // updates reach a record this host holds through invalidate(), through + // invalidateAll() followed by reconcile(), or through the forced refresh at + // startup. This scan does not silently re-base a baseline; it publishes what it read to the + // readers instead. A divergent record goes to refreshedRecords, which get() and getAll() + // report until this host writes, evicts or re-bases its own record - the entry names that + // baseline, so it stops applying the moment the cache entry is no longer the one it was read + // beside. A scan that finds the file equal to the baseline drops the entry again. if (!deepEqual(previous, item)) { - this.cache.set(taskId, item) + if (previous && !options.forceRefresh) { + this.refreshedRecords.set(taskId, { baseline: previous, item }) + } else { + this.cache.set(taskId, item) + } + } else { + this.refreshedRecords.delete(taskId) } } } catch (error) { @@ -407,6 +478,7 @@ export class TaskHistoryStore { for (const taskId of cacheIds) { if (!liveIds.has(taskId)) { this.cache.delete(taskId) + this.refreshedRecords.delete(taskId) this.taskFileMtimes.delete(taskId) } } @@ -794,8 +866,10 @@ export class TaskHistoryStore { this.cache.delete(taskId) } this.taskFileMtimes.delete(taskId) + this.refreshedRecords.delete(taskId) } catch { this.cache.delete(taskId) + this.refreshedRecords.delete(taskId) } }) } @@ -806,6 +880,7 @@ export class TaskHistoryStore { async invalidateAll(): Promise { return this.withLock(async () => { this.cache.clear() + this.refreshedRecords.clear() }) } @@ -882,6 +957,30 @@ export class TaskHistoryStore { return { id, ...this.computeDelta(cached, incoming) } } + /** + * The per-key delta a save writes: each key the incoming item changes against the reader view + * (the record get()/getAll() publish), so fields the caller left at the view never ride the + * delta over a newer peer record on disk. A key whose incoming value still equals the cache + * baseline while the view disagrees - a snapshot taken before the publish - keeps the cache + * baseline and drops out of the delta, so the stale-snapshot defense stays in place. + */ + private saveDelta(id: string, cache: HistoryItem, item: HistoryItem): Partial { + const view = this.readView(id) + if (view === undefined || view === cache) { + return this.computeDelta(cache, item) + } + const cacheRecord = cache as Record + const viewRecord = view as Record + return Object.fromEntries( + Object.entries(item as Record).filter(([key, value]) => { + if (deepEqual(value, viewRecord[key])) { + return false + } + return !(deepEqual(value, cacheRecord[key]) && !deepEqual(cacheRecord[key], viewRecord[key])) + }), + ) as Partial + } + /** * Write a HistoryItem to its per-task `history_item.json` file. * @@ -1098,6 +1197,7 @@ export class TaskHistoryStore { return { applied: false, item: disk.item } case "missing": this.cache.delete(taskId) + this.refreshedRecords.delete(taskId) return { applied: false } case "unreadable": return { applied: false, item: this.cache.get(taskId) } @@ -1247,6 +1347,7 @@ export class TaskHistoryStore { // record stays deleted. missingDiskRecord = true this.cache.delete(taskId) + this.refreshedRecords.delete(taskId) this.taskFileMtimes.delete(taskId) throw new Error( `[TaskHistoryStore] clearPendingActionIfMatching: task ${taskId} not found in cache`, @@ -1261,6 +1362,7 @@ export class TaskHistoryStore { const parsed = historyItemSchema.safeParse(existing) if (!parsed.success) { this.cache.delete(taskId) + this.refreshedRecords.delete(taskId) this.taskFileMtimes.delete(taskId) throw new Error( `[TaskHistoryStore] clearPendingActionIfMatching: task ${taskId} has an invalid disk record`, @@ -1268,6 +1370,7 @@ export class TaskHistoryStore { } if (parsed.data.id !== taskId) { this.cache.delete(taskId) + this.refreshedRecords.delete(taskId) this.taskFileMtimes.delete(taskId) throw new Error( `[TaskHistoryStore] clearPendingActionIfMatching: task ${taskId} has a disk record with mismatched id ${parsed.data.id}`, diff --git a/src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts b/src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts index e637a7630e..9acb25f2ea 100644 --- a/src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts +++ b/src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts @@ -594,6 +594,33 @@ describe("TaskHistoryStore real cross-host locking", () => { }) }) + it("keeps this host's own record as the baseline when a reconciliation runs around it", async () => { + await withTwoStores(async (storeA, storeB) => { + await storeA.upsert({ ...item("shared-task"), mode: "code" }) + const stale = storeA.get("shared-task")! + await storeB.invalidate("shared-task") + await storeB.upsert({ ...storeB.get("shared-task")!, mode: "architect" }) + await storeB.setAutoTitleIfAbsent("shared-task", "Peer title") + // In the failing case the reconciliation is a background actor: fs.watch + // debounces one 500 ms later, and on a loaded runner the row is slow enough + // for it to land inside the row, which is why the outcome flipped by timing + // instead of by policy. The row calls reconcile() directly on both sides of + // the settlement, so it cannot depend on which order the debounce picked. + await storeA.reconcile() + const result = await storeA.setAutoTitleIfAbsent("shared-task", "Title") + expect(result.applied).toBe(false) + await storeA.reconcile() + expect(storeA.get("shared-task")).toMatchObject({ mode: "code", autoTitle: "Peer title" }) + await storeA.upsert({ ...stale, tokensOut: 5 }) + await storeB.invalidate("shared-task") + expect(storeB.get("shared-task")).toMatchObject({ + mode: "architect", + tokensOut: 5, + autoTitle: "Peer title", + }) + }) + }) + it.each(["", " \n\t"])("rejects a blank title %j", async (blank) => { await withTwoStores(async (storeA, _storeB, storagePath) => { const result = await storeA.setAutoTitleIfAbsent("shared-task", blank) diff --git a/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts b/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts index 3e277ac867..30bd0a0f24 100644 --- a/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts +++ b/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts @@ -16,12 +16,32 @@ vi.mock("../../../utils/storage", () => ({ }), })) -// Mock safeWriteJson to use plain fs writes in tests (avoids proper-lockfile issues) +// Mock safeWriteJson to use plain fs writes (avoids proper-lockfile issues) but honor the merge +// callback the way production does, so a stale save exercises the real delta merge instead of a +// full overwrite of the file. vi.mock("../../../utils/safeWriteJson", () => ({ - safeWriteJson: vi.fn().mockImplementation(async (filePath: string, data: any) => { - await fs.mkdir(path.dirname(filePath), { recursive: true }) - await fs.writeFile(filePath, JSON.stringify(data, null, "\t"), "utf8") - }), + safeWriteJson: vi + .fn() + .mockImplementation( + async ( + filePath: string, + data: unknown, + options?: { merge?: (existing: unknown, incoming: unknown) => unknown }, + ) => { + await fs.mkdir(path.dirname(filePath), { recursive: true }) + if (options?.merge) { + let existing: unknown = null + try { + const raw = await fs.readFile(filePath, "utf8") + existing = JSON.parse(raw) + } catch { + // File does not exist or is corrupt + } + data = options.merge(existing, data) + } + await fs.writeFile(filePath, JSON.stringify(data, null, "\t"), "utf8") + }, + ), })) function makeHistoryItem(overrides: Partial = {}): HistoryItem { @@ -296,6 +316,345 @@ describe("TaskHistoryStore", () => { expect(store.get("removed-task")).toBeUndefined() }) + + it("publishes a peer record to the readers after a scan without re-basing the save baseline", async () => { + await store.initialize() + const peerUpdated = makeHistoryItem({ id: "peer-updated", ts: 5000, status: "active", tokensOut: 10 }) + const peerSecond = makeHistoryItem({ id: "peer-second", ts: 4000, status: "active", tokensOut: 20 }) + const unchanged = makeHistoryItem({ id: "unchanged", ts: 3000, status: "active", tokensOut: 30 }) + const otherWs = makeHistoryItem({ id: "other-ws", ts: 2000, workspace: "/other/workspace", tokensOut: 40 }) + await store.upsert(peerUpdated) + await store.upsert(peerSecond) + await store.upsert(unchanged) + await store.upsert(otherWs) + + // Two second-host tasks are rewritten on disk; a third task and another workspace's task + // stay at this host's records, so a complete-array assertion catches an omitted task. + const updatedFile = path.join(tmpDir, "tasks", "peer-updated", GlobalFileNames.historyItem) + const peerUpdatedView = { ...peerUpdated, status: "completed", completionResultSummary: "done over there" } + await fs.writeFile(updatedFile, JSON.stringify(peerUpdatedView)) + const secondFile = path.join(tmpDir, "tasks", "peer-second", GlobalFileNames.historyItem) + const peerSecondView = { ...peerSecond, mode: "architect" } + await fs.writeFile(secondFile, JSON.stringify(peerSecondView)) + + await store.reconcile() + + // The readers ClineProvider uses get the complete ordered arrays: every task is present, + // both peer records are reported as the scan read them, and the order is ts descending. + expect(store.getAll()).toEqual([peerUpdatedView, peerSecondView, unchanged, otherWs]) + expect(store.getByWorkspace("/test/workspace")).toEqual([peerUpdatedView, peerSecondView, unchanged]) + + // The save baselines are a separate view: they still hold this host's own records, which is + // what a save from a snapshot taken before the peer writes diffs against. + expect(store["cache"].get("peer-updated")?.status).toBe("active") + expect(store["cache"].get("peer-second")?.mode).toBeUndefined() + + // A write by this host is not shadowed by the peer view either: its delta carries only + // tokensOut, so the merge keeps the peer's completion on disk. + await store.upsert({ ...peerUpdated, tokensOut: 999 }) + expect(store.get("peer-updated")?.tokensOut).toBe(999) + expect(store["cache"].get("peer-updated")?.tokensOut).toBe(999) + const disk = JSON.parse(await fs.readFile(updatedFile, "utf8")) as HistoryItem + expect(disk.status).toBe("completed") + expect(disk.completionResultSummary).toBe("done over there") + expect(disk.tokensOut).toBe(999) + }) + + it("drops the published record when a later scan finds the file equal to the baseline", async () => { + await store.initialize() + const peerReverted = makeHistoryItem({ id: "peer-reverted", ts: 5000, status: "active", tokensOut: 10 }) + const peerSecond = makeHistoryItem({ id: "peer-second", ts: 4000, status: "active", tokensOut: 20 }) + const otherWs = makeHistoryItem({ id: "other-ws", ts: 2000, workspace: "/other/workspace", tokensOut: 30 }) + await store.upsert(peerReverted) + await store.upsert(peerSecond) + await store.upsert(otherWs) + + const revertedFile = path.join(tmpDir, "tasks", "peer-reverted", GlobalFileNames.historyItem) + const peerRecord = { ...peerReverted, status: "completed", completionResultSummary: "done over there" } + await fs.writeFile(revertedFile, JSON.stringify(peerRecord)) + const secondFile = path.join(tmpDir, "tasks", "peer-second", GlobalFileNames.historyItem) + await fs.writeFile(secondFile, JSON.stringify({ ...peerSecond, mode: "architect" })) + await store.reconcile() + expect(store.get("peer-reverted")?.status).toBe("completed") + expect(store.get("peer-second")?.mode).toBe("architect") + + // The peer host rewrites one file back to this host's record. The next scan finds that file + // equal to the baseline and retires its published view, while the second peer record stays + // published. The revert carries an explicit timestamp so the scan is not skipped by the + // per-file mtime guard. + const stamp = new Date(Date.now() + 5000) + await fs.writeFile(revertedFile, JSON.stringify(store["cache"].get("peer-reverted"))) + await fs.utimes(revertedFile, stamp, stamp) + await store.reconcile() + + // Complete arrays again: the reverted task falls back to this host's record, the second peer + // record is still the published one, and the other workspace's task never moved. + const peerSecondView = { ...peerSecond, mode: "architect" } + expect(store.getAll()).toEqual([peerReverted, peerSecondView, otherWs]) + expect(store.getByWorkspace("/test/workspace")).toEqual([peerReverted, peerSecondView]) + expect(store.get("peer-reverted")?.completionResultSummary).toBeUndefined() + }) + + it("lets a forced refresh re-base the record a plain scan had only published", async () => { + await store.initialize() + const mine = makeHistoryItem({ id: "peer-forced", status: "active", tokensOut: 10 }) + await store.upsert(mine) + + const taskFile = path.join(tmpDir, "tasks", "peer-forced", GlobalFileNames.historyItem) + const peerRecord = { ...mine, status: "completed", completionResultSummary: "done over there" } + await fs.writeFile(taskFile, JSON.stringify(peerRecord)) + + await store.reconcile() + expect(store.get("peer-forced")?.status).toBe("completed") + expect(store["cache"].get("peer-forced")?.status).toBe("active") + + // A forced refresh is the caller asking for disk to become this host's view, so the + // divergent record goes to the baseline instead of joining the published view. + await store.reconcile({ forceRefresh: true }) + + expect(store.get("peer-forced")?.status).toBe("completed") + expect(store["cache"].get("peer-forced")?.status).toBe("completed") + expect(store["cache"].get("peer-forced")?.completionResultSummary).toBe("done over there") + expect(store.getAll().find((item) => item.id === "peer-forced")?.status).toBe("completed") + }) + + it("stops applying a published record to the list once this host writes its own", async () => { + await store.initialize() + const mine = makeHistoryItem({ id: "peer-list", status: "active", tokensOut: 10 }) + await store.upsert(mine) + + const taskFile = path.join(tmpDir, "tasks", "peer-list", GlobalFileNames.historyItem) + const peerRecord = { ...mine, status: "completed", completionResultSummary: "done over there" } + await fs.writeFile(taskFile, JSON.stringify(peerRecord)) + await store.reconcile() + expect(store.getAll().find((item) => item.id === "peer-list")?.status).toBe("completed") + + // The published entry names this host's earlier record as its baseline. Once this host + // writes, that entry must not put the peer record back over the list. The save's delta + // omits status - the cache baseline still holds the value the caller sent - so the merge + // keeps the disk value and the readers fall back to the written record. + await store.upsert({ ...mine, status: "active", tokensOut: 42 }) + + const listed = store.getAll().find((item) => item.id === "peer-list") + expect(listed?.status).toBe("completed") + expect(listed?.tokensOut).toBe(42) + expect(listed?.completionResultSummary).toBe("done over there") + const disk = JSON.parse(await fs.readFile(taskFile, "utf8")) as HistoryItem + expect(disk.status).toBe("completed") + expect(disk.tokensOut).toBe(42) + expect(store["cache"].get("peer-list")?.tokensOut).toBe(42) + }) + + it("stops answering a single read from a published record once this host writes its own", async () => { + await store.initialize() + const mine = makeHistoryItem({ id: "peer-read", status: "active", tokensOut: 10 }) + await store.upsert(mine) + + const taskFile = path.join(tmpDir, "tasks", "peer-read", GlobalFileNames.historyItem) + const peerRecord = { ...mine, status: "completed", completionResultSummary: "done over there" } + await fs.writeFile(taskFile, JSON.stringify(peerRecord)) + await store.reconcile() + expect(store.get("peer-read")?.status).toBe("completed") + + // Same rule as the list: the published entry applies only while its baseline is still the + // record this host holds. The save's delta omits status - the cache baseline still holds + // the value the caller sent - so the merge keeps the disk value and the readers fall back + // to the written record. + await store.upsert({ ...mine, status: "active", tokensOut: 42 }) + + expect(store.get("peer-read")?.status).toBe("completed") + expect(store.get("peer-read")?.tokensOut).toBe(42) + const disk = JSON.parse(await fs.readFile(taskFile, "utf8")) as HistoryItem + expect(disk.status).toBe("completed") + expect(disk.tokensOut).toBe(42) + }) + + it("keeps a newer peer field when a save spreads the published record", async () => { + await store.initialize() + const actionA: NonNullable = { + kind: "create_subtask", + actionId: "action-a", + approvalText: "{}", + mode: "code", + message: "action A", + todos: [], + } + const actionB = { ...actionA, actionId: "action-b", message: "action B" } + const actionC = { ...actionA, actionId: "action-c", message: "action C" } + const mine = makeHistoryItem({ + id: "published-save", + status: "active", + pendingAction: actionA, + tokensOut: 10, + }) + await store.upsert(mine) + + // A scan publishes a record whose pending action the peer replaced. + const taskFile = path.join(tmpDir, "tasks", "published-save", GlobalFileNames.historyItem) + await fs.writeFile(taskFile, JSON.stringify({ ...mine, pendingAction: actionB })) + await store.reconcile() + expect(store.get("published-save")?.pendingAction).toEqual(actionB) + + // The peer writes a newer action after the scan published its record. + await fs.writeFile(taskFile, JSON.stringify({ ...mine, pendingAction: actionC })) + + // The caller reads the published record, changes one unrelated field, and saves. The save + // diffs the record it read, so pendingAction B must not ride the delta over C. + const read = store.get("published-save")! + await store.upsert({ ...read, tokensOut: 999 }) + + const disk = JSON.parse(await fs.readFile(taskFile, "utf8")) as HistoryItem + expect(disk.pendingAction).toEqual(actionC) + expect(disk.tokensOut).toBe(999) + expect(store.get("published-save")?.pendingAction).toEqual(actionC) + }) + + it("diffs a first save against the existing disk record", async () => { + await store.initialize() + const taskFile = path.join(tmpDir, "tasks", "first-save-disk", GlobalFileNames.historyItem) + await fs.mkdir(path.dirname(taskFile), { recursive: true }) + await fs.writeFile( + taskFile, + JSON.stringify(makeHistoryItem({ id: "first-save-disk", status: "active", tokensOut: 7 })), + ) + + // A second instance with an empty cache has no baseline: its first save carries the + // incoming fields as the delta, so a record already on disk must end up with the + // caller's tokensOut instead of the old one. An empty delta would leave the old + // record untouched and fail this row. + const fresh = new TaskHistoryStore(tmpDir) + await fresh.upsert(makeHistoryItem({ id: "first-save-disk", status: "active", tokensOut: 42 })) + + const disk = JSON.parse(await fs.readFile(taskFile, "utf8")) as HistoryItem + expect(disk.tokensOut).toBe(42) + }) + }) + + describe("save against the reader view (lost-update defense)", () => { + it("keeps a peer's post-scan fields when the caller saves one disputed change from get()", async () => { + await store.initialize() + const mine = makeHistoryItem({ id: "view-save", ts: 5000, status: "active", tokensOut: 10 }) + await store.upsert(mine) + const taskFile = path.join(tmpDir, "tasks", "view-save", GlobalFileNames.historyItem) + const peerView = { ...mine, tokensOut: 77, completionResultSummary: "peer summary" } + await fs.writeFile(taskFile, JSON.stringify(peerView)) + await store.reconcile() + expect(store.get("view-save")?.tokensOut).toBe(77) + + // The peer moves the record again after the scan: a save spread from get() must not + // carry the scan-time peer values back over them. + const peerAfter = { ...peerView, tokensOut: 88, completionResultSummary: "peer summary 2" } + await fs.writeFile(taskFile, JSON.stringify(peerAfter)) + + const held = store.get("view-save")! + await store.upsert({ ...held, tokensOut: 12 }) + + const disk = JSON.parse(await fs.readFile(taskFile, "utf-8")) + expect(disk.tokensOut).toBe(12) + expect(disk.completionResultSummary).toBe("peer summary 2") + }) + + it("keeps a peer's post-scan fields when the caller saves from getAll()", async () => { + await store.initialize() + const mine = makeHistoryItem({ id: "view-save-all", ts: 5000, status: "active", tokensOut: 10 }) + await store.upsert(mine) + const taskFile = path.join(tmpDir, "tasks", "view-save-all", GlobalFileNames.historyItem) + const peerView = { ...mine, tokensOut: 77, completionResultSummary: "peer summary" } + await fs.writeFile(taskFile, JSON.stringify(peerView)) + await store.reconcile() + expect(store.getAll()[0]?.tokensOut).toBe(77) + + const peerAfter = { ...peerView, tokensOut: 88, completionResultSummary: "peer summary 2" } + await fs.writeFile(taskFile, JSON.stringify(peerAfter)) + + const held = store.getAll().find((item) => item.id === "view-save-all")! + await store.upsert({ ...held, tokensOut: 12 }) + + const disk = JSON.parse(await fs.readFile(taskFile, "utf-8")) + expect(disk.tokensOut).toBe(12) + expect(disk.completionResultSummary).toBe("peer summary 2") + }) + + it("keeps the published record when a stale pre-publish snapshot saves a disputed key", async () => { + await store.initialize() + const mine = makeHistoryItem({ id: "stale-save", ts: 5000, status: "active", tokensOut: 10 }) + await store.upsert(mine) + const stale = { ...mine, tokensOut: 12 } + const taskFile = path.join(tmpDir, "tasks", "stale-save", GlobalFileNames.historyItem) + const peerView = { ...mine, tokensOut: 77, completionResultSummary: "peer summary" } + await fs.writeFile(taskFile, JSON.stringify(peerView)) + await store.reconcile() + + await store.upsert(stale) + + const disk = JSON.parse(await fs.readFile(taskFile, "utf-8")) + expect(disk.tokensOut).toBe(12) + expect(disk.completionResultSummary).toBe("peer summary") + }) + }) + + describe("refreshedRecords bookkeeping", () => { + async function publishEntry(id: string, ts: number): Promise { + const mine = makeHistoryItem({ id, ts, status: "active", tokensOut: 10 }) + await store.upsert(mine) + const taskFile = path.join(tmpDir, "tasks", id, GlobalFileNames.historyItem) + await fs.writeFile(taskFile, JSON.stringify({ ...mine, tokensOut: 77 })) + await store.reconcile() + expect(store["refreshedRecords"].has(id)).toBe(true) + expect(store.get(id)?.tokensOut).toBe(77) + } + + it("drops the entry when the task is deleted", async () => { + await store.initialize() + await publishEntry("bk-delete", 5000) + await store.delete("bk-delete") + expect(store["refreshedRecords"].has("bk-delete")).toBe(false) + expect(store.get("bk-delete")).toBeUndefined() + }) + + it("drops the entries when tasks are deleted in a batch", async () => { + await store.initialize() + await publishEntry("bk-batch-1", 5000) + await publishEntry("bk-batch-2", 4000) + await store.deleteMany(["bk-batch-1", "bk-batch-2"]) + expect(store["refreshedRecords"].has("bk-batch-1")).toBe(false) + expect(store["refreshedRecords"].has("bk-batch-2")).toBe(false) + }) + + it("drops the entry when invalidate() retires the published record", async () => { + await store.initialize() + await publishEntry("bk-invalidate", 5000) + await store.invalidate("bk-invalidate") + expect(store["refreshedRecords"].has("bk-invalidate")).toBe(false) + expect(store.get("bk-invalidate")?.tokensOut).toBe(77) + }) + + it("clears the map in invalidateAll()", async () => { + await store.initialize() + await publishEntry("bk-all-1", 5000) + await publishEntry("bk-all-2", 4000) + await store.invalidateAll() + expect(store["refreshedRecords"].size).toBe(0) + }) + + it("drops the entry when a reconcile evicts the task from disk", async () => { + await store.initialize() + await publishEntry("bk-evict", 5000) + await fs.rm(path.join(tmpDir, "tasks", "bk-evict"), { recursive: true, force: true }) + await store.reconcile() + expect(store["refreshedRecords"].has("bk-evict")).toBe(false) + expect(store.get("bk-evict")).toBeUndefined() + }) + + it("drops the entry when the auto-title settle finds the record missing", async () => { + await store.initialize() + await publishEntry("bk-settle", 5000) + await fs.rm(path.join(tmpDir, "tasks", "bk-settle"), { recursive: true, force: true }) + const result = await store.setAutoTitleIfAbsent("bk-settle", "Title") + expect(result.applied).toBe(false) + expect(store["refreshedRecords"].has("bk-settle")).toBe(false) + expect(store.get("bk-settle")).toBeUndefined() + }) }) describe("concurrent upsert() calls are serialized", () => { diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index fd22782226..649aba56ac 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -641,7 +641,7 @@ }, "core/task-persistence/__tests__/TaskHistoryStore.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 4 + "count": 3 } }, "core/task-persistence/__tests__/importRooTaskHistory.spec.ts": {