Skip to content

Commit 5268fac

Browse files
wesbillmanPinky
andauthored
Fix monotonic read-state merges (#884)
Signed-off-by: Wes <[email protected]> Co-authored-by: Pinky <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@sprout-oss.stage.blox.sqprod.co>
1 parent 0a4783c commit 5268fac

18 files changed

Lines changed: 324 additions & 233 deletions

‎desktop/src/app/AppShellContext.tsx‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,7 @@ type AppShellContextValue = {
77
channelId: string,
88
readAt: string | null | undefined,
99
) => void;
10-
markChannelUnread: (
11-
channelId: string,
12-
lastMessageAt: string | null | undefined,
13-
) => void;
10+
markChannelUnread: (channelId: string) => void;
1411
openChannelManagement: () => void;
1512
// NIP-RS read marker for a channel as a unix-seconds timestamp, or null
1613
// when unknown. Backed by the single AppShell-mounted ReadStateManager so
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import { applyRemoteContextTimestamp } from "./readStateManager.ts";
5+
6+
test("applyRemoteContextTimestamp ignores older remote read markers from newer sync events", () => {
7+
const effectiveState = new Map([["channel-1", 200]]);
8+
const contextSourceCreatedAt = new Map([["channel-1", 10]]);
9+
10+
const result = applyRemoteContextTimestamp({
11+
effectiveState,
12+
contextSourceCreatedAt,
13+
contextId: "channel-1",
14+
timestamp: 100,
15+
eventCreatedAt: 11,
16+
});
17+
18+
assert.equal(result, "unchanged");
19+
assert.equal(effectiveState.get("channel-1"), 200);
20+
assert.equal(contextSourceCreatedAt.get("channel-1"), 11);
21+
});
22+
23+
test("applyRemoteContextTimestamp advances to newer remote read markers", () => {
24+
const effectiveState = new Map([["channel-1", 100]]);
25+
const contextSourceCreatedAt = new Map([["channel-1", 10]]);
26+
27+
const result = applyRemoteContextTimestamp({
28+
effectiveState,
29+
contextSourceCreatedAt,
30+
contextId: "channel-1",
31+
timestamp: 200,
32+
eventCreatedAt: 11,
33+
});
34+
35+
assert.equal(result, "advanced");
36+
assert.equal(effectiveState.get("channel-1"), 200);
37+
assert.equal(contextSourceCreatedAt.get("channel-1"), 11);
38+
});
39+
40+
test("applyRemoteContextTimestamp keeps read markers monotonic even if sync events arrive out of order", () => {
41+
const effectiveState = new Map([["channel-1", 100]]);
42+
const contextSourceCreatedAt = new Map([["channel-1", 11]]);
43+
44+
const result = applyRemoteContextTimestamp({
45+
effectiveState,
46+
contextSourceCreatedAt,
47+
contextId: "channel-1",
48+
timestamp: 200,
49+
eventCreatedAt: 10,
50+
});
51+
52+
assert.equal(result, "advanced");
53+
assert.equal(effectiveState.get("channel-1"), 200);
54+
assert.equal(contextSourceCreatedAt.get("channel-1"), 11);
55+
});

‎desktop/src/features/channels/readState/readStateManager.ts‎

Lines changed: 62 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,49 @@ function slotIdKey(pubkey: string): string {
4747
return `${SLOT_ID_KEY_PREFIX}:${pubkey}`;
4848
}
4949

50+
export type ApplyRemoteContextResult = "unchanged" | "advanced";
51+
52+
function resolveRemoteContextTimestamp(args: {
53+
current: number;
54+
timestamp: number;
55+
}): { next: number; result: ApplyRemoteContextResult } {
56+
const next = Math.max(args.current, args.timestamp);
57+
return {
58+
next,
59+
result: next === args.current ? "unchanged" : "advanced",
60+
};
61+
}
62+
63+
export function applyRemoteContextTimestamp(args: {
64+
effectiveState: Map<string, number>;
65+
contextSourceCreatedAt: Map<string, number>;
66+
contextId: string;
67+
timestamp: number;
68+
eventCreatedAt: number;
69+
}): ApplyRemoteContextResult {
70+
const {
71+
effectiveState,
72+
contextSourceCreatedAt,
73+
contextId,
74+
timestamp,
75+
eventCreatedAt,
76+
} = args;
77+
const sourceCreatedAt = contextSourceCreatedAt.get(contextId) ?? 0;
78+
const current = effectiveState.get(contextId) ?? 0;
79+
const { next, result } = resolveRemoteContextTimestamp({
80+
current,
81+
timestamp,
82+
});
83+
84+
if (result === "advanced") {
85+
effectiveState.set(contextId, next);
86+
}
87+
if (eventCreatedAt > sourceCreatedAt) {
88+
contextSourceCreatedAt.set(contextId, eventCreatedAt);
89+
}
90+
return result;
91+
}
92+
5093
export class ReadStateManager {
5194
private pubkey: string;
5295
private relayClient: RelayClient;
@@ -60,9 +103,7 @@ export class ReadStateManager {
60103
private unsubscribeLive: (() => void) | null = null;
61104
private initialized = false;
62105
private maxFetchedCreatedAt = 0;
63-
private forcedContexts = new Set<string>();
64106
private contextSourceCreatedAt = new Map<string, number>();
65-
private pendingSyncedRollbacks = new Set<string>();
66107
private pendingSyncedAdvances = new Set<string>();
67108
private destroyed = false;
68109

@@ -101,7 +142,6 @@ export class ReadStateManager {
101142
}
102143

103144
markContextRead(contextId: string, unixTimestamp: number): void {
104-
this.forcedContexts.delete(contextId);
105145
this.advanceContext(contextId, unixTimestamp, { publishable: true });
106146
this.contextSourceCreatedAt.set(
107147
contextId,
@@ -113,16 +153,6 @@ export class ReadStateManager {
113153
this.advanceContext(contextId, unixTimestamp, { publishable: false });
114154
}
115155

116-
markContextUnread(contextId: string, lastMessageUnix: number): void {
117-
const rollbackTo = lastMessageUnix - 1;
118-
this.effectiveState.set(contextId, rollbackTo);
119-
this.publishableContextIds.add(contextId);
120-
this.forcedContexts.add(contextId);
121-
this.persistLocalState();
122-
this.notifyListeners();
123-
this.schedulePublish();
124-
}
125-
126156
private advanceContext(
127157
contextId: string,
128158
unixTimestamp: number,
@@ -241,16 +271,17 @@ export class ReadStateManager {
241271
}
242272

243273
for (const [ctx, ts] of Object.entries(blob.contexts)) {
244-
if (this.forcedContexts.has(ctx)) continue;
245-
const sourceCreatedAt = this.contextSourceCreatedAt.get(ctx) ?? 0;
246-
const current = this.effectiveState.get(ctx) ?? 0;
247-
if (event.created_at > sourceCreatedAt) {
248-
this.effectiveState.set(ctx, ts);
249-
this.contextSourceCreatedAt.set(ctx, event.created_at);
250-
} else if (event.created_at === sourceCreatedAt && ts !== current) {
251-
this.effectiveState.set(ctx, ts);
274+
const result = applyRemoteContextTimestamp({
275+
effectiveState: this.effectiveState,
276+
contextSourceCreatedAt: this.contextSourceCreatedAt,
277+
contextId: ctx,
278+
timestamp: ts,
279+
eventCreatedAt: event.created_at,
280+
});
281+
if (result !== "unchanged") {
282+
this.pendingSyncedAdvances.add(ctx);
283+
this.publishableContextIds.add(ctx);
252284
}
253-
this.publishableContextIds.add(ctx);
254285
}
255286

256287
if (blob.client_id === this.clientId) {
@@ -361,27 +392,15 @@ export class ReadStateManager {
361392

362393
let anyAdvanced = false;
363394
for (const [ctx, ts] of Object.entries(blob.contexts)) {
364-
if (this.forcedContexts.has(ctx)) continue;
365-
const sourceCreatedAt = this.contextSourceCreatedAt.get(ctx) ?? 0;
366-
const current = this.effectiveState.get(ctx) ?? 0;
367-
if (event.created_at > sourceCreatedAt) {
368-
if (this.effectiveState.get(ctx) !== ts) {
369-
if (ts < current && current > 0) {
370-
this.pendingSyncedRollbacks.add(ctx);
371-
this.pendingSyncedAdvances.delete(ctx);
372-
console.debug(
373-
`[ReadStateManager] synced rollback ctx=${ctx.substring(0, 12)}… from=${current} to=${ts}`,
374-
);
375-
} else if (ts > current) {
376-
this.pendingSyncedAdvances.add(ctx);
377-
this.pendingSyncedRollbacks.delete(ctx);
378-
}
379-
this.effectiveState.set(ctx, ts);
380-
anyAdvanced = true;
381-
}
382-
this.contextSourceCreatedAt.set(ctx, event.created_at);
383-
} else if (event.created_at === sourceCreatedAt && ts !== current) {
384-
this.effectiveState.set(ctx, ts);
395+
const result = applyRemoteContextTimestamp({
396+
effectiveState: this.effectiveState,
397+
contextSourceCreatedAt: this.contextSourceCreatedAt,
398+
contextId: ctx,
399+
timestamp: ts,
400+
eventCreatedAt: event.created_at,
401+
});
402+
if (result === "advanced") {
403+
this.pendingSyncedAdvances.add(ctx);
385404
anyAdvanced = true;
386405
}
387406
if (!this.publishableContextIds.has(ctx)) {
@@ -467,7 +486,6 @@ export class ReadStateManager {
467486
}
468487
}
469488
this.lastPublishedContexts = contexts;
470-
this.forcedContexts.clear();
471489
this.maxFetchedCreatedAt = Math.max(
472490
this.maxFetchedCreatedAt,
473491
event.created_at,
@@ -544,12 +562,6 @@ export class ReadStateManager {
544562
);
545563
}
546564

547-
drainSyncedRollbacks(): ReadonlySet<string> {
548-
const drained = this.pendingSyncedRollbacks;
549-
this.pendingSyncedRollbacks = new Set<string>();
550-
return drained;
551-
}
552-
553565
drainSyncedAdvances(): ReadonlySet<string> {
554566
const drained = this.pendingSyncedAdvances;
555567
this.pendingSyncedAdvances = new Set<string>();

‎desktop/src/features/channels/readState/useReadState.ts‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import type { RelayClient } from "@/shared/api/relayClientSession";
44

55
const noopGetTimestamp = () => null;
66
const noopMarkRead = () => {};
7-
const noopMarkUnread = () => {};
8-
const noopDrainRollbacks = (): ReadonlySet<string> => new Set<string>();
97
const noopDrainAdvances = (): ReadonlySet<string> => new Set<string>();
108

119
/**
@@ -66,24 +64,13 @@ export function useReadState(
6664
[],
6765
);
6866

69-
const markContextUnread = React.useCallback(
70-
(contextId: string, lastMessageUnix: number): void => {
71-
managerRef.current?.markContextUnread(contextId, lastMessageUnix);
72-
},
73-
[],
74-
);
75-
7667
const seedContextRead = React.useCallback(
7768
(contextId: string, unixTimestamp: number): void => {
7869
managerRef.current?.seedContextRead(contextId, unixTimestamp);
7970
},
8071
[],
8172
);
8273

83-
const drainSyncedRollbacks = React.useCallback((): ReadonlySet<string> => {
84-
return managerRef.current?.drainSyncedRollbacks() ?? new Set<string>();
85-
}, []);
86-
8774
const drainSyncedAdvances = React.useCallback((): ReadonlySet<string> => {
8875
return managerRef.current?.drainSyncedAdvances() ?? new Set<string>();
8976
}, []);
@@ -97,9 +84,7 @@ export function useReadState(
9784
getEffectiveTimestamp: noopGetTimestamp,
9885
isReady: false,
9986
markContextRead: noopMarkRead,
100-
markContextUnread: noopMarkUnread,
10187
seedContextRead: noopMarkRead,
102-
drainSyncedRollbacks: noopDrainRollbacks,
10388
drainSyncedAdvances: noopDrainAdvances,
10489
readStateVersion: 0,
10590
};
@@ -109,9 +94,7 @@ export function useReadState(
10994
getEffectiveTimestamp,
11095
isReady,
11196
markContextRead,
112-
markContextUnread,
11397
seedContextRead,
114-
drainSyncedRollbacks,
11598
drainSyncedAdvances,
11699
readStateVersion,
117100
};

‎desktop/src/features/channels/ui/ChannelScreen.tsx‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ import {
3434
} from "@/features/messages/lib/formatTimelineMessages";
3535
import { buildThreadPanelData } from "@/features/messages/lib/threadPanel";
3636
import { imetaMediaFromTags } from "@/features/messages/lib/imetaMediaMarkdown";
37-
import type { TimelineMessage } from "@/features/messages/types";
3837
import { useFetchOlderMessages } from "@/features/messages/useFetchOlderMessages";
3938
import { useLoadMissingAncestors } from "@/features/messages/useLoadMissingAncestors";
4039
import { useChannelTyping } from "@/features/messages/useChannelTyping";
@@ -334,14 +333,10 @@ export function ChannelScreen({
334333
: undefined,
335334
[activeChannel, handleToggleReaction],
336335
);
337-
const handleMarkUnread = React.useCallback(
338-
(message: TimelineMessage) => {
339-
if (!activeChannelId) return;
340-
const messageIso = new Date(message.createdAt * 1_000).toISOString();
341-
markChannelUnread(activeChannelId, messageIso);
342-
},
343-
[activeChannelId, markChannelUnread],
344-
);
336+
const handleMarkUnread = React.useCallback(() => {
337+
if (!activeChannelId) return;
338+
markChannelUnread(activeChannelId);
339+
}, [activeChannelId, markChannelUnread]);
345340
const {
346341
channelAgentSessionAgents,
347342
closeAgentSession: handleCloseAgentSession,

0 commit comments

Comments
 (0)