Skip to content

Commit e5d39bd

Browse files
kazemek21codex
andcommitted
Add conditional undo for explicit reads
Co-authored-by: Codex (gpt-6-luna) <[email protected]> Signed-off-by: Kyle Zemek <[email protected]> Co-authored-by: Codex (gpt-6.1-sol) <[email protected]>
1 parent 0397581 commit e5d39bd

4 files changed

Lines changed: 1057 additions & 30 deletions

File tree

‎docs/unread.md‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -530,9 +530,27 @@ marker tuples or change automatic observation.
530530
Capture requires initialized read-state storage (`await unread.ensure()` before
531531
preparation). A failed capture rejects every invocation of that operation rather
532532
than moving the snapshot to save time; prepare again after readiness/recovery.
533-
Storage failures retain the cut for retry. Access revoke/regrant, cache clear or
534-
session disposal invalidate captured intent. The thread operation additionally
535-
requires its captured message evidence to remain valid.
533+
Storage failures retain the cut for retry. Access revoke/regrant, cache clear,
534+
or session disposal invalidate captured intent; leaving the channel invalidates
535+
only Undo, not the saved read. The thread operation additionally requires its
536+
captured message evidence to remain valid.
537+
538+
An individual saved explicit-read result may expose an optional `undo` only when
539+
that action cleared saved local-unread journal markers and cleared no
540+
forced-message marker or covered overlay. The handle is also withheld if a force
541+
mark for covered messages is queued while the read saves. Undo restores only the
542+
local-unread journal markers that exact saved action removed, in a new storage
543+
transaction; it does not restore overlays or rewind or publish a read frontier.
544+
The handle is conditional on the exact saved journal revision and the
545+
operation's access/lifecycle evidence. Its revision guard covers the whole
546+
journal: any later save that advances the revision, including an unrelated
547+
marker or quiet read-state save, makes the handle stale; bookkeeping saves that
548+
leave the revision unchanged do not. This whole-journal expiry is deliberately
549+
conservative rather than per-target. `markAllChannelsRead()` omits its
550+
per-channel handles because later saves in the sweep expire earlier ones. The
551+
thread operation also depends on its captured message evidence. A failed undo
552+
save can be retried with the same handle; duplicate or stale attempts reject.
553+
Consumers must tolerate hosts that do not provide `undo`.
536554

537555
## Explicit clearing matrix
538556

‎src/features/relay/read-state.ts‎

Lines changed: 129 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ export type ReadMutationResult = Readonly<{
5757
operationId: string;
5858
durability: "saved";
5959
sync: "pending" | "local-only";
60+
/** Local-only restore of saved unread journal markers only; forced-message
61+
* overlays are not restored. Any later journal revision, even unrelated, or
62+
* lost operation validity makes the handle stale. */
63+
undo?: () => Promise<ReadMutationResult>;
6064
}>;
6165
export type ReadPublisherLock = (
6266
signal: AbortSignal,
@@ -250,6 +254,10 @@ export function createReadState({
250254
* so a fence on local intent sees other windows' saves, not this cache.
251255
*/
252256
type Validity = (current: ReadJournal) => boolean;
257+
type LocalUnreadUndo = {
258+
keys: ReadonlySet<string>;
259+
valid: () => boolean;
260+
};
253261
type LocalUnreadAttempt = {
254262
key: string;
255263
saved?: { revision: number; previous: number };
@@ -416,6 +424,75 @@ export function createReadState({
416424
});
417425
}
418426
});
427+
function undoLocalUnread(
428+
actionSlot: string,
429+
actionRevision: number,
430+
cleared: readonly string[],
431+
valid: Validity,
432+
options?: LocalUnreadUndo,
433+
): (() => Promise<ReadMutationResult>) | undefined {
434+
if (
435+
!options ||
436+
!cleared.length ||
437+
!cleared.every((key) => options.keys.has(key))
438+
)
439+
return;
440+
return () => {
441+
const attempts: LocalUnreadAttempt[] = cleared.map((key) => ({ key }));
442+
for (const attempt of attempts) pendingLocalUnread.add(attempt);
443+
return queue(async () => {
444+
await ready;
445+
if (!journal)
446+
throw new Error("Saved read state unavailable; retry storage first");
447+
try {
448+
const saved = await save((current) => {
449+
// Revision catches newer mark-then-clear intent; slot also catches a
450+
// replacement journal whose counter has reached the same revision.
451+
if (
452+
!valid(current) ||
453+
!options.valid() ||
454+
current.slot !== actionSlot ||
455+
current.revision !== actionRevision ||
456+
cleared.some((key) => current.localUnread[key] !== undefined)
457+
)
458+
throw new ObservationExpired();
459+
const revision = current.revision + 1;
460+
const localUnread = { ...current.localUnread };
461+
for (const key of cleared) localUnread[key] = revision;
462+
return {
463+
...current,
464+
revision,
465+
localUnread,
466+
acceptedRevision:
467+
current.acceptedRevision === current.revision
468+
? revision
469+
: current.acceptedRevision,
470+
};
471+
});
472+
for (const attempt of attempts)
473+
attempt.saved = { revision: saved.revision, previous: 0 };
474+
health({
475+
status:
476+
saved.pending || saved.revision > saved.acceptedRevision
477+
? "pending"
478+
: "local",
479+
error: undefined,
480+
});
481+
return {
482+
operationId: `${saved.slot}:${saved.revision}`,
483+
durability: "saved" as const,
484+
sync: "local-only" as const,
485+
};
486+
} catch (error) {
487+
if (!(error instanceof ObservationExpired))
488+
health({ status: "error", error: errorText(error) });
489+
throw error;
490+
}
491+
}).finally(() => {
492+
for (const attempt of attempts) pendingLocalUnread.delete(attempt);
493+
});
494+
};
495+
}
419496
if (broadcast)
420497
broadcast.onmessage = () => {
421498
void queue(async () => {
@@ -880,6 +957,7 @@ export function createReadState({
880957
observedFrontier?: (state: ReadState) => number | undefined,
881958
fence?: LocalUnreadFence,
882959
localUnreadAttempt?: LocalUnreadAttempt,
960+
undoOptions?: LocalUnreadUndo,
883961
): Promise<ReadMutationResult> {
884962
const automatic =
885963
key.startsWith("msg:") && timestamp !== undefined && unread === undefined;
@@ -934,6 +1012,7 @@ export function createReadState({
9341012
? await capturedValidity(valid, fence)
9351013
: valid;
9361014
let previousLocalUnread = 0;
1015+
const clearedLocalUnread: string[] = [];
9371016
const saved = await save((current) => {
9381017
if (!currentValid(current)) throw new ObservationExpired();
9391018
if (
@@ -973,7 +1052,12 @@ export function createReadState({
9731052
previousLocalUnread = localUnread[key] ?? 0;
9741053
// Automatic observations do not clear explicit local manual-unread intent.
9751054
if (unread === false)
976-
for (const clearKey of clearLocalKeys) delete localUnread[clearKey];
1055+
for (const clearKey of new Set(clearLocalKeys)) {
1056+
const previous = localUnread[clearKey];
1057+
if (undoOptions && previous !== undefined)
1058+
clearedLocalUnread.push(clearKey);
1059+
delete localUnread[clearKey];
1060+
}
9771061
if (unread === true) localUnread[key] = revision;
9781062
const own = advanceOwn(
9791063
current.own,
@@ -1055,13 +1139,21 @@ export function createReadState({
10551139
error: undefined,
10561140
});
10571141
if (timestamp !== undefined) schedule();
1142+
const undo = undoLocalUnread(
1143+
saved.slot,
1144+
saved.revision,
1145+
clearedLocalUnread,
1146+
currentValid,
1147+
undoOptions,
1148+
);
10581149
return {
10591150
operationId: `${saved.slot}:${saved.revision}`,
10601151
durability: "saved",
10611152
sync:
10621153
capability === "frontier-sync" && timestamp !== undefined
10631154
? "pending"
10641155
: "local-only",
1156+
...(undo && { undo }),
10651157
};
10661158
} catch (error) {
10671159
if (automaticRead) automaticRead.status = "failed";
@@ -1400,6 +1492,7 @@ export function createReadState({
14001492
/** Verified observation ancestry, evaluated only inside the fenced transaction. */
14011493
observedFrontier?: (state: ReadState) => number | undefined,
14021494
fence?: LocalUnreadFence,
1495+
undoOptions?: LocalUnreadUndo,
14031496
) =>
14041497
mutate(
14051498
key,
@@ -1409,13 +1502,27 @@ export function createReadState({
14091502
clearLocalKeys,
14101503
observedFrontier,
14111504
fence,
1505+
undefined,
1506+
undoOptions,
14121507
),
14131508
clearLocalUnread: (
14141509
key: string,
14151510
keys: readonly string[],
14161511
valid: Validity,
14171512
fence?: LocalUnreadFence,
1418-
) => mutate(key, undefined, false, valid, keys, undefined, fence),
1513+
undoOptions?: LocalUnreadUndo,
1514+
) =>
1515+
mutate(
1516+
key,
1517+
undefined,
1518+
false,
1519+
valid,
1520+
keys,
1521+
undefined,
1522+
fence,
1523+
undefined,
1524+
undoOptions,
1525+
),
14191526
/** Atomic explicit subtree read; local-only hosts clear intent without
14201527
* fabricating frontiers. A `quiet` save (a row's `seen:` marks) reads
14211528
* nothing, so it is counted apart from unread intent (`intentRevision`). */
@@ -1431,7 +1538,7 @@ export function createReadState({
14311538
quiet = false,
14321539
fence?: LocalUnreadFence,
14331540
clearLocalKeys: readonly string[] = [],
1434-
options: { preserveCapturedSet?: boolean } = {},
1541+
options: { preserveCapturedSet?: boolean; undo?: LocalUnreadUndo } = {},
14351542
) =>
14361543
queue(async () => {
14371544
await ready;
@@ -1441,6 +1548,7 @@ export function createReadState({
14411548
const currentValid = fence
14421549
? await capturedValidity(valid, fence)
14431550
: valid;
1551+
const clearedLocalUnread = new Set<string>();
14441552
const saved = await save((current) => {
14451553
if (!currentValid(current)) throw new ObservationExpired();
14461554
if (
@@ -1468,10 +1576,16 @@ export function createReadState({
14681576
recent[key] = revision;
14691577
frontiers[key] = Math.max(frontiers[key] ?? 0, timestamp);
14701578
}
1471-
delete localUnread[key];
14721579
}
1473-
if (clearForce) delete localUnread[clearForce];
1474-
for (const key of clearLocalKeys) delete localUnread[key];
1580+
const clearLocalUnread = (key: string) => {
1581+
const previous = localUnread[key];
1582+
if (options.undo && previous !== undefined)
1583+
clearedLocalUnread.add(key);
1584+
delete localUnread[key];
1585+
};
1586+
for (const { key } of messages) clearLocalUnread(key);
1587+
if (clearForce) clearLocalUnread(clearForce);
1588+
for (const key of clearLocalKeys) clearLocalUnread(key);
14751589
const kept = Object.keys(frontiers).length
14761590
? retainMarks(
14771591
current,
@@ -1548,13 +1662,22 @@ export function createReadState({
15481662
error: undefined,
15491663
});
15501664
if (capability === "frontier-sync" && messages.length) schedule();
1665+
const clearedKeys = [...clearedLocalUnread];
1666+
const undo = undoLocalUnread(
1667+
saved.slot,
1668+
saved.revision,
1669+
clearedKeys,
1670+
currentValid,
1671+
options.undo,
1672+
);
15511673
return {
15521674
operationId: `${saved.slot}:${saved.revision}`,
15531675
durability: "saved" as const,
15541676
sync:
15551677
capability === "frontier-sync" && messages.length
15561678
? ("pending" as const)
15571679
: ("local-only" as const),
1680+
...(undo && { undo }),
15581681
};
15591682
} catch (error) {
15601683
if (!(error instanceof ObservationExpired))

0 commit comments

Comments
 (0)