Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
21b1334
test: events.replay with beforeId and limit pages through the worker …
V3RON Oct 20, 2026
e69f9e6
feat(history): events.replay pages back from a named event (#764)
V3RON Oct 20, 2026
44fd5dc
feat(contract): protocol 52 for events.replay paging (#764)
V3RON Oct 20, 2026
99663fa
test: protocol 52 pins (#764)
V3RON Oct 20, 2026
b43291e
test: replayPage with beforeId and limit returns the events just olde…
V3RON Oct 20, 2026
b5ba39f
test: replayPage pages same-timestamp same-seq events from different …
V3RON Oct 20, 2026
d99bd95
test: GET /v1/events with before and limit dispatches events.replay a…
V3RON Oct 20, 2026
5d39097
feat(http): GET /v1/events reads before and limit (#764)
V3RON Oct 20, 2026
f0f5c52
test: replayPage with limit alone returns the newest n and falls back…
V3RON Oct 20, 2026
9814ba0
feat(history): replayPage with limit alone returns the newest events …
V3RON Oct 20, 2026
9881379
test: eventsPageQuery accepts good pages and refuses bad limits, ids …
V3RON Oct 20, 2026
ab51ec9
feat(contract): eventsPageQuery checks limit, before and their mix wi…
V3RON Oct 20, 2026
a33efb5
test: each eventsPageQuery refusal answers 400 over HTTP (#764)
V3RON Oct 20, 2026
f50bb86
test: a worker's relayed event is returned by before paging on a gate…
V3RON Oct 20, 2026
c66f604
test: the events.replay input schema bounds beforeId and limit and re…
V3RON Oct 20, 2026
e8a594c
feat(contract): events.replay input bounds beforeId and limit (#764)
V3RON Oct 20, 2026
fb19aeb
docs: events paging in the HTTP API and module manuals (#764)
V3RON Oct 20, 2026
b9eeb34
test: events.replay with limit alone reaches the newest n through bot…
V3RON Oct 20, 2026
fdd75c7
test: events paging covers the not-writing ring, a failed beforeId re…
V3RON Oct 20, 2026
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
4 changes: 2 additions & 2 deletions src/contract/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Three identities:

## Protocol version

- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 51, max: 51 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`.
- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 52, max: 52 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`.
- Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless
a compatibility path stays side by side. `.agents/scripts/protocol-bump-check.mjs` checks
it on push and in CI; it counts every file here as a shape but tests, `index.ts` and the
Expand All @@ -68,7 +68,7 @@ Three identities:

- `SimlockErrorCode` is a closed union (`ErrorDetailsMap`). `ERROR_TABLE` gives each code
`kind` (`transport` | `protocol` | `domain`), `cliExitCode` and `httpStatus`.
- `HISTORY_NOT_KEPT` (exit 12, 422, `details.oldestTs`) and `HISTORY_UNAVAILABLE` (exit 1, 503) are `usage.get`'s; `includeLedger` adds `requests[]` (at most 100,000, newest; `ledgerTruncated` when cut); the window it takes is bounded by `usageWindowSchema` (integers to 8.64e15, `from < to`, 90 days at most) and `usageWindow` (`usage-window.ts`) parses the CLI's flags once for every surface.
- `HISTORY_NOT_KEPT` (exit 12, 422, `details.oldestTs`) and `HISTORY_UNAVAILABLE` (exit 1, 503) are `usage.get`'s and `events.replay`'s with `beforeId`; `includeLedger` adds `requests[]` (at most 100,000, newest; `ledgerTruncated` when cut); the window it takes is bounded by `usageWindowSchema` (integers to 8.64e15, `from < to`, 90 days at most) and `usageWindow` (`usage-window.ts`) parses the CLI's flags once for every surface. `events.replay` takes `beforeId` and `limit` (1 to 500), refused with `sinceTs`; `eventsPageQuery` (`events-page.ts`) parses the HTTP query once, with the bounds.
- `fromWireError` wraps an unknown code as `UNKNOWN_DAEMON_ERROR`. That code and `CANCELLED`
are built client side only.
- `CODES_WITH_DECLARED_DETAILS`: codes whose `details` are contract. The compiler keeps it
Expand Down
26 changes: 26 additions & 0 deletions src/contract/events-page.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";

import { eventsPageQuery } from "./events-page.js";

describe("eventsPageQuery", () => {
it("accepts 5, 500 and an id evt_a-B_9, and refuses 0, 501, 05, +5, ' 5', 5.0, 1e2, x, an id not-an-id, before with since, and limit with since, each with its message", () => {
expect(eventsPageQuery({ limit: "5" })).toEqual({ page: { limit: 5 } });
expect(eventsPageQuery({ limit: "500" })).toEqual({ page: { limit: 500 } });
expect(eventsPageQuery({ before: "evt_a-B_9" })).toEqual({ page: { beforeId: "evt_a-B_9" } });
expect(eventsPageQuery({ since: "1h" })).toEqual({ page: {} });

const badLimit = { refused: "limit must be a whole number from 1 to 500" };
for (const limit of ["0", "501", "05", "+5", " 5", "5.0", "1e2", "x", ""]) {
expect(eventsPageQuery({ before: "evt_abc", limit })).toEqual(badLimit);
}
for (const before of ["not-an-id", "evt_", ""]) {
expect(eventsPageQuery({ before })).toEqual({ refused: "before must be an event id" });
}
expect(eventsPageQuery({ before: "evt_abc", since: "1h" })).toEqual({
refused: "before and since cannot be used together",
});
expect(eventsPageQuery({ limit: "50", since: "1h" })).toEqual({
refused: "limit and since cannot be used together",
});
});
});
54 changes: 54 additions & 0 deletions src/contract/events-page.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { EVENT_ID_PATTERN } from "./schemas.js";

export const EVENTS_PAGE_MAX = 500;
export const EVENTS_PAGE_DEFAULT = 100;

export interface EventsPageAsk {
readonly before?: string | undefined;
readonly limit?: string | undefined;
readonly since?: string | undefined;
}

export type EventsPageAnswer =
| { readonly page: { readonly beforeId?: string; readonly limit?: number } }
| { readonly refused: string };

const LIMIT_DIGITS = /^[1-9]\d{0,2}$/;

export function eventsPageQuery(ask: EventsPageAsk): EventsPageAnswer {
if (ask.before !== undefined && !EVENT_ID_PATTERN.test(ask.before)) {
return { refused: "before must be an event id" };
}
const limit = ask.limit === undefined ? undefined : parseLimit(ask.limit);
if (ask.limit !== undefined && limit === undefined) {
return { refused: "limit must be a whole number from 1 to 500" };
}
if (ask.since !== undefined && ask.before !== undefined) {
return { refused: "before and since cannot be used together" };
}
if (ask.since !== undefined && limit !== undefined) {
return { refused: "limit and since cannot be used together" };
}
return {
page: {
...(ask.before === undefined ? {} : { beforeId: ask.before }),
...(limit === undefined ? {} : { limit }),
},
};
}

function parseLimit(value: string): number | undefined {
if (!LIMIT_DIGITS.test(value)) return undefined;
const limit = Number(value);
return limit <= EVENTS_PAGE_MAX ? limit : undefined;
}

export const EVENTS_PAGE_WITH_SINCE_MESSAGE = "beforeId and limit cannot be used with sinceTs";

export function eventsPageWithoutSince(input: {
readonly beforeId?: unknown;
readonly limit?: unknown;
readonly sinceTs?: unknown;
}): boolean {
return input.sinceTs === undefined || (input.beforeId === undefined && input.limit === undefined);
}
1 change: 1 addition & 0 deletions src/contract/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ export * from "./pushes.js";
export * from "./relay.js";
export * from "./roles.js";
export * from "./schemas.js";
export * from "./events-page.js";
export * from "./usage-window.js";
export * from "./worker-view.js";
15 changes: 15 additions & 0 deletions src/contract/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1631,3 +1631,18 @@ describe("usage.get input", () => {
expect(parse({ from: 0 }).success).toBe(false);
});
});

describe("events.replay input", () => {
const parse = (input: unknown) => OPERATIONS["events.replay"].input.safeParse(input);

it("accepts beforeId and limit in bounds, and refuses limit 0, 501 and 1.5, a beforeId of evt_ or abc, and beforeId or limit with sinceTs", () => {
expect(parse({ beforeId: "evt_abc", limit: 1 }).success).toBe(true);
expect(parse({ limit: 500 }).success).toBe(true);
expect(parse({ sinceTs: 5 }).success).toBe(true);

for (const limit of [0, 501, 1.5]) expect(parse({ limit }).success).toBe(false);
for (const beforeId of ["evt_", "abc"]) expect(parse({ beforeId }).success).toBe(false);
expect(parse({ beforeId: "evt_abc", sinceTs: 5 }).success).toBe(false);
expect(parse({ limit: 5, sinceTs: 5 }).success).toBe(false);
});
});
14 changes: 13 additions & 1 deletion src/contract/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@
import { z } from "zod";

import { CONSOLE_URL_MAX_LENGTH } from "./console-url.js";
import {
EVENTS_PAGE_MAX,
EVENTS_PAGE_WITH_SINCE_MESSAGE,
eventsPageWithoutSince,
} from "./events-page.js";
import { parseOsConstraint } from "./os-range.js";
import { relayChannelSchema, relayHeadersSchema, relayIdSchema } from "./relay.js";
import { ownsLease, type AuthorizeContext, type Role } from "./roles.js";
Expand All @@ -24,6 +29,7 @@ import {
deviceRecordSchema,
doctorReportSchema,
eventEnvelopeSchema,
EVENT_ID_PATTERN,
hostFactsSchema,
historyStatusSchema,
hostLoadSchema,
Expand Down Expand Up @@ -645,7 +651,13 @@ export const eventsReplay = defineOperation({
name: "events.replay",
role: "admin",
effect: "read",
input: z.object({ sinceTs: z.number().optional() }),
input: z
.object({
beforeId: z.string().regex(EVENT_ID_PATTERN).optional(),
limit: z.number().int().min(1).max(EVENTS_PAGE_MAX).optional(),
sinceTs: z.number().optional(),
})
.refine(eventsPageWithoutSince, { message: EVENTS_PAGE_WITH_SINCE_MESSAGE }),
output: z.array(eventEnvelopeSchema),
});

Expand Down
2 changes: 1 addition & 1 deletion src/contract/protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,6 @@ describe("helloRequestSchema", () => {

describe("PROTOCOL_VERSION_RANGE", () => {
it("is one above the base branch's, for the alerts.test operation", () => {
expect(PROTOCOL_VERSION_RANGE).toEqual({ max: 51, min: 51 });
expect(PROTOCOL_VERSION_RANGE).toEqual({ max: 52, min: 52 });
});
});
2 changes: 1 addition & 1 deletion src/contract/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export interface ProtocolRange {
const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() });

/** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 51, max: 51 };
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 52, max: 52 };

const LEGACY_DAEMON_PROTOCOL_VERSION = 2;

Expand Down
2 changes: 1 addition & 1 deletion src/daemon-protocol/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {

describe("daemon protocol", () => {
it("keeps the current protocol version and newline framing", () => {
expect(DAEMON_PROTOCOL_VERSION).toBe(51);
expect(DAEMON_PROTOCOL_VERSION).toBe(52);
expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n');
});

Expand Down
2 changes: 1 addition & 1 deletion src/daemon/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ An HTTP bind failure after a good start stops the daemon (`http-start-failed`).
Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid.
Both are fixed for the connection's life.
3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE`
is `{ min: 51, max: 51 }` (`src/contract/protocol.ts`). No overlap → the
is `{ min: 52, max: 52 }` (`src/contract/protocol.ts`). No overlap → the
connection stays open, and every request but `daemon.stop` gets
`PROTOCOL_VERSION_UNSUPPORTED`.
4. **Request** — one frame → one `dispatch()` call. While stopping: `DAEMON_STOPPING`.
Expand Down
26 changes: 26 additions & 0 deletions src/daemon/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
import type { z } from "zod";

import type { EventEnvelope } from "../bus/index.js";
import type { EventsPageRead } from "../history/index.js";
import type { Clock } from "../ports/clock.js";
import type { Logger } from "../ports/logger.js";
import type { LinkChannel } from "../link/index.js";
Expand Down Expand Up @@ -430,3 +432,27 @@ export async function usageAnswer(
{ oldestTs: result.oldestTs },
);
}

export async function eventsPageAnswer(read: Promise<EventsPageRead>): Promise<EventEnvelope[]> {
let result: EventsPageRead;
try {
result = await read;
} catch (error) {
throw new DispatchError(
"INTERNAL",
`The events could not be read: ${error instanceof Error ? error.message : String(error)}`,
);
}
if (result.kind === "events") return result.events;
if (result.kind === "unavailable") {
throw new DispatchError(
"HISTORY_UNAVAILABLE",
"The history could not be read, so no older events can be returned; see daemon.log.",
);
}
throw new DispatchError(
"HISTORY_NOT_KEPT",
`The history does not hold that event; it starts at ${new Date(result.oldestTs).toISOString()}.`,
{ oldestTs: result.oldestTs },
);
}
81 changes: 78 additions & 3 deletions src/daemon/dispatcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type { EventHistoryHandle } from "../history/index.js";
import {
fixedEventHistory,
HOUR,
plainProjection,
removeUsageRigs,
requested,
ringEventHistory,
Expand Down Expand Up @@ -133,8 +134,8 @@ function stallOptions(

function resolveEventHistoryOverride(
eventBus: EventBus,
override: Pick<EventHistoryHandle, "replay" | "status"> | undefined,
): Pick<EventHistoryHandle, "replay" | "status"> {
override: Pick<EventHistoryHandle, "replay" | "replayPage" | "status"> | undefined,
): Pick<EventHistoryHandle, "replay" | "replayPage" | "status"> {
return override ?? ringEventHistory(eventBus);
}

Expand Down Expand Up @@ -270,7 +271,7 @@ async function buildDispatcher(
readonly passthroughOverride?: PassthroughResolver;
readonly execEnv?: NodeJS.ProcessEnv;
/** Stands in for the event history, so `events.replay` can be checked against it. */
readonly eventHistory?: Pick<EventHistoryHandle, "replay" | "status">;
readonly eventHistory?: Pick<EventHistoryHandle, "replay" | "replayPage" | "status">;
readonly historyPath?: string;
readonly withoutTokens?: boolean;
/** `status.get`'s host block; a fixed machine with no tools by default. */
Expand Down Expand Up @@ -1358,6 +1359,7 @@ describe("Dispatcher: events.replay", () => {
asked.push(input);
return fromHistory;
},
replayPage: async () => ({ events: [], kind: "events" }),
status: () => ({ opened: true, writing: true }),
},
});
Expand All @@ -1369,6 +1371,77 @@ describe("Dispatcher: events.replay", () => {
});
});

describe("Dispatcher: events.replay paging", () => {
afterEach(removeUsageRigs);

const admin = session({ role: "admin" });

async function pagedRig(
rows: number,
options: Parameters<typeof usageRig>[0] = {},
): Promise<{
readonly rig: Awaited<ReturnType<typeof usageRig>>;
readonly ids: string[];
readonly dispatcher: Dispatcher;
}> {
const rig = await usageRig(options);
for (let row = 0; row < rows; row += 1) {
rig.at(T0 + row);
rig.emit("daemon.stopping", { reason: `r${row + 1}` });
}
const { dispatcher } = await buildDispatcher({ eventHistory: rig.history });
return { dispatcher, ids: rig.bus.replay().map((event) => event.id), rig };
}

const reasons = (events: readonly { readonly payload?: unknown }[]): unknown[] =>
events.map((event) => (event.payload as { reason: string }).reason);

it("events.replay with beforeId and limit pages through the worker dispatcher over a real history: the page, HISTORY_NOT_KEPT, an empty table, HISTORY_UNAVAILABLE, and 100 at most for beforeId alone", async () => {
const { dispatcher, ids } = await pagedRig(150);
const page = await dispatcher.dispatch(
"events.replay",
{ beforeId: ids[4] as string, limit: 2 },
admin,
);
expect(reasons(page)).toEqual(["r3", "r4"]);
const unbounded = await dispatcher.dispatch(
"events.replay",
{ beforeId: ids[149] as string },
admin,
);
expect(unbounded).toHaveLength(100);
await expect(
dispatcher.dispatch("events.replay", { beforeId: "evt_gone", limit: 2 }, admin),
).rejects.toMatchObject({ code: "HISTORY_NOT_KEPT", details: { oldestTs: T0 } });

const empty = await pagedRig(0);
await expect(
empty.dispatcher.dispatch("events.replay", { beforeId: "evt_any", limit: 2 }, admin),
).resolves.toEqual([]);

const failing = plainProjection("failing", () => ({
apply: () => {
throw new Error("projection broke");
},
prune: () => undefined,
}));
const notWriting = await pagedRig(1, { projections: [failing] });
expect(notWriting.rig.history.status().writing).toBe(false);
const unstarted = await buildDispatcher();
for (const { dispatcher: target } of [notWriting, unstarted]) {
await expect(
target.dispatch("events.replay", { beforeId: "evt_any", limit: 2 }, admin),
).rejects.toMatchObject({ code: "HISTORY_UNAVAILABLE" });
}
});

it("events.replay with limit alone returns the newest n events, oldest first, through the worker dispatcher", async () => {
const { dispatcher } = await pagedRig(5);
const page = await dispatcher.dispatch("events.replay", { limit: 2 }, admin);
expect(reasons(page)).toEqual(["r4", "r5"]);
});
});

describe("Dispatcher: config.get eventLog", () => {
it("config.get reports eventLog.retention and maxBytes and no rotateBytes", async () => {
const { dispatcher } = await buildDispatcher();
Expand Down Expand Up @@ -4507,6 +4580,8 @@ describe("Dispatcher: usage.get", () => {
const gate = { open: true };
const eventHistory = {
replay: (input?: { readonly sinceTs?: number }) => rig.history.replay(input),
replayPage: (input: { readonly beforeId?: string; readonly limit: number }) =>
rig.history.replayPage(input),
status: () => ({ ...rig.history.status(), opened: gate.open && rig.history.status().opened }),
};
return { eventHistory, gate, rig, ...options };
Expand Down
15 changes: 13 additions & 2 deletions src/daemon/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import {
capabilityReason,
type capabilitySchema,
consoleUrlField,
EVENTS_PAGE_DEFAULT,
fitPlatformCatalog,
OPERATIONS,
requestedDevice,
Expand All @@ -72,6 +73,7 @@ import {
DispatchError,
identityGet,
runDispatch,
eventsPageAnswer,
usageAnswer,
type DispatchSession,
type ErasedHandler,
Expand Down Expand Up @@ -137,7 +139,7 @@ export interface DispatcherOptions {
readonly components: Pick<ComponentInstaller, "install" | "inProgress" | "list" | "remove">;
readonly config: Config;
readonly doctor?: Doctor;
readonly eventHistory: Pick<EventHistoryHandle, "replay" | "status">;
readonly eventHistory: Pick<EventHistoryHandle, "replay" | "replayPage" | "status">;
readonly deviceModes: DeviceModeReader;
readonly leases: LeaseCommands;
readonly logger?: Logger;
Expand Down Expand Up @@ -812,7 +814,16 @@ export class Dispatcher {
#usageGet: Handler<"usage.get"> = (input) => usageAnswer(this.#usage.get(input));

#eventsReplay: Handler<"events.replay"> = (input) =>
this.options.eventHistory.replay(input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs });
input.beforeId === undefined && input.limit === undefined
? this.options.eventHistory.replay(
input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs },
)
: eventsPageAnswer(
this.options.eventHistory.replayPage({
...(input.beforeId === undefined ? {} : { beforeId: input.beforeId }),
limit: input.limit ?? EVENTS_PAGE_DEFAULT,
}),
);

#eventsSubscribe: Handler<"events.subscribe"> = (_input, session) => {
const subscriptionId = session.manageEventSubscription(true);
Expand Down
Loading
Loading