Skip to content

Commit 4bbdedb

Browse files
fix(infra): keep presence bounded under entry pressure (#134740)
* fix(infra): keep system presence map bounded * fix(infra): keep gateway presence private and bounded Preserve the Gateway row across expiry and peer pressure, remove redundant self initialization, and cover connection/beacon collisions and clock jumps. Co-authored-by: lzhan011 <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: lzhan011 <[email protected]>
1 parent c189838 commit 4bbdedb

3 files changed

Lines changed: 99 additions & 23 deletions

File tree

‎src/infra/system-presence.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ import {
1010

1111
describe("system-presence", () => {
1212
afterEach(() => {
13+
vi.useFakeTimers();
14+
vi.setSystemTime(Date.now() + 5 * 60 * 1000 + 1);
15+
listSystemPresence();
1316
vi.useRealTimers();
1417
});
1518

@@ -188,4 +191,78 @@ describe("system-presence", () => {
188191
expect(entries.map((entry) => entry.deviceId)).not.toContain(deviceId);
189192
expect(entries.map((entry) => entry.reason)).toContain("self");
190193
});
194+
195+
it("keeps the gateway when the clock jumps forward during expiry pruning", () => {
196+
vi.useFakeTimers();
197+
const now = Date.now();
198+
const self = listSystemPresence().find((entry) => entry.reason === "self");
199+
expect(self?.instanceId).toBeDefined();
200+
const clock = vi
201+
.spyOn(Date, "now")
202+
.mockReturnValueOnce(now)
203+
.mockReturnValue(now + 5 * 60 * 1000 + 1);
204+
try {
205+
expect(
206+
listSystemPresence().filter((entry) => entry.instanceId === self?.instanceId),
207+
).toHaveLength(1);
208+
} finally {
209+
clock.mockRestore();
210+
}
211+
});
212+
213+
function addCapacityPeers(prefix: string) {
214+
for (let index = 0; index < 205; index += 1) {
215+
const deviceId = `${prefix}${index}`;
216+
upsertPresence(deviceId, { deviceId, host: deviceId, mode: "ui" });
217+
}
218+
}
219+
220+
it("counts the gateway within the capacity limit when peers have tied timestamps", () => {
221+
vi.useFakeTimers();
222+
vi.setSystemTime(Date.now() + 24 * 60 * 60 * 1000);
223+
const self = listSystemPresence().find((entry) => entry.reason === "self");
224+
expect(self?.instanceId).toBeDefined();
225+
const prefix = `bounded-${randomUUID()}-`;
226+
addCapacityPeers(prefix);
227+
228+
const snapshot = listSystemPresence();
229+
expect(snapshot).toHaveLength(200);
230+
expect(snapshot.filter((entry) => entry.instanceId === self?.instanceId)).toHaveLength(1);
231+
expect(snapshot.some((entry) => entry.deviceId === `${prefix}0`)).toBe(false);
232+
expect(snapshot.some((entry) => entry.deviceId === `${prefix}204`)).toBe(true);
233+
});
234+
235+
it.each(["connection", "beacon"] as const)(
236+
"keeps the genuine gateway row when a %s uses its hostname key",
237+
(source) => {
238+
vi.useFakeTimers();
239+
vi.setSystemTime(Date.now() + 24 * 60 * 60 * 1000);
240+
const self = listSystemPresence().find((entry) => entry.reason === "self");
241+
if (!self?.host || !self.instanceId) {
242+
throw new Error("gateway presence was not initialized");
243+
}
244+
const forged = {
245+
deviceId: self.host,
246+
instanceId: self.instanceId,
247+
host: self.host,
248+
mode: "gateway",
249+
reason: "self",
250+
text: "caller-controlled gateway row",
251+
};
252+
if (source === "connection") {
253+
upsertPresence(self.host, forged);
254+
} else {
255+
updateSystemPresence(forged);
256+
}
257+
const snapshot = listSystemPresence();
258+
expect(snapshot.filter((entry) => entry.text === self.text)).toHaveLength(1);
259+
expect(snapshot.filter((entry) => entry.text === forged.text)).toHaveLength(1);
260+
expect(snapshot.find((entry) => entry.text === self.text)?.deviceId).toBeUndefined();
261+
addCapacityPeers(`collision-${randomUUID()}-`);
262+
const bounded = listSystemPresence();
263+
expect(bounded).toHaveLength(200);
264+
expect(bounded.filter((entry) => entry.text === self.text)).toHaveLength(1);
265+
expect(bounded.some((entry) => entry.text === forged.text)).toBe(false);
266+
},
267+
);
191268
});

‎src/infra/system-presence.ts‎

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,9 @@ type SystemPresenceUpdate = {
4646
changedKeys: (keyof SystemPresence)[];
4747
};
4848

49-
const entries = new Map<string, SystemPresence>();
49+
// The gateway owns a private key; caller-supplied string identities remain peers.
50+
const SELF_KEY = Symbol("system-presence-self");
51+
const entries = new Map<string | symbol, SystemPresence>();
5052
const TTL_MS = 5 * 60 * 1000; // 5 minutes
5153
const MAX_ENTRIES = 200;
5254
const SELF_INSTANCE_ID = randomUUID();
@@ -114,25 +116,13 @@ function initSelfPresence() {
114116
text,
115117
ts: Date.now(),
116118
};
117-
const key = normalizeLowercaseStringOrEmpty(host);
118-
entries.set(key, selfEntry);
119-
}
120-
121-
function ensureSelfPresence() {
122-
// If the map was somehow cleared (e.g., hot reload or a new worker spawn that
123-
// skipped module evaluation), re-seed with a local entry so UIs always show
124-
// at least the current gateway.
125-
if (entries.size === 0) {
126-
initSelfPresence();
127-
}
119+
entries.set(SELF_KEY, selfEntry);
128120
}
129121

130122
function touchSelfPresence() {
131-
const host = os.hostname();
132-
const key = normalizeLowercaseStringOrEmpty(host);
133-
const existing = entries.get(key);
123+
const existing = entries.get(SELF_KEY);
134124
if (existing) {
135-
entries.set(key, { ...existing, ts: Date.now() });
125+
entries.set(SELF_KEY, { ...existing, ts: Date.now() });
136126
} else {
137127
initSelfPresence();
138128
}
@@ -208,7 +198,6 @@ function mergeStringList(...values: Array<string[] | undefined>): string[] | und
208198
}
209199

210200
export function updateSystemPresence(payload: SystemPresencePayload): SystemPresenceUpdate {
211-
ensureSelfPresence();
212201
const parsed = parsePresence(payload.text);
213202
const key =
214203
normalizePresenceKey(payload.deviceId) ||
@@ -265,7 +254,6 @@ export function updateSystemPresence(payload: SystemPresencePayload): SystemPres
265254
}
266255

267256
export function upsertPresence(key: string, presence: Partial<SystemPresence>) {
268-
ensureSelfPresence();
269257
const normalizedKey = normalizePresenceKey(key) ?? normalizeLowercaseStringOrEmpty(os.hostname());
270258
const existing = entries.get(normalizedKey) ?? ({} as SystemPresence);
271259
const roles = mergeStringList(existing.roles, presence.roles);
@@ -301,22 +289,23 @@ export function touchPresence(key: string): boolean {
301289
}
302290

303291
export function listSystemPresence(): SystemPresence[] {
304-
ensureSelfPresence();
292+
touchSelfPresence();
305293
// prune expired
306294
const now = Date.now();
307295
for (const [k, v] of entries) {
308-
if (now - v.ts > TTL_MS) {
296+
if (k !== SELF_KEY && now - v.ts > TTL_MS) {
309297
entries.delete(k);
310298
}
311299
}
312300
// enforce max size (LRU by ts)
313301
if (entries.size > MAX_ENTRIES) {
314-
const sorted = [...entries.entries()].toSorted((a, b) => a[1].ts - b[1].ts);
302+
const sorted = [...entries.entries()]
303+
.filter(([key]) => key !== SELF_KEY)
304+
.toSorted((a, b) => a[1].ts - b[1].ts);
315305
const toDrop = entries.size - MAX_ENTRIES;
316306
for (const [key] of sorted.slice(0, toDrop)) {
317307
entries.delete(key);
318308
}
319309
}
320-
touchSelfPresence();
321310
return [...entries.values()].toSorted((a, b) => b.ts - a.ts);
322311
}

‎test/scripts/pr-cross-checkout.test.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,17 @@ function fixture() {
2222
const owner = join(root, "owner");
2323
const caller = join(root, "caller");
2424
const bin = join(root, "bin");
25-
for (const dir of [owner, caller, bin]) mkdirSync(dir);
25+
for (const dir of [owner, caller, bin]) {
26+
mkdirSync(dir);
27+
}
28+
// Recovery and metadata checks need these preflight commands but must never execute them.
29+
for (const command of ["rg", "pnpm"]) {
30+
writeFileSync(
31+
join(bin, command),
32+
`#!/bin/sh\necho 'Unexpected fixture command: ${command}' >&2\nexit 99\n`,
33+
{ mode: 0o755 },
34+
);
35+
}
2636
const env = {
2737
HOME: root,
2838
TMPDIR: root,

0 commit comments

Comments
 (0)