Merge current master into external agent sleep recovery

This commit is contained in:
Dotta committed 2026-11-14 23:58:18 -06:00
commit e5604f3e4d
88 files changed
+3360 -350

No files matched your search

@@ -0,0 +1,57 @@
import { AsyncLocalStorage } from "node:async_hooks";
import type { RequestHandler, Response } from "express";
export const AUTHORIZATION_READ_MAX_AGE_MS = 2_000;
type ReadScope = { open: boolean; entries: Map<string, { value: Promise<unknown>; readAt: number }> };
const reads = new AsyncLocalStorage<ReadScope>();
function closeWhenResponseStarts(res: Response, close: () => void) {
const { write, flushHeaders, writeHead } = res;
res.write = function (this: Response, ...args: Parameters<Response["write"]>) {
close();
return write.apply(this, args);
} as Response["write"];
res.flushHeaders = function (this: Response) {
close();
return flushHeaders.call(this);
};
res.writeHead = function (this: Response, ...args: Parameters<Response["writeHead"]>) {
close();
return writeHead.apply(this, args);
} as Response["writeHead"];
res.once("finish", close);
res.once("close", close);
}
export const authorizationReadScope: RequestHandler = (req, res, next) => {
if (req.method !== "GET" && req.method !== "HEAD") {
next();
return;
}
const scope: ReadScope = { open: true, entries: new Map() };
const actor = req.actor;
if (actor?.type === "board" && actor.source === "session" && actor.userId && typeof actor.isInstanceAdmin === "boolean") {
scope.entries.set(`admin:${actor.userId}`, { value: Promise.resolve(actor.isInstanceAdmin), readAt: Date.now() });
}
closeWhenResponseStarts(res, () => {
scope.open = false;
scope.entries.clear();
});
reads.run(scope, next);
};
export function readOncePerRequest<T>(key: string, read: () => Promise<T>): Promise<T> {
const scope = reads.getStore();
if (!scope?.open) return read();
const now = Date.now();
const cached = scope.entries.get(key);
if (cached && now - cached.readAt <= AUTHORIZATION_READ_MAX_AGE_MS) return cached.value as Promise<T>;
const entry = { value: read() as Promise<unknown>, readAt: now };
scope.entries.set(key, entry);
entry.value.catch(() => {
if (scope.entries.get(key) === entry) scope.entries.delete(key);
});
return entry.value as Promise<T>;
}
+16 -26
View File
@@ -1,3 +1,4 @@
import { readOncePerRequest } from "./authorization-read-scope.js";
import { and, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agentInteractionDenial, type AgentInteractionDenial, type AgentInteractionOperation } from "./agent-interaction-policy.js";
@@ -725,14 +726,21 @@ export async function canActorReadIssuePrivacy(db: Db | DbTransaction, actor: Au
}
/** Filter every externally reachable task query with the same privacy predicate. */
export async function readInstanceAdmin(db: Db | DbTransaction, userId: string): Promise<boolean> {
return db
.select({ id: instanceUserRoles.id })
.from(instanceUserRoles)
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
.limit(1)
.then((rows) => rows.length > 0);
}
export async function issueReadSqlCondition(db: Db | DbTransaction, actor: AuthorizationActor): Promise<SQL<boolean>> {
if (actor.authorizingUserId) return issuePrivacyCondition(actor);
if (issuePrivacyMode() !== "enforce") return sql<boolean>`true`;
if (actor.source === "local_implicit" || actor.isInstanceAdmin) return sql<boolean>`true`;
if (actor.type === "board" && !actor.ignoreInstanceAdmin && actor.source !== "cloud_tenant"
&& await db.select({ id: instanceUserRoles.id }).from(instanceUserRoles)
.where(and(eq(instanceUserRoles.userId, actor.userId ?? ""), eq(instanceUserRoles.role, "instance_admin")))
.limit(1).then(rows => rows.length > 0)) return sql<boolean>`true`;
&& await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))) return sql<boolean>`true`;
return issuePrivacyCondition(actor);
}
@@ -745,15 +753,7 @@ export async function projectReadSqlCondition(db: Db | DbTransaction, actor: Aut
actor.type === "board"
&& !actor.ignoreInstanceAdmin
&& actor.source !== "cloud_tenant"
&& Boolean(await db
.select({ id: instanceUserRoles.id })
.from(instanceUserRoles)
.where(and(
eq(instanceUserRoles.userId, actor.userId ?? ""),
eq(instanceUserRoles.role, "instance_admin"),
))
.limit(1)
.then((rows) => rows[0] ?? null))
&& await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))
) return sql<boolean>`true`;
return projectPrivacyCondition(actor);
}
@@ -928,18 +928,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
async function isInstanceAdmin(userId: string | null | undefined): Promise<boolean> {
if (!userId) return false;
return batchRead(`admin:${userId}`, async () => {
if (
await db
.select({ id: instanceUserRoles.id })
.from(instanceUserRoles)
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
.then((rows) => rows[0] ?? null)
) {
return true;
}
return false;
});
return batchRead(`admin:${userId}`, () => readOncePerRequest(`admin:${userId}`, () => readInstanceAdmin(db, userId)));
}
async function getActiveMembership(
@@ -947,7 +936,8 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
principalType: PrincipalType,
principalId: string,
) {
return batchRead(`membership:${companyId}:${principalType}:${principalId}`, async () => {
const key = `membership:${companyId}:${principalType}:${principalId}`;
return batchRead(key, () => readOncePerRequest(key, async () => {
return db
.select()
.from(companyMemberships)
@@ -960,7 +950,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
),
)
.then((rows) => rows[0] ?? null);
});
}));
}
async function loadResponsibleUserSnapshot(companyId: string, userId: string): Promise<ResponsibleUserSnapshot> {
@@ -1,4 +1,4 @@
import { readGitHubResponseRun } from "./response-run-state.js";
import { readGitHubResponseRuns, type GitHubResponseRunRead } from "./response-run-state.js";
import { githubRunReplyState } from "../../chat-run-publications.js";
import { and, asc, eq, gt, isNotNull, or, sql } from "drizzle-orm";
import { chatActions, chatConversations, chatEndpointLeases, chatEndpointResources,
@@ -57,16 +57,34 @@ export function registerGitHubAcknowledgementWork(
actionId ? eq(chatActions.id, actionId) : undefined,
)).orderBy(asc(chatActions.id)).limit(100);
}
async function entry(row: Awaited<ReturnType<typeof page>>[number]): Promise<Entry | null> {
const { latestRun, ownsLatestRequest } = await readGitHubResponseRun(db, {
companyId: row.companyId, endpointId: row.endpointId, agentId: row.agentId,
issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId,
});
// Execution success alone does not decide whether a final response exists.
// Presentation/publication commits invalidate this parked request.
if (row.issueId && ownsLatestRequest && latestRun?.nativePresentationPending &&
await githubRunReplyState(db, { companyId: row.companyId, endpointId: row.endpointId,
issueId: row.issueId, runId: latestRun.id }) === "none") return null;
type Row = Awaited<ReturnType<typeof page>>[number];
async function entry(row: Row, read: GitHubResponseRunRead): Promise<Entry | null> {
// A request whose requester provenance changed stays due, so the
// acknowledgement owner revokes it. It must not stop the rest of the page.
if (!("forbidden" in read)) {
const { latestRun, ownsLatestRequest } = read;
// Execution success alone does not decide whether a final response exists.
// Presentation/publication commits invalidate this parked request.
if (row.issueId && ownsLatestRequest && latestRun?.nativePresentationPending &&
await githubRunReplyState(db, { companyId: row.companyId, endpointId: row.endpointId,
issueId: row.issueId, runId: latestRun.id }) === "none") return null;
}
return schedule(row);
}
/** The entries of a page, by position, from one batched run-state read. */
async function entries(rows: Row[]) {
const reads = await readGitHubResponseRuns(db, rows.map(row => ({ companyId: row.companyId, endpointId: row.endpointId,
agentId: row.agentId, issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId })));
const values: Array<Entry | null> = [];
for (const [index, row] of rows.entries()) values.push(await entry(row, reads[index]!));
return values;
}
async function current(actionId: string) {
const [row] = await page(undefined, undefined, actionId);
return row ? (await entries([row]))[0] ?? null : null;
}
/** When the request is due, from its own row. */
function schedule(row: Row): Entry | null {
let dueAt = row.status === "failed" ? Date.parse(String(row.result?.retryAt)) : 0;
if (!Number.isFinite(dueAt)) throw new Error("GitHub acknowledgement has an invalid retry deadline");
const fast = row.fast;
@@ -89,23 +107,24 @@ export function registerGitHubAcknowledgementWork(
(!scope.endpointId || value.endpointId === scope.endpointId) && (!scope.repositoryId || value.repositoryId === scope.repositoryId) &&
(!scope.number || value.number === scope.number)),
load: async (scope?: Scope, signal?: AbortSignal) => {
const entries: Entry[] = [];
const loaded: Entry[] = [];
let cursor: string | undefined;
while (canRun() && !signal?.aborted) {
const rows = await page(scope, cursor);
for (const row of rows) { const value = await entry(row); if (value) entries.push(value); }
if (rows.length < 100) return entries;
for (const value of await entries(rows)) if (value) loaded.push(value);
if (rows.length < 100) return loaded;
cursor = rows[rows.length - 1].id;
}
throw signal?.reason ?? new Error("GitHub acknowledgement recovery stopped");
},
check: async (value: Entry, signal?: AbortSignal) => {
const [row] = await page(undefined, undefined, value.id);
const current = row ? await entry(row) : null;
if (!current || current.dueAt > Date.now() || !canRun() || signal?.aborted) return current;
await acknowledge(current.deliveryId, () => canRun() && !signal?.aborted);
const due = await current(value.id);
if (!due || due.dueAt > Date.now() || !canRun() || signal?.aborted) return due;
await acknowledge(due.deliveryId, () => canRun() && !signal?.aborted);
// A request that is still owed keeps its saved deadline. The next check
// reads its run state again before it acknowledges.
const [remaining] = await page(undefined, undefined, value.id);
return remaining ? await entry(remaining) : null;
return remaining ? schedule(remaining) : null;
},
}, canRun);
}
@@ -1,6 +1,6 @@
import type { Db } from "@paperclipai/db";
import { githubRunReplyState } from "../../chat-run-publications.js";
import { readGitHubResponseRun } from "./response-run-state.js";
import { readGitHubResponseRun, type GitHubResponseRunRead } from "./response-run-state.js";
export { responseRunColumns as githubResponseRunColumns } from "./response-run-state.js";
export type GitHubResponseExecutionInput = {
@@ -14,8 +14,11 @@ export type GitHubResponseExecutionInput = {
deliveryCreatedAt: Date;
};
export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput) {
const { latestRun, ownsLatestRequest } = await readGitHubResponseRun(db, input);
/** `read` is this request's state from a batched page read, if the caller has it. */
export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput, read?: GitHubResponseRunRead) {
const state = read ?? await readGitHubResponseRun(db, input);
if ("forbidden" in state) throw state.forbidden;
const { latestRun, ownsLatestRequest } = state;
const requestRunning = ownsLatestRequest && latestRun?.status === "running";
const terminal = latestRun && ["succeeded", "failed", "interrupted", "timed_out", "cancelled"].includes(latestRun.status);
const run = terminal && (ownsLatestRequest || input.issueStatus === "blocked") ? latestRun : null;
@@ -4,7 +4,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { chatMessageLinks, createDb, heartbeatRuns, type Db } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
import { chatRunSourceMessageId } from "../run-origin.js";
import { readGitHubResponseRun, responseRunColumns } from "./response-run-state.js";
import { readGitHubResponseRun, readGitHubResponseRuns, responseRunColumns } from "./response-run-state.js";
const support = await getEmbeddedPostgresTestSupport();
const suite = support.supported ? describe : describe.skip;
@@ -195,6 +195,18 @@ suite("GitHub response run state", () => {
.toEqual(new Set(["native", "legacy"]));
}, 120_000);
it("reads a page of requests in one latest-run statement with the state each single read returns", async () => {
const all = inputs();
const single = [];
for (const input of all) single.push(await readGitHubResponseRun(db, input));
const statements: string[] = [], prior = db.$client.options.debug;
db.$client.options.debug = (_connection, query) => { statements.push(query); };
let batch;
try { batch = await readGitHubResponseRuns(db, all); } finally { db.$client.options.debug = prior; }
expect(batch).toEqual(single);
expect(statements.filter(query => /from "heartbeat_runs"|join "heartbeat_runs"/.test(query))).toHaveLength(1);
}, 120_000);
it("reads a few runs of the issue, not the agent's whole run history", async () => {
const tenant = tenants[0]!;
const request = tenant.requests[0]!;
@@ -1,6 +1,7 @@
import { and, eq, sql } from "drizzle-orm";
import { and, eq, sql, type SQL } from "drizzle-orm";
import { chatMessageLinks, heartbeatRuns, type Db } from "@paperclipai/db";
import { chatRunSourceMessageId } from "../run-origin.js";
import type { HttpError } from "../../../errors.js";
import { chatRunSourceMessageId, chatRunSourceMessageIds } from "../run-origin.js";
export const responseRunColumns = {
id: heartbeatRuns.id,
@@ -47,35 +48,97 @@ export const responseRunColumns = {
'wakeCommentIds', ${heartbeatRuns.contextSnapshot}->'wakeCommentIds'
)`,
};
/** Shared request ownership and presentation state for delivery and recovery. */
export async function readGitHubResponseRun(db: Db, input: {
export type GitHubResponseRunInput = {
companyId: string; endpointId: string; agentId: string; issueId: string | null;
deliveryId: string; sourceMessageId: string | null;
}) {
const { issueId } = input;
if (!issueId) return { latestRun: undefined, ownsLatestRequest: false };
const latestRunId = sql`(select latest.id from (
(select r.id, r.created_at from ${heartbeatRuns} r
where r.company_id = ${input.companyId} and r.native_issue_id = ${issueId} and r.agent_id = ${input.agentId}
order by r.created_at desc, r.id desc limit 1)
union all
(select r.id, r.created_at from ${heartbeatRuns} r
where r.company_id = ${input.companyId} and r.native_issue_id is null
and r.context_snapshot->>'issueId' = ${issueId} and r.agent_id = ${input.agentId}
order by r.created_at desc, r.id desc limit 1)
) latest order by latest.created_at desc, latest.id desc limit 1)`;
const wokeForRequest = sql<boolean>`exists (select 1 from ${chatMessageLinks} l
where l.company_id = ${input.companyId} and l.endpoint_id = ${input.endpointId}
and l.delivery_id = ${input.deliveryId} and l.direction = 'inbound'
and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'
or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`;
const [row] = await db.select({ ...responseRunColumns, wokeForRequest }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, input.companyId), sql`${heartbeatRuns.id} = ${latestRunId}`));
};
type RunRow = Omit<Awaited<ReturnType<typeof readRunRows>>[number], "ordinal">;
export type GitHubResponseRunState = { latestRun: Omit<RunRow, "wokeForRequest"> | undefined; ownsLatestRequest: boolean };
/** The state of one request of a batch, or the 403 that its single read throws. */
export type GitHubResponseRunRead = GitHubResponseRunState | { forbidden: HttpError };
/** A value of the run reads: a literal of one request in a single read, or a
* column of the request row in a batch read. */
type Value = string | SQL;
type Of = Record<"companyId" | "endpointId" | "agentId" | "issueId" | "deliveryId", Value>;
/** The assigned agent's latest run bound to the issue, where a run's issue is
* coalesce(native_issue_id, context_snapshot->>'issueId'). The two precedence
* branches are disjoint and each uses an issue index. */
const latestRunId = (of: Of) => sql`(select latest.id from (
(select r.id, r.created_at from ${heartbeatRuns} r
where r.company_id = ${of.companyId}::uuid and r.native_issue_id = ${of.issueId}::uuid and r.agent_id = ${of.agentId}::uuid
order by r.created_at desc, r.id desc limit 1)
union all
(select r.id, r.created_at from ${heartbeatRuns} r
where r.company_id = ${of.companyId}::uuid and r.native_issue_id is null
and r.context_snapshot->>'issueId' = ${of.issueId}::text and r.agent_id = ${of.agentId}::uuid
order by r.created_at desc, r.id desc limit 1)
) latest order by latest.created_at desc, latest.id desc limit 1)`;
/** Whether the run woke for one of the request's inbound comments. */
const wokeForRequest = (of: Of) => sql<boolean>`exists (select 1 from ${chatMessageLinks} l
where l.company_id = ${of.companyId}::uuid and l.endpoint_id = ${of.endpointId}::uuid
and l.delivery_id = ${of.deliveryId}::uuid and l.direction = 'inbound'
and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'
or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`;
const request = sql.identifier("github_response_request");
const column = (name: string) => sql`${request}.${sql.identifier(name)}`;
const columns: Array<[keyof Of, string]> = [["companyId", "company_id"], ["endpointId", "endpoint_id"],
["agentId", "agent_id"], ["issueId", "issue_id"], ["deliveryId", "delivery_id"]];
/** The latest run of each request, in one statement. For each request row the
* lateral subquery is the single read with the request columns in place of
* the literals. */
async function readRunRows(db: Db, inputs: Array<GitHubResponseRunInput & { issueId: string }>) {
const of = Object.fromEntries(columns.map(([key, name]) => [key, column(name)])) as Of;
return db.select({ ordinal: sql<number>`${column("ordinal")}`.mapWith(Number), ...responseRunColumns,
wokeForRequest: wokeForRequest(of) })
.from(sql`unnest(${sql.join(columns.map(([key]) => sql`${sql.param(inputs.map(input => input[key]))}::uuid[]`), sql`, `)})
with ordinality as ${request}(${sql.join([...columns.map(([, name]) => sql.identifier(name)), sql.identifier("ordinal")], sql`, `)})
cross join lateral (select ${latestRunId(of)} as id) latest_request_run`)
.innerJoin(heartbeatRuns, and(sql`${heartbeatRuns.id} = latest_request_run.id`,
sql`${heartbeatRuns.companyId} = ${column("company_id")}`));
}
function ownership(input: GitHubResponseRunInput, row: RunRow | undefined, originMessageId: string | null): GitHubResponseRunState {
if (!row) return { latestRun: undefined, ownsLatestRequest: false };
const { wokeForRequest: requestRunIsLatest, ...latestRun } = row;
const originMessageId = latestRun.activeIdentityContextId ? await chatRunSourceMessageId(db, latestRun,
{ allowLegacyWakeComment: true, provider: "github" }) : null;
const ownsLatestRequest = requestRunIsLatest ||
(!!input.sourceMessageId && originMessageId === input.sourceMessageId);
return { latestRun, ownsLatestRequest };
}
/** Shared request ownership and presentation state for delivery and recovery. */
export async function readGitHubResponseRun(db: Db, input: GitHubResponseRunInput): Promise<GitHubResponseRunState> {
const { issueId } = input;
if (!issueId) return { latestRun: undefined, ownsLatestRequest: false };
const of = { ...input, issueId };
const [row] = await db.select({ ...responseRunColumns, wokeForRequest: wokeForRequest(of) }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, input.companyId), sql`${heartbeatRuns.id} = ${latestRunId(of)}`));
const originMessageId = row?.activeIdentityContextId ? await chatRunSourceMessageId(db, row,
{ allowLegacyWakeComment: true, provider: "github" }) : null;
return ownership(input, row, originMessageId);
}
/** `readGitHubResponseRun` for a page of requests: one latest-run read for the
* whole page, then one batched provenance check of its distinct runs, which
* reuses the single check's reads. Each request gets, by position, the state a
* separate call returns or the 403 that call throws. */
export async function readGitHubResponseRuns(db: Db, inputs: GitHubResponseRunInput[]): Promise<GitHubResponseRunRead[]> {
const bound = inputs.flatMap((input, index) => input.issueId ? [{ index, input: { ...input, issueId: input.issueId } }] : []);
const found = new Map<number, RunRow>();
if (bound.length) {
for (const { ordinal, ...row } of await readRunRows(db, bound.map(entry => entry.input))) found.set(bound[ordinal - 1]!.index, row);
}
const runs = [...new Map([...found.values()].filter(row => row.activeIdentityContextId).map(row => [row.id, row])).values()];
const checked = await chatRunSourceMessageIds(db, runs, { allowLegacyWakeComment: true, provider: "github" });
const origins = new Map(runs.map((run, index) => [run.id, checked[index]!]));
return inputs.map((input, index) => {
const row = found.get(index);
const origin = row ? origins.get(row.id) : undefined;
if (origin && "forbidden" in origin) return { forbidden: origin.forbidden };
return ownership(input, row, origin?.messageId ?? null);
});
}
@@ -68,7 +68,12 @@ suite("GitHub response sweep scopes", () => {
builder.from = ((...args: Parameters<typeof from>) => {
const selection = from(...args), execute = selection.execute.bind(selection);
selection.execute = (async () => {
if (selection.toSQL().sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) reads += 1;
// Count requests whose run state is read. A batched read names its
// requests in arrays, so count the requests rather than statements.
const query = selection.toSQL();
if (query.sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) {
reads += Array.isArray(query.params[0]) ? query.params[0].length : 1;
}
return execute();
}) as typeof selection.execute;
return selection;
@@ -7,6 +7,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro
import { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js";
import { idleWorkSnapshot } from "../../task-admission.js";
import { registerGitHubAcknowledgementWork } from "./acknowledgement-work.js";
import { registerGitHubTerminalResponseWork } from "./terminal-response-work.js";
const support = await getEmbeddedPostgresTestSupport();
@@ -40,7 +41,9 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", ()
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); });
type Request = { issueId: string; deliveryId: string; actionId: string; commentId: string };
async function seed() {
/** `waiting`: processed, non-final responses as on staging. `received`: every
* request still owes its first acknowledgement. */
async function seed(shape: "waiting" | "received" = "waiting") {
const client = db.$client;
const companyId = randomUUID(), agentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "GitHub backlog", issuePrefix: `G${companyId.slice(0, 7)}` });
@@ -75,13 +78,14 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", ()
const latest = request === STALE_PER_ISSUE;
const [action] = await db.insert(chatActions).values({ companyId, endpointId: endpoint, conversationId: conversation,
deliveryId: delivery, kind: "github_response_comment", providerActionId: `github_response:${delivery}`,
payload: { agentId }, status: "processed",
result: { id: String(1_000 + index), url: `https://github.com/paperclipai/paperclip/pull/${issueNumber}#c${index}`,
payload: { agentId }, status: shape === "received" ? "received" : "processed",
result: shape === "received" ? null : { id: String(1_000 + index),
url: `https://github.com/paperclipai/paperclip/pull/${issueNumber}#c${index}`,
final: latest, versionAt: new Date(base).toISOString(), ...(latest ? {} : { code: code(index) }) },
updatedAt: new Date(base + index * 60_000) }).returning();
requests.push({ issueId: issue, deliveryId: delivery, actionId: action!.id, commentId: comment });
}
stale.push(...requests.slice(0, STALE_PER_ISSUE));
stale.push(...(shape === "received" ? requests : requests.slice(0, STALE_PER_ISSUE)));
// The latest run answered the newest request, through its identity context.
const runId = randomUUID(), contextId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issue, issueId: issue,
@@ -95,13 +99,14 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", ()
return { companyId, agentId, endpointId: endpoint as string, stale, runs };
}
async function start() {
async function start(register: typeof registerGitHubTerminalResponseWork = registerGitHubTerminalResponseWork) {
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true,
onError: error => errors.push(error) });
const worker = registerGitHubTerminalResponseWork(db, coordinator, async deliveryId => {
const worker = register(db, coordinator, async deliveryId => {
acknowledged.push(deliveryId);
// Stand in for the real acknowledgement, which records a final response.
await db.update(chatActions).set({ result: sql`${chatActions.result} || '{"final": true}'::jsonb`, updatedAt: new Date() })
await db.update(chatActions).set({ status: "processed", updatedAt: new Date(),
result: sql`coalesce(${chatActions.result}, '{}'::jsonb) || '{"final": true}'::jsonb` })
.where(and(eq(chatActions.deliveryId, deliveryId), eq(chatActions.kind, "github_response_comment")));
}, () => true);
await worker.ready;
@@ -150,6 +155,31 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", ()
expect(await finals(f.stale.map(request => request.actionId))).toBe(0);
}, 300_000);
it("reads a page of waiting responses in a constant number of statements", async () => {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
await seed();
const first = await observe(async () => { await start(); await advance(5_000); });
console.info(`terminal response sweep, first pass: ${first.statements} statements `
+ `(${first.provenance} run identity reads) for ${STALE} rows in 2 pages`);
expect(acknowledged).toEqual([]);
// Per page: the page, its latest runs, the batched context and link reads, and the wait keys.
expect(first.provenance).toBeLessThanOrEqual(2);
expect(first.statements).toBeLessThanOrEqual(2 * 5);
}, 300_000);
it("acknowledges every owed request of a page when one run's requester provenance changed", async () => {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
const f = await seed("received");
// One task's latest run lost its accepted identity context, so reading its
// requester provenance is forbidden. Only that task's requests are affected.
await db.update(runIdentityContexts).set({ status: "revoked" }).where(eq(runIdentityContexts.runId, f.runs[3]!.runId));
const first = await observe(async () => { await start(registerGitHubAcknowledgementWork); await advance(30_000); });
console.info(`acknowledgement sweep: ${first.statements} statements (${first.provenance} run identity reads) `
+ `for ${f.stale.length} owed requests`);
expect(new Set(acknowledged)).toEqual(new Set(f.stale.map(request => request.deliveryId)));
expect(acknowledged).toHaveLength(f.stale.length);
}, 300_000);
it("still settles a waiting response once a run that owns it ends", async () => {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
const f = await seed();
@@ -5,6 +5,7 @@ import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordina
import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js";
import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js";
import { githubResponseExecution } from "./response-execution.js";
import { readGitHubResponseRuns, type GitHubResponseRunRead } from "./response-run-state.js";
import { githubResponseReconstructionIntervalMs, type GitHubResponseSweepScope as Scope } from "./response-sweep-scope.js";
import { HttpError } from "../../../errors.js";
type Entry = { id: string; companyId: string; endpointId: string; deliveryId: string;
@@ -87,12 +88,9 @@ export function registerGitHubTerminalResponseWork(
* recorded. A wait on the owning run's reply or presentation is never
* recorded: a publication that commits it changes no wait-key input, and a
* restart can lose the hint that its lease release sends. */
async function entry(row: Row): Promise<Entry | { parkable: boolean }> {
const pending: Entry = { id: row.id, companyId: row.companyId, endpointId: row.endpointId, deliveryId: row.deliveryId!,
issueId: row.issueId, conversationId: row.conversationId, repositoryId: row.repositoryId,
number: row.number ? Number(row.number) : null, dueAt: row.leaseExpiresAt ? Date.parse(row.leaseExpiresAt) : 0 };
async function entry(row: Row, read: GitHubResponseRunRead): Promise<Entry | { parkable: boolean }> {
try {
const execution = await githubResponseExecution(db, { ...row, agentId: row.agentId!, deliveryId: row.deliveryId! });
const execution = await githubResponseExecution(db, { ...row, agentId: row.agentId!, deliveryId: row.deliveryId! }, read);
if (execution.body === undefined || execution.reply === "unsettled" ||
(execution.paused && row.result?.pausedVersion === execution.version))
return { parkable: !execution.presentationPending && execution.reply === "none" };
@@ -101,7 +99,24 @@ export function registerGitHubTerminalResponseWork(
// Keep this request eligible for the acknowledgement owner's authority
// check and cancellation; it must not poison discovery for other requests.
}
return pending;
return pending(row);
}
/** The request's entry, before its run state is read. */
function pending(row: Row): Entry {
return { id: row.id, companyId: row.companyId, endpointId: row.endpointId, deliveryId: row.deliveryId!,
issueId: row.issueId, conversationId: row.conversationId, repositoryId: row.repositoryId,
number: row.number ? Number(row.number) : null, dueAt: row.leaseExpiresAt ? Date.parse(row.leaseExpiresAt) : 0 };
}
/** The entries of a page, by position, from one batched run-state read. */
async function entries(rows: Row[], signal?: AbortSignal) {
const reads = await readGitHubResponseRuns(db, rows.map(row => ({ companyId: row.companyId, endpointId: row.endpointId,
agentId: row.agentId!, issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId })));
const values: Array<Awaited<ReturnType<typeof entry>>> = [];
for (const [index, row] of rows.entries()) {
if (!canRun() || signal?.aborted) throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped");
values.push(await entry(row, reads[index]!));
}
return values;
}
/** Record the wait of requests that cannot progress yet. A request whose row
* changed after the read gets no key and is read again. The write leaves
@@ -119,8 +134,8 @@ export function registerGitHubTerminalResponseWork(
async function current(actionId: string) {
const [row] = await page(undefined, undefined, actionId);
if (!row) return null;
const value = await entry(row);
if (!("parkable" in value)) return value;
const [value] = await entries([row]);
if (!("parkable" in value!)) return value!;
if (value.parkable) await park([row]);
return null;
}
@@ -135,18 +150,17 @@ export function registerGitHubTerminalResponseWork(
(!scope.endpointId || value.endpointId === scope.endpointId) && (!scope.repositoryId || value.repositoryId === scope.repositoryId) &&
(!scope.number || value.number === scope.number)),
load: async (scope?: Scope, signal?: AbortSignal) => {
const entries: Entry[] = [];
const loaded: Entry[] = [];
let cursor: string | undefined;
while (canRun() && !signal?.aborted) {
const rows = await page(scope, cursor);
const values = await entries(rows, signal);
const waiting: Row[] = [];
for (const row of rows) {
if (!canRun() || signal?.aborted) throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped");
const value = await entry(row);
if (!("parkable" in value)) entries.push(value); else if (value.parkable) waiting.push(row);
for (const [index, value] of values.entries()) {
if (!("parkable" in value)) loaded.push(value); else if (value.parkable) waiting.push(rows[index]!);
}
await park(waiting);
if (rows.length < 100) return entries;
if (rows.length < 100) return loaded;
cursor = rows[rows.length - 1].id;
}
throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped");
@@ -155,7 +169,10 @@ export function registerGitHubTerminalResponseWork(
const due = await current(value.id);
if (!due || due.dueAt > Date.now() || !canRun() || signal?.aborted) return due;
await acknowledge(due.deliveryId, () => canRun() && !signal?.aborted);
return current(value.id);
// Keep a request that still waits for the next check, which reads its
// run state again before it acknowledges. One check reads it once.
const [remaining] = await page(undefined, undefined, value.id);
return remaining ? pending(remaining) : null;
},
}, canRun);
}
@@ -18,6 +18,7 @@ import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { NativeExecutionContext } from "./native-runtime/native-execution-context.js";
import { assertPluginTaskSourceAttachment, assertPluginTaskSourceRecovery } from "./native-runtime/plugin-task-source-recovery.js";
import { pluginAgentRuntimeIdentity } from "./plugin-agent-runtime-state.js";
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest } from "../vendor/paperclip-runner/index.js";
import { assertPluginTaskOwnershipDispatch, PluginTaskOwnershipPendingError, readyPortableTaskSource, reconcilePluginTaskAdmission } from "./plugin-task-ownership.js";
export type PluginTaskDescription = Extract<PluginEnvironmentTaskResult, { kind: "description" }>;
@@ -61,6 +62,12 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
expectedTaskId?: string;
}): Promise<PluginEnvironmentTaskResult> {
const operation = environmentTaskOperationSchema.parse(input.operation);
if (operation.kind === "prepare" && (operation.preparationDigest !== undefined || operation.runDigest !== undefined)) {
const preparationDigest = runnerLaunchPreparationDigest(operation.requirements as Parameters<typeof runnerLaunchPreparationDigest>[0]);
if (operation.preparationDigest !== preparationDigest || operation.runDigest !== runnerLaunchRunDigest(preparationDigest, operation.requirements as Parameters<typeof runnerLaunchRunDigest>[1])) {
throw new Error("Plugin Runner launch digest mismatch");
}
}
const [row] = await db.select({ lease: environmentLeases, environment: environments, run: heartbeatRuns })
.from(environmentLeases)
.leftJoin(environments, eq(environments.id, environmentLeases.environmentId))
@@ -534,12 +541,13 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
}
if (freshWorkspace && parsed.kind === "description" && parsed.freshWorkspaceVersion !== 1)
throw new Error("Plugin-provided fresh workspace preparation unavailable");
if (operation.kind === "prepare" && parsed.kind === "prepared" && parsed.projectAuthCheckAtSubmit) {
if (operation.kind === "prepare" && parsed.kind === "prepared" && (parsed.projectAuthChecked || parsed.projectAuthCheckAtSubmit)) {
const harness = operation.requirements.provider === "acpx" ? operation.requirements.settings.acpxAgent : operation.requirements.provider;
if (!harness) throw new Error("Plugin Runner prepared provider unavailable");
const provider = harness === "codex" ? "openai" : harness === "claude" ? "anthropic" : harness;
const saved = await db.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({
runnerTaskProjectAuthValidation: { configurationId: parsed.launch.configurationId, provider, projectIds, atSubmit: true },
runnerTaskProjectAuthValidation: { configurationId: parsed.launch.configurationId, provider, projectIds,
...(parsed.projectAuthChecked ? {} : { atSubmit: true }) },
})}::jsonb` }).where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, input.companyId),
eq(environmentLeases.status, "active"), sql`coalesce(${environmentLeases.metadata}->>'runnerTaskRetiring', 'false') != 'true'`)).returning({ id: environmentLeases.id });
if (saved.length !== 1) throw new Error("Plugin Runner project validation lease expired");
+29 -15
View File
@@ -544,14 +544,23 @@ export function folderService(db: Db, mutationLockHeld = false) {
throw conflict("Could not create project skill folder");
}
async function findCurrentBundledCategory(companyId: string, systemKey: string, name: string) {
const rows = await getRows(companyId, "skill");
const existing = rows.find((row) => row.systemKey === systemKey);
if (!existing || existing.name !== name || !rows.some((row) => row.systemKey === "bundled")) return null;
return buildFolderViews(rows).get(existing.id) ?? null;
}
async function ensureBundledCategory(companyId: string, category: string): Promise<Folder> {
if (!mutationLockHeld) {
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).ensureBundledCategory(companyId, category));
}
const root = await ensureContainer(companyId, "bundled", "Bundled");
const name = normalizeName(category);
const slug = normalizeFolderSlug(category);
const systemKey = `bundled:${slug}`;
if (!mutationLockHeld) {
const current = await findCurrentBundledCategory(companyId, systemKey, name);
if (current) return current;
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).ensureBundledCategory(companyId, category));
}
const root = await ensureContainer(companyId, "bundled", "Bundled");
for (let attempt = 0; attempt < 3; attempt += 1) {
const resolved = await uniqueSystemSlug(companyId, root.id, slug, systemKey, "bundled");
if (resolved.id) {
@@ -576,16 +585,15 @@ export function folderService(db: Db, mutationLockHeld = false) {
throw conflict("Could not create bundled skill folder");
}
async function pruneEmptyBundledCategories(companyId: string, retainedCategories: string[]): Promise<void> {
if (!mutationLockHeld) {
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).pruneEmptyBundledCategories(companyId, retainedCategories));
}
const root = await findSystemFolder(companyId, "bundled");
if (!root) return;
const rows = await getRows(companyId, "skill");
async function emptyBundledCategoryIds(companyId: string, retainedCategories: string[], rows: FolderRow[]) {
const root = rows.find((row) => row.kind === "skill" && row.systemKey === "bundled");
if (!root) return [];
const retainedSystemKeys = new Set(
retainedCategories.map((category) => `bundled:${normalizeFolderSlug(category)}`),
);
const candidates = rows.filter((row) => row.parentId === root.id && row.systemKey?.startsWith("bundled:")
&& !retainedSystemKeys.has(row.systemKey));
if (candidates.length === 0) return [];
const usedFolderIds = new Set(
await db
.select({ folderId: companySkills.folderId })
@@ -594,10 +602,16 @@ export function folderService(db: Db, mutationLockHeld = false) {
.then((skills) => skills.flatMap((skill) => skill.folderId ? [skill.folderId] : [])),
);
const parentIds = new Set(rows.flatMap((row) => row.parentId ? [row.parentId] : []));
for (const row of rows) {
if (row.parentId !== root.id || !row.systemKey?.startsWith("bundled:")) continue;
if (retainedSystemKeys.has(row.systemKey) || usedFolderIds.has(row.id) || parentIds.has(row.id)) continue;
await db.delete(folders).where(and(eq(folders.companyId, companyId), eq(folders.id, row.id)));
return candidates.filter((row) => !usedFolderIds.has(row.id) && !parentIds.has(row.id)).map((row) => row.id);
}
async function pruneEmptyBundledCategories(companyId: string, retainedCategories: string[]): Promise<void> {
if (!mutationLockHeld) {
if ((await emptyBundledCategoryIds(companyId, retainedCategories, await getRows(companyId, "skill"))).length === 0) return;
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).pruneEmptyBundledCategories(companyId, retainedCategories));
}
for (const id of await emptyBundledCategoryIds(companyId, retainedCategories, await getRows(companyId, "skill"))) {
await db.delete(folders).where(and(eq(folders.companyId, companyId), eq(folders.id, id)));
}
}
+6 -2
View File
@@ -343,8 +343,12 @@ export function issueReferenceService(db: Db) {
}
}
async function listIssueReferenceSummary(issueId: string, dbOrTx: any = db): Promise<IssueRelatedWorkSummary> {
const issue = await issueById(issueId, dbOrTx);
async function listIssueReferenceSummary(
issueId: string,
dbOrTx: any = db,
known?: { companyId: string },
): Promise<IssueRelatedWorkSummary> {
const issue = known ? { id: issueId, companyId: known.companyId } : await issueById(issueId, dbOrTx);
if (!issue) throw notFound("Issue not found");
const [outboundRows, inboundRows] = await Promise.all([
@@ -3429,7 +3429,10 @@ export function issueThreadInteractionService(
woken,
};
},
listForIssue: async (issueId: string) => {
listForIssue: async (
issueId: string,
known?: { status: string; companyId: string; executionWorkspaceId: string | null },
) => {
const [rows, issue] = await Promise.all([
db
.select()
@@ -3439,7 +3442,7 @@ export function issueThreadInteractionService(
asc(issueThreadInteractions.createdAt),
asc(issueThreadInteractions.id),
),
db
known ? { status: known.status, companyId: known.companyId, executionWorkspaceId: known.executionWorkspaceId } : db
.select({
status: issues.status,
companyId: issues.companyId,
+62 -48
View File
@@ -9124,10 +9124,9 @@ export function issueService(db: Db) {
issue: Pick<IssueRow, "id" | "companyId" | "updatedAt">,
userId: string,
) => {
const [[activity], [archive]] = await Promise.all([
lastActivityStatsForIssues(db, issue.companyId, [issue.id]),
inboxArchiveRowsForIssues(db, issue.companyId, userId, [issue.id]),
]);
const [archive] = await inboxArchiveRowsForIssues(db, issue.companyId, userId, [issue.id]);
if (!archive) return activeInboxArchiveFields(archive, issue.updatedAt);
const [activity] = await lastActivityStatsForIssues(db, issue.companyId, [issue.id]);
const lastActivityAt =
latestIssueActivityAt(
issue.updatedAt,
@@ -9215,8 +9214,8 @@ export function issueService(db: Db) {
return getIssueByIdentifier(identifier);
},
getCurrentScheduledRetry: async (issueId: string) => {
const issue = await db
getCurrentScheduledRetry: async (issueId: string, known?: { companyId: string }) => {
const issue = known ? { id: issueId, companyId: known.companyId } : await db
.select({ id: issues.id, companyId: issues.companyId })
.from(issues)
.where(eq(issues.id, issueId))
@@ -9225,8 +9224,8 @@ export function issueService(db: Db) {
return getCurrentScheduledRetryForIssue(issue.id, issue.companyId);
},
getRelationSummaries: async (issueId: string) => {
const issue = await db
getRelationSummaries: async (issueId: string, known?: { companyId: string }) => {
const issue = known ? { id: issueId, companyId: known.companyId } : await db
.select({ id: issues.id, companyId: issues.companyId })
.from(issues)
.where(eq(issues.id, issueId))
@@ -14633,9 +14632,12 @@ export function issueService(db: Db) {
findMentionedProjectIds: async (
issueId: string,
opts?: { includeCommentBodies?: boolean },
opts?: {
includeCommentBodies?: boolean;
issue?: { companyId: string; title: string; description: string | null };
},
) => {
const issue = await db
const issue = opts?.issue ?? await db
.select({
companyId: issues.companyId,
title: issues.title,
@@ -14686,7 +14688,7 @@ export function issueService(db: Db) {
return [...mentionedIds].filter((projectId) => valid.has(projectId));
},
getAncestors: async (issueId: string) => {
getAncestors: async (issueId: string, known?: { parentId: string | null }) => {
const raw: Array<{
id: string;
identifier: string | null;
@@ -14698,44 +14700,56 @@ export function issueService(db: Db) {
projectId: string | null;
goalId: string | null;
}> = [];
const visited = new Set<string>([issueId]);
const start = await db
.select()
.from(issues)
.where(eq(issues.id, issueId))
.then((r) => r[0] ?? null);
let currentId = start?.parentId ?? null;
while (currentId && !visited.has(currentId) && raw.length < 50) {
visited.add(currentId);
const parent = await db
.select({
id: issues.id,
identifier: issues.identifier,
title: issues.title,
description: issues.description,
status: issues.status,
priority: issues.priority,
assigneeAgentId: issues.assigneeAgentId,
projectId: issues.projectId,
goalId: issues.goalId,
parentId: issues.parentId,
})
const firstParentId = known
? known.parentId
: await db
.select({ parentId: issues.parentId })
.from(issues)
.where(eq(issues.id, currentId))
.then((r) => r[0] ?? null);
if (!parent) break;
raw.push({
id: parent.id,
identifier: parent.identifier ?? null,
title: parent.title,
description: parent.description ?? null,
status: parent.status,
priority: parent.priority,
assigneeAgentId: parent.assigneeAgentId ?? null,
projectId: parent.projectId ?? null,
goalId: parent.goalId ?? null,
});
currentId = parent.parentId ?? null;
.where(eq(issues.id, issueId))
.then((r) => r[0]?.parentId ?? null);
if (firstParentId && firstParentId !== issueId) {
const chain = await db.execute<{
id: string;
identifier: string | null;
title: string;
description: string | null;
status: string;
priority: string;
assignee_agent_id: string | null;
project_id: string | null;
goal_id: string | null;
}>(sql`
with recursive chain as (
select i.id, i.identifier, i.title, i.description, i.status, i.priority,
i.assignee_agent_id, i.project_id, i.goal_id, i.parent_id,
1 as depth, array[${issueId}::uuid, i.id] as path
from ${issues} i
where i.id = ${firstParentId}::uuid
union all
select p.id, p.identifier, p.title, p.description, p.status, p.priority,
p.assignee_agent_id, p.project_id, p.goal_id, p.parent_id,
chain.depth + 1, chain.path || p.id
from chain
join ${issues} p on p.id = chain.parent_id
where chain.depth < 50 and not (p.id = any(chain.path))
)
select id, identifier, title, description, status, priority, assignee_agent_id, project_id, goal_id
from chain
order by depth
`);
for (const parent of chain) {
raw.push({
id: parent.id,
identifier: parent.identifier ?? null,
title: parent.title,
description: parent.description ?? null,
status: parent.status,
priority: parent.priority,
assigneeAgentId: parent.assignee_agent_id ?? null,
projectId: parent.project_id ?? null,
goalId: parent.goal_id ?? null,
});
}
}
// Batch-fetch referenced projects and goals
@@ -3,6 +3,7 @@ import type { SQL } from "drizzle-orm";
import { PgDialect } from "drizzle-orm/pg-core";
import type { Db } from "@paperclipai/db";
import { startNativeSessionExecutionLeaseRenewal } from "./native-execution-lease.js";
import { startServerMetrics, stopServerMetrics } from "../server-metrics.js";
const dialect = new PgDialect();
@@ -134,6 +135,24 @@ describe("native execution renewal ownership", () => {
expect(returning).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
});
it("counts a renewal deadline that passes as a missed lease renewal for the server metrics", async () => {
const metrics = startServerMetrics();
try {
vi.useFakeTimers();
const { input, returning } = fixture();
let complete!: (value: { runId: string }[]) => void;
returning.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));
const guard = startNativeSessionExecutionLeaseRenewal(input);
await vi.advanceTimersByTimeAsync(30_000);
expect(metrics.snapshot().leaseRenewalsMissed).toBe(0);
await vi.advanceTimersByTimeAsync(30_000);
expect(metrics.snapshot().leaseRenewalsMissed).toBe(1);
complete([{ runId: "run" }]);
await expect(guard.stop()).rejects.toThrow("native_session_lease_renewal_deadline");
} finally {
stopServerMetrics(metrics);
}
});
it("hands preparation renewal to the same owner's executor at the next attempt", async () => {
vi.useFakeTimers();
const { input, returning } = fixture();
@@ -5,6 +5,7 @@ import { currentNativeControllerIdentity, type NativeControllerIdentity } from "
import { OPERATOR_ATTESTED_CONTROLLER_HOST } from "./native-controller-host-recovery.js";
import { NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE } from "./native-runner-ownership.js";
import { REMOTE_CONTROLLER_LEASE_MS } from "./native-runner-recovery-contract.js";
import { recordMissedLeaseRenewal } from "../server-metrics.js";
export const NATIVE_SESSION_EXECUTION_LEASE_TTL_MS = 20 * 60_000;
const NATIVE_SESSION_EXECUTION_LEASE_RENEW_INTERVAL_MS = 5 * 60_000;
@@ -613,7 +614,10 @@ export function startNativeSessionExecutionLeaseRenewal(input: RenewalInput): Na
state!.loss = Promise.resolve().then(state!.input.onLost).catch(() => undefined);
};
const deadline = (delay: number) => {
const timer = setTimeout(() => lose(new Error("native_session_lease_renewal_deadline")), Math.max(0, delay));
const timer = setTimeout(() => {
recordMissedLeaseRenewal();
lose(new Error("native_session_lease_renewal_deadline"));
}, Math.max(0, delay));
timer.unref?.();
return timer;
};
@@ -16756,6 +16756,7 @@ async function createRunnerdBackendWithinSessionClaim(
configuredEnvironment: taskConfiguredEnvironment,
releaseResumeVersion: description.releaseResumeVersion,
resumeLaunchInputsVersion: description.resumeLaunchInputsVersion,
launchDigestVersion: description.launchDigestVersion,
authorityRunId: description.releaseResumeVersion === 1 ? input.execution.binding.runId : undefined,
releasedSource: input.remoteWarmRecovery?.releasedSource,
sessionHandoff: !!input.remoteWarmRecovery?.portableSourceTaskId,
@@ -2,6 +2,7 @@ import { nativeResponsePresentationWork } from "./native-response-presentation-w
import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js";
import { plugins } from "@paperclipai/db";
import { readTaskPanelActivations } from "../plugin-task-panels.js";
import { startServerMetrics, stopServerMetrics } from "../server-metrics.js";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { and, asc, eq, sql } from "drizzle-orm";
import { createHash, generateKeyPairSync, randomUUID } from "node:crypto";
@@ -548,6 +549,21 @@ describe("PaperclipControlPlanePort conformance", () => {
payload: { itemId: "ending-item", kind: "commandExecution", text: "***REDACTED***" } }]);
});
it("records the lateness of each committed runner event once for the server metrics", async () => {
const metrics = startServerMetrics();
try {
const f = await terminalObserverFixture();
const event = { ...f.event, emittedAt: new Date(Date.now() - 2_000).toISOString() };
await f.port.appendEvent(event);
await f.port.appendEvent(event);
const snapshot = metrics.snapshot();
expect(snapshot.runEventLatenessSamples).toBe(1);
expect(snapshot.runEventLatenessP99Ms).toBeGreaterThanOrEqual(1_900);
} finally {
stopServerMetrics(metrics);
}
});
it("completes a native run when a bound secret equals a protocol word", async () => {
const observed: PrpEvent[] = [];
const f = await terminalObserverFixture({ secrets: ["interrupted", "completed", "succeeded", "satisfied"],
@@ -1020,6 +1036,27 @@ describe("PaperclipControlPlanePort conformance", () => {
return { port, binding, identity, runnerId, event, stored, streamed };
};
it("measures every row of a streaming batch from the batch commit, not after earlier rows' observers", async () => {
const metrics = startServerMetrics();
const recorded: number[] = [];
const record = metrics.recordRunEventLatenessMs.bind(metrics);
metrics.recordRunEventLatenessMs = (ms: number) => { recorded.push(ms); record(ms); };
try {
const f = await streamingFixture({ streamingBatchMs: 600_000, onCommittedEvent: async (event) => {
if (event.sourceSeq === 2) await new Promise(resolve => setTimeout(resolve, 1_200));
} });
await f.port.appendEvent(f.event(1), f.streamed);
const deltas = [2, 3, 4].map(sourceSeq => f.port.appendEvent(f.event(sourceSeq), f.streamed));
await f.port.appendEvent(f.event(5, "tool.execution.started"));
await Promise.all(deltas);
const batch = recorded.slice(1, 4);
expect(batch).toHaveLength(3);
expect(Math.max(...batch) - Math.min(...batch)).toBeLessThan(500);
} finally {
stopServerMetrics(metrics);
}
});
it("commits the first text delta at once and later deltas in one batch before the next other event", async () => {
const committed: number[] = [];
// A timer this long would time the test out: only the first delta and the
@@ -39,6 +39,7 @@ import { eligibleNativeTaskSessionPublication, publishNativeTaskSessionInTransac
import { lockNativeRunnerCheckpointOwner, nativeRunnerCheckpointOwnerLock, validateNativeRunnerCheckpointOwner, inspectNativeRunnerUpgradeHeader, type NativeRunnerCheckpointOwner } from "./native-runner-checkpoint.js";
import { crashPoint } from "@paperclipai/shared/crash-points";
import { NATIVE_PROVIDER_DURABLE_EVENT_TYPES } from "./native-retired-backup-source.js";
import { recordRunEventCommitted } from "../server-metrics.js";
export interface PaperclipControlPlaneBinding {
companyId: string;
@@ -476,10 +477,11 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
this.#assertActive(options);
const pendingObservation = this.#deferredEventObservers.get(observerKey);
const persisted = await appendHeartbeatRunEvent(this.#db, input);
const committedAtMs = Date.now();
this.#assertActive(options);
const persistenceEndedAt = persistenceStartedAt + performance.now() - persistenceClock;
let observation = pendingObservation ?? this.#deferredEventObservers.get(observerKey);
if (!observation) observation = this.#observePersistedEvent(event, persisted, persistenceStartedAt, persistenceEndedAt);
if (!observation) observation = this.#observePersistedEvent(event, persisted, persistenceStartedAt, persistenceEndedAt, committedAtMs);
if (options?.deferPostCommitObservers) {
this.#deferredEventObservers.set(observerKey, observation);
void observation.then(() => {
@@ -503,9 +505,11 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
persisted: AppendHeartbeatRunEventResult,
persistenceStartedAt: number,
persistenceEndedAt: number,
committedAtMs: number,
): Promise<void> {
try { await this.#onEventPersistence?.(event, persistenceStartedAt, persistenceEndedAt); } catch {}
if (persisted.disposition === "committed") {
recordRunEventCommitted(event.emittedAt, committedAtMs);
try {
publishLiveEvent({
companyId: this.#binding.companyId,
@@ -590,11 +594,12 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
for (const pending of batch) pending.reject(error);
return;
}
const committedAtMs = Date.now();
for (const [index, pending] of batch.entries()) {
const persisted = receipts[index]!;
const endedAt = pending.startedAtMs + performance.now() - pending.startedClock;
try {
await this.#observePersistedEvent(pending.event, persisted, pending.startedAtMs, endedAt);
await this.#observePersistedEvent(pending.event, persisted, pending.startedAtMs, endedAt, committedAtMs);
} catch (error) {
pending.reject(error);
continue;
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import type { RunnerProviderLaunchRequirements } from "@paperclipai/paperclip-runner";
import type { RunnerProcessLaunchSpec } from "../../vendor/paperclip-runner/index.js";
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessLaunchSpec } from "../../vendor/paperclip-runner/index.js";
import { createPluginRunnerTaskOwner } from "./plugin-runner-task.js";
import { NativeExecutionContext } from "./native-execution-context.js";
@@ -831,6 +831,66 @@ it.each(["codex", "claude"])("reuses a warm %s process across run authorities wi
expect(nextTask.mock.calls.filter(([op])=>op.kind==="stop")).toHaveLength(1);
});
it.each([
["advertised", 1 as const],
["not advertised", undefined],
] as const)("launch digests are sent on prepare only when the plugin has %s them", async (_label, version) => {
const {task} = provider();
ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}});
const input = {taskId:"task",task,projectIds:[],harness:"codex",projectAuthCheckVersion:1 as const,warmTaskVersion:1 as const,
accountIdentity:"account",credentialIdentity:"revision",pollMs:1,launchDigestVersion:version};
const owner = createPluginRunnerTaskOwner(input);
await prepare(owner, launchRequirements("codex"));
const registration = await owner.registration({} as never,"run");
const spec = launchSpec(); spec.nativeRunner!.lifecyclePolicy = {mode:"warm",idleTimeoutMs:300000};
const handle = owner.launcher(spec); registration.activate(); await registration.ready();
const nextIdentity={...requirements.identity,runId:"next-run",turnId:"next-turn",itemId:"next-item"};
const nextRegistration=await owner.registration({} as never,"next-run");
await owner.driver.prepareLaunch!({...launchRequirements("codex"),identity:nextIdentity});
const prepares=task.mock.calls.map(([op])=>op).filter(op=>op.kind==="prepare");
expect(prepares).toHaveLength(2);
if (version === 1) {
const [first, next] = prepares as Array<{preparationDigest?:string;runDigest?:string}>;
expect(first.preparationDigest).toBe(runnerLaunchPreparationDigest(launchRequirements("codex")));
expect(next.preparationDigest).toBe(first.preparationDigest);
expect(first.runDigest).toBe(runnerLaunchRunDigest(first.preparationDigest!, launchRequirements("codex")));
expect(next.runDigest).toBe(runnerLaunchRunDigest(first.preparationDigest!, {...launchRequirements("codex"),identity:nextIdentity}));
expect(next.runDigest).not.toBe(first.runDigest);
} else {
for (const op of prepares) expect(op).not.toHaveProperty("preparationDigest");
for (const op of prepares) expect(op).not.toHaveProperty("runDigest");
}
await registration.release(); nextRegistration.activate(); await nextRegistration.ready();
await nextRegistration.release(); await nextRegistration.checkpoint("settled"); await handle.completion;
});
it.each([
["checked inside prepare", true, ["prepare"]],
["left to Core", false, ["prepare", "check_project_auth"]],
] as const)("a warm attach whose project authentication is %s makes only the round trips it needs", async (_label, checked, kinds) => {
const {task} = provider();
ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}});
const input = {taskId:"task",task,projectIds:[],harness:"codex",projectAuthCheckVersion:1 as const,warmTaskVersion:1 as const,
accountIdentity:"account",credentialIdentity:"revision",pollMs:1};
const owner = createPluginRunnerTaskOwner(input);
await prepare(owner, launchRequirements("codex"));
const registration = await owner.registration({} as never,"run");
const spec = launchSpec(); spec.nativeRunner!.lifecyclePolicy = {mode:"warm",idleTimeoutMs:300000};
const handle = owner.launcher(spec); registration.activate(); await registration.ready();
const originalTask=task.getMockImplementation()!;
const nextTask=vi.fn(async op=>{
const result=await originalTask(op) as Record<string,unknown>;
return op.kind === "prepare" && checked ? {...result,projectAuthChecked:true} : result;
});
owner.rebind({...input,task:nextTask});
const nextRegistration=await owner.registration({} as never,"next-run");
const nextIdentity={...requirements.identity,runId:"next-run",turnId:"next-turn",itemId:"next-item"};
await owner.driver.prepareLaunch!({...launchRequirements("codex"),identity:nextIdentity});
expect(nextTask.mock.calls.map(([op])=>op.kind)).toEqual(kinds);
await registration.release(); nextRegistration.activate(); await nextRegistration.ready();
await nextRegistration.release(); await nextRegistration.checkpoint("settled"); await handle.completion;
});
it.each(["codex", "claude"])("adopts a verified retained %s task without submitting a replacement", async harness => {
const {task}=provider();
ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}});
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
import { setTimeout as delay } from "node:timers/promises";
import { environmentTaskOperationSchema, environmentTaskResultSchema, parseEnvironmentTaskResult, type PluginEnvironmentTaskOperation, type PluginEnvironmentTaskResult, type PluginEnvironmentTaskCredential } from "@paperclipai/plugin-sdk";
import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity";
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent } from "../../vendor/paperclip-runner/index.js";
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
import type { NativeExecutionContext } from "./native-execution-context.js";
@@ -50,6 +50,7 @@ export function createPluginRunnerTaskOwner(input: {
warmTaskVersion?: 1;
releaseResumeVersion?: 1;
resumeLaunchInputsVersion?: 1;
launchDigestVersion?: 1;
releasedSource?: DurableRecoveryIdentity;
sessionHandoff?: boolean;
onResumed?: (identity: DurableRecoveryIdentity) => Promise<void>;
@@ -143,7 +144,9 @@ export function createPluginRunnerTaskOwner(input: {
if (input.githubBroker && input.githubCredentialBrokerVersion !== 1) {
throw new Error("Update the environment plugin to support the GitHub credential broker v1");
}
const preparationDigest = input.launchDigestVersion === 1 ? runnerLaunchPreparationDigest(requirements) : undefined;
const result = await call(environmentTaskOperationSchema.parse({ kind: "prepare", requirements,
...(preparationDigest ? { preparationDigest, runDigest: runnerLaunchRunDigest(preparationDigest, requirements) } : {}),
...(input.githubBroker ? { githubBroker: input.githubBroker } : {}),
projectIds: [...input.projectIds], ...(recovery ? { recovery } : {}),
...(input.resumeFrom && (!authorityRunId || !launchIdentity || launchIdentity.runId === authorityRunId || sourceRecovery)
@@ -155,7 +158,7 @@ export function createPluginRunnerTaskOwner(input: {
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
if (result.kind !== "prepared") throw new Error("Plugin Runner preparation unavailable");
if (input.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner managed project authentication validation unavailable");
if (launched || !result.projectAuthCheckAtSubmit) await checkProjectAuth(result.launch.configurationId);
if (!result.projectAuthChecked && (launched || !result.projectAuthCheckAtSubmit)) await checkProjectAuth(result.launch.configurationId);
preparedLaunchId = result.launch.configurationId;
preparedIdentity = requirements.identity;
return result.launch;
+17 -6
View File
@@ -326,10 +326,16 @@ function pickPrimaryWorkspace(
}
/** Batch-load workspace refs for a set of projects. */
async function attachWorkspaces(db: Db, rows: ProjectWithGoals[]): Promise<ProjectWithGoals[]> {
async function attachWorkspaces(
db: Db,
rows: ProjectWithGoals[],
options: { workspaceProvider?: boolean } = {},
): Promise<ProjectWithGoals[]> {
if (rows.length === 0) return [];
const providerCatalog = await listProjectWorkspaceProviders(db, rows[0]!.companyId);
const providerCatalog = options.workspaceProvider === false
? null
: await listProjectWorkspaceProviders(db, rows[0]!.companyId);
const projectIds = rows.map((r) => r.id);
const workspaceRows = await db
.select()
@@ -412,8 +418,10 @@ async function attachWorkspaces(db: Db, rows: ProjectWithGoals[]): Promise<Proje
workspaces,
primaryWorkspace,
managedByPlugin: managedByProjectId.get(row.id) ?? null,
workspaceProvider: resolveProjectWorkspaceProvider(row.executionWorkspacePolicy, providerCatalog,
workspaces.some(workspace => Boolean(workspace.repoUrl))),
...(providerCatalog ? {
workspaceProvider: resolveProjectWorkspaceProvider(row.executionWorkspacePolicy, providerCatalog,
workspaces.some(workspace => Boolean(workspace.repoUrl))),
} : {}),
};
});
}
@@ -708,7 +716,10 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
});
};
const getProjectById = async (id: string): Promise<ProjectWithGoals | null> => {
const getProjectById = async (
id: string,
options: { workspaceProvider?: boolean } = {},
): Promise<ProjectWithGoals | null> => {
const row = await db
.select()
.from(projects)
@@ -717,7 +728,7 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
if (!row) return null;
const [withGoals] = await attachGoals(db, [row]);
if (!withGoals) return null;
const [enriched] = await attachWorkspaces(db, [withGoals]);
const [enriched] = await attachWorkspaces(db, [withGoals], options);
return enriched ?? null;
};
+18 -22
View File
@@ -3,9 +3,8 @@ import { databaseWorkPending, reconcileDatabaseWork } from "@paperclipai/db/work
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { runChildProcess } from "../adapters/utils.js";
import { currentControllerProcessStamp, currentProcessStartedAtMs, type ControllerProcess } from "./controller-process-identity.js";
import { currentControllerProcessStamp, currentProcessSpaceHash, currentProcessStartedAtMs, observedProcessStartedAt, type ControllerProcess } from "./controller-process-identity.js";
import { currentProcessProbe } from "./owner-proof.js";
import { proveRunProcessGone } from "./run-process-owner.js";
import { and, eq, sql } from "drizzle-orm";
@@ -148,28 +147,25 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
});
it.skipIf(process.platform === "win32")("normal accounting Retry reconstructs an uncommitted legacy receipt after its real controller and child exited", async () => {
const identityModule = new URL('./controller-process-identity.ts', import.meta.url).href;
const loader = fileURLToPath(import.meta.resolve('tsx/esm'));
async function joinedIdentity() {
const command = `console.error("accounting-identity:program-entered"); const identity = await import(${JSON.stringify(identityModule)}); console.error("accounting-identity:module-imported"); await identity.currentProcessStartedAtMs(); console.error("accounting-identity:birth-read"); console.log(JSON.stringify(identity.currentControllerProcessStamp()));`;
let groupId: number | null = null;
let observedStderrChars = 0;
const result = await runChildProcess(randomUUID(), process.execPath,
['--import', loader, '--input-type=module', '-e', command], {
cwd: process.cwd(), env: { NODE_OPTIONS: process.env.NODE_OPTIONS ?? '', PATH: process.env.PATH ?? '' },
timeoutSec: 5, graceSec: 1, onLog: async (stream, chunk) => {
if (stream === "stderr" && observedStderrChars < 8192) {
const observed = chunk.slice(0, 8192 - observedStderrChars);
observedStderrChars += observed.length;
process.stderr.write(observed);
}
},
onSpawn: async meta => { groupId = meta.processGroupId ?? null; },
});
expect(result.exitCode, JSON.stringify({ exitCode: result.exitCode, signal: result.signal, timedOut: result.timedOut, pid: result.pid, startedAt: result.startedAt, stdoutTail: result.stdout.slice(-8192), stderrTail: result.stderr.slice(-8192) })).toBe(0);
const identity = JSON.parse(result.stdout.trim()) as ControllerProcess;
expect(identity.processStartedAt).not.toBeNull();
const command = `process.on("SIGUSR2", () => process.exit(0)); setInterval(() => {}, 60_000); process.stdout.write("ready\\n");`;
let pid: number | null = null, groupId: number | null = null, startedAt: number | null = null, released = false;
const result = await runChildProcess(randomUUID(), process.execPath, ['-e', command], {
cwd: process.cwd(), env: { PATH: process.env.PATH ?? '' },
timeoutSec: 5, graceSec: 1,
onSpawn: async meta => { pid = meta.pid; groupId = meta.processGroupId ?? null; },
onLog: async (stream, chunk) => {
if (stream !== "stdout" || released || pid === null || !chunk.includes("ready")) return;
released = true;
startedAt = await observedProcessStartedAt(pid);
process.kill(pid, "SIGUSR2");
},
});
expect(result.exitCode, JSON.stringify({ exitCode: result.exitCode, signal: result.signal, timedOut: result.timedOut, pid: result.pid, stdoutTail: result.stdout.slice(-8192), stderrTail: result.stderr.slice(-8192) })).toBe(0);
expect(startedAt).not.toBeNull();
expect(Number.isSafeInteger(groupId) && groupId! > 1).toBe(true);
const identity: ControllerProcess = { bootId: randomUUID(), pid: pid!, hostHash: currentProcessSpaceHash(),
processStartedAt: new Date(startedAt!).toISOString() };
return { ...identity, groupId };
}
const controller = await joinedIdentity(), child = await joinedIdentity();
+274
View File
@@ -0,0 +1,274 @@
import { randomBytes } from "node:crypto";
import { readFileSync } from "node:fs";
import {
createHistogram,
monitorEventLoopDelay,
performance,
type EventLoopUtilization,
type IntervalHistogram,
type RecordableHistogram,
} from "node:perf_hooks";
import type { RequestHandler } from "express";
import { databaseStatementCount, type DedicatedDbConnectionStats } from "@paperclipai/db";
import { readBuildCommit } from "../build-commit.js";
export const SERVER_METRICS_ENV = "PAPERCLIP_SERVER_METRICS";
export const SERVER_METRICS_SCHEMA = "paperclip.server-metrics.v1";
export const SERVER_METRICS_BUCKET_MS = 10_000;
export const SERVER_METRICS_BUCKETS = 6;
const EVENT_LOOP_DELAY_RESOLUTION_MS = 20;
const LINUX_CLOCK_TICK_MS = 10;
export type ServerMetricsSnapshot = {
schema: typeof SERVER_METRICS_SCHEMA;
processId: string;
buildRevision: string | null;
uptimeSec: number;
sampledAt: string;
windowMs: number;
mainThreadCpu: number | null;
processCpu: number;
eventLoopUtilization: number;
eventLoopDelayP99Ms: number;
statementsPerSecond: number;
runEventLatenessP99Ms: number | null;
runEventLatenessSamples: number;
agentApiPreHandlerP99Ms: number | null;
agentApiPreHandlerSamples: number;
leaseRenewalsMissed: number;
dedicatedConnections: DedicatedDbConnectionStats | null;
};
export type ServerMetricsProbes = {
now: () => number;
wallNow: () => number;
eventLoopUtilization: (current?: EventLoopUtilization, previous?: EventLoopUtilization) => EventLoopUtilization;
processCpuMicros: () => number;
mainThreadCpuMs: () => number | null;
statementCount: () => number;
uptimeSec: () => number;
dedicatedConnections: () => DedicatedDbConnectionStats | null;
};
type Checkpoint = {
at: number;
elu: EventLoopUtilization;
processCpuMicros: number;
mainThreadCpuMs: number | null;
statements: number;
};
function readLinuxMainThreadCpuMs(): number | null {
if (process.platform !== "linux") return null;
try {
const stat = readFileSync(`/proc/self/task/${process.pid}/stat`, "utf8");
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
const ticks = Number(fields[11]) + Number(fields[12]);
return Number.isFinite(ticks) ? ticks * LINUX_CLOCK_TICK_MS : null;
} catch {
return null;
}
}
const defaultProbes: ServerMetricsProbes = {
now: () => performance.now(),
wallNow: () => Date.now(),
eventLoopUtilization: (current, previous) => performance.eventLoopUtilization(current, previous),
processCpuMicros: () => {
const usage = process.cpuUsage();
return usage.user + usage.system;
},
mainThreadCpuMs: readLinuxMainThreadCpuMs,
statementCount: databaseStatementCount,
uptimeSec: () => process.uptime(),
dedicatedConnections: () => null,
};
const round = (value: number, digits: number) => Number(value.toFixed(digits));
export class ServerMetricsCollector {
readonly processId: string;
readonly buildRevision: string | null;
private readonly probes: ServerMetricsProbes;
private readonly bucketMs: number;
private readonly starts: Array<Checkpoint | null>;
private readonly lateness: RecordableHistogram[];
private readonly preHandler: RecordableHistogram[];
private readonly delayP99Ns: number[];
private readonly merged = createHistogram();
private readonly eventLoopDelay: IntervalHistogram | null;
private current = 0;
private missedLeaseRenewals = 0;
private timer: NodeJS.Timeout | null = null;
private stopped = false;
constructor(options: { probes?: Partial<ServerMetricsProbes>; bucketMs?: number; buckets?: number;
buildRevision?: string | null; monitorEventLoop?: boolean; processId?: string } = {}) {
this.processId = options.processId ?? randomBytes(8).toString("hex");
this.probes = { ...defaultProbes, ...options.probes };
this.bucketMs = options.bucketMs ?? SERVER_METRICS_BUCKET_MS;
const buckets = options.buckets ?? SERVER_METRICS_BUCKETS;
this.buildRevision = options.buildRevision === undefined ? readBuildCommit() : options.buildRevision;
this.starts = Array.from({ length: buckets }, () => null);
this.lateness = Array.from({ length: buckets }, () => createHistogram());
this.preHandler = Array.from({ length: buckets }, () => createHistogram());
this.delayP99Ns = Array.from({ length: buckets }, () => 0);
this.eventLoopDelay = options.monitorEventLoop === false ? null
: monitorEventLoopDelay({ resolution: EVENT_LOOP_DELAY_RESOLUTION_MS });
this.eventLoopDelay?.enable();
this.starts[0] = this.checkpoint();
this.arm();
}
private checkpoint(): Checkpoint {
return {
at: this.probes.now(),
elu: this.probes.eventLoopUtilization(),
processCpuMicros: this.probes.processCpuMicros(),
mainThreadCpuMs: this.probes.mainThreadCpuMs(),
statements: this.probes.statementCount(),
};
}
private arm(): void {
if (this.stopped) return;
this.timer = setTimeout(() => {
this.timer = null;
this.rotate();
this.arm();
}, this.bucketMs);
this.timer.unref();
}
rotate(): void {
const now = this.checkpoint();
const started = this.starts[this.current]!;
const steps = Math.min(this.starts.length - 1, Math.max(1, Math.floor((now.at - started.at) / this.bucketMs)));
if (this.eventLoopDelay) {
this.delayP99Ns[this.current] = this.eventLoopDelay.percentile(99);
this.eventLoopDelay.reset();
}
for (let step = 0; step < steps; step += 1) {
this.current = (this.current + 1) % this.starts.length;
this.lateness[this.current]!.reset();
this.preHandler[this.current]!.reset();
this.delayP99Ns[this.current] = 0;
this.starts[this.current] = null;
}
this.starts[this.current] = now;
}
recordRunEventLatenessMs(ms: number): void {
this.lateness[this.current]!.record(Math.max(1, Math.round(ms * 1000)));
}
recordAgentApiPreHandlerMs(ms: number): void {
this.preHandler[this.current]!.record(Math.max(1, Math.round(ms * 1000)));
}
recordMissedLeaseRenewal(): void {
this.missedLeaseRenewals += 1;
}
private windowP99Ms(histograms: RecordableHistogram[]): { p99Ms: number | null; samples: number } {
this.merged.reset();
for (const histogram of histograms) if (histogram.count > 0) this.merged.add(histogram);
const samples = this.merged.count;
return { p99Ms: samples > 0 ? round(this.merged.percentile(99) / 1000, 3) : null, samples };
}
snapshot(): ServerMetricsSnapshot {
const now = this.checkpoint();
let oldest = this.starts[this.current]!;
for (let offset = 1; offset < this.starts.length; offset += 1) {
const start = this.starts[(this.current + offset) % this.starts.length];
if (start) { oldest = start; break; }
}
const windowMs = Math.max(1, now.at - oldest.at);
let delayP99Ns = this.eventLoopDelay?.percentile(99) ?? 0;
for (let index = 0; index < this.starts.length; index += 1) {
if (index !== this.current && this.starts[index]) delayP99Ns = Math.max(delayP99Ns, this.delayP99Ns[index]!);
}
const lateness = this.windowP99Ms(this.lateness);
const preHandler = this.windowP99Ms(this.preHandler);
return {
schema: SERVER_METRICS_SCHEMA,
processId: this.processId,
buildRevision: this.buildRevision,
uptimeSec: Math.round(this.probes.uptimeSec()),
sampledAt: new Date(this.probes.wallNow()).toISOString(),
windowMs: Math.round(windowMs),
mainThreadCpu: now.mainThreadCpuMs !== null && oldest.mainThreadCpuMs !== null
? round((now.mainThreadCpuMs - oldest.mainThreadCpuMs) / windowMs, 4) : null,
processCpu: round((now.processCpuMicros - oldest.processCpuMicros) / 1000 / windowMs, 4),
eventLoopUtilization: round(this.probes.eventLoopUtilization(now.elu, oldest.elu).utilization, 4),
eventLoopDelayP99Ms: round(delayP99Ns / 1e6, 3),
statementsPerSecond: round((now.statements - oldest.statements) / (windowMs / 1000), 2),
runEventLatenessP99Ms: lateness.p99Ms,
runEventLatenessSamples: lateness.samples,
agentApiPreHandlerP99Ms: preHandler.p99Ms,
agentApiPreHandlerSamples: preHandler.samples,
leaseRenewalsMissed: this.missedLeaseRenewals,
dedicatedConnections: this.probes.dedicatedConnections(),
};
}
stop(): void {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
this.timer = null;
this.eventLoopDelay?.disable();
}
}
let active: ServerMetricsCollector | null = null;
export function serverMetricsEnabledFromEnv(env: NodeJS.ProcessEnv): boolean {
const value = env[SERVER_METRICS_ENV]?.trim().toLowerCase();
if (value === undefined || value === "") return false;
if (value === "true" || value === "1") return true;
if (value === "false" || value === "0") return false;
throw new Error(`${SERVER_METRICS_ENV} must be "true" or "false", got: ${env[SERVER_METRICS_ENV]}`);
}
export function startServerMetrics(dedicatedConnections?: () => DedicatedDbConnectionStats | null): ServerMetricsCollector {
active ??= new ServerMetricsCollector(dedicatedConnections ? { probes: { dedicatedConnections } } : {});
return active;
}
export function stopServerMetrics(collector: ServerMetricsCollector): void {
collector.stop();
if (active === collector) active = null;
}
export function activeServerMetrics(): ServerMetricsCollector | null {
return active;
}
export function recordRunEventCommitted(emittedAt: string | null | undefined, committedAtMs: number): void {
if (!active || !emittedAt) return;
const emitted = Date.parse(emittedAt);
if (Number.isFinite(emitted)) active.recordRunEventLatenessMs(committedAtMs - emitted);
}
export function recordMissedLeaseRenewal(): void {
active?.recordMissedLeaseRenewal();
}
const arrivedAt = Symbol("serverMetricsArrivedAt");
type TimedRequest = { [arrivedAt]?: number };
export function serverMetricsArrival(): RequestHandler {
return (req, _res, next) => {
(req as TimedRequest)[arrivedAt] = performance.now();
next();
};
}
export function serverMetricsAgentPreHandler(collector: ServerMetricsCollector): RequestHandler {
return (req, _res, next) => {
const started = (req as TimedRequest)[arrivedAt];
if (started !== undefined && req.actor?.type === "agent") collector.recordAgentApiPreHandlerMs(performance.now() - started);
next();
};
}