fix(webui): preserve session caches during history revalidation (#6636)
This commit is contained in:
1 parent
1046a37be1
commit
0ce10533d3
7 files changed
+68
-43
No files matched your search
@@ -520,7 +520,6 @@ export function useNanobotStream(
|
||||
pending.owner.finishRead(pending.read);
|
||||
if (transcriptRef.current === pending.owner) publishHistory();
|
||||
}, [publishHistory]);
|
||||
const latestReadOwnerRef = useRef<ThreadTranscript>();
|
||||
const detailRequestsRef = useRef(new Map<string, Promise<{ ref: string; events: ThreadProjectionEvent[] } | null>>());
|
||||
const reconcileCanonical = useCallback((generation: number, canonical: ReturnType<typeof persistedCanonicalRunState>, accepted: boolean) => {
|
||||
if (!chatId) return;
|
||||
@@ -542,9 +541,6 @@ export function useNanobotStream(
|
||||
const owner = transcriptRef.current;
|
||||
const controller = new AbortController();
|
||||
const generation = chatId ? client.getRunGeneration(chatId) : 0;
|
||||
const read = owner.begin(latestReadOwnerRef.current === owner ? "latest" : "initial");
|
||||
latestReadOwnerRef.current = owner;
|
||||
publishHistory();
|
||||
let disposed = false;
|
||||
let superseded = false;
|
||||
let publishing = false;
|
||||
@@ -573,6 +569,10 @@ export function useNanobotStream(
|
||||
};
|
||||
const cached = webuiThreadCache.get(historyKey);
|
||||
if (cached && owner.paging.version === 0) install(cached, false, true);
|
||||
// A restored projection or cached seed already has history. Revalidate it
|
||||
// as latest so a safe disjoint window can replace its durable baseline.
|
||||
const read = owner.begin(owner.paging.version > 0 ? "latest" : "initial");
|
||||
publishHistory();
|
||||
const unsubscribe = webuiThreadCache.subscribe(historyKey, (body) => {
|
||||
if (publishing) return;
|
||||
superseded = true;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/** Byte- and entry-bounded in-memory LRU for WebUI state. */
|
||||
/** Byte- and entry-bounded LRU; non-evictable working state is outside that budget. */
|
||||
export class MemoryLruCache<T> {
|
||||
private entries = new Map<string, { value: T; bytes: number }>();
|
||||
private sizes = new WeakMap<object, number>();
|
||||
private bytes = 0;
|
||||
|
||||
constructor(
|
||||
private maxBytes: number,
|
||||
@@ -24,40 +22,51 @@ export class MemoryLruCache<T> {
|
||||
}
|
||||
|
||||
set(key: string, value: T): void {
|
||||
this.delete(key);
|
||||
const bytes = this.estimate(value);
|
||||
// A rejected replacement must not leave a stale snapshot under this key.
|
||||
this.delete(key);
|
||||
if (this.canEvict(key) && (bytes > this.maxBytes || this.maxEntries < 1)) return;
|
||||
this.entries.set(key, { value, bytes });
|
||||
this.bytes += bytes;
|
||||
for (const candidate of this.entries.keys()) {
|
||||
if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break;
|
||||
if (this.canEvict(candidate)) this.delete(candidate);
|
||||
|
||||
let reclaimableBytes = 0;
|
||||
let reclaimableEntries = 0;
|
||||
for (const [candidate, entry] of this.entries) {
|
||||
if (!this.canEvict(candidate)) continue;
|
||||
reclaimableBytes += entry.bytes;
|
||||
reclaimableEntries++;
|
||||
}
|
||||
for (const [candidate, entry] of this.entries) {
|
||||
if (reclaimableBytes <= this.maxBytes && reclaimableEntries <= this.maxEntries) break;
|
||||
if (!this.canEvict(candidate)) continue;
|
||||
this.delete(candidate);
|
||||
reclaimableBytes -= entry.bytes;
|
||||
reclaimableEntries--;
|
||||
}
|
||||
}
|
||||
|
||||
delete(key: string): void {
|
||||
const entry = this.entries.get(key);
|
||||
if (entry) this.bytes -= entry.bytes;
|
||||
this.entries.delete(key);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.entries.clear();
|
||||
this.sizes = new WeakMap<object, number>();
|
||||
this.bytes = 0;
|
||||
}
|
||||
|
||||
private estimate(value: unknown): number {
|
||||
private estimate(value: unknown, seen = new WeakSet<object>()): number {
|
||||
if (typeof value === "string") return value.length * 2;
|
||||
if (!value || typeof value !== "object") return 8;
|
||||
const cached = this.sizes.get(value);
|
||||
if (cached !== undefined) return cached;
|
||||
const values = value instanceof Map ? Array.from(value.entries())
|
||||
: value instanceof Set ? Array.from(value) : Object.values(value);
|
||||
const size = 32 + values.reduce<number>(
|
||||
(total, item) => total + this.estimate(item),
|
||||
0,
|
||||
);
|
||||
this.sizes.set(value, size);
|
||||
return size;
|
||||
if (seen.has(value)) return 0;
|
||||
seen.add(value);
|
||||
let bytes = 32;
|
||||
if (value instanceof Map) {
|
||||
for (const [key, item] of value) {
|
||||
bytes += this.estimate(key, seen) + this.estimate(item, seen);
|
||||
}
|
||||
} else {
|
||||
for (const item of value instanceof Set ? value : Object.values(value)) {
|
||||
bytes += this.estimate(item, seen);
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ export class ThreadMessageCache extends MemoryLruCache<ThreadTranscriptSnapshot>
|
||||
|
||||
constructor(
|
||||
isPinned: (key: string) => boolean,
|
||||
maxBytes = 16 * 1024 * 1024,
|
||||
maxBytes = 32 * 1024 * 1024,
|
||||
maxEntries = 12,
|
||||
) {
|
||||
super(maxBytes, maxEntries, (key) => !isPinned(key));
|
||||
|
||||
@@ -60,7 +60,7 @@ export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload
|
||||
private readonly listeners = new Map<string, Set<(body: WebuiThreadPersistedPayload) => void>>();
|
||||
|
||||
constructor(
|
||||
maxBytes = 16 * 1024 * 1024,
|
||||
maxBytes = 32 * 1024 * 1024,
|
||||
maxEntries = 12,
|
||||
) {
|
||||
super(maxBytes, maxEntries);
|
||||
|
||||
@@ -6,15 +6,19 @@ it.each([
|
||||
{ collection: "Map keys", small: new Map([["turn", "source"]]), large: new Map([["x".repeat(64), "source"]]) },
|
||||
{ collection: "Map values", small: new Map([["turn", "source"]]), large: new Map([["turn", "x".repeat(64)]]) },
|
||||
{ collection: "Set members", small: new Set(["turn"]), large: new Set(["x".repeat(64)]) },
|
||||
])("counts nested $collection toward the byte budget", ({ small, large }) => {
|
||||
const cache = new MemoryLruCache<{ members: typeof large }>(160, 2);
|
||||
const snapshot = { members: small };
|
||||
])("counts shared nested $collection once and re-estimates changed snapshots", ({ small, large }) => {
|
||||
const cache = new MemoryLruCache<{ members: typeof large }>(110, 2);
|
||||
const snapshot = { members: small, alias: small };
|
||||
cache.set("small", snapshot);
|
||||
expect(cache.get("small")).toBe(snapshot);
|
||||
|
||||
cache.set("large", { members: large });
|
||||
expect(cache.get("large")).toBeUndefined();
|
||||
|
||||
cache.set("small", snapshot);
|
||||
expect(cache.get("small")).toBe(snapshot);
|
||||
|
||||
// A saved transcript can share mutable collections with its next snapshot.
|
||||
if (small instanceof Map) small.set("turn", "x".repeat(64));
|
||||
else small.add("x".repeat(64));
|
||||
cache.set("small", snapshot);
|
||||
expect(cache.get("small")).toBeUndefined();
|
||||
});
|
||||
@@ -15,13 +15,25 @@ it("keeps recently visited chats within the entry budget", () => {
|
||||
.toEqual([rows, undefined, rows]);
|
||||
});
|
||||
|
||||
it("bounds large replay snapshots while retaining temporary chats", () => {
|
||||
it("bounds large replay snapshots without charging temporary chats to the reusable budget", () => {
|
||||
const cache = new ThreadMessageCache((key) => key === "temporary", 4096, 2);
|
||||
cache.set("temporary", snapshot);
|
||||
cache.set("large", new ThreadTranscript([{ ...rows[0], content: "x".repeat(4096) }]).save());
|
||||
cache.set("ordinary-a", snapshot);
|
||||
cache.set("ordinary-b", snapshot);
|
||||
const large = new ThreadTranscript([{ ...rows[0], content: "x".repeat(4096) }]).save();
|
||||
cache.set("large", large);
|
||||
expect(cache.get("large")).toBeUndefined();
|
||||
expect(cache.get("temporary")?.projection.messages).toBe(rows);
|
||||
cache.delete("temporary");
|
||||
expect(cache.peek("ordinary-a")).toBe(snapshot);
|
||||
expect(cache.peek("ordinary-b")).toBe(snapshot);
|
||||
|
||||
cache.set("temporary", large);
|
||||
expect(cache.get("temporary")).toBe(large);
|
||||
expect(cache.get("ordinary-a")).toBe(snapshot);
|
||||
expect(cache.peek("ordinary-b")).toBe(snapshot);
|
||||
|
||||
cache.set("small", snapshot);
|
||||
expect(cache.get("small")?.projection.messages).toBe(rows);
|
||||
expect(cache.peek("ordinary-a")).toBe(snapshot);
|
||||
expect(cache.peek("ordinary-b")).toBeUndefined();
|
||||
expect(cache.get("small")).toBe(snapshot);
|
||||
cache.delete("temporary");
|
||||
expect(cache.get("small")).toBe(snapshot);
|
||||
});
|
||||
@@ -3263,7 +3263,7 @@ describe("ThreadShell", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("recovers an uncommitted reset lineage on the next canonical hydrate", async () => {
|
||||
it("adopts a disjoint latest window immediately when returning to a cached session", async () => {
|
||||
const client = makeClient();
|
||||
let chatACalls = 0;
|
||||
vi.stubGlobal(
|
||||
@@ -3309,8 +3309,8 @@ describe("ThreadShell", () => {
|
||||
rerender(view("lineage-chat-a"));
|
||||
await waitFor(() => expect(chatACalls).toBe(2));
|
||||
|
||||
expect(screen.getByText("committed old lineage")).toBeInTheDocument();
|
||||
expect(screen.queryByText("disjoint new lineage")).not.toBeInTheDocument();
|
||||
expect(await screen.findByText("disjoint new lineage")).toBeInTheDocument();
|
||||
expect(screen.queryByText("committed old lineage")).not.toBeInTheDocument();
|
||||
|
||||
act(() => client._emitSessionUpdate("lineage-chat-a", "thread"));
|
||||
|
||||
|
||||
Reference in new issue
Block a user