Repository navigation
fix(task-history): keep the save baseline stable and report peer records to readers #2846
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
1a4702c
c62af5c
1e82e11
1c8d77d
ab9a780
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<void> | ||
| private cache: Map<string, HistoryItem> = 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<string, RefreshedRecord> = new Map() | ||
| private taskFileMtimes: Map<string, number> = new Map() | ||
| private writeLock: Promise<void> = 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<void> { | ||
| 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<void> { | ||
| // 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 }) | ||
|
easonLiangWorldedtech marked this conversation as resolved.
Resolved
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep lifecycle updater inputs consistent with published reads. After a peer interrupts a child, reconciliation publishes
This worked before reconciliation stopped updating the cache. Repeated scans cannot repair it because the file mtime has not changed. Refresh the lifecycle inputs before the atomic operation, without replacing the baseline used for unrelated stale saves. Add a regression test through
|
||
| } 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<void> { | ||
| 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<HistoryItem> { | ||
| const view = this.readView(id) | ||
| if (view === undefined || view === cache) { | ||
| return this.computeDelta(cache, item) | ||
|
Comment on lines
+969
to
+970
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Preserve the published save baseline across auto-title settlement. A caller can retain a published record with If Before this change, reconciliation placed The reader fallback after settlement is allowed. The held record still needs its save baseline. Preserve that baseline across auto-title-only cache updates. Add a regression test for this event order.
|
||
| } | ||
| const cacheRecord = cache as Record<string, unknown> | ||
| const viewRecord = view as Record<string, unknown> | ||
| return Object.fromEntries( | ||
| Object.entries(item as Record<string, unknown>).filter(([key, value]) => { | ||
| if (deepEqual(value, viewRecord[key])) { | ||
| return false | ||
| } | ||
| return !(deepEqual(value, cacheRecord[key]) && !deepEqual(cacheRecord[key], viewRecord[key])) | ||
| }), | ||
| ) as Partial<HistoryItem> | ||
| } | ||
|
|
||
| /** | ||
| * Write a HistoryItem to its per-task `history_item.json` file. | ||
| * | ||
|
Comment on lines
957
to
986
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
|
@@ -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,13 +1362,15 @@ 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`, | ||
| ) | ||
| } | ||
| 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}`, | ||
|
|
||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Uh oh!
There was an error while loading. Please reload this page.