From ad51a3ecc57990362dc9027b4c4e5310181206c8 Mon Sep 17 00:00:00 2001 From: Joseph Mearman Date: Sun, 15 Nov 2026 16:09:21 +0000 Subject: [PATCH 1/2] fix(core): hold a coordinator's state until its claim is accepted, and evict by time offline A coordinator's snapshot or announcement can be read before the claim that names it is accepted, so what was refused only for want of that authority is held per sender and applied when its claim is accepted. A held record expires after one claim wait, is dropped when a claim naming another peer is accepted, and a held departure is applied only if the agent's record is as it was when it was held. At the bound on agents, the record offline longest is evicted, in the order the store saw them go offline and found without scanning every record. New agents are counted per origin (the host a peer was reached at, or this machine) instead of per device key, and an origin at its bound replaces its own offline record. The identity cache entry that forget cleared was keyed differently and is no longer touched. Once a store's own agent is offline, a snapshot's record of it is ignored instead of applied whole, and a dialled coordinator's records are covered by a test. --- src/core/deferred-intake.ts | 105 ++++++++ src/core/delivery-engine.ts | 12 +- src/core/known-agents.ts | 35 +++ src/core/mesh-store.ts | 4 +- src/core/peer-lifecycle.ts | 83 +++--- src/core/stale-agent-checker.ts | 4 +- src/core/state-intake.ts | 151 +++++------ src/test/coordinator-failover.unit.test.ts | 3 +- .../delivery-engine-own-agent.unit.test.ts | 30 ++- .../peer-lifecycle-claim-order.unit.test.ts | 132 ++++++++++ src/test/peer-lifecycle.unit.test.ts | 237 +++++++++++++++--- src/test/stale-agent-checker.unit.test.ts | 5 - src/test/state-intake.unit.test.ts | 187 +++++++++----- 13 files changed, 767 insertions(+), 221 deletions(-) create mode 100644 src/core/deferred-intake.ts create mode 100644 src/core/known-agents.ts create mode 100644 src/test/peer-lifecycle-claim-order.unit.test.ts diff --git a/src/core/deferred-intake.ts b/src/core/deferred-intake.ts new file mode 100644 index 00000000..11078b85 --- /dev/null +++ b/src/core/deferred-intake.ts @@ -0,0 +1,105 @@ +/** + * State a peer sent before this side had accepted the claim that makes the peer the coordinator. The coordinator's own snapshot and announcements can be read ahead of the claim that names it, since they arrive on a different queue of the same session, so what is refused only for want of that authority is held and taken once a claim naming the sender is accepted. What is held is bounded, expires after one claim wait, and is dropped when a claim naming another peer is accepted, since the sender then is not the coordinator; a held departure is applied only if the agent's record is as it was when the report was held, so a report about an agent that has since come back is not applied. + */ + +import type { AgentIdentity } from "./types.js"; + +/** The most peers whose state is held at once. */ +export const MAX_HELD_SENDERS = 16; + +/** The most agent records held for one sender: the most one snapshot may carry that a store would keep, a few hundred at a time being what a coordinator relays. */ +export const MAX_HELD_AGENTS_PER_SENDER = 256; + +/** The most departures held for one sender. */ +export const MAX_HELD_DEPARTURES_PER_SENDER = 64; + +interface Held { + readonly heldAt: number; + readonly agents: Map; + /** Each held departure, with the version of the agent's record when it was held (undefined when there was none). */ + readonly departures: Map; +} + +/** What a claim naming a sender released. */ +export interface Released { + readonly agents: readonly AgentIdentity[]; + readonly departures: readonly string[]; +} + +export class DeferredIntake { + private readonly bySender = new Map(); + + /** + * @param now - The current time in milliseconds. + * @param ttlMs - How long a sender's held state stays valid, counted from the first thing held for it. + * @param versionOf - The version of the record this store holds for an agent, if any. + */ + constructor( + private readonly now: () => number, + private readonly ttlMs: number, + private readonly versionOf: (agentId: string) => number | undefined, + ) {} + + private heldFor(senderId: string): Held | undefined { + const now = this.now(); + const existing = this.bySender.get(senderId); + if (existing !== undefined && now - existing.heldAt <= this.ttlMs) { + return existing; + } + this.bySender.delete(senderId); + for (const [id, held] of this.bySender) { + if (now - held.heldAt > this.ttlMs) this.bySender.delete(id); + } + if (this.bySender.size >= MAX_HELD_SENDERS) return undefined; + const created: Held = { + heldAt: now, + agents: new Map(), + departures: new Map(), + }; + this.bySender.set(senderId, created); + return created; + } + + holdAgent(senderId: string, agent: Readonly): void { + const held = this.heldFor(senderId); + if (held === undefined) return; + if ( + held.agents.size >= MAX_HELD_AGENTS_PER_SENDER && + !held.agents.has(agent.id) + ) { + return; + } + held.agents.set(agent.id, { ...agent }); + } + + holdDeparture(senderId: string, agentId: string): void { + const held = this.heldFor(senderId); + if (held === undefined) return; + if ( + held.departures.size >= MAX_HELD_DEPARTURES_PER_SENDER && + !held.departures.has(agentId) + ) { + return; + } + held.departures.set(agentId, this.versionOf(agentId)); + } + + /** What a claim naming `holderId` releases: its held state if still valid. Everything held for any other sender is dropped, since a claim naming someone else was accepted. */ + release(holderId: string): Released { + const held = this.bySender.get(holderId); + const expired = held !== undefined && this.now() - held.heldAt > this.ttlMs; + this.bySender.clear(); + if (held === undefined || expired) return { agents: [], departures: [] }; + return { + agents: [...held.agents.values()], + departures: [...held.departures] + .filter(([agentId, version]) => this.versionOf(agentId) === version) + .map(([agentId]) => agentId), + }; + } + + /** Drops what is held for a sender whose connection ended. */ + drop(senderId: string): void { + this.bySender.delete(senderId); + } +} diff --git a/src/core/delivery-engine.ts b/src/core/delivery-engine.ts index 45caac91..b06082fe 100644 --- a/src/core/delivery-engine.ts +++ b/src/core/delivery-engine.ts @@ -213,13 +213,11 @@ export class DeliveryEngine { continue; } const own = this.deps.agents.get(id); - if ( - own !== undefined && - this.isOwnRunningAgent(id, own) && - agent.status === "offline" - ) { - // The same authority rule as an agent_offline patch: a snapshot from a peer that still holds this store's agent as offline (the previous coordinator retired it) must not overwrite a running agent, or the store would gossip itself offline for good. - void this.reassertOwnAgent(own, agent.version); + if (own !== undefined && id === this.deps.getPeerId()) { + // This store is the authority on its own agent, so a snapshot's record of it is never applied. One that says offline while the agent runs (the previous coordinator retired it) is contradicted, or the store would gossip itself offline for good; any other is ignored, and an agent that this store has itself set offline stays as it set it. + if (this.isOwnRunningAgent(id, own) && agent.status === "offline") { + void this.reassertOwnAgent(own, agent.version); + } continue; } if (existingVersion === agent.version) { diff --git a/src/core/known-agents.ts b/src/core/known-agents.ts new file mode 100644 index 00000000..7255b764 --- /dev/null +++ b/src/core/known-agents.ts @@ -0,0 +1,35 @@ +/** + * The agents a store knows of, with the order in which their records went offline, so that a store at its bound can give up the record that has been offline longest. The order is the one in which this store first saw each record offline, kept while it stays offline and dropped when it comes back or is removed; it is local to the store and never sent. + */ + +import type { AgentIdentity } from "./types.js"; + +export class KnownAgents extends Map { + /** The offline records in the order they went offline: an id is added when its record is first seen offline and keeps its place while it stays, so the first is the one offline longest. */ + private readonly offlineOrder = new Set(); + + override set(agentId: string, agent: AgentIdentity): this { + super.set(agentId, agent); + if (agent.status === "offline") { + this.offlineOrder.add(agentId); + } else { + this.offlineOrder.delete(agentId); + } + return this; + } + + override delete(agentId: string): boolean { + this.offlineOrder.delete(agentId); + return super.delete(agentId); + } + + override clear(): void { + this.offlineOrder.clear(); + super.clear(); + } + + /** The ids of the offline records, the one that went offline longest ago first. */ + offlineOldestFirst(): IterableIterator { + return this.offlineOrder.values(); + } +} diff --git a/src/core/mesh-store.ts b/src/core/mesh-store.ts index 0a8e2ee1..4aa5b00f 100644 --- a/src/core/mesh-store.ts +++ b/src/core/mesh-store.ts @@ -43,6 +43,7 @@ import { type LedgerGaps, } from "./account-ledger.js"; import { StaleAgentChecker } from "./stale-agent-checker.js"; +import { KnownAgents } from "./known-agents.js"; import { PeerLifecycle } from "./peer-lifecycle.js"; import { CoordinatorRole, @@ -133,7 +134,7 @@ export class MeshStore implements CommsStore { onError: this.reportError, }); - private readonly agents = new Map(); + private readonly agents = new KnownAgents(); private readonly rooms = new Map(); private readonly messages = new Map(); private readonly dms = new Map(); @@ -432,7 +433,6 @@ export class MeshStore implements CommsStore { this.staleAgentChecker = new StaleAgentChecker({ agents: this.agents, deliveryQueues: this.deliveryQueues, - identityCache: this.identityCache, peerInfo: this.peerInfo, notifyRoomsOfStatus: async (agentId, status) => this.deliveryEngine.notifyRoomsOfStatus(agentId, status), diff --git a/src/core/peer-lifecycle.ts b/src/core/peer-lifecycle.ts index 1858294f..f2bde337 100644 --- a/src/core/peer-lifecycle.ts +++ b/src/core/peer-lifecycle.ts @@ -5,10 +5,13 @@ */ import { reportRejection } from "./detached-work.js"; +import { DeferredIntake } from "./deferred-intake.js"; +import type { KnownAgents } from "./known-agents.js"; import { AgentSlots, admitPatch, admitSnapshot, + isAwaitingAuthority, type StateSender, } from "./state-intake.js"; import { normaliseWireState } from "./wire-protocol.js"; @@ -32,12 +35,11 @@ import type { StaleAgentChecker } from "./stale-agent-checker.js"; import type { RoomProtocol } from "./room-protocol.js"; import type { CoordinatorRole } from "./coordinator-role.js"; import type { ConnectionHandle, MeshTransport } from "./transport.js"; -import type { AgentIdentity } from "./types.js"; /** The state and collaborators PeerLifecycle needs from MeshStore. peerInfo/agents are direct references into MeshStore's own fields; coordinatorPort is a readonly value copied once; serialise is MeshStore's own retained method (constraint: it must stay directly on MeshStore.prototype, so PeerLifecycle calls it through this closure rather than owning it); roomProtocol/deliveryEngine/staleAgentChecker are the already-constructed instances (construction order: ... -\> roomProtocol -\> ... -\> staleAgentChecker -\> peerLifecycle), narrowed to what peer-lifecycle bookkeeping ever needs. */ export interface PeerLifecycleDeps { peerInfo: Map; - agents: Map; + agents: KnownAgents; coordinatorPort: number; /** The UDP port the coordinator-free first-contact presence binds (agent-comms#341). Undefined means no presence at all: only the bridge entry points set it (bridge-mesh.ts), so a store built by anything else, a test included, never cross-discovers another store. */ firstContactPort?: number | undefined; @@ -71,6 +73,8 @@ export interface PeerLifecycleDeps { | "current" | "onHolderAccepted" >; + /** The current time in milliseconds; absent means the system clock. */ + now?: (() => number) | undefined; /** Reports a failed takeover or rejoin. The crash-race path runs detached from any caller that could handle a rejection, so this is the only signal that a coordinator loss was noticed but not recovered from. */ onError?: ((error: Error) => void) | undefined; } @@ -78,9 +82,6 @@ export interface PeerLifecycleDeps { /** How many peers a refusal has been reported for, at most, before the record starts again: a report is made once per peer, so a flood of peers cannot flood the error channel or this set. */ const MAX_REPORTED_PEERS = 1024; -/** How many departure announcements wait for their sender to be accepted as the holder. */ -const MAX_DEFERRED_DEPARTURES = 64; - /** How much of a peer's id a report names: enough to tell peers apart in a log. */ const SHORT_ID_LENGTH = 12; @@ -105,8 +106,8 @@ export class PeerLifecycle { /** The peers a refusal has been reported for. */ private readonly reportedPeers = new Set(); - /** Offline reports refused because their sender was not yet known to be the holder, by sender, replayed when it is. */ - private readonly deferredDepartures = new Map>(); + /** What a sender gave before the claim that makes it the coordinator was accepted, applied when that claim is. */ + private readonly deferred: DeferredIntake; /** Guards against a second contest running while the first is still binding or rejoining -- a coordinator whose process dies can close more than one session to this side, and each close arrives as its own disconnect. */ private contestingCoordinatorRole = false; @@ -123,10 +124,13 @@ export class PeerLifecycle { forget: (agentId) => { deps.staleAgentChecker.forget(agentId); }, - hasPeer: (agentId) => deps.peerInfo.has(agentId), ownId: () => deps.getPeerId(), - now: Date.now, }); + this.deferred = new DeferredIntake( + deps.now ?? Date.now, + ROOM_REQUEST_TIMEOUT_MS, + (agentId) => deps.agents.get(agentId)?.version, + ); } /** Starts the coordinator-free presence (agent-comms#341) when a firstContactPort was configured: each discovered peer (carrying the host its beacon came from) is fed through handlePeerList, whose dial-out plus the peer_list every established connection shares (handlePeerConnected) forms the mesh transitively with no coordinator's handout. A no-op with no port, and on a second call. */ @@ -287,21 +291,28 @@ export class PeerLifecycle { this.deps.coordinatorRole.current()?.holder === handle.id, }; const ownId = this.deps.getPeerId(); - const claims = this.slots.open(handle.id); + const claims = this.slots.open(this.originOf(handle.id)); if (msg.method === "state_sync") { - const { value, refused } = admitSnapshot( + const { value, refused, awaitingAuthority } = admitSnapshot( normaliseWireState(msg.state), sender, ownId, claims, ); + for (const agent of awaitingAuthority) { + this.deferred.holdAgent(handle.id, agent); + } this.reportRefused(handle.id, refused); this.deps.deliveryEngine.applyStateSync(value); } else if (msg.method === "state_update") { if (!admitPatch(msg.patch, sender, ownId, claims)) { - // A departure announced by a successor can arrive before the claim that makes it the holder does, over another session of the same pair: it waits for that claim instead of being lost. - if (msg.patch.type === "agent_offline") { - this.deferDeparture(handle.id, msg.patch.agentId); + // What the coordinator sends can be read before the claim that names it is accepted, over another queue of the same session: what is refused only for want of that authority waits for the claim instead of being lost. + if (isAwaitingAuthority(msg.patch, sender)) { + if (msg.patch.type === "agent_upsert") { + this.deferred.holdAgent(handle.id, msg.patch.agent); + } else if (msg.patch.type === "agent_offline") { + this.deferred.holdDeparture(handle.id, msg.patch.agentId); + } } this.reportRefused(handle.id, 1); return; @@ -310,24 +321,36 @@ export class PeerLifecycle { } } - private deferDeparture(senderId: string, agentId: string): void { - let total = 0; - for (const waiting of this.deferredDepartures.values()) - total += waiting.size; - if (total >= MAX_DEFERRED_DEPARTURES) return; - const waiting = this.deferredDepartures.get(senderId) ?? new Set(); - waiting.add(agentId); - this.deferredDepartures.set(senderId, waiting); + /** Where a peer's agents are counted from: the host it was reached at, this machine for a peer reached on it, and the peer itself when this side has no entry for it. A host that presents many device keys is one origin. */ + private originOf(peerId: string): string { + const info = this.deps.peerInfo.get(peerId); + if (info === undefined) return `peer:${peerId}`; + return info.host === undefined ? "machine" : `host:${info.host}`; } - /** Applies the departures that `holderId` announced before it was accepted as the holder, now that it is. Detached: it runs from the election's acceptance of a claim. */ + /** Applies what `holderId` gave before it was accepted as the holder, now that it is. Detached: it runs from the election's acceptance of a claim. */ handleHolderAccepted(holderId: string): void { - const waiting = this.deferredDepartures.get(holderId); - if (waiting === undefined) return; - this.deferredDepartures.delete(holderId); + const released = this.deferred.release(holderId); + if (released.agents.length === 0 && released.departures.length === 0) { + return; + } + const sender: StateSender = { id: holderId, isCoordinator: true }; + const records = admitSnapshot( + { + agents: Object.fromEntries(released.agents.map((a) => [a.id, a])), + rooms: {}, + messages: {}, + dms: {}, + deliveryQueues: {}, + }, + sender, + this.deps.getPeerId(), + this.slots.open(this.originOf(holderId)), + ); + this.deps.deliveryEngine.applyStateSync(records.value); this.detach( Promise.all( - [...waiting].map(async (agentId) => + released.departures.map(async (agentId) => this.deps.deliveryEngine.applyPatch({ type: "agent_offline", agentId, @@ -339,8 +362,8 @@ export class PeerLifecycle { /** Forgets what is kept for a connection that ended. */ private forgetSource(peerId: string): void { - this.slots.release(peerId); - this.deferredDepartures.delete(peerId); + this.slots.release(this.originOf(peerId)); + this.deferred.drop(peerId); this.reportedPeers.delete(peerId); } @@ -393,8 +416,8 @@ export class PeerLifecycle { /** The awaitable form of handlePeerDisconnected, which TransportEvents forces to be synchronous. A departing peer leaves the peer list. When it held the elected coordinator role, the role is recovered first (the lowest surviving device-id claims at a raised term), so the new holder is already in place by the time the departed peer's agent record is retired; when it held the well-known port this side dialled, the vacated port is contested too. */ async handlePeerDeparture(peerId: string): Promise { - this.deps.peerInfo.delete(peerId); this.forgetSource(peerId); + this.deps.peerInfo.delete(peerId); await this.deps.coordinatorRole.handleDeparture(peerId, async () => this.retireDepartedAgent(peerId), ); diff --git a/src/core/stale-agent-checker.ts b/src/core/stale-agent-checker.ts index 9853d798..89280a73 100644 --- a/src/core/stale-agent-checker.ts +++ b/src/core/stale-agent-checker.ts @@ -10,7 +10,6 @@ import type { MeshStatePatch, PeerInfo } from "./wire-protocol.js"; export interface StaleAgentCheckerDeps { agents: Map; deliveryQueues: Map; - identityCache: Map; peerInfo: Map; notifyRoomsOfStatus: (agentId: string, status: AgentStatus) => Promise; broadcastPatch: (patch: MeshStatePatch) => Promise; @@ -87,11 +86,10 @@ export class StaleAgentChecker { for (const id of purgeIds) this.forget(id); } - /** Forgets everything the store holds for an agent: its record, its peer entry, its cached identity and its queued deliveries. */ + /** Forgets everything the store holds for an agent: its record, its peer entry and its queued deliveries. */ forget(agentId: string): void { this.deps.agents.delete(agentId); this.deps.peerInfo.delete(agentId); - this.deps.identityCache.delete(agentId); this.deps.deliveryQueues.delete(agentId); } diff --git a/src/core/state-intake.ts b/src/core/state-intake.ts index 3c996013..7013aeaf 100644 --- a/src/core/state-intake.ts +++ b/src/core/state-intake.ts @@ -3,7 +3,7 @@ */ import { parseDisplayName } from "./display-name.js"; -import { parseIsoTimestampMs } from "./iso-timestamp.js"; +import type { KnownAgents } from "./known-agents.js"; import type { AgentIdentity } from "./types.js"; import type { MeshStatePatch, SerialisedState } from "./wire-protocol.js"; @@ -15,8 +15,8 @@ export const MAX_SNAPSHOT_ENTRIES = 4096; /** The most agents a store keeps. Past it, a new agent takes the place of an offline record, and is refused only when no record is offline; one already known is still updated. At least the largest snapshot, so a full snapshot of a full mesh fits. */ export const MAX_KNOWN_AGENTS = 4096; -/** The most agents one connection may introduce over its life. A conforming peer introduces its own agent, or as coordinator relays the mesh, so far fewer. */ -export const MAX_NEW_AGENTS_PER_SOURCE = 256; +/** The most agents one origin may have introduced that a store still holds: the host a peer was reached at, or this machine for a peer reached on it, so a host that presents many device keys is still one origin. At this number an origin's new agent takes the place of that origin's own offline record, and is refused only when it has none. */ +export const MAX_AGENTS_PER_ORIGIN = 512; /** Who sent state, and whether this side takes that peer to be the coordinator. */ export interface StateSender { @@ -30,13 +30,18 @@ export interface Admitted { readonly refused: number; } +/** What the intake did with a snapshot, and which refused agent records were refused only for want of the sender's authority, which a later claim can give it. */ +export interface AdmittedSnapshot extends Admitted { + readonly awaitingAuthority: readonly AgentIdentity[]; +} + /** Whether `sender` may speak for the agent `agentId`: it is that agent's own store, or the coordinator. */ function mayDescribeAgent(sender: StateSender, agentId: string): boolean { return sender.id === agentId || sender.isCoordinator; } /** Whether a record is one a conforming peer sends: it sits under its own id and its name is one a registration would have kept as it is. */ -function isWellFormedAgent( +export function isWellFormedAgent( key: string, agent: Readonly, ): boolean { @@ -48,23 +53,13 @@ function isWellFormedAgent( ); } -/** - * The order records are evicted in: a start time that does not parse, or lies in the future, first (no conforming record has one), then the oldest start. No time of going offline is recorded, so the start time stands in for it. - */ -function evictionRank(agent: Readonly, now: number): number { - const startedAt = parseIsoTimestampMs(agent.startedAt); - return startedAt === undefined || startedAt > now - ? Number.NEGATIVE_INFINITY - : startedAt; -} - /** What a claim needs of the store's agent slots. */ interface ClaimSlots { has: (agentId: string) => boolean; size: number; - introducedBy: (sourceId: string) => number; - noteIntroduced: (sourceId: string) => void; - evictOne: (keep: ReadonlySet) => boolean; + heldFrom: (origin: string, keep: ReadonlySet) => number; + tag: (agentId: string, origin: string) => void; + evictOne: (keep: ReadonlySet, origin?: string) => boolean; } /** The claims on agent slots that the records of one message make. */ @@ -73,17 +68,20 @@ export class AgentClaims { constructor( private readonly slots: Readonly, - private readonly sourceId: string, + private readonly origin: string, ) {} has(agentId: string): boolean { return this.slots.has(agentId); } - /** Whether the store takes a record for `agentId`: it already holds one, or it can hold a new one. A new one counts against the connection that introduced it, and past the store's bound takes the place of an offline record. */ + /** Whether the store takes a record for `agentId`: it already holds one, or it can hold a new one. A new one counts against the origin that introduced it, and past the bound of the origin or of the store takes the place of an offline record. */ claim(agentId: string): boolean { if (this.slots.has(agentId) || this.claimed.has(agentId)) return true; - if (this.slots.introducedBy(this.sourceId) >= MAX_NEW_AGENTS_PER_SOURCE) { + if ( + this.slots.heldFrom(this.origin, this.claimed) >= MAX_AGENTS_PER_ORIGIN && + !this.slots.evictOne(this.claimed, this.origin) + ) { return false; } if ( @@ -93,38 +91,37 @@ export class AgentClaims { return false; } this.claimed.add(agentId); - this.slots.noteIntroduced(this.sourceId); + this.slots.tag(agentId, this.origin); return true; } } /** What an AgentSlots reads of, and does to, the store. */ export interface AgentSlotsStore { - readonly agents: ReadonlyMap; + readonly agents: KnownAgents; /** Forgets everything the store holds for an agent it evicts. */ forget: (agentId: string) => void; - /** Whether the store still has a peer entry for the agent: an offline record without one is evicted before one with one. */ - hasPeer: (agentId: string) => boolean; /** The id of the store's own agent, which is never evicted. */ ownId: () => string; - /** The current time, in milliseconds since the epoch. */ - now: () => number; } -/** The places a store can hold agents, and how many new ones each connection has introduced. */ +/** The places a store can hold agents, and which origin introduced each. */ export class AgentSlots implements ClaimSlots { - private readonly introduced = new Map(); + /** The agents each origin introduced and the store still holds, or has just claimed. */ + private readonly byOrigin = new Map>(); + + private readonly originOf = new Map(); constructor(private readonly store: AgentSlotsStore) {} - /** Starts the claims of one message from `sourceId`. */ - open(sourceId: string): AgentClaims { - return new AgentClaims(this, sourceId); + /** Starts the claims of one message from `origin`. */ + open(origin: string): AgentClaims { + return new AgentClaims(this, origin); } - /** Forgets what a connection introduced, once it has ended. */ - release(sourceId: string): void { - this.introduced.delete(sourceId); + /** Forgets what an origin introduced, once nothing of it is held. */ + release(origin: string): void { + this.heldFrom(origin, new Set()); } has(agentId: string): boolean { @@ -135,42 +132,39 @@ export class AgentSlots implements ClaimSlots { return this.store.agents.size; } - introducedBy(sourceId: string): number { - return this.introduced.get(sourceId) ?? 0; + /** How many agents `origin` introduced that the store still holds, besides those in `keep`, which a message has claimed and not yet stored. */ + heldFrom(origin: string, keep: ReadonlySet): number { + const ids = this.byOrigin.get(origin); + if (ids === undefined) return 0; + for (const id of ids) { + if (!this.store.agents.has(id) && !keep.has(id)) { + ids.delete(id); + this.originOf.delete(id); + } + } + if (ids.size === 0) this.byOrigin.delete(origin); + return ids.size; } - noteIntroduced(sourceId: string): void { - this.introduced.set(sourceId, this.introducedBy(sourceId) + 1); + tag(agentId: string, origin: string): void { + this.originOf.set(agentId, origin); + const ids = this.byOrigin.get(origin) ?? new Set(); + ids.add(agentId); + this.byOrigin.set(origin, ids); } - /** Evicts the record that is least worth keeping and returns whether there was one. Only an offline record is evictable, and never one in `keep` or the store's own. */ - evictOne(keep: ReadonlySet): boolean { - const now = this.store.now(); - let victim: { id: string; unconnected: boolean; rank: number } | undefined; - for (const [id, agent] of this.store.agents) { - if ( - agent.status !== "offline" || - keep.has(id) || - id === this.store.ownId() - ) { - continue; - } - const candidate = { - id, - unconnected: !this.store.hasPeer(id), - rank: evictionRank(agent, now), - }; - if ( - victim === undefined || - (candidate.unconnected && !victim.unconnected) || - (candidate.unconnected === victim.unconnected && - candidate.rank < victim.rank) - ) { - victim = candidate; - } + /** Evicts the record that has been offline longest and returns whether there was one, among those `origin` introduced when it is given. Only an offline record is evictable, and never one in `keep` or the store's own. */ + evictOne(keep: ReadonlySet, origin?: string): boolean { + const ownId = this.store.ownId(); + let victim: string | undefined; + for (const id of this.store.agents.offlineOldestFirst()) { + if (keep.has(id) || id === ownId) continue; + if (origin !== undefined && this.originOf.get(id) !== origin) continue; + victim = id; + break; } if (victim === undefined) return false; - this.store.forget(victim.id); + this.store.forget(victim); return true; } } @@ -195,18 +189,18 @@ export function admitSnapshot( sender: Readonly, ownId: string, claims: AgentClaims, -): Admitted { +): AdmittedSnapshot { let refused = 0; const agents: Record = {}; + const awaitingAuthority: AgentIdentity[] = []; for (const [key, agent] of Object.entries(state.agents)) { const contradictable = key === ownId && agent.status === "offline" && claims.has(key); - if ( - !isWellFormedAgent(key, agent) || - !(mayDescribeAgent(sender, key) || contradictable) || - !claims.claim(key) - ) { + const wellFormed = isWellFormedAgent(key, agent); + const authorised = mayDescribeAgent(sender, key) || contradictable; + if (!wellFormed || !authorised || !claims.claim(key)) { refused += 1; + if (wellFormed && !authorised) awaitingAuthority.push(agent); continue; } agents[key] = agent; @@ -231,6 +225,7 @@ export function admitSnapshot( deliveryQueues: queues.kept, }, refused, + awaitingAuthority, }; } @@ -256,3 +251,19 @@ export function admitPatch( } return true; } + +/** Whether a patch was refused only because its sender is not known to be the coordinator, which a later claim can make it. */ +export function isAwaitingAuthority( + patch: Readonly, + sender: Readonly, +): boolean { + if (patch.type === "agent_upsert") { + return ( + isWellFormedAgent(patch.agent.id, patch.agent) && + !mayDescribeAgent(sender, patch.agent.id) + ); + } + return ( + patch.type === "agent_offline" && !mayDescribeAgent(sender, patch.agentId) + ); +} diff --git a/src/test/coordinator-failover.unit.test.ts b/src/test/coordinator-failover.unit.test.ts index 583572fa..a39e0433 100644 --- a/src/test/coordinator-failover.unit.test.ts +++ b/src/test/coordinator-failover.unit.test.ts @@ -2,6 +2,7 @@ * PeerLifecycle's failover decisions, exercised against fakes with a real CoordinatorRole: which disconnects contest the vacated well-known port (agent-comms#285), what a peer that loses the bind race does instead, how the elected coordinator role is recovered when its holder departs (agent-comms#341), and who retires a departed peer's own agent record. The real-socket counterparts live in coordinator-failover.integration.test.ts and coordinator-election.integration.test.ts. */ +import { KnownAgents } from "../core/known-agents.js"; import { afterEach, test, expect, vi } from "vitest"; import { deviceIdFromHex } from "wire-mesh-core/domain/device-id"; import type { CoordinatorFrame } from "wire-mesh-core/generated/protocol"; @@ -101,7 +102,7 @@ function makeHarness(options: Readonly = {}): Harness { claims: [], }; const peerInfo = new Map(); - const agents = new Map(); + const agents = new KnownAgents(); const roomStatusNotifications: Harness["roomStatusNotifications"] = []; const errors: Error[] = []; const notEnrolled = new Set(options.notEnrolled); diff --git a/src/test/delivery-engine-own-agent.unit.test.ts b/src/test/delivery-engine-own-agent.unit.test.ts index 598125b2..ffcae5f1 100644 --- a/src/test/delivery-engine-own-agent.unit.test.ts +++ b/src/test/delivery-engine-own-agent.unit.test.ts @@ -133,19 +133,33 @@ describe("DeliveryEngine — applyStateSync own agent", () => { }); }); - it("accepts a snapshot's offline copy of this store's own agent once it has itself set it offline", () => { + it("ignores a snapshot's copy of this store's own agent once it has itself set it offline, rather than taking the copy whole", () => { const h = makeHarness(); - h.deps.agents.set(PEER_ID, agent({ status: "offline" })); + h.deps.agents.set( + PEER_ID, + agent({ status: "offline", name: "own", tags: ["own"] }), + ); h.engine.applyStateSync( - snapshotWith(agent({ status: "offline", version: SNAPSHOT_REVISION })), + snapshotWith( + agent({ + status: "offline", + version: SNAPSHOT_REVISION, + name: "theirs", + tags: ["theirs"], + }), + ), ); - expect(h.deps.agents.get(PEER_ID)?.version).toBe(SNAPSHOT_REVISION); + const own = h.deps.agents.get(PEER_ID); + expect(own?.version).toBe(LOCAL_REVISION); + expect(own?.name).toBe("own"); + expect(own?.tags).toEqual(["own"]); + expect(own?.status).toBe("offline"); expect(h.transport.broadcast).not.toHaveBeenCalled(); }); - it("applies a snapshot's copy of this store's own agent as usual when it is not offline", () => { + it("does not apply a snapshot's copy of this store's own agent, as it is the authority on it, and takes the copy of an agent it holds none of", () => { const h = makeHarness(); h.deps.agents.set(PEER_ID, agent({ name: "before" })); @@ -155,8 +169,12 @@ describe("DeliveryEngine — applyStateSync own agent", () => { ), ); - expect(h.deps.agents.get(PEER_ID)?.name).toBe("after"); + expect(h.deps.agents.get(PEER_ID)?.name).toBe("before"); expect(h.transport.broadcast).not.toHaveBeenCalled(); + + const fresh = makeHarness(); + fresh.engine.applyStateSync(snapshotWith(agent({ name: "restored" }))); + expect(fresh.deps.agents.get(PEER_ID)?.name).toBe("restored"); }); it("leaves a snapshot's offline copy of another agent alone", () => { diff --git a/src/test/peer-lifecycle-claim-order.unit.test.ts b/src/test/peer-lifecycle-claim-order.unit.test.ts new file mode 100644 index 00000000..d0648884 --- /dev/null +++ b/src/test/peer-lifecycle-claim-order.unit.test.ts @@ -0,0 +1,132 @@ +/** + * The state of a coordinator read before the claim that names it is accepted, with a real CoordinatorRole: the snapshot and the claim arrive on different queues of one session, so either can be read first, and a joiner must end with the coordinator's records whichever it is. + */ + +import { expect, test, vi } from "vitest"; +import { deviceIdFromHex } from "wire-mesh-core/domain/device-id"; +import { CoordinatorRole } from "../core/coordinator-role.js"; +import { KnownAgents } from "../core/known-agents.js"; +import { + PeerLifecycle, + type PeerLifecycleDeps, +} from "../core/peer-lifecycle.js"; +import type { AgentIdentity } from "../core/types.js"; +import type { SerialisedState } from "../core/wire-protocol.js"; + +const DEVICE_ID_HEX_LENGTH = 64; +const SELF = "1".repeat(DEVICE_ID_HEX_LENGTH); +const HOLDER = "2".repeat(DEVICE_ID_HEX_LENGTH); +const RELAYED = "3".repeat(DEVICE_ID_HEX_LENGTH); + +function relayed(): AgentIdentity { + return { + id: RELAYED, + version: 1, + name: "relayed", + harness: "pi", + cwd: "/tmp", + pid: 1, + startedAt: "2026-01-01T00:00:00.000Z", + visibility: "visible", + status: "offline", + tags: [], + subscribedRooms: [], + }; +} + +function snapshot(): SerialisedState { + return { + agents: { [RELAYED]: relayed() }, + rooms: {}, + messages: {}, + dms: {}, + deliveryQueues: {}, + }; +} + +function joiner(): { + lifecycle: PeerLifecycle; + role: CoordinatorRole; + applyStateSync: ReturnType< + typeof vi.fn + >; +} { + const role = new CoordinatorRole({ + getPeerId: () => SELF, + claimWaitMs: 1000, + requireTransport: () => ({ + broadcastCoordinatorClaim: async () => Promise.resolve(), + sendCoordinatorClaim: async () => Promise.resolve(), + electionPeerIds: () => new Set([HOLDER]), + }), + onGained: async () => Promise.resolve(), + onLost: async () => Promise.resolve(), + onError: (error) => { + throw error; + }, + }); + const applyStateSync = + vi.fn(); + const agents = new KnownAgents(); + const deps: PeerLifecycleDeps = { + peerInfo: new Map(), + agents, + coordinatorPort: 1, + getPeerId: () => SELF, + getCoordinatorPeerId: () => undefined, + staleAgentChecker: { + forget: () => {}, + }, + requireTransport: () => ({}) as never, + serialise: () => snapshot(), + roomProtocol: { flushPendingRoomRequests: async () => Promise.resolve() }, + deliveryEngine: { + applyStateSync, + applyPatch: async () => Promise.resolve(), + notifyRoomsOfStatus: async () => Promise.resolve(), + broadcastPatch: async () => Promise.resolve(), + bump: (entity) => entity, + }, + coordinatorRole: role, + }; + return { lifecycle: new PeerLifecycle(deps), role, applyStateSync }; +} + +const claim = { + type: "coordinator", + term: 0, + coordinator: deviceIdFromHex(HOLDER), +} as const; + +test("a snapshot read before the claim that names its sender is accepted still gives the joiner the relayed records", async () => { + const { lifecycle, role, applyStateSync } = joiner(); + + await lifecycle.handleDataMessage( + { id: HOLDER }, + { method: "state_sync", state: snapshot() }, + ); + expect(applyStateSync).toHaveBeenLastCalledWith( + expect.objectContaining({ agents: {} }), + ); + + await role.handleClaim({ id: HOLDER }, claim); + + expect(applyStateSync).toHaveBeenLastCalledWith( + expect.objectContaining({ agents: { [RELAYED]: relayed() } }), + ); +}); + +test("a snapshot read after the claim is taken at once", async () => { + const { lifecycle, role, applyStateSync } = joiner(); + + await role.handleClaim({ id: HOLDER }, claim); + await lifecycle.handleDataMessage( + { id: HOLDER }, + { method: "state_sync", state: snapshot() }, + ); + + expect(applyStateSync).toHaveBeenCalledTimes(1); + expect(applyStateSync).toHaveBeenLastCalledWith( + expect.objectContaining({ agents: { [RELAYED]: relayed() } }), + ); +}); diff --git a/src/test/peer-lifecycle.unit.test.ts b/src/test/peer-lifecycle.unit.test.ts index aca4d378..cd9632f1 100644 --- a/src/test/peer-lifecycle.unit.test.ts +++ b/src/test/peer-lifecycle.unit.test.ts @@ -6,6 +6,9 @@ import { PeerLifecycle, type PeerLifecycleDeps, } from "../core/peer-lifecycle.js"; +import { KnownAgents } from "../core/known-agents.js"; +import { MAX_AGENTS_PER_ORIGIN } from "../core/state-intake.js"; +import { ROOM_REQUEST_TIMEOUT_MS } from "../core/request-timeouts.js"; import type { AgentIdentity, DeliveryEvent } from "../core/types.js"; import type { PeerInfo, SerialisedState } from "../core/wire-protocol.js"; @@ -28,6 +31,10 @@ function emptyState(): SerialisedState { } interface Harness { + /** The time the lifecycle reads, in milliseconds. */ + clock: { now: number }; + /** The peer this side dialled as its coordinator. */ + dialled: { coordinator: string | undefined }; deps: PeerLifecycleDeps; lifecycle: PeerLifecycle; transport: { @@ -75,13 +82,18 @@ function makeHarness(): Harness { holder: COORDINATOR_ID, })), }; - const agents = new Map(); + const agents = new KnownAgents(); + const clock = { now: 0 }; + const dialled: { coordinator: string | undefined } = { + coordinator: undefined, + }; const deps: PeerLifecycleDeps = { peerInfo: new Map(), agents, coordinatorPort: COORDINATOR_PORT, getPeerId: () => OWNER_ID, - getCoordinatorPeerId: () => undefined, + getCoordinatorPeerId: () => dialled.coordinator, + now: () => clock.now, staleAgentChecker: { forget: (agentId) => { agents.delete(agentId); @@ -104,6 +116,8 @@ function makeHarness(): Harness { }; return { deps, + clock, + dialled, lifecycle: new PeerLifecycle(deps), transport, flushPendingRoomRequests, @@ -450,57 +464,204 @@ describe("PeerLifecycle — handleDataMessage", () => { expect(h.applyStateSync).toHaveBeenLastCalledWith(emptyState()); }); - it("applies a departure its sender announced before its claim was accepted, once the claim is", async () => { + it("takes foreign agent records from the coordinator this side dialled, and from no other peer", async () => { const h = makeHarness(); + h.dialled.coordinator = "dialled"; + await h.lifecycle.handleDataMessage( + { id: "dialled" }, + { method: "state_sync", state: stateOf(named("peer-b")) }, + ); + expect(h.applyStateSync).toHaveBeenLastCalledWith(stateOf(named("peer-b"))); + + await h.lifecycle.handleDataMessage( + { id: "not-dialled" }, + { method: "state_sync", state: stateOf(named("peer-c")) }, + ); + expect(h.applyStateSync).toHaveBeenLastCalledWith(emptyState()); + }); + + it("counts the agents of peers reached at one host together, however many device keys they use, and those of peers at another host apart", async () => { + const h = makeHarness(); + const introduce = async (id: string, host: string): Promise => { + h.deps.peerInfo.set(id, { ...peerInfo(id), host }); + await h.lifecycle.handleDataMessage( + { id }, + { method: "state_sync", state: stateOf(named(id)) }, + ); + }; + for (let n = 0; n < MAX_AGENTS_PER_ORIGIN; n++) { + await introduce(`key-${String(n)}`, "10.0.0.9"); + h.deps.agents.set(`key-${String(n)}`, named(`key-${String(n)}`)); + } + + await introduce("one-key-too-many", "10.0.0.9"); + expect(h.applyStateSync).toHaveBeenLastCalledWith(emptyState()); + + await introduce("elsewhere", "10.0.0.10"); + expect(h.applyStateSync).toHaveBeenLastCalledWith( + stateOf(named("elsewhere")), + ); + }); + + describe("what a sender gives before its claim is accepted", () => { const departure = { method: "state_update", patch: { type: "agent_offline", agentId: "gone" }, } as const; - await h.lifecycle.handleDataMessage({ id: "successor" }, departure); - expect(h.applyPatch).not.toHaveBeenCalled(); + it("applies a departure once the claim is accepted, and once", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage({ id: "successor" }, departure); + expect(h.applyPatch).not.toHaveBeenCalled(); - h.lifecycle.handleHolderAccepted("someone-else"); - expect(h.applyPatch).not.toHaveBeenCalled(); + h.lifecycle.handleHolderAccepted("successor"); + await vi.waitFor(() => { + expect(h.applyPatch).toHaveBeenCalledWith(departure.patch); + }); - h.lifecycle.handleHolderAccepted("successor"); - await vi.waitFor(() => { - expect(h.applyPatch).toHaveBeenCalledWith(departure.patch); + h.lifecycle.handleHolderAccepted("successor"); + expect(h.applyPatch).toHaveBeenCalledTimes(1); }); - h.lifecycle.handleHolderAccepted("successor"); - expect(h.applyPatch).toHaveBeenCalledTimes(1); - }); + it("applies the foreign agent records of a snapshot once the claim is accepted, which the joiner would otherwise lose", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage( + { id: "successor" }, + { + method: "state_sync", + state: stateOf(named("peer-b"), named("peer-c")), + }, + ); + expect(h.applyStateSync).toHaveBeenLastCalledWith(emptyState()); - it("takes the announcement of a holder through the hook it gives the coordinator role", async () => { - const h = makeHarness(); - await h.lifecycle.handleDataMessage( - { id: "successor" }, - { - method: "state_update", - patch: { type: "agent_offline", agentId: "gone" }, - }, - ); + h.lifecycle.handleHolderAccepted("successor"); - h.coordinatorRole.onHolderAccepted?.("successor"); + expect(h.applyStateSync).toHaveBeenLastCalledWith( + stateOf(named("peer-b"), named("peer-c")), + ); + }); - await vi.waitFor(() => { - expect(h.applyPatch).toHaveBeenCalledTimes(1); + it("applies an agent update once the claim is accepted", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage( + { id: "successor" }, + { + method: "state_update", + patch: { type: "agent_upsert", agent: named("peer-b") }, + }, + ); + expect(h.applyPatch).not.toHaveBeenCalled(); + + h.lifecycle.handleHolderAccepted("successor"); + + expect(h.applyStateSync).toHaveBeenLastCalledWith( + stateOf(named("peer-b")), + ); }); - }); - it("forgets a departure still waiting when its sender leaves", async () => { - const h = makeHarness(); - await h.lifecycle.handleDataMessage( - { id: "successor" }, - { - method: "state_update", - patch: { type: "agent_offline", agentId: "gone" }, - }, - ); - await h.lifecycle.handlePeerDeparture("successor"); - h.lifecycle.handleHolderAccepted("successor"); - expect(h.applyPatch).not.toHaveBeenCalled(); + it("holds no record that is malformed, since no claim makes it acceptable", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage( + { id: "successor" }, + { + method: "state_sync", + state: stateOf(named("peer-b", "bad\u001b[2J")), + }, + ); + + h.lifecycle.handleHolderAccepted("successor"); + + expect(h.applyStateSync).toHaveBeenCalledTimes(1); + }); + + it("drops what it holds when a claim naming another peer is accepted first", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage({ id: "successor" }, departure); + await h.lifecycle.handleDataMessage( + { id: "successor" }, + { method: "state_sync", state: stateOf(named("peer-b")) }, + ); + + h.lifecycle.handleHolderAccepted("someone-else"); + h.lifecycle.handleHolderAccepted("successor"); + + expect(h.applyPatch).not.toHaveBeenCalled(); + expect(h.applyStateSync).toHaveBeenCalledTimes(1); + }); + + it("does not apply a departure about an agent whose record changed since it was held", async () => { + const h = makeHarness(); + h.deps.agents.set("gone", { ...named("gone"), version: 1 }); + await h.lifecycle.handleDataMessage({ id: "successor" }, departure); + h.deps.agents.set("gone", { ...named("gone"), version: 2 }); + + h.lifecycle.handleHolderAccepted("successor"); + + expect(h.applyPatch).not.toHaveBeenCalled(); + }); + + it("does not apply what it held for longer than one claim wait", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage({ id: "successor" }, departure); + await h.lifecycle.handleDataMessage( + { id: "successor" }, + { method: "state_sync", state: stateOf(named("peer-b")) }, + ); + h.clock.now += ROOM_REQUEST_TIMEOUT_MS + 1; + + h.lifecycle.handleHolderAccepted("successor"); + + expect(h.applyPatch).not.toHaveBeenCalled(); + expect(h.applyStateSync).toHaveBeenCalledTimes(1); + }); + + it("holds afresh what arrives after an earlier hold expired, and applies it", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage({ id: "successor" }, departure); + h.clock.now += ROOM_REQUEST_TIMEOUT_MS + 1; + await h.lifecycle.handleDataMessage( + { id: "successor" }, + { method: "state_sync", state: stateOf(named("peer-b")) }, + ); + + h.lifecycle.handleHolderAccepted("successor"); + + expect(h.applyPatch).not.toHaveBeenCalled(); + expect(h.applyStateSync).toHaveBeenLastCalledWith( + stateOf(named("peer-b")), + ); + }); + + it("applies what it held within one claim wait", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage({ id: "successor" }, departure); + h.clock.now += ROOM_REQUEST_TIMEOUT_MS; + + h.lifecycle.handleHolderAccepted("successor"); + + await vi.waitFor(() => { + expect(h.applyPatch).toHaveBeenCalledTimes(1); + }); + }); + + it("takes the announcement of a holder through the hook it gives the coordinator role", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage({ id: "successor" }, departure); + + h.coordinatorRole.onHolderAccepted?.("successor"); + + await vi.waitFor(() => { + expect(h.applyPatch).toHaveBeenCalledTimes(1); + }); + }); + + it("forgets what it holds when the sender leaves", async () => { + const h = makeHarness(); + await h.lifecycle.handleDataMessage({ id: "successor" }, departure); + await h.lifecycle.handlePeerDeparture("successor"); + h.lifecycle.handleHolderAccepted("successor"); + expect(h.applyPatch).not.toHaveBeenCalled(); + }); }); it("applies neither for a message method it doesn't dispatch on", async () => { diff --git a/src/test/stale-agent-checker.unit.test.ts b/src/test/stale-agent-checker.unit.test.ts index 65a09e0b..2b91d3aa 100644 --- a/src/test/stale-agent-checker.unit.test.ts +++ b/src/test/stale-agent-checker.unit.test.ts @@ -63,11 +63,9 @@ interface Harness { function harness(agents: readonly AgentIdentity[]): Harness { const agentsMap = new Map(agents.map((a) => [a.id, a])); const deliveryQueues = new Map(); - const identityCache = new Map(); const peerInfo = new Map(); for (const a of agents) { deliveryQueues.set(a.id, []); - identityCache.set(a.id, { id: a.id }); peerInfo.set(a.id, { id: a.id, port: 1, startedAt: a.startedAt }); } const notifyRoomsOfStatus = vi.fn(async (): Promise => @@ -77,7 +75,6 @@ function harness(agents: readonly AgentIdentity[]): Harness { const deps: StaleAgentCheckerDeps = { agents: agentsMap, deliveryQueues: deliveryQueues, - identityCache, peerInfo, notifyRoomsOfStatus, broadcastPatch: broadcastPatch, @@ -257,11 +254,9 @@ describe("StaleAgentChecker", () => { expect(deps.agents.has("a1")).toBe(false); expect(deps.peerInfo.has("a1")).toBe(false); - expect(deps.identityCache.has("a1")).toBe(false); expect(deps.deliveryQueues.has("a1")).toBe(false); expect(deps.agents.size).toBe(0); expect(deps.peerInfo.size).toBe(0); - expect(deps.identityCache.size).toBe(0); expect(deps.deliveryQueues.size).toBe(0); }); diff --git a/src/test/state-intake.unit.test.ts b/src/test/state-intake.unit.test.ts index 9f846256..87a8b03a 100644 --- a/src/test/state-intake.unit.test.ts +++ b/src/test/state-intake.unit.test.ts @@ -5,12 +5,13 @@ import { describe, expect, it } from "vitest"; import { AgentSlots, + MAX_AGENTS_PER_ORIGIN, MAX_KNOWN_AGENTS, - MAX_NEW_AGENTS_PER_SOURCE, MAX_SNAPSHOT_ENTRIES, admitPatch, admitSnapshot, } from "../core/state-intake.js"; +import { KnownAgents } from "../core/known-agents.js"; import type { AgentIdentity, Room } from "../core/types.js"; import type { SerialisedState } from "../core/wire-protocol.js"; @@ -18,9 +19,9 @@ const DEVICE_ID_HEX_LENGTH = 64; const SENDER = "a".repeat(DEVICE_ID_HEX_LENGTH); const OTHER = "b".repeat(DEVICE_ID_HEX_LENGTH); const SELF = "d".repeat(DEVICE_ID_HEX_LENGTH); -const NOW = Date.parse("2026-06-01T00:00:00.000Z"); const OVER_CAP = 3; -const EVICTABLE = 5; +const EVICTABLE = 3; +const EVICTION_ORDER = 3; const OVERSIZE_COLLECTIONS = 4; const COLLECTIONS_OVER_CAP = OVERSIZE_COLLECTIONS * OVER_CAP; @@ -75,18 +76,18 @@ function state(agents: readonly AgentIdentity[]): SerialisedState { const peer = { id: SENDER, isCoordinator: false }; const coordinator = { id: SENDER, isCoordinator: true }; -/** A store holding `held`, with the claims one message from `sourceId` makes on it; `forgotten` lists what was evicted. */ +/** A store holding `held`, which went offline in the order given, with the claims one message from `origin` makes on it; `forgotten` lists what was evicted. */ function storeHolding( held: readonly AgentIdentity[], - options: { sourceId?: string; connected?: readonly string[] } = {}, + origin = "host:a", ): { - agents: Map; + agents: KnownAgents; slots: AgentSlots; forgotten: string[]; claims: ReturnType; } { - const { sourceId = SENDER, connected = [] } = options; - const agents = new Map(held.map((a) => [a.id, a])); + const agents = new KnownAgents(); + for (const a of held) agents.set(a.id, a); const forgotten: string[] = []; const slots = new AgentSlots({ agents, @@ -94,14 +95,26 @@ function storeHolding( forgotten.push(id); agents.delete(id); }, - hasPeer: (id) => connected.includes(id), ownId: () => SELF, - now: () => NOW, }); - return { agents, slots, forgotten, claims: slots.open(sourceId) }; + return { agents, slots, forgotten, claims: slots.open(origin) }; } -function offline(id: string, startedAt: string): AgentIdentity { +/** Claims a record for `id` and, as the store does once a claim is admitted, holds it. */ +function take( + held: ReturnType, + id: string, + status: AgentIdentity["status"] = "active", +): boolean { + const taken = held.claims.claim(id); + if (taken) held.agents.set(id, agent(id, { status })); + return taken; +} + +function offline( + id: string, + startedAt = "2026-01-01T00:00:00.000Z", +): AgentIdentity { return agent(id, { status: "offline", startedAt }); } @@ -227,7 +240,7 @@ describe("a snapshot", () => { describe("a store that holds the most agents it keeps", () => { it("evicts an offline record to take a new agent, and still updates one it knows", () => { - const held = fullStore([offline("old", "2020-01-01T00:00:00.000Z")]); + const held = fullStore([offline("old")]); const { claims, forgotten, agents } = storeHolding(held); const { value, refused } = admitSnapshot( @@ -260,61 +273,117 @@ describe("a store that holds the most agents it keeps", () => { expect(forgotten).toEqual([]); }); - it("evicts a record with no peer before one with a peer, a start that is in the future or unreadable before an old one, then the oldest", () => { - const held = fullStore([ - offline("connected-oldest", "2000-01-01T00:00:00.000Z"), - offline("unconnected-recent", "2026-05-01T00:00:00.000Z"), - offline("unconnected-oldest", "2001-01-01T00:00:00.000Z"), - offline("unconnected-future", "2099-01-01T00:00:00.000Z"), - offline("unconnected-unreadable", "not a time"), - ]); - const { slots, forgotten } = storeHolding(held, { - connected: ["connected-oldest"], - }); - const claims = slots.open(SENDER); + it("evicts the record that went offline longest ago, whatever its start time: a long-running agent that just went offline outlasts a short one that went offline long ago", () => { + const held = storeHolding( + fullStore([ + offline("went-offline-first", "2026-05-01T00:00:00.000Z"), + offline("went-offline-second", "2001-01-01T00:00:00.000Z"), + offline("went-offline-third", "2099-01-01T00:00:00.000Z"), + ]), + ); - for (let n = 0; n < EVICTABLE; n++) { - claims.claim(`new-${String(n)}`); - } + for (let n = 0; n < EVICTABLE; n++) take(held, `new-${String(n)}`); - expect(forgotten.slice(0, 2).sort()).toEqual([ - "unconnected-future", - "unconnected-unreadable", - ]); - expect(forgotten.slice(2)).toEqual([ - "unconnected-oldest", - "unconnected-recent", - "connected-oldest", + expect(held.forgotten.slice(0, EVICTION_ORDER)).toEqual([ + "went-offline-first", + "went-offline-second", + "went-offline-third", ]); }); + it("counts the time a record went offline from the status change, and again from the next one after it came back", () => { + const held = storeHolding( + fullStore([offline("flapping"), offline("steady")]), + ); + held.agents.set("flapping", agent("flapping")); + held.agents.set("flapping", offline("flapping")); + + take(held, "new-1"); + + expect(held.forgotten).toEqual(["steady"]); + }); + + it("keeps the time a record went offline while it is set offline again", () => { + const held = storeHolding(fullStore([offline("first"), offline("second")])); + held.agents.set("first", offline("first")); + + take(held, "new-1"); + + expect(held.forgotten).toEqual(["first"]); + }); + it("never evicts the store's own agent, or a record the same message just claimed", () => { - const held = fullStore([offline(SELF, "2000-01-01T00:00:00.000Z")]); + const held = fullStore([offline(SELF)]); const { claims, forgotten } = storeHolding(held); expect(claims.claim("new-1")).toBe(false); expect(forgotten).toEqual([]); - const room = storeHolding([ - ...fullStore().slice(1), - offline("old", "2000-01-01T00:00:00.000Z"), - ]); + const room = storeHolding([...fullStore().slice(1), offline("old")]); expect(room.claims.claim("first")).toBe(true); expect(room.claims.claim("second")).toBe(false); }); + + it("finds the record to evict without looking at every record held", () => { + const held = storeHolding(fullStore([offline("old")])); + const reads: string[] = []; + const real = held.agents.offlineOldestFirst.bind(held.agents); + held.agents.offlineOldestFirst = () => { + const keys = real(); + return { + [Symbol.iterator]() { + return this; + }, + next() { + const step = keys.next(); + if (step.done !== true) reads.push(step.value); + return step; + }, + }; + }; + + expect(take(held, "new-1")).toBe(true); + expect(reads).toEqual(["old"]); + }); }); -describe("what one connection introduces", () => { - it("is bounded over its life, and starts again when the connection has ended", () => { - const { slots } = storeHolding([]); - for (let n = 0; n < MAX_NEW_AGENTS_PER_SOURCE; n++) { - expect(slots.open(SENDER).claim(`a-${String(n)}`)).toBe(true); +describe("what one origin introduces", () => { + it("is bounded by the agents of it that the store holds, whatever keys they use, and another origin is not affected", () => { + const held = storeHolding([]); + for (let n = 0; n < MAX_AGENTS_PER_ORIGIN; n++) { + expect(take(held, `a-${String(n)}`)).toBe(true); } - expect(slots.open(SENDER).claim("one-too-many")).toBe(false); - expect(slots.open(OTHER).claim("another-source")).toBe(true); + expect(take(held, "one-too-many")).toBe(false); + + held.claims = held.slots.open("host:b"); + expect(take(held, "another-origin")).toBe(true); + }); + + it("takes the place of the origin's own offline record at its bound, and never another origin's", () => { + const held = storeHolding([]); + held.claims = held.slots.open("host:b"); + take(held, "b-offline", "offline"); + held.claims = held.slots.open("host:a"); + take(held, "a-offline", "offline"); + for (let n = 1; n < MAX_AGENTS_PER_ORIGIN; n++) { + take(held, `a-${String(n)}`); + } + + held.claims = held.slots.open("host:a"); + expect(take(held, "a-new")).toBe(true); + + expect(held.forgotten).toEqual(["a-offline"]); + expect(held.agents.has("b-offline")).toBe(true); + }); + + it("stops counting an agent the store no longer holds", () => { + const held = storeHolding([]); + for (let n = 0; n < MAX_AGENTS_PER_ORIGIN; n++) + take(held, `a-${String(n)}`); + held.agents.delete("a-0"); - slots.release(SENDER); - expect(slots.open(SENDER).claim("again")).toBe(true); + held.claims = held.slots.open("host:a"); + expect(take(held, "a-new")).toBe(true); }); }); @@ -323,17 +392,17 @@ describe("a patch", () => { it("takes an agent update from the agent's own store and from the coordinator, and from no one else", () => { const update = { type: "agent_upsert", agent: agent(OTHER) } as const; - const take = ( + const taken = ( sender: Readonly<{ id: string; isCoordinator: boolean }>, ): boolean => admitPatch(update, sender, SELF, storeHolding([]).claims); - expect(take({ id: OTHER, isCoordinator: false })).toBe(true); - expect(take(coordinator)).toBe(true); - expect(take(peer)).toBe(false); + expect(taken({ id: OTHER, isCoordinator: false })).toBe(true); + expect(taken(coordinator)).toBe(true); + expect(taken(peer)).toBe(false); }); it("takes an offline report under the same rule, and one about the receiver's own agent from anyone", () => { - const take = ( + const taken = ( agentId: string, sender: Readonly<{ id: string; isCoordinator: boolean }>, ): boolean => @@ -344,10 +413,10 @@ describe("a patch", () => { storeHolding([]).claims, ); - expect(take(OTHER, peer)).toBe(false); - expect(take(OTHER, coordinator)).toBe(true); - expect(take(OTHER, { id: OTHER, isCoordinator: false })).toBe(true); - expect(take(SELF, peer)).toBe(true); + expect(taken(OTHER, peer)).toBe(false); + expect(taken(OTHER, coordinator)).toBe(true); + expect(taken(OTHER, { id: OTHER, isCoordinator: false })).toBe(true); + expect(taken(SELF, peer)).toBe(true); }); it("refuses an update about the receiver's own agent from anyone but the coordinator", () => { From fc4d205a2af6d1342da30dbb3c028031c7ab7679 Mon Sep 17 00:00:00 2001 From: Joseph Mearman Date: Sun, 15 Nov 2026 16:39:31 +0000 Subject: [PATCH 2/2] fix(core): keep the offline order true to presence, and count new agents per connection A record whose status is changed by gossiped presence is stored again, so the order in which records went offline follows the real status: an agent brought back is no longer the first to be evicted, and one taken offline becomes evictable. Eviction also checks the record's status before taking it. The bound on new agents is per connection, taken from the sender and not from the host a peer entry names, which any trusted peer can rewrite. What a connection introduced is forgotten when the store removes or evicts the record, and not only when the connection is checked again. --- src/core/delivery-engine.ts | 2 + src/core/known-agents.ts | 19 +++++- src/core/peer-lifecycle.ts | 13 +--- src/core/state-intake.ts | 77 +++++++++++++----------- src/test/delivery-engine.unit.test.ts | 30 +++++++++- src/test/peer-lifecycle.unit.test.ts | 35 ++++++----- src/test/state-intake.unit.test.ts | 85 ++++++++++++++++++++++----- 7 files changed, 185 insertions(+), 76 deletions(-) diff --git a/src/core/delivery-engine.ts b/src/core/delivery-engine.ts index b06082fe..3b71d153 100644 --- a/src/core/delivery-engine.ts +++ b/src/core/delivery-engine.ts @@ -73,6 +73,8 @@ export class DeliveryEngine { if (agent === undefined || agent.status === status) return; agent.status = status; this.bump(agent); + // Stored again, since the agents map follows a record's status only through its own mutations. + this.deps.agents.set(agentId, agent); void this.notifyRoomsOfStatus(agentId, status); } diff --git a/src/core/known-agents.ts b/src/core/known-agents.ts index 7255b764..c60100a5 100644 --- a/src/core/known-agents.ts +++ b/src/core/known-agents.ts @@ -1,5 +1,5 @@ /** - * The agents a store knows of, with the order in which their records went offline, so that a store at its bound can give up the record that has been offline longest. The order is the one in which this store first saw each record offline, kept while it stays offline and dropped when it comes back or is removed; it is local to the store and never sent. + * The agents a store knows of, with the order in which their records went offline, so that a store at its bound can give up the record that has been offline longest. The order follows a record's status only through `set`, so a caller that changes a stored record's status in place must store it again; it is the order in which this store first saw each record offline, kept while it stays offline and dropped when it comes back or is removed, local to the store and never sent. */ import type { AgentIdentity } from "./types.js"; @@ -8,6 +8,13 @@ export class KnownAgents extends Map { /** The offline records in the order they went offline: an id is added when its record is first seen offline and keeps its place while it stays, so the first is the one offline longest. */ private readonly offlineOrder = new Set(); + private readonly deletionListeners: ((agentId: string) => void)[] = []; + + /** Calls `listener` with the id of every record that is removed, by `delete` or `clear`. */ + onDeleted(listener: (agentId: string) => void): void { + this.deletionListeners.push(listener); + } + override set(agentId: string, agent: AgentIdentity): this { super.set(agentId, agent); if (agent.status === "offline") { @@ -20,12 +27,20 @@ export class KnownAgents extends Map { override delete(agentId: string): boolean { this.offlineOrder.delete(agentId); - return super.delete(agentId); + const removed = super.delete(agentId); + if (removed) this.notifyDeleted(agentId); + return removed; } override clear(): void { + const ids = [...this.keys()]; this.offlineOrder.clear(); super.clear(); + for (const id of ids) this.notifyDeleted(id); + } + + private notifyDeleted(agentId: string): void { + for (const listener of this.deletionListeners) listener(agentId); } /** The ids of the offline records, the one that went offline longest ago first. */ diff --git a/src/core/peer-lifecycle.ts b/src/core/peer-lifecycle.ts index f2bde337..6d2d708f 100644 --- a/src/core/peer-lifecycle.ts +++ b/src/core/peer-lifecycle.ts @@ -291,7 +291,7 @@ export class PeerLifecycle { this.deps.coordinatorRole.current()?.holder === handle.id, }; const ownId = this.deps.getPeerId(); - const claims = this.slots.open(this.originOf(handle.id)); + const claims = this.slots.open(handle.id); if (msg.method === "state_sync") { const { value, refused, awaitingAuthority } = admitSnapshot( normaliseWireState(msg.state), @@ -321,13 +321,6 @@ export class PeerLifecycle { } } - /** Where a peer's agents are counted from: the host it was reached at, this machine for a peer reached on it, and the peer itself when this side has no entry for it. A host that presents many device keys is one origin. */ - private originOf(peerId: string): string { - const info = this.deps.peerInfo.get(peerId); - if (info === undefined) return `peer:${peerId}`; - return info.host === undefined ? "machine" : `host:${info.host}`; - } - /** Applies what `holderId` gave before it was accepted as the holder, now that it is. Detached: it runs from the election's acceptance of a claim. */ handleHolderAccepted(holderId: string): void { const released = this.deferred.release(holderId); @@ -345,7 +338,7 @@ export class PeerLifecycle { }, sender, this.deps.getPeerId(), - this.slots.open(this.originOf(holderId)), + this.slots.open(holderId), ); this.deps.deliveryEngine.applyStateSync(records.value); this.detach( @@ -362,7 +355,7 @@ export class PeerLifecycle { /** Forgets what is kept for a connection that ended. */ private forgetSource(peerId: string): void { - this.slots.release(this.originOf(peerId)); + this.slots.release(peerId); this.deferred.drop(peerId); this.reportedPeers.delete(peerId); } diff --git a/src/core/state-intake.ts b/src/core/state-intake.ts index 7013aeaf..b0e01731 100644 --- a/src/core/state-intake.ts +++ b/src/core/state-intake.ts @@ -15,8 +15,8 @@ export const MAX_SNAPSHOT_ENTRIES = 4096; /** The most agents a store keeps. Past it, a new agent takes the place of an offline record, and is refused only when no record is offline; one already known is still updated. At least the largest snapshot, so a full snapshot of a full mesh fits. */ export const MAX_KNOWN_AGENTS = 4096; -/** The most agents one origin may have introduced that a store still holds: the host a peer was reached at, or this machine for a peer reached on it, so a host that presents many device keys is still one origin. At this number an origin's new agent takes the place of that origin's own offline record, and is refused only when it has none. */ -export const MAX_AGENTS_PER_ORIGIN = 512; +/** The most agents one connection may have introduced that a store still holds. It bounds a single connection, not a host or a machine: one that presents many device keys has a bound for each, and only MAX_KNOWN_AGENTS bounds them together. At this number a connection's new agent takes the place of that connection's own offline record, and is refused only when it has none. */ +export const MAX_AGENTS_PER_SOURCE = 512; /** Who sent state, and whether this side takes that peer to be the coordinator. */ export interface StateSender { @@ -57,9 +57,9 @@ export function isWellFormedAgent( interface ClaimSlots { has: (agentId: string) => boolean; size: number; - heldFrom: (origin: string, keep: ReadonlySet) => number; - tag: (agentId: string, origin: string) => void; - evictOne: (keep: ReadonlySet, origin?: string) => boolean; + heldFrom: (source: string, keep: ReadonlySet) => number; + tag: (agentId: string, source: string) => void; + evictOne: (keep: ReadonlySet, source?: string) => boolean; } /** The claims on agent slots that the records of one message make. */ @@ -68,19 +68,19 @@ export class AgentClaims { constructor( private readonly slots: Readonly, - private readonly origin: string, + private readonly source: string, ) {} has(agentId: string): boolean { return this.slots.has(agentId); } - /** Whether the store takes a record for `agentId`: it already holds one, or it can hold a new one. A new one counts against the origin that introduced it, and past the bound of the origin or of the store takes the place of an offline record. */ + /** Whether the store takes a record for `agentId`: it already holds one, or it can hold a new one. A new one counts against the connection that introduced it, and past the bound of the connection or of the store takes the place of an offline record. */ claim(agentId: string): boolean { if (this.slots.has(agentId) || this.claimed.has(agentId)) return true; if ( - this.slots.heldFrom(this.origin, this.claimed) >= MAX_AGENTS_PER_ORIGIN && - !this.slots.evictOne(this.claimed, this.origin) + this.slots.heldFrom(this.source, this.claimed) >= MAX_AGENTS_PER_SOURCE && + !this.slots.evictOne(this.claimed, this.source) ) { return false; } @@ -91,7 +91,7 @@ export class AgentClaims { return false; } this.claimed.add(agentId); - this.slots.tag(agentId, this.origin); + this.slots.tag(agentId, this.source); return true; } } @@ -105,23 +105,32 @@ export interface AgentSlotsStore { ownId: () => string; } -/** The places a store can hold agents, and which origin introduced each. */ +/** The places a store can hold agents, and which connection introduced each. */ export class AgentSlots implements ClaimSlots { - /** The agents each origin introduced and the store still holds, or has just claimed. */ - private readonly byOrigin = new Map>(); + /** The agents each connection introduced and the store still holds, or has just claimed. */ + private readonly bySource = new Map>(); - private readonly originOf = new Map(); + private readonly sourceOf = new Map(); - constructor(private readonly store: AgentSlotsStore) {} + constructor(private readonly store: AgentSlotsStore) { + store.agents.onDeleted((agentId) => { + const source = this.sourceOf.get(agentId); + if (source === undefined) return; + this.sourceOf.delete(agentId); + const ids = this.bySource.get(source); + ids?.delete(agentId); + if (ids?.size === 0) this.bySource.delete(source); + }); + } - /** Starts the claims of one message from `origin`. */ - open(origin: string): AgentClaims { - return new AgentClaims(this, origin); + /** Starts the claims of one message from `source`. */ + open(source: string): AgentClaims { + return new AgentClaims(this, source); } - /** Forgets what an origin introduced, once nothing of it is held. */ - release(origin: string): void { - this.heldFrom(origin, new Set()); + /** Forgets what a connection introduced that the store no longer holds, once the connection has ended. */ + release(source: string): void { + this.heldFrom(source, new Set()); } has(agentId: string): boolean { @@ -132,34 +141,36 @@ export class AgentSlots implements ClaimSlots { return this.store.agents.size; } - /** How many agents `origin` introduced that the store still holds, besides those in `keep`, which a message has claimed and not yet stored. */ - heldFrom(origin: string, keep: ReadonlySet): number { - const ids = this.byOrigin.get(origin); + /** How many agents `source` introduced that the store still holds, besides those in `keep`, which a message has claimed and not yet stored. */ + heldFrom(source: string, keep: ReadonlySet): number { + const ids = this.bySource.get(source); if (ids === undefined) return 0; for (const id of ids) { if (!this.store.agents.has(id) && !keep.has(id)) { ids.delete(id); - this.originOf.delete(id); + this.sourceOf.delete(id); } } - if (ids.size === 0) this.byOrigin.delete(origin); + if (ids.size === 0) this.bySource.delete(source); return ids.size; } - tag(agentId: string, origin: string): void { - this.originOf.set(agentId, origin); - const ids = this.byOrigin.get(origin) ?? new Set(); + tag(agentId: string, source: string): void { + this.sourceOf.set(agentId, source); + const ids = this.bySource.get(source) ?? new Set(); ids.add(agentId); - this.byOrigin.set(origin, ids); + this.bySource.set(source, ids); } - /** Evicts the record that has been offline longest and returns whether there was one, among those `origin` introduced when it is given. Only an offline record is evictable, and never one in `keep` or the store's own. */ - evictOne(keep: ReadonlySet, origin?: string): boolean { + /** Evicts the record that has been offline longest and returns whether there was one, among those `source` introduced when it is given. Only an offline record is evictable, and never one in `keep` or the store's own. */ + evictOne(keep: ReadonlySet, source?: string): boolean { const ownId = this.store.ownId(); let victim: string | undefined; for (const id of this.store.agents.offlineOldestFirst()) { if (keep.has(id) || id === ownId) continue; - if (origin !== undefined && this.originOf.get(id) !== origin) continue; + // The order is kept by `set`, so a record whose status changed without being stored again is not taken for an offline one. + if (this.store.agents.get(id)?.status !== "offline") continue; + if (source !== undefined && this.sourceOf.get(id) !== source) continue; victim = id; break; } diff --git a/src/test/delivery-engine.unit.test.ts b/src/test/delivery-engine.unit.test.ts index e161125a..ad85b257 100644 --- a/src/test/delivery-engine.unit.test.ts +++ b/src/test/delivery-engine.unit.test.ts @@ -3,6 +3,7 @@ */ import { beforeEach, describe, expect, it, vi } from "vitest"; import { loadRoomTokens } from "../core/identity-store.js"; +import { KnownAgents } from "../core/known-agents.js"; import { randomId } from "../core/random-id.js"; import { DeliveryEngine, @@ -146,7 +147,7 @@ function makeHarness() { const sendRoomRequestToMember = vi.fn().mockResolvedValue(undefined); const revocationRecord = vi.fn().mockResolvedValue(undefined); const deps: DeliveryEngineDeps = { - agents: new Map(), + agents: new KnownAgents(), rooms: new Map(), messages: new Map(), dms: new Map(), @@ -223,6 +224,33 @@ describe("DeliveryEngine — handlePresenceAdvert", () => { }); }); +describe("DeliveryEngine — handlePresenceAdvert and the order of offline records", () => { + function offlineOrder(h: ReturnType): string[] { + const agents = h.deps.agents; + if (!(agents instanceof KnownAgents)) throw new Error("not KnownAgents"); + return [...agents.offlineOldestFirst()]; + } + + it("takes a record that presence brings back out of the offline order, so it is not the first to be evicted", () => { + const h = makeHarness(); + h.deps.agents.set(OTHER_ID, agent({ status: "offline", version: 1 })); + expect(offlineOrder(h)).toEqual([OTHER_ID]); + + h.engine.handlePresenceAdvert(OTHER_ID, "active"); + + expect(offlineOrder(h)).toEqual([]); + }); + + it("puts a record that presence takes offline into the offline order", () => { + const h = makeHarness(); + h.deps.agents.set(OTHER_ID, agent({ status: "active", version: 1 })); + + h.engine.handlePresenceAdvert(OTHER_ID, "offline"); + + expect(offlineOrder(h)).toEqual([OTHER_ID]); + }); +}); + describe("DeliveryEngine — handleRevocationAnnounce", () => { it("records a gossiped revocation entry against this store's own identity", async () => { const h = makeHarness(); diff --git a/src/test/peer-lifecycle.unit.test.ts b/src/test/peer-lifecycle.unit.test.ts index cd9632f1..cae05177 100644 --- a/src/test/peer-lifecycle.unit.test.ts +++ b/src/test/peer-lifecycle.unit.test.ts @@ -7,7 +7,7 @@ import { type PeerLifecycleDeps, } from "../core/peer-lifecycle.js"; import { KnownAgents } from "../core/known-agents.js"; -import { MAX_AGENTS_PER_ORIGIN } from "../core/state-intake.js"; +import { MAX_AGENTS_PER_SOURCE } from "../core/state-intake.js"; import { ROOM_REQUEST_TIMEOUT_MS } from "../core/request-timeouts.js"; import type { AgentIdentity, DeliveryEvent } from "../core/types.js"; import type { PeerInfo, SerialisedState } from "../core/wire-protocol.js"; @@ -480,27 +480,34 @@ describe("PeerLifecycle — handleDataMessage", () => { expect(h.applyStateSync).toHaveBeenLastCalledWith(emptyState()); }); - it("counts the agents of peers reached at one host together, however many device keys they use, and those of peers at another host apart", async () => { + it("counts the agents a connection introduced against that connection, whatever host the peer list names for it, so a rewritten peer entry moves nothing", async () => { const h = makeHarness(); - const introduce = async (id: string, host: string): Promise => { - h.deps.peerInfo.set(id, { ...peerInfo(id), host }); + const relay = async ( + from: string, + ...agents: readonly AgentIdentity[] + ): Promise => { await h.lifecycle.handleDataMessage( - { id }, - { method: "state_sync", state: stateOf(named(id)) }, + { id: from }, + { method: "state_sync", state: stateOf(...agents) }, ); }; - for (let n = 0; n < MAX_AGENTS_PER_ORIGIN; n++) { - await introduce(`key-${String(n)}`, "10.0.0.9"); - h.deps.agents.set(`key-${String(n)}`, named(`key-${String(n)}`)); + h.dialled.coordinator = "relayer"; + h.deps.peerInfo.set("victim", { ...peerInfo("victim"), host: "10.0.0.9" }); + for (let n = 0; n < MAX_AGENTS_PER_SOURCE; n++) { + await relay("relayer", named(`fake-${String(n)}`)); + h.deps.agents.set(`fake-${String(n)}`, named(`fake-${String(n)}`)); } - await introduce("one-key-too-many", "10.0.0.9"); + // The relayer now has its own peer entry rewritten to the victim's host, and the victim's entry is rewritten to the relayer's. + h.deps.peerInfo.set("relayer", { + ...peerInfo("relayer"), + host: "10.0.0.9", + }); + await relay("relayer", named("one-too-many")); expect(h.applyStateSync).toHaveBeenLastCalledWith(emptyState()); - await introduce("elsewhere", "10.0.0.10"); - expect(h.applyStateSync).toHaveBeenLastCalledWith( - stateOf(named("elsewhere")), - ); + await relay("victim", named("victim")); + expect(h.applyStateSync).toHaveBeenLastCalledWith(stateOf(named("victim"))); }); describe("what a sender gives before its claim is accepted", () => { diff --git a/src/test/state-intake.unit.test.ts b/src/test/state-intake.unit.test.ts index 87a8b03a..9b4a5f62 100644 --- a/src/test/state-intake.unit.test.ts +++ b/src/test/state-intake.unit.test.ts @@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest"; import { AgentSlots, - MAX_AGENTS_PER_ORIGIN, + MAX_AGENTS_PER_SOURCE, MAX_KNOWN_AGENTS, MAX_SNAPSHOT_ENTRIES, admitPatch, @@ -76,10 +76,10 @@ function state(agents: readonly AgentIdentity[]): SerialisedState { const peer = { id: SENDER, isCoordinator: false }; const coordinator = { id: SENDER, isCoordinator: true }; -/** A store holding `held`, which went offline in the order given, with the claims one message from `origin` makes on it; `forgotten` lists what was evicted. */ +/** A store holding `held`, which went offline in the order given, with the claims one message from `source` makes on it; `forgotten` lists what was evicted. */ function storeHolding( held: readonly AgentIdentity[], - origin = "host:a", + source = "conn-a", ): { agents: KnownAgents; slots: AgentSlots; @@ -97,7 +97,7 @@ function storeHolding( }, ownId: () => SELF, }); - return { agents, slots, forgotten, claims: slots.open(origin) }; + return { agents, slots, forgotten, claims: slots.open(source) }; } /** Claims a record for `id` and, as the store does once a claim is admitted, holds it. */ @@ -303,6 +303,33 @@ describe("a store that holds the most agents it keeps", () => { expect(held.forgotten).toEqual(["steady"]); }); + it("takes an agent that comes back, with its record stored again, out of the records to evict, and one that goes offline in that way into them", () => { + const held = storeHolding( + fullStore([offline("comes-back"), agent("goes-offline")]), + ); + const back = held.agents.get("comes-back"); + const out = held.agents.get("goes-offline"); + if (back === undefined || out === undefined) throw new Error("missing"); + back.status = "active"; + held.agents.set("comes-back", back); + out.status = "offline"; + held.agents.set("goes-offline", out); + + take(held, "new-1"); + + expect(held.forgotten).toEqual(["goes-offline"]); + }); + + it("never evicts a record whose status changed without being stored again, whatever the offline order says", () => { + const held = storeHolding(fullStore([offline("stale-order")])); + const stale = held.agents.get("stale-order"); + if (stale === undefined) throw new Error("missing"); + stale.status = "active"; + + expect(take(held, "new-1")).toBe(false); + expect(held.forgotten).toEqual([]); + }); + it("keeps the time a record went offline while it is set offline again", () => { const held = storeHolding(fullStore([offline("first"), offline("second")])); held.agents.set("first", offline("first")); @@ -347,42 +374,68 @@ describe("a store that holds the most agents it keeps", () => { }); }); -describe("what one origin introduces", () => { - it("is bounded by the agents of it that the store holds, whatever keys they use, and another origin is not affected", () => { +describe("what one connection introduces", () => { + it("is bounded by the agents of it that the store holds, and another connection is not affected", () => { const held = storeHolding([]); - for (let n = 0; n < MAX_AGENTS_PER_ORIGIN; n++) { + for (let n = 0; n < MAX_AGENTS_PER_SOURCE; n++) { expect(take(held, `a-${String(n)}`)).toBe(true); } expect(take(held, "one-too-many")).toBe(false); - held.claims = held.slots.open("host:b"); - expect(take(held, "another-origin")).toBe(true); + held.claims = held.slots.open("conn-b"); + expect(take(held, "another-connection")).toBe(true); }); - it("takes the place of the origin's own offline record at its bound, and never another origin's", () => { + it("takes the place of the connection's own offline record at its bound, and never another connection's", () => { const held = storeHolding([]); - held.claims = held.slots.open("host:b"); + held.claims = held.slots.open("conn-b"); take(held, "b-offline", "offline"); - held.claims = held.slots.open("host:a"); + held.claims = held.slots.open("conn-a"); take(held, "a-offline", "offline"); - for (let n = 1; n < MAX_AGENTS_PER_ORIGIN; n++) { + for (let n = 1; n < MAX_AGENTS_PER_SOURCE; n++) { take(held, `a-${String(n)}`); } - held.claims = held.slots.open("host:a"); + held.claims = held.slots.open("conn-a"); expect(take(held, "a-new")).toBe(true); expect(held.forgotten).toEqual(["a-offline"]); expect(held.agents.has("b-offline")).toBe(true); }); + it("forgets the connection of an agent the store evicts or removes without waiting for that connection to be checked again", () => { + const tracked = (slots: AgentSlots): number => { + const bySource: unknown = Reflect.get(slots, "bySource"); + const sourceOf: unknown = Reflect.get(slots, "sourceOf"); + if (!(bySource instanceof Map) || !(sourceOf instanceof Map)) { + throw new Error("the slots keep their bookkeeping elsewhere"); + } + return bySource.size + sourceOf.size; + }; + const deleted = storeHolding([]); + take(deleted, "gone"); + expect(tracked(deleted.slots)).toBeGreaterThan(0); + deleted.agents.delete("gone"); + expect(tracked(deleted.slots)).toBe(0); + + const cleared = storeHolding([]); + take(cleared, "gone"); + cleared.agents.clear(); + expect(tracked(cleared.slots)).toBe(0); + + const evicted = storeHolding(fullStore([offline("old")])); + take(evicted, "new-1"); + const sourceOf: unknown = Reflect.get(evicted.slots, "sourceOf"); + expect(sourceOf instanceof Map && sourceOf.has("old")).toBe(false); + }); + it("stops counting an agent the store no longer holds", () => { const held = storeHolding([]); - for (let n = 0; n < MAX_AGENTS_PER_ORIGIN; n++) + for (let n = 0; n < MAX_AGENTS_PER_SOURCE; n++) take(held, `a-${String(n)}`); held.agents.delete("a-0"); - held.claims = held.slots.open("host:a"); + held.claims = held.slots.open("conn-a"); expect(take(held, "a-new")).toBe(true); }); });