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
2 changes: 1 addition & 1 deletion e2e/gateway-smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ describe("gateway smoke", () => {
headers: auth,
method: "POST",
});
expect(created.status).toBe(201);
expect(created.status, await created.clone().text()).toBe(201);
return (await created.json()) as RequestBody;
};
const readGranted = async (requestId: string): Promise<RequestBody> => {
Expand Down
2 changes: 1 addition & 1 deletion src/gateway/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ no live link → `WORKER_UNREACHABLE`; a worker `UNKNOWN_LEASE` drops the entry.
no TTL timer. Relayed `lease.expired`/`lease.released` remove the entry and push `lease-lost`.
Exec forwards the namespaced requester; `gateway.execTimeoutMs` is a backstop over the worker's `exec.timeoutMs`.
The lease index is in memory, rebuilt from each view's leases whose requester starts `gw:<id>:`;
missing from 2 snapshots in a row → dropped; kept across a disconnect, forgotten with the view.
missing from 2 snapshots in a row → dropped; kept across a disconnect, forgotten with the view. A lease the worker answered released or `UNKNOWN_LEASE` (even if its relayed event already forgot it) is not added back by a later snapshot that still lists it.

**HTTP relay** (`GatewayRelay.relay`, used by `../agent-device/front/relay-host-link.ts` and `../stream/`):

Expand Down
54 changes: 54 additions & 0 deletions src/gateway/fleet-coordinator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1619,6 +1619,60 @@ describe("FleetLeaseCoordinator dispatch", () => {
expect((retry as RequesterAlreadyLeasedError).existingLeaseId).toBe(grant.lease.id);
});

it("grants a requester's next lease when a worker view read before its release lands after it (#898)", async () => {
const { coordinator, directory, workers } = harness();
const client = new ScriptedWorkerClient();
directory.add("wrk_a", client);
connectWorker(workers, "wrk_a");
client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" });
const first = await coordinator.request(REQUEST, requestOptions());
client.releaseLeaseQueue.push({ kind: "ok" });
await coordinator.release(first.lease.id);

workers.refresh("wrk_a", {
leases: [{ ...leaseFixture("lse_1", "dev_1"), requesterId: `${GATEWAY_PREFIX}agent-1` }],
});
workers.refresh("wrk_a", { leases: [] });

client.requestLeaseQueue.push({
grant: grantFixture({ lease: leaseFixture("lse_2", "dev_1") as LeaseRecord }),
kind: "grant",
});
const second = await coordinator
.request(REQUEST, requestOptions({ noWait: true }))
.catch((error: unknown) => error);
expect(second).toMatchObject({ lease: { id: "wrk_a.lse_2" } });
});

it.each(["release", "releaseAll"] as const)(
"grants the next lease when %s's relayed event came before the worker's answer and a stale view follows (#898)",
async (how) => {
const { coordinator, directory, workers, leaseIndex } = harness();
const client = new ScriptedWorkerClient();
directory.add("wrk_a", client);
connectWorker(workers, "wrk_a");
client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" });
const first = await coordinator.request(REQUEST, requestOptions());
client.onReleaseLease = (leaseId) => leaseIndex.removeByWorkerLease("wrk_a", leaseId);
if (how === "release") await coordinator.release(first.lease.id);
else await coordinator.releaseAll();

workers.refresh("wrk_a", {
leases: [{ ...leaseFixture("lse_1", "dev_1"), requesterId: `${GATEWAY_PREFIX}agent-1` }],
});
workers.refresh("wrk_a", { leases: [] });

client.requestLeaseQueue.push({
grant: grantFixture({ lease: leaseFixture("lse_2", "dev_1") as LeaseRecord }),
kind: "grant",
});
const second = await coordinator
.request(REQUEST, requestOptions({ noWait: true }))
.catch((error: unknown) => error);
expect(second).toMatchObject({ lease: { id: "wrk_a.lse_2" } });
},
);

it("release-all attaches the leases it already released to a later failure's own details (H8)", async () => {
const { coordinator, directory, workers, leaseIndex } = harness();
const clientA = new ScriptedWorkerClient();
Expand Down
24 changes: 24 additions & 0 deletions src/gateway/lease-index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,30 @@ describe("FleetLeaseIndex", () => {
expect(index.resolve("wrk_1.ad-7f3a")).toBeUndefined();
});

it("a stale snapshot does not re-add a lease whose relayed release event arrived before the worker's answer (#898)", () => {
const index = new FleetLeaseIndex(PREFIX);
index.add(entry());
index.removeByWorkerLease("wrk_1", "lse_1");
index.remove("wrk_1.lse_1");

index.rebuildFromWorker("wrk_1", [reported("lse_1")]);

expect(index.leaseCount("alice")).toBe(0);
});

it("a caller-chosen ID released and granted again is rebuilt from a later snapshot (#898)", () => {
const index = new FleetLeaseIndex(PREFIX);
const bare = entry({ gatewayLeaseId: "ad-7f3a", workerLeaseId: "ad-7f3a" });
index.add(bare);
index.remove("ad-7f3a");
index.add(bare);
index.forgetWorker("wrk_1");

index.rebuildFromWorker("wrk_1", [chosen("ad-7f3a")]);

expect(index.resolve("ad-7f3a")).toMatchObject({ workerId: "wrk_1" });
});

it("a rebuilt lease flagged idChosenByRequester whose ID does not match the leaseId pattern is prefixed and logged", () => {
const logger = new RecordingLogger();
const index = new FleetLeaseIndex(PREFIX, logger);
Expand Down
48 changes: 24 additions & 24 deletions src/gateway/lease-index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,14 @@ export class FleetLeaseIndex {
* again by the *next* `rebuildFromWorker` call for that worker: still absent one full
* generation later is what promotes "missing" to "gone" (see `rebuildFromWorker`'s own doc). */
readonly #missingSince = new Map<string, number>();
/** C1 (round 2 review): gateway lease ids `removeByWorkerLease` just forgot -- an ordinary
* worker-relayed `lease.expired`/`lease.released` -- kept around only long enough to flag the
* one thing that should never legitimately happen next: the *same* id reappearing in a
* `rebuildFromWorker` snapshot moments later. That can only mean a snapshot that started
* gathering data before the relayed fact landed is completing after it, stale by the time it
* arrives; a worker never reissues a lease id, so this is not a real re-grant to admit
* quietly. Bounded (see `#noteRemovedByEvent`) so a long-running gateway's memory does not grow
* with every release it has ever relayed. */
/** why: an id a relayed `lease.expired`/`lease.released` just forgot that reappears in a
* snapshot means that snapshot is stale, which `#addReported` logs. Bounded so a long-running
* gateway does not remember every release it ever relayed. */
readonly #removedByEvent = new Map<string, true>();
/** How many recently-event-removed ids `#removedByEvent` remembers before evicting the
* oldest -- generous relative to how many leases could plausibly be mid-flight across the
* fleet at once, small relative to a gateway's uptime. */
static readonly #removedByEventCapacity = 200;
/** why: a worker view read before the worker answered a release can land after it and still
* list the lease; re-adding it refuses the requester's next lease until two more views miss it.
* The answer is newer than that view, so `#addReported` skips these ids. */
readonly #endedByWorkerAnswer = new Map<string, true>();

constructor(
private readonly gatewayRequesterPrefix: string,
Expand Down Expand Up @@ -158,6 +153,7 @@ export class FleetLeaseIndex {
add(entry: FleetLeaseEntry): boolean {
const existing = this.#byGatewayId.get(entry.gatewayLeaseId);
if (existing !== undefined && existing.workerId !== entry.workerId) return false;
this.#endedByWorkerAnswer.delete(entry.gatewayLeaseId);
this.#byGatewayId.set(entry.gatewayLeaseId, entry);
const ids = this.#byRequester.get(entry.requesterId) ?? new Set<string>();
ids.add(entry.gatewayLeaseId);
Expand All @@ -169,6 +165,9 @@ export class FleetLeaseIndex {
/** Forgets one lease by its gateway id -- the gateway's own `lease.release` completing. */
remove(gatewayLeaseId: string): FleetLeaseEntry | undefined {
const entry = this.#byGatewayId.get(gatewayLeaseId);
// why: the worker's `lease.released` event travels the uplink before the RPC reply, so the
// relayed event may already have forgotten the entry; the answer still ends the lease.
remember(this.#endedByWorkerAnswer, gatewayLeaseId);
if (entry === undefined) return undefined;
this.#forget(entry);
return entry;
Expand All @@ -187,20 +186,10 @@ export class FleetLeaseIndex {
const entry = this.findByWorkerLease(workerId, workerLeaseId);
if (entry === undefined) return undefined;
this.#forget(entry);
this.#noteRemovedByEvent(entry.gatewayLeaseId);
remember(this.#removedByEvent, entry.gatewayLeaseId);
return entry;
}

/** Records `gatewayLeaseId` as just forgotten by a relayed worker event, for `#addReported`'s
* resurrection check -- see `#removedByEvent`'s own doc. Evicts the oldest entry once the
* bound is hit; `Map` iterates insertion order, so its first key is always the oldest. */
#noteRemovedByEvent(gatewayLeaseId: string): void {
this.#removedByEvent.set(gatewayLeaseId, true);
if (this.#removedByEvent.size <= FleetLeaseIndex.#removedByEventCapacity) return;
const oldest = this.#removedByEvent.keys().next().value;
if (oldest !== undefined) this.#removedByEvent.delete(oldest);
}

/**
* Adds every gateway-issued lease a worker's current view reports that this index does not
* already know (ADR §30's reconnect rebuild; also the ordinary per-refresh path, since
Expand Down Expand Up @@ -256,7 +245,7 @@ export class FleetLeaseIndex {
}
reported.add(gatewayLeaseId);
this.#missingSince.delete(gatewayLeaseId);
if (existing !== undefined) continue;
if (existing !== undefined || this.#endedByWorkerAnswer.has(gatewayLeaseId)) continue;
// C1 (round 2 review): this id was forgotten moments ago by the worker's own relayed
// `lease.expired`/`lease.released` -- reappearing in a snapshot now means that snapshot
// was gathered before the relayed fact landed and is only completing late (see
Expand Down Expand Up @@ -369,6 +358,17 @@ export class FleetLeaseIndex {
}
}

// why: generous next to how many leases can be mid-flight at once, small next to a gateway's uptime.
const REMOVED_IDS_CAPACITY = 200;

// why: a Map iterates in insertion order, so its first key is the oldest to evict.
function remember(ids: Map<string, true>, gatewayLeaseId: string): void {
ids.set(gatewayLeaseId, true);
if (ids.size <= REMOVED_IDS_CAPACITY) return;
const oldest = ids.keys().next().value;
if (oldest !== undefined) ids.delete(oldest);
}

function workerKey(workerId: string, workerLeaseId: string): string {
return `${workerId} ${workerLeaseId}`;
}
4 changes: 4 additions & 0 deletions src/gateway/test-support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,9 @@ export class ScriptedWorkerClient {
requestLeaseDefault: RequestLeaseOutcome = { kind: "error", error: noCapacityError() };
readonly renewLeaseQueue: RenewLeaseOutcome[] = [];
readonly releaseLeaseQueue: ReleaseLeaseOutcome[] = [];
/** why: a real worker's `lease.released` event reaches the gateway before the release reply;
* a test sets this to relay that event from inside the call. */
onReleaseLease: ((leaseId: string) => void) | undefined;
readonly execQueue: ExecOutcome[] = [];
/**
* H4 (round 3 review): the `options` most recently passed to `exec` -- captured before
Expand Down Expand Up @@ -475,6 +478,7 @@ export class ScriptedWorkerClient {
this.#throwIfFailing();
const outcome = this.releaseLeaseQueue.shift();
if (outcome?.kind === "error") throw outcome.error;
this.onReleaseLease?.(input.leaseId);
return { leaseId: input.leaseId };
}

Expand Down
Loading