perf(events): ask once per handle when a refresh screens rows, and share handle reads

A socket refresh asks whether a share handle still stands once per
handle, holder and app, rather than once per row: rows through one
handle share its grant. Concurrent cache misses on one handle share a
single read; a forget drops the shared read so later callers start a
fresh one.
This commit is contained in:
Daniel Salazar committed 2026-10-31 01:03:28 -07:00
1 parent 158316ee2c
commit 03f577f5a7
4 files changed
+94 -7

No files matched your search

@@ -384,6 +384,37 @@ describe('rows made through a share handle', () => {
SESSION_SUBSCRIPTION_TTL_SECONDS - 10,
);
});
it('asks about each handle once per holder and app on refresh', async () => {
const holder = USER + 7000;
const rows = [
through(holder, 0, { socketId: 'socket-a' }),
through(holder, 1, {
socketId: 'socket-a',
token: 'k#owner#app#ws:a:',
}),
through(holder, 2, {
socketId: 'socket-a',
token: 'k#owner#app#ws:b:',
}),
through(holder, 3, { socketId: 'socket-a', appUid: 'app-x' }),
through(holder, 4, {
socketId: 'socket-a',
subject: `kv:${OTHER_HANDLE}:*`,
}),
];
for (const row of rows) await store.add(row);
const stillHeld = vi.fn(async (row: SessionSubscription) =>
row.subject.includes(HANDLE),
);
const { lapsed } = await store.refresh(holder, 'socket-a', {
stillHeld,
});
expect(stillHeld).toHaveBeenCalledTimes(3);
expect(lapsed).toEqual([rows[4]]);
});
});
describe('removal', () => {
@@ -848,7 +848,9 @@ export class EventSubscriptionStore extends PuterStore {
* A row made through a share handle is kept only if `stillHeld` says the
* handle still stands; the rest come back as `lapsed`, untouched, for the
* caller to end. Without that, a live socket would hold a retired handle's
* rows in the owner's keyspace for as long as it stays connected.
* rows in the owner's keyspace for as long as it stays connected. Rows
* through one handle share its grant, so it's asked once per handle, holder
* and app.
*
* Returns every (owner, token) pair the socket still holds, and the value
* variant of each one a row asks KV values on, so the caller can
@@ -873,6 +875,17 @@ export class EventSubscriptionStore extends PuterStore {
const reasserted: RefreshResult['reasserted'] = [];
const lapsed: SessionSubscription[] = [];
const asked = new Map<string, Promise<boolean>>();
const stillHeld = (row: SessionSubscription, handle: string) => {
if (!options.stillHeld) return true;
const key = `${handle}|${row.holderUserId}|${row.appUid ?? ''}`;
let answer = asked.get(key);
if (!answer) {
answer = options.stillHeld(row);
asked.set(key, answer);
}
return answer;
};
for (const [ownerUserId, owned] of byOwner(refs)) {
const read = this.clients.redis.pipeline();
for (const ref of owned)
@@ -888,11 +901,12 @@ export class EventSubscriptionStore extends PuterStore {
row ? kvHandleFromSubject(row.subject) : null,
);
const held = await Promise.all(
rows.map((row, i) =>
row && handles[i] !== null && options.stillHeld
? options.stillHeld(row)
: true,
),
rows.map((row, i) => {
const handle = handles[i];
return row && handle !== null
? stillHeld(row, handle)
: true;
}),
);
rows.forEach((row, i) => {
if (row && !held[i]) lapsed.push(row);
@@ -608,6 +608,26 @@ describe('the live cache across nodes', () => {
});
});
it('reads a handle once for concurrent misses', async () => {
const row = await store().mint(
input({ appUid: 'app-forget', keyPrefix: 'forget-concurrent:' }),
);
// The test engine runs primary reads through `read` too, so this
// counts every query.
const read = vi.spyOn(env.server.clients.db, 'read');
try {
const [first, second] = await Promise.all([
store().getLive(row.handle),
store().getLive(row.handle),
]);
expect(first).not.toBeNull();
expect(second).toBe(first);
expect(handleReads(read)).toBe(1);
} finally {
read.mockRestore();
}
});
it('reads nothing for an id whose mac does not verify', async () => {
const row = await store().mint(
input({ appUid: 'app-forget', keyPrefix: 'forget-d:' }),
@@ -226,6 +226,8 @@ export class KvShareHandleStore extends PuterStore {
ttlMs: FORGOTTEN_TTL_MS,
});
#forgets = 0;
/** Reads in flight, so concurrent misses on one handle share a query. */
readonly #reading = new Map<string, Promise<LiveKvShareHandle | null>>();
async mint(input: MintKvShareHandleInput): Promise<KvShareHandle> {
const row: KvShareHandle = {
@@ -310,6 +312,8 @@ export class KvShareHandleStore extends PuterStore {
#forgetOwner(ownerUserId: number): void {
this.#forgottenOwners.set(ownerUserId, ++this.#forgets);
this.#live.deleteWhere(({ row }) => row.ownerUserId === ownerUserId);
// A read's owner is only known once it returns.
this.#reading.clear();
}
/**
@@ -320,7 +324,8 @@ export class KvShareHandleStore extends PuterStore {
* A forged id is refused without a read. Only a signed id falls back to the
* primary on a replica miss: that is for read-after-mint, and legacy ids
* are no longer minted. A handle or owner forgotten in the last minute,
* before or during the read, is read from the primary too.
* before or during the read, is read from the primary too. Concurrent
* misses on one handle share one read.
*/
async getLive(handle: string): Promise<LiveKvShareHandle | null> {
const kind = kvHandleIdKind(handle, this.config.jwt_secret_v2);
@@ -329,6 +334,22 @@ export class KvShareHandleStore extends PuterStore {
if (cached) return cached;
if (this.#missing.has(handle)) return null;
const reading = this.#reading.get(handle);
if (reading) return reading;
const read = this.#readLive(handle, kind);
this.#reading.set(handle, read);
try {
return await read;
} finally {
if (this.#reading.get(handle) === read)
this.#reading.delete(handle);
}
}
async #readLive(
handle: string,
kind: 'signed' | 'legacy',
): Promise<LiveKvShareHandle | null> {
let before = this.#forgets;
const primary = this.#forgotten.has(handle);
let rows = primary
@@ -371,6 +392,7 @@ export class KvShareHandleStore extends PuterStore {
this.#forgotten.set(handle, ++this.#forgets);
this.#live.delete(handle);
this.#missing.delete(handle);
this.#reading.delete(handle);
}
/** Drops the cached copies on this node and every other one. */