Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions src/core/deferred-intake.ts
Original file line number Diff line number Diff line change
@@ -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<string, AgentIdentity>;
/** Each held departure, with the version of the agent's record when it was held (undefined when there was none). */
readonly departures: Map<string, number | undefined>;
}

/** 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<string, Held>();

/**
* @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<AgentIdentity>): 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);
}
}
14 changes: 7 additions & 7 deletions src/core/delivery-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -213,13 +215,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) {
Expand Down
50 changes: 50 additions & 0 deletions src/core/known-agents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* 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";

export class KnownAgents extends Map<string, AgentIdentity> {
/** 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<string>();

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") {
this.offlineOrder.add(agentId);
} else {
this.offlineOrder.delete(agentId);
}
return this;
}

override delete(agentId: string): boolean {
this.offlineOrder.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. */
offlineOldestFirst(): IterableIterator<string> {
return this.offlineOrder.values();
}
}
4 changes: 2 additions & 2 deletions src/core/mesh-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -133,7 +134,7 @@ export class MeshStore implements CommsStore {
onError: this.reportError,
});

private readonly agents = new Map<string, AgentIdentity>();
private readonly agents = new KnownAgents();
private readonly rooms = new Map<string, Room>();
private readonly messages = new Map<string, RoomMessage[]>();
private readonly dms = new Map<string, DmMessage[]>();
Expand Down Expand Up @@ -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),
Expand Down
76 changes: 46 additions & 30 deletions src/core/peer-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<string, PeerInfo>;
agents: Map<string, AgentIdentity>;
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;
Expand Down Expand Up @@ -71,16 +73,15 @@ 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;
}

/** 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;

Expand All @@ -105,8 +106,8 @@ export class PeerLifecycle {
/** The peers a refusal has been reported for. */
private readonly reportedPeers = new Set<string>();

/** 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<string, Set<string>>();
/** 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;
Expand All @@ -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. */
Expand Down Expand Up @@ -289,19 +293,26 @@ export class PeerLifecycle {
const ownId = this.deps.getPeerId();
const claims = this.slots.open(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;
Expand All @@ -310,24 +321,29 @@ 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<string>();
waiting.add(agentId);
this.deferredDepartures.set(senderId, waiting);
}

/** 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(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,
Expand All @@ -340,7 +356,7 @@ 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.deferred.drop(peerId);
this.reportedPeers.delete(peerId);
}

Expand Down Expand Up @@ -393,8 +409,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<void> {
this.deps.peerInfo.delete(peerId);
this.forgetSource(peerId);
this.deps.peerInfo.delete(peerId);
await this.deps.coordinatorRole.handleDeparture(peerId, async () =>
this.retireDepartedAgent(peerId),
);
Expand Down
4 changes: 1 addition & 3 deletions src/core/stale-agent-checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import type { MeshStatePatch, PeerInfo } from "./wire-protocol.js";
export interface StaleAgentCheckerDeps {
agents: Map<string, AgentIdentity>;
deliveryQueues: Map<string, DeliveryEvent[]>;
identityCache: Map<string, { id: string }>;
peerInfo: Map<string, PeerInfo>;
notifyRoomsOfStatus: (agentId: string, status: AgentStatus) => Promise<void>;
broadcastPatch: (patch: MeshStatePatch) => Promise<void>;
Expand Down Expand Up @@ -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);
}

Expand Down
Loading
Loading