mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 23:06:17 +01:00
Merge current master into external agent sleep recovery
This commit is contained in:
commit
e5604f3e4d
88 files changed
+3360
-350
No files matched your search
@@ -0,0 +1,290 @@
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { and, eq as equals } from "drizzle-orm";
|
||||
import { authUsers, companyMemberships, instanceUserRoles, issues, projects } from "@paperclipai/db";
|
||||
import { actorMiddleware } from "../middleware/auth.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
import { issueRoutes } from "../routes/issues.js";
|
||||
import { AUTHORIZATION_READ_MAX_AGE_MS, authorizationReadScope, readOncePerRequest } from "../services/authorization-read-scope.js";
|
||||
import { readInstanceAdmin } from "../services/authorization.js";
|
||||
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
|
||||
import { describeEmbeddedPostgres, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("authorization reads per request", () => {
|
||||
const ctx = useEmbeddedPostgres("authorization-request-reads-");
|
||||
|
||||
function appFor(userId: string) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(actorMiddleware(ctx.db, {
|
||||
deploymentMode: "authenticated",
|
||||
resolveSession: async () => ({
|
||||
session: { id: `session-${userId}`, userId },
|
||||
user: { id: userId, name: "Reader", email: `${userId}@example.test` },
|
||||
}),
|
||||
}));
|
||||
app.use(authorizationReadScope);
|
||||
app.use("/api", issueRoutes(ctx.db, {} as never));
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
async function seed(name: string) {
|
||||
const company = await seedCompanyWithBoardAccess(ctx.db, name);
|
||||
const now = new Date();
|
||||
await ctx.db.insert(authUsers).values({
|
||||
id: company.userId, name, email: `${company.userId}@example.test`, emailVerified: true, createdAt: now, updatedAt: now,
|
||||
});
|
||||
const [project] = await ctx.db.insert(projects).values({ companyId: company.companyId, name: `${name} project` }).returning();
|
||||
const [issue] = await ctx.db.insert(issues).values({
|
||||
companyId: company.companyId, title: `${name} task`, status: "todo", projectId: project!.id, createdByUserId: company.userId,
|
||||
}).returning();
|
||||
return { ...company, issue: issue! };
|
||||
}
|
||||
|
||||
it("reads the instance role once per request and the membership once for the authorization of one issue read", async () => {
|
||||
const { host, port } = (ctx.db.$client as unknown as { options: { host: string[]; port: number[] } }).options;
|
||||
const meter = meterDatabaseStatements(ctx.db, `postgres://${host[0]}:${port[0]}/authorization`);
|
||||
try {
|
||||
const fixture = await seed("Reads");
|
||||
const app = appFor(fixture.userId);
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
meter.startLog();
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
const log = meter.stopLog();
|
||||
const roleReads = log.filter((entry) => /from "instance_user_roles"/.test(entry.sql));
|
||||
const membershipReads = log.filter((entry) => /from "company_memberships"/.test(entry.sql));
|
||||
expect(roleReads).toHaveLength(1);
|
||||
expect(membershipReads).toHaveLength(2);
|
||||
|
||||
meter.startLog();
|
||||
await request(app).get(`/api/companies/${fixture.companyId}/issues`).expect(200);
|
||||
await request(app).get(`/api/companies/${fixture.companyId}/issues/summaries?ids=${fixture.issue.id}`).expect(200);
|
||||
const listLog = meter.stopLog();
|
||||
expect(listLog.filter((entry) => /from "instance_user_roles"/.test(entry.sql))).toHaveLength(2);
|
||||
} finally {
|
||||
meter.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("denies the very next request after the membership is removed", async () => {
|
||||
const fixture = await seed("Revoked");
|
||||
const app = appFor(fixture.userId);
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(404);
|
||||
}, 60_000);
|
||||
function membershipRead(companyId: string, userId: string) {
|
||||
return readOncePerRequest(`membership:${companyId}:user:${userId}`, () => ctx.db.select({ id: companyMemberships.id })
|
||||
.from(companyMemberships)
|
||||
.where(and(equals(companyMemberships.companyId, companyId), equals(companyMemberships.principalId, userId),
|
||||
equals(companyMemberships.status, "active")))
|
||||
.then((rows) => rows.length > 0));
|
||||
}
|
||||
|
||||
function streamApp(userId: string, companyId: string, events: { afterRevoke: Promise<void>; late: (allowed: boolean) => void }) {
|
||||
const app = express();
|
||||
app.use(actorMiddleware(ctx.db, {
|
||||
deploymentMode: "authenticated",
|
||||
resolveSession: async () => ({
|
||||
session: { id: `session-${userId}`, userId },
|
||||
user: { id: userId, name: "Reader", email: `${userId}@example.test` },
|
||||
}),
|
||||
}));
|
||||
app.use(authorizationReadScope);
|
||||
app.get("/stream", async (_req, res) => {
|
||||
const atConnect = await membershipRead(companyId, userId);
|
||||
res.writeHead(200, { "Content-Type": "text/event-stream" });
|
||||
res.flushHeaders();
|
||||
res.write(`data: ${atConnect}\n\n`);
|
||||
await events.afterRevoke;
|
||||
res.end(`data: ${await membershipRead(companyId, userId)}\n\n`);
|
||||
});
|
||||
app.get("/later", async (_req, res) => {
|
||||
await membershipRead(companyId, userId);
|
||||
setTimeout(() => { void events.afterRevoke.then(() => membershipRead(companyId, userId)).then(events.late); }, 0);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
it("re-reads the membership during a stream after it is removed", async () => {
|
||||
const fixture = await seed("Stream");
|
||||
let revoked!: () => void;
|
||||
const afterRevoke = new Promise<void>((resolve) => { revoked = resolve; });
|
||||
const app = streamApp(fixture.userId, fixture.companyId, { afterRevoke, late: () => {} });
|
||||
const pending = request(app).get("/stream").buffer(true).parse((res, done) => {
|
||||
let text = "";
|
||||
res.on("data", (chunk: Buffer) => {
|
||||
text += chunk.toString();
|
||||
if (text.includes("data: true") && !text.includes("data: false")) {
|
||||
void ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId)).then(revoked);
|
||||
}
|
||||
});
|
||||
res.on("end", () => done(null, text));
|
||||
});
|
||||
const response = await pending;
|
||||
expect(response.body).toBe("data: true\n\ndata: false\n\n");
|
||||
}, 60_000);
|
||||
|
||||
it("re-reads in a callback that runs after the response and after a revoke", async () => {
|
||||
const fixture = await seed("Later");
|
||||
let revoked!: () => void;
|
||||
const afterRevoke = new Promise<void>((resolve) => { revoked = resolve; });
|
||||
let late!: (allowed: boolean) => void;
|
||||
const lateResult = new Promise<boolean>((resolve) => { late = resolve; });
|
||||
const app = streamApp(fixture.userId, fixture.companyId, { afterRevoke, late });
|
||||
await request(app).get("/later").expect(200);
|
||||
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
|
||||
revoked();
|
||||
expect(await lateResult).toBe(false);
|
||||
}, 60_000);
|
||||
|
||||
it("seeds the instance role from a session read that matches the authorization predicate", async () => {
|
||||
const now = new Date();
|
||||
const cases = [
|
||||
{ userId: `user-admin-${Date.now()}`, roles: ["instance_admin"], expected: true },
|
||||
{ userId: `user-other-${Date.now()}`, roles: ["instance_viewer"], expected: false },
|
||||
{ userId: `user-none-${Date.now()}`, roles: [], expected: false },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
await ctx.db.insert(authUsers).values({ id: entry.userId, name: entry.userId, email: `${entry.userId}@example.test`,
|
||||
emailVerified: true, createdAt: now, updatedAt: now });
|
||||
if (entry.roles.length) await ctx.db.insert(instanceUserRoles).values(entry.roles.map((role) => ({ userId: entry.userId, role })));
|
||||
const app = express();
|
||||
app.use(actorMiddleware(ctx.db, {
|
||||
deploymentMode: "authenticated",
|
||||
resolveSession: async () => ({ session: { id: `session-${entry.userId}`, userId: entry.userId },
|
||||
user: { id: entry.userId, name: "Admin check", email: `${entry.userId}@example.test` } }),
|
||||
}));
|
||||
app.get("/actor", (req, res) => { res.json({ isInstanceAdmin: req.actor.isInstanceAdmin }); });
|
||||
const seeded = (await request(app).get("/actor").expect(200)).body.isInstanceAdmin;
|
||||
expect({ seeded, read: await readInstanceAdmin(ctx.db, entry.userId) }).toEqual({ seeded: entry.expected, read: entry.expected });
|
||||
}
|
||||
await ctx.db.delete(instanceUserRoles);
|
||||
}, 60_000);
|
||||
|
||||
it("treats HEAD like GET for an authorized read and denies it after a revoke", async () => {
|
||||
const fixture = await seed("Head");
|
||||
const app = appFor(fixture.userId);
|
||||
await request(app).head(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
|
||||
await request(app).head(`/api/issues/${fixture.issue.id}`).expect(404);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe("authorization read scope boundaries", () => {
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
|
||||
function countingApp(actor: Express.Request["actor"] = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false }) {
|
||||
let reads = 0;
|
||||
const gates: Array<() => void> = [];
|
||||
const app = express();
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = actor;
|
||||
next();
|
||||
});
|
||||
app.use(authorizationReadScope);
|
||||
app.all("/read", async (req, res) => {
|
||||
const read = () => readOncePerRequest("membership:company-1:user:user-1", async () => ++reads);
|
||||
const first = await read();
|
||||
if (req.query.wait) await new Promise<void>((resolve) => gates.push(resolve));
|
||||
res.json({ first, second: await read(), admin: await readOncePerRequest("admin:user-1", async () => "read") });
|
||||
});
|
||||
return { app, gates, reads: () => reads };
|
||||
}
|
||||
|
||||
it("shares a read only inside one GET request", async () => {
|
||||
const { app, reads } = countingApp();
|
||||
expect((await request(app).get("/read")).body).toEqual({ first: 1, second: 1, admin: false });
|
||||
expect((await request(app).get("/read")).body).toEqual({ first: 2, second: 2, admin: false });
|
||||
expect(reads()).toBe(2);
|
||||
});
|
||||
|
||||
it("reads again for every call in a write request", async () => {
|
||||
const { app, reads } = countingApp();
|
||||
expect((await request(app).post("/read")).body).toEqual({ first: 1, second: 2, admin: "read" });
|
||||
expect((await request(app).delete("/read")).body).toEqual({ first: 3, second: 4, admin: "read" });
|
||||
expect(reads()).toBe(4);
|
||||
});
|
||||
|
||||
it("keeps overlapping GET requests apart", async () => {
|
||||
const { app, gates } = countingApp();
|
||||
const slow = request(app).get("/read?wait=1").then((res) => res.body);
|
||||
while (gates.length === 0) await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
const fast = await request(app).get("/read");
|
||||
gates[0]!();
|
||||
expect(await slow).toEqual({ first: 1, second: 1, admin: false });
|
||||
expect(fast.body).toEqual({ first: 2, second: 2, admin: false });
|
||||
});
|
||||
it("ignores an entry older than the age bound", async () => {
|
||||
const { app, gates, reads } = countingApp();
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
const pending = request(app).get("/read?wait=1").then((res) => res.body);
|
||||
while (gates.length === 0) await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
vi.setSystemTime(Date.now() + AUTHORIZATION_READ_MAX_AGE_MS + 1);
|
||||
gates[0]!();
|
||||
expect(await pending).toEqual({ first: 1, second: 2, admin: "read" });
|
||||
expect(reads()).toBe(2);
|
||||
});
|
||||
|
||||
it("does not keep a rejected read", async () => {
|
||||
let attempts = 0;
|
||||
const app = express();
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false };
|
||||
next();
|
||||
});
|
||||
app.use(authorizationReadScope);
|
||||
app.get("/read", async (_req, res) => {
|
||||
const read = () => readOncePerRequest("membership:company-1:user:user-1", async () => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) throw new Error("connection reset");
|
||||
return attempts;
|
||||
});
|
||||
const first = await read().catch((error: Error) => error.message);
|
||||
res.json({ first, second: await read(), third: await read() });
|
||||
});
|
||||
expect((await request(app).get("/read")).body).toEqual({ first: "connection reset", second: 2, third: 2 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an agent key", { type: "agent", source: "agent_key", agentId: "agent-1", companyId: "company-1" }],
|
||||
["a board key", { type: "board", source: "board_key", userId: "user-1", isInstanceAdmin: true }],
|
||||
["a cloud tenant", { type: "board", source: "cloud_tenant", userId: "user-1", isInstanceAdmin: true }],
|
||||
] as const)("seeds nothing for %s", async (_label, actor) => {
|
||||
const { app } = countingApp(actor as Express.Request["actor"]);
|
||||
expect((await request(app).get("/read")).body.admin).toBe("read");
|
||||
});
|
||||
it("keeps response hooks that later middleware installs", async () => {
|
||||
const app = express();
|
||||
app.use(authorizationReadScope);
|
||||
app.use((_req, res, next) => {
|
||||
const { writeHead, write } = res;
|
||||
let writes = 0;
|
||||
res.writeHead = function (this: typeof res, ...args: Parameters<typeof res.writeHead>) {
|
||||
this.setHeader("x-late-hook", "kept");
|
||||
return writeHead.apply(this, args);
|
||||
} as typeof res.writeHead;
|
||||
res.write = function (this: typeof res, ...args: Parameters<typeof res.write>) {
|
||||
writes += 1;
|
||||
res.locals.writes = writes;
|
||||
return write.apply(this, args);
|
||||
} as typeof res.write;
|
||||
next();
|
||||
});
|
||||
app.get("/json", (_req, res) => { res.json({ ok: true }); });
|
||||
app.get("/stream", (_req, res) => {
|
||||
res.write("a");
|
||||
res.write("b");
|
||||
res.end(String(res.locals.writes));
|
||||
});
|
||||
const json = await request(app).get("/json").expect(200);
|
||||
expect(json.headers["x-late-hook"]).toBe("kept");
|
||||
const stream = await request(app).get("/stream").expect(200);
|
||||
expect(stream.headers["x-late-hook"]).toBe("kept");
|
||||
expect(stream.text).toBe("ab2");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import request from "supertest";
|
||||
import { expect, it } from "vitest";
|
||||
import { boardCensusRoutes, boardSessionApp, seedBoardRouteFixture } from "./helpers/route-census-fixture.js";
|
||||
import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
import { createStatementCensus, formatStatementCensus } from "./helpers/statement-census.js";
|
||||
|
||||
describeEmbeddedPostgres("board route statement census", () => {
|
||||
const ctx = useEmbeddedPostgres("board-route-census-");
|
||||
|
||||
it("answers every polled and page-load board route and reports statements per request", async () => {
|
||||
const census = createStatementCensus(ctx.db);
|
||||
try {
|
||||
const fixture = await seedBoardRouteFixture(ctx.db, "Census");
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const report: string[] = [];
|
||||
for (const [label, path] of boardCensusRoutes(fixture)) {
|
||||
const warm = await request(app).get(path);
|
||||
expect(warm.status, `${label}: ${JSON.stringify(warm.body)}`).toBe(200);
|
||||
const measured = await census.measure(() => request(app).get(path).expect(200), { stacks: true });
|
||||
expect(measured.statements, label).toBeGreaterThan(0);
|
||||
report.push(formatStatementCensus(label, measured, Number(process.env.PAPERCLIP_STATEMENT_CENSUS_TOP ?? 5)));
|
||||
}
|
||||
if (process.env.PAPERCLIP_STATEMENT_CENSUS) writeFileSync(process.env.PAPERCLIP_STATEMENT_CENSUS, `${report.join("\n\n")}\n`);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import request from "supertest";
|
||||
import { and, eq, like } from "drizzle-orm";
|
||||
import { expect, it } from "vitest";
|
||||
import { folders } from "@paperclipai/db";
|
||||
import { companySkillRoutes } from "../routes/company-skills.js";
|
||||
import { folderService } from "../services/folders.js";
|
||||
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
|
||||
import { describeEmbeddedPostgres, routeApp, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("GET /api/companies/:companyId/skills statements per request", () => {
|
||||
const ctx = useEmbeddedPostgres("company-skills-list-statements-");
|
||||
|
||||
function meter() {
|
||||
const { host, port } = (ctx.db.$client as unknown as { options: { host: string[]; port: number[] } }).options;
|
||||
return meterDatabaseStatements(ctx.db, `postgres://${host[0]}:${port[0]}/skills`);
|
||||
}
|
||||
|
||||
const bundledFolders = (companyId: string) => ctx.db.select().from(folders)
|
||||
.where(and(eq(folders.companyId, companyId), like(folders.systemKey, "bundled%")));
|
||||
|
||||
it("lists skills with plain reads once the bundled folders exist", async () => {
|
||||
const statements = meter();
|
||||
try {
|
||||
const company = await seedCompanyWithBoardAccess(ctx.db, "Skills list");
|
||||
const app = routeApp(ctx.db, company.actor, (db) => companySkillRoutes(db));
|
||||
const first = await request(app).get(`/api/companies/${company.companyId}/skills`).expect(200);
|
||||
expect(first.body.length).toBeGreaterThan(0);
|
||||
const foldersAfterFirst = await bundledFolders(company.companyId);
|
||||
|
||||
const before = statements.read();
|
||||
statements.startLog();
|
||||
const second = await request(app).get(`/api/companies/${company.companyId}/skills`).expect(200);
|
||||
const log = statements.stopLog();
|
||||
const after = statements.read();
|
||||
|
||||
expect(second.body).toEqual(first.body);
|
||||
expect(after.transactions - before.transactions).toBe(0);
|
||||
expect(log.filter((entry) => /pg_advisory/.test(entry.sql))).toEqual([]);
|
||||
expect(after.statements - before.statements).toBeLessThanOrEqual(45);
|
||||
expect(await bundledFolders(company.companyId)).toEqual(foldersAfterFirst);
|
||||
} finally {
|
||||
statements.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("creates exactly one folder when two first requests ensure the same category at once", async () => {
|
||||
const company = await seedCompanyWithBoardAccess(ctx.db, "Skills race");
|
||||
const [left, right] = await Promise.all([
|
||||
folderService(ctx.db).ensureBundledCategory(company.companyId, "Race Category"),
|
||||
folderService(ctx.db).ensureBundledCategory(company.companyId, "Race Category"),
|
||||
]);
|
||||
expect(left.id).toBe(right.id);
|
||||
const rows = await bundledFolders(company.companyId);
|
||||
expect(rows.filter((row) => row.systemKey === "bundled:race-category")).toHaveLength(1);
|
||||
expect(rows.filter((row) => row.systemKey === "bundled")).toHaveLength(1);
|
||||
|
||||
const app = routeApp(ctx.db, company.actor, (db) => companySkillRoutes(db));
|
||||
await Promise.all([
|
||||
request(app).get(`/api/companies/${company.companyId}/skills`).expect(200),
|
||||
request(app).get(`/api/companies/${company.companyId}/skills`).expect(200),
|
||||
]);
|
||||
const systemKeys = (await bundledFolders(company.companyId)).map((row) => row.systemKey);
|
||||
expect(new Set(systemKeys).size).toBe(systemKeys.length);
|
||||
}, 60_000);
|
||||
|
||||
it("still renames a changed category and prunes an empty one under the lock", async () => {
|
||||
const statements = meter();
|
||||
try {
|
||||
const company = await seedCompanyWithBoardAccess(ctx.db, "Skills repair");
|
||||
const svc = folderService(ctx.db);
|
||||
const locked = async (write: () => Promise<unknown>) => {
|
||||
const before = statements.read();
|
||||
statements.startLog();
|
||||
await write();
|
||||
const log = statements.stopLog();
|
||||
const lockIndex = log.findIndex((entry) => /pg_advisory_xact_lock/.test(entry.sql));
|
||||
const writes = log.filter((entry) => /^\s*(insert|update|delete)\b/i.test(entry.sql));
|
||||
return {
|
||||
transactions: statements.read().transactions - before.transactions,
|
||||
lockedBeforeWrite: lockIndex >= 0 && writes.every((entry) => entry.inTransaction && log.indexOf(entry) > lockIndex),
|
||||
writes: writes.length,
|
||||
};
|
||||
};
|
||||
|
||||
const created = await locked(() => svc.ensureBundledCategory(company.companyId, "Repair Category"));
|
||||
expect(created).toMatchObject({ transactions: 1, lockedBeforeWrite: true });
|
||||
expect(created.writes).toBeGreaterThan(0);
|
||||
const [category] = (await bundledFolders(company.companyId)).filter((row) => row.systemKey === "bundled:repair-category");
|
||||
await ctx.db.update(folders).set({ name: "Renamed by hand" }).where(eq(folders.id, category!.id));
|
||||
const renamed = await locked(() => svc.ensureBundledCategory(company.companyId, "Repair Category"));
|
||||
expect(renamed).toMatchObject({ transactions: 1, lockedBeforeWrite: true, writes: 1 });
|
||||
expect((await bundledFolders(company.companyId)).find((row) => row.id === category!.id)?.name).toBe("Repair Category");
|
||||
|
||||
expect(await locked(() => svc.pruneEmptyBundledCategories(company.companyId, ["Repair Category"])))
|
||||
.toEqual({ transactions: 0, lockedBeforeWrite: false, writes: 0 });
|
||||
expect((await bundledFolders(company.companyId)).map((row) => row.id)).toContain(category!.id);
|
||||
expect(await locked(() => svc.pruneEmptyBundledCategories(company.companyId, [])))
|
||||
.toEqual({ transactions: 1, lockedBeforeWrite: true, writes: 1 });
|
||||
expect((await bundledFolders(company.companyId)).map((row) => row.id)).not.toContain(category!.id);
|
||||
} finally {
|
||||
statements.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { environmentTaskErrorCodeData, environmentTaskOperationSchema, parseEnvi
|
||||
readEnvironmentTaskErrorCode, readEnvironmentTaskErrorDiagnostic } from "@paperclipai/plugin-sdk";
|
||||
import { executeEnvironmentTask, isSettledReadyRunnerState, settleDispatchedEnvironmentTask } from "../services/environment-task-runtime.js";
|
||||
import { NativeExecutionContext } from "../services/native-runtime/native-execution-context.js";
|
||||
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest } from "../vendor/paperclip-runner/index.js";
|
||||
|
||||
const state = vi.hoisted(() => ({ plugin: {} as any, release: vi.fn(), identity: vi.fn(), config: vi.fn() }));
|
||||
vi.mock("../services/provider-fresh-workspace.js", () => ({
|
||||
@@ -344,7 +345,7 @@ describe("plugin-provided Runner execution", () => {
|
||||
await expect(executeEnvironmentTask(database(row(), []).db, denied as never, { companyId: "company", leaseId, operation })).rejects.toThrow("project unavailable");
|
||||
expect(denied.call).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([false, true])("prepares scoped configuration with submit-time auth %s", async atSubmit => {
|
||||
it("accepts prepare launch digests only when they match the requirements", async () => {
|
||||
const operation = { kind: "prepare" as const, projectIds: [projectId], requirements: {
|
||||
schema: "paperclip.runner.launch-requirements.v1" as const,
|
||||
identity: { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run",
|
||||
@@ -353,7 +354,35 @@ describe("plugin-provided Runner execution", () => {
|
||||
settings: {}, approvalPolicy: "on-request" as const, readOnly: false,
|
||||
preparedConversation: false, includeCollaborationModeInstructions: true,
|
||||
} };
|
||||
const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}), launch: { configurationId: "configuration-1",
|
||||
const preparationDigest = runnerLaunchPreparationDigest(operation.requirements);
|
||||
const runDigest = runnerLaunchRunDigest(preparationDigest, operation.requirements);
|
||||
const result = { kind: "prepared", taskId: "attempt-1", launch: { configurationId: "configuration-1",
|
||||
requirementsDigest: `sha256:${"a".repeat(64)}`, provider: { kind: "codex" } } };
|
||||
const accepted = worker(result);
|
||||
await expect(executeEnvironmentTask(database().db, accepted as never, { companyId: "company", leaseId,
|
||||
operation: { ...operation, preparationDigest, runDigest } })).resolves.toEqual(result);
|
||||
expect(accepted.call).toHaveBeenCalledWith("original", "environmentTask", expect.objectContaining({
|
||||
operation: expect.objectContaining({ preparationDigest, runDigest }) }), 15_000);
|
||||
const forged = `sha256:${"b".repeat(64)}`;
|
||||
for (const digests of [{ preparationDigest: forged, runDigest }, { preparationDigest, runDigest: forged },
|
||||
{ preparationDigest }, { runDigest }]) {
|
||||
const refused = worker(result);
|
||||
await expect(executeEnvironmentTask(database().db, refused as never, { companyId: "company", leaseId,
|
||||
operation: { ...operation, ...digests } })).rejects.toThrow("launch digest mismatch");
|
||||
expect(refused.call).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
it.each([[false, false], [true, false], [false, true], [true, true]])("prepares scoped configuration with submit-time auth %s and in-prepare auth %s", async (atSubmit, checked) => {
|
||||
const operation = { kind: "prepare" as const, projectIds: [projectId], requirements: {
|
||||
schema: "paperclip.runner.launch-requirements.v1" as const,
|
||||
identity: { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run",
|
||||
normalizedSessionId: "session", turnId: "turn", itemId: "item" },
|
||||
provider: "codex" as const, model: "selected", instructions: "Core instructions", runtimeContext: null,
|
||||
settings: {}, approvalPolicy: "on-request" as const, readOnly: false,
|
||||
preparedConversation: false, includeCollaborationModeInstructions: true,
|
||||
} };
|
||||
const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}),
|
||||
...(checked ? {projectAuthChecked: true} : {}), launch: { configurationId: "configuration-1",
|
||||
requirementsDigest: `sha256:${"a".repeat(64)}`, provider: { kind: "codex" } } };
|
||||
const workers = worker(result), store = database();
|
||||
await expect(executeEnvironmentTask(store.db, workers as never, { companyId: "company", leaseId, operation }))
|
||||
@@ -361,9 +390,10 @@ describe("plugin-provided Runner execution", () => {
|
||||
expect(workers.call).toHaveBeenCalledWith("original", "environmentTask", expect.objectContaining({
|
||||
companyId: "company", runId: "run", agentId: "agent", projectIds: [projectId], operation,
|
||||
}), 15_000);
|
||||
expect(store.sets).toHaveLength(atSubmit ? 2 : 1);
|
||||
if (atSubmit) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({
|
||||
runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId], atSubmit: true },
|
||||
expect(store.sets).toHaveLength(atSubmit || checked ? 2 : 1);
|
||||
if (atSubmit || checked) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({
|
||||
runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId],
|
||||
...(checked ? {} : { atSubmit: true }) },
|
||||
}));
|
||||
const denied = worker(result);
|
||||
const inactive = row(); inactive.lease.status = "released";
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
{
|
||||
"id": "<id:0>",
|
||||
"companyId": "<id:1>",
|
||||
"conversationAgentId": null,
|
||||
"conversationUserId": null,
|
||||
"conversationState": null,
|
||||
"conversationSessionGeneration": 0,
|
||||
"conversationBoundaryCommentId": null,
|
||||
"projectId": "<id:2>",
|
||||
"projectWorkspaceId": null,
|
||||
"goalId": null,
|
||||
"parentId": "<id:3>",
|
||||
"visibility": "open",
|
||||
"privacyRootIssueId": null,
|
||||
"privacyParentIssueId": null,
|
||||
"title": "Detail task",
|
||||
"titleNeedsGeneration": false,
|
||||
"description": "Uses [@Detail project](project://<id:2>)",
|
||||
"status": "in_progress",
|
||||
"statusVersion": 0,
|
||||
"lastStatusDecisionId": null,
|
||||
"workMode": "standard",
|
||||
"harnessKind": null,
|
||||
"priority": "high",
|
||||
"reviewPolicy": null,
|
||||
"assigneeAgentId": "<id:4>",
|
||||
"assigneeUserId": null,
|
||||
"checkoutRunId": null,
|
||||
"executionRunId": null,
|
||||
"executionAgentNameKey": null,
|
||||
"executionLockedAt": null,
|
||||
"createdByAgentId": null,
|
||||
"createdByUserId": "<user>",
|
||||
"responsibleUserId": null,
|
||||
"issueNumber": null,
|
||||
"identifier": null,
|
||||
"originKind": "manual",
|
||||
"originId": null,
|
||||
"originRunId": null,
|
||||
"originIssueId": null,
|
||||
"originIdentityContextId": null,
|
||||
"continuationIdentityContextId": null,
|
||||
"originFingerprint": "default",
|
||||
"requestDepth": 0,
|
||||
"billingCode": null,
|
||||
"assigneeAdapterOverrides": null,
|
||||
"executionPolicy": null,
|
||||
"executionState": null,
|
||||
"monitorNextCheckAt": null,
|
||||
"monitorWakeRequestedAt": null,
|
||||
"monitorLastTriggeredAt": null,
|
||||
"monitorAttemptCount": 0,
|
||||
"monitorNotes": null,
|
||||
"monitorScheduledBy": null,
|
||||
"executionWorkspaceId": null,
|
||||
"workspaceBindingRevision": 0,
|
||||
"workspaceSelection": null,
|
||||
"workspacePendingSelection": null,
|
||||
"executionWorkspacePreference": null,
|
||||
"executionWorkspaceSettings": null,
|
||||
"sourceTrust": null,
|
||||
"unblockDescriptor": null,
|
||||
"blockedTransitionAt": null,
|
||||
"blockedOwnerNotifiedAt": null,
|
||||
"startedAt": null,
|
||||
"completedAt": null,
|
||||
"cancelledAt": null,
|
||||
"hiddenAt": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>",
|
||||
"displayStatus": "todo",
|
||||
"externalConversationState": null,
|
||||
"labels": [],
|
||||
"labelIds": [],
|
||||
"watchdog": null,
|
||||
"ancestors": [
|
||||
{
|
||||
"id": "<id:3>",
|
||||
"identifier": null,
|
||||
"title": "Detail parent",
|
||||
"description": null,
|
||||
"status": "todo",
|
||||
"priority": "medium",
|
||||
"assigneeAgentId": null,
|
||||
"projectId": null,
|
||||
"goalId": null,
|
||||
"project": null,
|
||||
"goal": null
|
||||
},
|
||||
{
|
||||
"id": "<id:6>",
|
||||
"identifier": null,
|
||||
"title": "Detail grandparent",
|
||||
"description": null,
|
||||
"status": "todo",
|
||||
"priority": "medium",
|
||||
"assigneeAgentId": null,
|
||||
"projectId": "<id:2>",
|
||||
"goalId": null,
|
||||
"project": {
|
||||
"id": "<id:2>",
|
||||
"name": "Detail project",
|
||||
"description": null,
|
||||
"status": "backlog",
|
||||
"goalId": null,
|
||||
"workspaces": [],
|
||||
"primaryWorkspace": null
|
||||
},
|
||||
"goal": null
|
||||
}
|
||||
],
|
||||
"blockerAttention": {
|
||||
"state": "none",
|
||||
"reason": null,
|
||||
"unresolvedBlockerCount": 0,
|
||||
"coveredBlockerCount": 0,
|
||||
"stalledBlockerCount": 0,
|
||||
"attentionBlockerCount": 0,
|
||||
"pendingFinalizeBlockerIssueIds": [],
|
||||
"sampleBlockerIdentifier": null,
|
||||
"sampleStalledBlockerIdentifier": null,
|
||||
"blockingTreeLive": false,
|
||||
"directBlockerIssueId": null,
|
||||
"terminalBlockerIssueId": null,
|
||||
"terminalBlocker": null
|
||||
},
|
||||
"reviewAttention": {
|
||||
"state": "none",
|
||||
"paths": [],
|
||||
"reason": null
|
||||
},
|
||||
"successfulRunHandoff": null,
|
||||
"executionBlocker": null,
|
||||
"interruption": null,
|
||||
"scheduledRetry": null,
|
||||
"activeRecoveryAction": null,
|
||||
"stalledDependencies": [],
|
||||
"blockedBy": [
|
||||
{
|
||||
"id": "<id:7>",
|
||||
"identifier": null,
|
||||
"title": "Detail blocker",
|
||||
"status": "todo",
|
||||
"displayStatus": "todo",
|
||||
"priority": "medium",
|
||||
"assigneeAgentId": null,
|
||||
"assigneeUserId": null,
|
||||
"scheduledRetry": null,
|
||||
"activeRecoveryAction": null
|
||||
}
|
||||
],
|
||||
"blocks": [],
|
||||
"relatedWork": {
|
||||
"outbound": [],
|
||||
"inbound": []
|
||||
},
|
||||
"referencedIssueIdentifiers": [],
|
||||
"planDocument": null,
|
||||
"documentSummaries": [],
|
||||
"legacyPlanDocument": null,
|
||||
"project": {
|
||||
"id": "<id:2>",
|
||||
"companyId": "<id:1>",
|
||||
"urlKey": "detail-project",
|
||||
"goalId": null,
|
||||
"goalIds": [],
|
||||
"goals": [],
|
||||
"name": "Detail project",
|
||||
"description": null,
|
||||
"visibility": "open",
|
||||
"personalOwnerUserId": null,
|
||||
"status": "backlog",
|
||||
"leadAgentId": null,
|
||||
"targetDate": null,
|
||||
"color": null,
|
||||
"icon": null,
|
||||
"env": null,
|
||||
"pauseReason": null,
|
||||
"pausedAt": null,
|
||||
"executionWorkspacePolicy": null,
|
||||
"codebase": {
|
||||
"workspaceId": null,
|
||||
"repoUrl": null,
|
||||
"repoRef": null,
|
||||
"defaultRef": null,
|
||||
"repoName": null,
|
||||
"localFolder": null,
|
||||
"managedFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"effectiveLocalFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"origin": "managed_checkout"
|
||||
},
|
||||
"workspaces": [],
|
||||
"primaryWorkspace": null,
|
||||
"managedByPlugin": null,
|
||||
"archivedAt": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>"
|
||||
},
|
||||
"goal": null,
|
||||
"mentionedProjects": [
|
||||
{
|
||||
"id": "<id:2>",
|
||||
"companyId": "<id:1>",
|
||||
"goalId": null,
|
||||
"name": "Detail project",
|
||||
"description": null,
|
||||
"visibility": "open",
|
||||
"privacyOwnerUserId": null,
|
||||
"personalOwnerUserId": null,
|
||||
"status": "backlog",
|
||||
"leadAgentId": null,
|
||||
"decisionOwnerUserId": null,
|
||||
"targetDate": null,
|
||||
"color": null,
|
||||
"icon": null,
|
||||
"env": null,
|
||||
"gitAuthorizationGrantId": null,
|
||||
"gitAuthorizedByUserId": null,
|
||||
"pauseReason": null,
|
||||
"pausedAt": null,
|
||||
"executionWorkspacePolicy": null,
|
||||
"archivedAt": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>",
|
||||
"urlKey": "detail-project",
|
||||
"goalIds": [],
|
||||
"goals": [],
|
||||
"codebase": {
|
||||
"workspaceId": null,
|
||||
"repoUrl": null,
|
||||
"repoRef": null,
|
||||
"defaultRef": null,
|
||||
"repoName": null,
|
||||
"localFolder": null,
|
||||
"managedFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"effectiveLocalFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"origin": "managed_checkout"
|
||||
},
|
||||
"workspaces": [],
|
||||
"primaryWorkspace": null,
|
||||
"managedByPlugin": null,
|
||||
"workspaceProvider": {
|
||||
"source": "core",
|
||||
"pluginId": null,
|
||||
"displayName": "Core / local",
|
||||
"providers": [],
|
||||
"effectivePolicy": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"currentExecutionWorkspace": null,
|
||||
"workProducts": [
|
||||
{
|
||||
"id": "<id:8>",
|
||||
"companyId": "<id:1>",
|
||||
"projectId": "<id:2>",
|
||||
"issueId": "<id:0>",
|
||||
"executionWorkspaceId": null,
|
||||
"runtimeServiceId": null,
|
||||
"type": "pull_request",
|
||||
"provider": "github",
|
||||
"externalId": null,
|
||||
"title": "Fixture PR",
|
||||
"url": "https://example.test/pr/1",
|
||||
"status": "open",
|
||||
"reviewState": "none",
|
||||
"isPrimary": false,
|
||||
"healthStatus": "unknown",
|
||||
"summary": null,
|
||||
"metadata": null,
|
||||
"sourceTrust": null,
|
||||
"createdByRunId": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>"
|
||||
}
|
||||
],
|
||||
"externalChannelBinding": null,
|
||||
"createdFrom": null
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import net from "node:net";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
|
||||
export type MeteredStatement = { sql: string; parameters: number; rows: number; ms: number; inTransaction: boolean };
|
||||
export type MeteredStatement = { sql: string; parameters: number; rows: number; ms: number; inTransaction: boolean; stack?: string };
|
||||
|
||||
type Method = (this: unknown, ...args: unknown[]) => unknown;
|
||||
|
||||
@@ -27,6 +27,7 @@ export function meterDatabaseStatements(db: Db, databaseUrl: string) {
|
||||
const totals = { statements: 0, transactions: 0, waits: 0, rows: 0, sqlBytes: 0 };
|
||||
let inFlight = 0;
|
||||
let log: MeteredStatement[] | null = null;
|
||||
let captureStacks = false;
|
||||
const visited = new WeakSet<object>();
|
||||
const visit = (value: unknown, inTransaction: boolean) => {
|
||||
if ((typeof value !== "object" || value === null) && typeof value !== "function") return;
|
||||
@@ -42,7 +43,13 @@ export function meterDatabaseStatements(db: Db, databaseUrl: string) {
|
||||
if (inFlight === 0) totals.waits += 1;
|
||||
inFlight += 1;
|
||||
const pending = Reflect.apply(unsafe, this, args) as PromiseLike<{ length: number }>;
|
||||
const entry = { sql: query, parameters: Array.isArray(args[1]) ? args[1].length : 0, rows: 0, ms: 0, inTransaction };
|
||||
const entry: MeteredStatement = { sql: query, parameters: Array.isArray(args[1]) ? args[1].length : 0, rows: 0, ms: 0, inTransaction };
|
||||
if (log && captureStacks) {
|
||||
const limit = Error.stackTraceLimit;
|
||||
Error.stackTraceLimit = 60;
|
||||
entry.stack = new Error().stack;
|
||||
Error.stackTraceLimit = limit;
|
||||
}
|
||||
log?.push(entry);
|
||||
// The query starts one microtask after its first `then`, so a caller
|
||||
// can still select the result format on the returned query.
|
||||
@@ -79,7 +86,7 @@ export function meterDatabaseStatements(db: Db, databaseUrl: string) {
|
||||
/** The totals since the client started. Subtract two readings to meter one request. */
|
||||
read: () => ({ ...totals, bytesReceived: bytesReceived() }),
|
||||
/** Records every statement until `stopLog`. */
|
||||
startLog: () => { log = []; },
|
||||
startLog: (options: { stacks?: boolean } = {}) => { log = []; captureStacks = options.stacks === true; },
|
||||
stopLog: () => {
|
||||
const recorded = log ?? [];
|
||||
log = null;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import express from "express";
|
||||
import { agents, authUsers, issueComments, issueWorkProducts, issues, projects, type Db } from "@paperclipai/db";
|
||||
import { actorMiddleware } from "../../middleware/auth.js";
|
||||
import { errorHandler } from "../../middleware/error-handler.js";
|
||||
import { activityRoutes } from "../../routes/activity.js";
|
||||
import { agentRoutes } from "../../routes/agents.js";
|
||||
import { companySkillRoutes } from "../../routes/company-skills.js";
|
||||
import { dashboardRoutes } from "../../routes/dashboard.js";
|
||||
import { issueRoutes } from "../../routes/issues.js";
|
||||
import { sidebarBadgeRoutes } from "../../routes/sidebar-badges.js";
|
||||
import { seedCompanyWithBoardAccess } from "./route-test-harness.js";
|
||||
|
||||
export function boardSessionApp(db: Db, sessionUserId: () => string | null) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(actorMiddleware(db, {
|
||||
deploymentMode: "authenticated",
|
||||
resolveSession: async () => {
|
||||
const userId = sessionUserId();
|
||||
return userId ? {
|
||||
session: { id: `session-${userId}`, userId },
|
||||
user: { id: userId, name: "Board user", email: `${userId}@example.test` },
|
||||
} : null;
|
||||
},
|
||||
}));
|
||||
app.use("/api", issueRoutes(db, {} as never));
|
||||
app.use("/api", agentRoutes(db));
|
||||
app.use("/api", activityRoutes(db));
|
||||
app.use("/api", companySkillRoutes(db));
|
||||
app.use("/api", sidebarBadgeRoutes(db));
|
||||
app.use("/api", dashboardRoutes(db));
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
export async function seedBoardRouteFixture(db: Db, name: string, commentCount = 3) {
|
||||
const company = await seedCompanyWithBoardAccess(db, name);
|
||||
const now = new Date("2026-11-01T00:00:00.000Z");
|
||||
await db.insert(authUsers).values({
|
||||
id: company.userId, name, email: `${company.userId}@example.test`, emailVerified: true, createdAt: now, updatedAt: now,
|
||||
});
|
||||
const [agent] = await db.insert(agents).values({
|
||||
companyId: company.companyId, name: `${name} agent`, role: "engineer", adapterType: "process", status: "idle",
|
||||
}).returning();
|
||||
const [project] = await db.insert(projects).values({ companyId: company.companyId, name: `${name} project` }).returning();
|
||||
const [parent] = await db.insert(issues).values({
|
||||
companyId: company.companyId, title: `${name} parent`, status: "todo", createdByUserId: company.userId,
|
||||
createdAt: now, updatedAt: now,
|
||||
}).returning();
|
||||
const [issue] = await db.insert(issues).values({
|
||||
companyId: company.companyId, title: `${name} task`, description: "Fixture task", status: "in_progress",
|
||||
priority: "high", parentId: parent!.id, projectId: project!.id, assigneeAgentId: agent!.id,
|
||||
createdByUserId: company.userId, createdAt: now, updatedAt: now,
|
||||
}).returning();
|
||||
if (commentCount > 0) {
|
||||
await db.insert(issueComments).values(Array.from({ length: commentCount }, (_, index) => ({
|
||||
companyId: company.companyId, issueId: issue!.id, authorUserId: company.userId, authorType: "user" as const,
|
||||
body: `Comment ${index}`, createdAt: new Date(now.getTime() + (index + 1) * 1000), updatedAt: now,
|
||||
})));
|
||||
}
|
||||
await db.insert(issueWorkProducts).values({
|
||||
companyId: company.companyId, projectId: project!.id, issueId: issue!.id, type: "pull_request", provider: "github",
|
||||
title: "Fixture PR", url: "https://example.test/pr/1", status: "open", createdAt: now, updatedAt: now,
|
||||
});
|
||||
return { ...company, agent: agent!, project: project!, parent: parent!, issue: issue! };
|
||||
}
|
||||
|
||||
export type BoardRouteFixture = Awaited<ReturnType<typeof seedBoardRouteFixture>>;
|
||||
|
||||
export function boardCensusRoutes(fixture: BoardRouteFixture) {
|
||||
const { companyId, issue, parent } = fixture;
|
||||
return [
|
||||
["GET /api/issues/:id", `/api/issues/${issue.id}`],
|
||||
["GET /api/issues/:id/comments", `/api/issues/${issue.id}/comments`],
|
||||
["GET /api/issues/:id/activity", `/api/issues/${issue.id}/activity`],
|
||||
["GET /api/issues/:id/interactions", `/api/issues/${issue.id}/interactions`],
|
||||
["GET /api/issues/:id/work-products", `/api/issues/${issue.id}/work-products`],
|
||||
["GET /api/companies/:id/issues", `/api/companies/${companyId}/issues`],
|
||||
["GET /api/companies/:id/issues/summaries?ids", `/api/companies/${companyId}/issues/summaries?ids=${issue.id},${parent.id}`],
|
||||
["GET /api/companies/:id/live-runs", `/api/companies/${companyId}/live-runs`],
|
||||
["GET /api/companies/:id/skills", `/api/companies/${companyId}/skills`],
|
||||
["GET /api/companies/:id/sidebar-badges", `/api/companies/${companyId}/sidebar-badges`],
|
||||
["GET /api/companies/:id/dashboard", `/api/companies/${companyId}/dashboard`],
|
||||
["GET /api/companies/:id/agents", `/api/companies/${companyId}/agents`],
|
||||
["GET /api/companies/:id/chats", `/api/companies/${companyId}/chats`],
|
||||
] as const;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { meterDatabaseStatements, type MeteredStatement } from "./database-statement-meter.js";
|
||||
|
||||
export type StatementShape = { shape: string; count: number; callers: string[] };
|
||||
export type RequestCensus = { statements: number; transactions: number; shapes: StatementShape[]; log: MeteredStatement[] };
|
||||
|
||||
export function normalizeStatementShape(sql: string) {
|
||||
return sql
|
||||
.replace(/\s+/g, " ")
|
||||
.replace(/\$\d+(?:\s*,\s*\$\d+)*/g, "$n")
|
||||
.replace(/\(\s*\$n\s*\)(?:\s*,\s*\(\s*\$n\s*\))+/g, "($n)")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function statementCaller(stack: string | undefined, depth = 3) {
|
||||
if (!stack) return "unknown";
|
||||
const frames = stack.split("\n").slice(1).map((line) => line.trim())
|
||||
.filter((line) => line.includes("/server/src/") && !line.includes("/__tests__/"))
|
||||
.slice(0, depth)
|
||||
.map((line) => {
|
||||
const match = /at (?:async )?(?:(\S+) )?\(?.*\/server\/src\/([^:)]+):(\d+)/.exec(line);
|
||||
return match ? `${match[2]}:${match[3]}${match[1] ? ` ${match[1]}` : ""}` : line;
|
||||
});
|
||||
return frames.length > 0 ? frames.join(" < ") : "unknown";
|
||||
}
|
||||
|
||||
export function groupStatementShapes(log: MeteredStatement[]): StatementShape[] {
|
||||
const byShape = new Map<string, StatementShape>();
|
||||
for (const entry of log) {
|
||||
const shape = normalizeStatementShape(entry.sql);
|
||||
const group = byShape.get(shape) ?? { shape, count: 0, callers: [] };
|
||||
group.count += 1;
|
||||
const caller = statementCaller(entry.stack);
|
||||
if (!group.callers.includes(caller)) group.callers.push(caller);
|
||||
byShape.set(shape, group);
|
||||
}
|
||||
return [...byShape.values()].sort((left, right) => right.count - left.count);
|
||||
}
|
||||
|
||||
export function createStatementCensus(db: Db) {
|
||||
const { host, port } = (db.$client as unknown as { options: { host: string[]; port: number[] } }).options;
|
||||
const meter = meterDatabaseStatements(db, `postgres://${host[0]}:${port[0]}/census`);
|
||||
return {
|
||||
async measure(run: () => Promise<unknown>, options: { stacks?: boolean } = {}): Promise<RequestCensus> {
|
||||
const before = meter.read();
|
||||
meter.startLog(options);
|
||||
let log: MeteredStatement[];
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
log = meter.stopLog();
|
||||
}
|
||||
const after = meter.read();
|
||||
return {
|
||||
statements: after.statements - before.statements,
|
||||
transactions: after.transactions - before.transactions,
|
||||
shapes: groupStatementShapes(log),
|
||||
log,
|
||||
};
|
||||
},
|
||||
uninstall: () => meter.uninstall(),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatStatementCensus(label: string, census: RequestCensus, top = 5) {
|
||||
const lines = [`${label}: ${census.statements} statements, ${census.transactions} transactions`];
|
||||
for (const shape of census.shapes.slice(0, top)) {
|
||||
lines.push(` ${String(shape.count).padStart(3)}x ${shape.shape.slice(0, 160)}`);
|
||||
for (const caller of shape.callers.slice(0, 3)) lines.push(` ${caller}`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { agentApiKeys, agents, authUsers, boardApiKeys, companies, companyMemberships, createDb, databaseStatementCount,
|
||||
instanceUserRoles } from "@paperclipai/db";
|
||||
import { createApp } from "../app.js";
|
||||
import { activeServerMetrics, recordMissedLeaseRenewal, recordRunEventCommitted } from "../services/server-metrics.js";
|
||||
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
|
||||
import { createStorageService } from "../storage/service.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const describePostgres = support.supported ? describe : describe.skip;
|
||||
const PATH = "/api/instance/server-metrics";
|
||||
const FIELDS = [
|
||||
"schema", "processId", "buildRevision", "uptimeSec", "sampledAt", "windowMs", "mainThreadCpu", "processCpu",
|
||||
"eventLoopUtilization", "eventLoopDelayP99Ms", "statementsPerSecond", "runEventLatenessP99Ms", "runEventLatenessSamples",
|
||||
"agentApiPreHandlerP99Ms", "agentApiPreHandlerSamples", "leaseRenewalsMissed", "dedicatedConnections",
|
||||
].sort();
|
||||
|
||||
type Db = ReturnType<typeof createDb>;
|
||||
type App = Awaited<ReturnType<typeof createApp>>;
|
||||
|
||||
describePostgres("instance server metrics route", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: Db;
|
||||
let directory: string;
|
||||
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||
const ids = { companyId: randomUUID(), agentId: randomUUID(), adminId: randomUUID(), memberId: randomUUID() };
|
||||
const keys = { admin: `pcp_board_${randomUUID()}`, member: `pcp_board_${randomUUID()}`, agent: `pcp_agent_${randomUUID()}` };
|
||||
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("instance-server-metrics-");
|
||||
db = createDb(database.connectionString);
|
||||
directory = await mkdtemp(join(tmpdir(), "instance-server-metrics-storage-"));
|
||||
await db.insert(companies).values({ id: ids.companyId, name: "Metrics company", issuePrefix: "MET" });
|
||||
await db.insert(authUsers).values([ids.adminId, ids.memberId].map(id => ({ id, name: "Person", email: `${id}@example.com`,
|
||||
createdAt: new Date(), updatedAt: new Date() })));
|
||||
await db.insert(instanceUserRoles).values({ userId: ids.adminId, role: "instance_admin" });
|
||||
await db.insert(agents).values({ id: ids.agentId, companyId: ids.companyId, name: "Metrics agent", adapterType: "process",
|
||||
status: "idle", permissions: {}, runtimeConfig: { heartbeat: { wakeOnDemand: false, intervalSec: 0 } } });
|
||||
await db.insert(companyMemberships).values([
|
||||
{ companyId: ids.companyId, principalType: "user", principalId: ids.memberId, membershipRole: "owner", status: "active" },
|
||||
{ companyId: ids.companyId, principalType: "agent", principalId: ids.agentId, membershipRole: "member", status: "active" },
|
||||
]);
|
||||
await db.insert(boardApiKeys).values([
|
||||
{ userId: ids.adminId, name: "Admin", keyHash: hash(keys.admin) },
|
||||
{ userId: ids.memberId, name: "Member", keyHash: hash(keys.member) },
|
||||
]);
|
||||
await db.insert(agentApiKeys).values({ companyId: ids.companyId, agentId: ids.agentId, name: "Agent", keyHash: hash(keys.agent),
|
||||
responsibleUserId: ids.memberId });
|
||||
}, 120_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end();
|
||||
await database?.cleanup();
|
||||
if (directory) await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function serve<T>(serverMetricsEnabled: boolean, body: (call: (path: string, token?: string) => Promise<{ status: number; body: any; text: string }>) => Promise<T>) {
|
||||
const app: App = await createApp(db, {
|
||||
uiMode: "none", serverPort: 0, bindHost: "127.0.0.1", allowedHostnames: ["127.0.0.1"],
|
||||
deploymentMode: "authenticated", deploymentExposure: "private", authReady: true, companyDeletionEnabled: false,
|
||||
managedPluginAutoInstall: [], storageService: createStorageService(createLocalDiskStorageProvider(directory)),
|
||||
decisionServiceOptions: { wakeOriginAgent: async () => null }, serverMetricsEnabled,
|
||||
});
|
||||
await app.locals.bundledPluginsStartup;
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
try {
|
||||
await new Promise<void>(resolve => server.once("listening", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("No HTTP test address");
|
||||
const call = async (path: string, token?: string) => {
|
||||
const response = await fetch(`http://127.0.0.1:${address.port}${path}`, { headers: token ? { authorization: `Bearer ${token}` } : {} });
|
||||
const text = await response.text();
|
||||
let parsed: unknown = null;
|
||||
try { parsed = JSON.parse(text); } catch { parsed = null; }
|
||||
return { status: response.status, body: parsed, text };
|
||||
};
|
||||
return await body(call);
|
||||
} finally {
|
||||
await app.locals.paperclipShutdown?.();
|
||||
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
it("serves numbers to an instance admin only, and they move with load", async () => {
|
||||
await serve(true, async (call) => {
|
||||
expect(activeServerMetrics()).not.toBeNull();
|
||||
expect([401, 403]).toContain((await call(PATH)).status);
|
||||
expect((await call(PATH, keys.member)).status).toBe(403);
|
||||
expect((await call(PATH, keys.agent)).status).toBe(403);
|
||||
|
||||
const first = await call(PATH, keys.admin);
|
||||
expect(first.status).toBe(200);
|
||||
expect(Object.keys(first.body).sort()).toEqual(FIELDS);
|
||||
expect(first.body).toMatchObject({ schema: "paperclip.server-metrics.v1", processId: expect.stringMatching(/^[0-9a-f]{16}$/) });
|
||||
expect(first.body.buildRevision === null || /^[0-9a-f]{40}$/.test(first.body.buildRevision)).toBe(true);
|
||||
for (const field of ["uptimeSec", "windowMs", "processCpu", "eventLoopUtilization", "eventLoopDelayP99Ms", "statementsPerSecond",
|
||||
"runEventLatenessSamples", "agentApiPreHandlerSamples", "leaseRenewalsMissed"]) {
|
||||
expect(typeof first.body[field], field).toBe("number");
|
||||
}
|
||||
expect(first.body.eventLoopUtilization).toBeGreaterThanOrEqual(0);
|
||||
expect(first.body.dedicatedConnections).toMatchObject({ limit: expect.any(Number), inUse: expect.any(Number), waiting: expect.any(Number),
|
||||
queued: expect.any(Number) });
|
||||
expect(first.body.eventLoopUtilization).toBeLessThanOrEqual(1);
|
||||
|
||||
const statementsBefore = databaseStatementCount();
|
||||
for (let index = 0; index < 5; index += 1) expect((await call("/api/agents/me", keys.agent)).status).toBe(200);
|
||||
expect(databaseStatementCount()).toBeGreaterThan(statementsBefore);
|
||||
recordRunEventCommitted(new Date(Date.now() - 750).toISOString(), Date.now());
|
||||
recordMissedLeaseRenewal();
|
||||
|
||||
const second = await call(PATH, keys.admin);
|
||||
expect(second.status).toBe(200);
|
||||
expect(second.body.processId).toBe(first.body.processId);
|
||||
expect(second.body.agentApiPreHandlerSamples).toBeGreaterThanOrEqual(first.body.agentApiPreHandlerSamples + 5);
|
||||
expect(second.body.agentApiPreHandlerP99Ms).toBeGreaterThan(0);
|
||||
expect(second.body.statementsPerSecond).toBeGreaterThan(0);
|
||||
expect(second.body.runEventLatenessSamples).toBe(first.body.runEventLatenessSamples + 1);
|
||||
expect(second.body.runEventLatenessP99Ms).toBeGreaterThanOrEqual(700);
|
||||
expect(second.body.leaseRenewalsMissed).toBe(first.body.leaseRenewalsMissed + 1);
|
||||
for (const secret of [...Object.values(ids), ...Object.values(keys)]) expect(second.text).not.toContain(secret);
|
||||
expect(second.text).not.toMatch(/select|insert|update|from\s/i);
|
||||
});
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
}, 240_000);
|
||||
|
||||
it("is absent and collects nothing when the kill switch is off", async () => {
|
||||
await serve(false, async (call) => {
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
expect((await call(PATH, keys.admin)).status).toBe(404);
|
||||
expect((await call(PATH, keys.member)).status).toBe(404);
|
||||
expect((await call("/api/agents/me", keys.agent)).status).toBe(200);
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
});
|
||||
}, 240_000);
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import request from "supertest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { expect, it } from "vitest";
|
||||
import { authUsers, companies, companyMemberships, issueRelations, issues } from "@paperclipai/db";
|
||||
import { boardSessionApp, seedBoardRouteFixture } from "./helpers/route-census-fixture.js";
|
||||
import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
import { createStatementCensus, formatStatementCensus } from "./helpers/statement-census.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
|
||||
|
||||
const GOLDEN = new URL("./fixtures/issue-detail-response.json", import.meta.url);
|
||||
|
||||
function normalizeResponse(body: unknown, issuePrefix: string) {
|
||||
const ids = new Map<string, string>();
|
||||
const text = JSON.stringify(body, null, 2)
|
||||
.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, (id) => {
|
||||
if (!ids.has(id)) ids.set(id, `<id:${ids.size}>`);
|
||||
return ids.get(id)!;
|
||||
})
|
||||
.replace(/"[^"]*\/instances\/[^/"]+\//g, "\"<home>/")
|
||||
.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g, "<time>")
|
||||
.replaceAll(issuePrefix, "<prefix>")
|
||||
.replace(/user-<id:\d+>/g, "<user>");
|
||||
return `${text}\n`;
|
||||
}
|
||||
|
||||
describeEmbeddedPostgres("GET /api/issues/:id statements per request", () => {
|
||||
const ctx = useEmbeddedPostgres("issue-detail-statements-");
|
||||
|
||||
async function seed() {
|
||||
const fixture = await seedBoardRouteFixture(ctx.db, "Detail");
|
||||
const [grandparent] = await ctx.db.insert(issues).values({
|
||||
companyId: fixture.companyId, title: "Detail grandparent", status: "todo", projectId: fixture.project.id,
|
||||
createdByUserId: fixture.userId, createdAt: new Date("2026-10-30T00:00:00.000Z"), updatedAt: new Date("2026-10-30T00:00:00.000Z"),
|
||||
}).returning();
|
||||
await ctx.db.update(issues).set({ parentId: grandparent!.id }).where(eq(issues.id, fixture.parent.id));
|
||||
const [blocker] = await ctx.db.insert(issues).values({
|
||||
companyId: fixture.companyId, title: "Detail blocker", status: "todo", createdByUserId: fixture.userId,
|
||||
createdAt: new Date("2026-10-31T00:00:00.000Z"), updatedAt: new Date("2026-10-31T00:00:00.000Z"),
|
||||
}).returning();
|
||||
await ctx.db.insert(issueRelations).values({
|
||||
companyId: fixture.companyId, issueId: blocker!.id, relatedIssueId: fixture.issue.id, type: "blocks",
|
||||
});
|
||||
await ctx.db.update(issues).set({ description: `Uses [@Detail project](project://${fixture.project.id})` })
|
||||
.where(eq(issues.id, fixture.issue.id));
|
||||
const [company] = await ctx.db.select({ issuePrefix: companies.issuePrefix }).from(companies)
|
||||
.where(eq(companies.id, fixture.companyId));
|
||||
return { ...fixture, grandparent: grandparent!, blocker: blocker!, issuePrefix: company!.issuePrefix };
|
||||
}
|
||||
|
||||
it("answers the issue detail with the same JSON in fewer statements", async () => {
|
||||
const census = createStatementCensus(ctx.db);
|
||||
try {
|
||||
const fixture = await seed();
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const path = `/api/issues/${fixture.issue.id}`;
|
||||
await request(app).get(path).expect(200);
|
||||
let response: request.Response | undefined;
|
||||
const measured = await census.measure(async () => {
|
||||
response = await request(app).get(path).expect(200);
|
||||
}, { stacks: true });
|
||||
|
||||
const normalized = normalizeResponse(response!.body, fixture.issuePrefix);
|
||||
if (process.env.PAPERCLIP_WRITE_ISSUE_DETAIL_GOLDEN) writeFileSync(GOLDEN, normalized);
|
||||
expect(normalized).toBe(readFileSync(GOLDEN, "utf8"));
|
||||
expect(response!.body.ancestors.map((ancestor: { id: string }) => ancestor.id))
|
||||
.toEqual([fixture.parent.id, fixture.grandparent.id]);
|
||||
expect(response!.body.blockedBy.map((relation: { id: string }) => relation.id)).toEqual([fixture.blocker.id]);
|
||||
expect(response!.body.mentionedProjects.map((project: { id: string }) => project.id)).toEqual([fixture.project.id]);
|
||||
expect(measured.statements, formatStatementCensus(path, measured, 80)).toBeLessThanOrEqual(64);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("keeps the access rules: another company's user, a missing issue and a hidden issue", async () => {
|
||||
const fixture = await seed();
|
||||
const outsider = await seedBoardRouteFixture(ctx.db, "Outsider");
|
||||
const [hidden] = await ctx.db.insert(issues).values({
|
||||
companyId: fixture.companyId, title: "Hidden", status: "todo", hiddenAt: new Date(),
|
||||
}).returning();
|
||||
const memberApp = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const outsiderApp = boardSessionApp(ctx.db, () => outsider.userId);
|
||||
const anonymousApp = boardSessionApp(ctx.db, () => null);
|
||||
|
||||
const statuses = {
|
||||
outsiderReadsMemberIssue: (await request(outsiderApp).get(`/api/issues/${fixture.issue.id}`)).status,
|
||||
memberReadsOtherCompanyIssue: (await request(memberApp).get(`/api/issues/${outsider.issue.id}`)).status,
|
||||
memberReadsMissingIssue: (await request(memberApp).get(`/api/issues/${randomUUID()}`)).status,
|
||||
anonymousReadsMemberIssue: (await request(anonymousApp).get(`/api/issues/${fixture.issue.id}`)).status,
|
||||
};
|
||||
expect(statuses).toEqual({
|
||||
outsiderReadsMemberIssue: 404,
|
||||
memberReadsOtherCompanyIssue: 404,
|
||||
memberReadsMissingIssue: 404,
|
||||
anonymousReadsMemberIssue: 404,
|
||||
});
|
||||
const hiddenResponse = await request(memberApp).get(`/api/issues/${hidden!.id}`);
|
||||
expect(hiddenResponse.status).toBe(200);
|
||||
expect(hiddenResponse.body.hiddenAt).not.toBeNull();
|
||||
}, 60_000);
|
||||
|
||||
it("denies the very next request after the membership is removed", async () => {
|
||||
const fixture = await seed();
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(404);
|
||||
await ctx.db.delete(authUsers).where(eq(authUsers.id, fixture.userId));
|
||||
}, 60_000);
|
||||
it("walks the ancestor chain nearest first, stops at a cycle and ignores a task that is its own parent", async () => {
|
||||
const fixture = await seed();
|
||||
const svc = issueService(ctx.db);
|
||||
await ctx.db.update(issues).set({ parentId: fixture.parent.id }).where(eq(issues.id, fixture.grandparent.id));
|
||||
const expected = [fixture.parent.id, fixture.grandparent.id];
|
||||
expect((await svc.getAncestors(fixture.issue.id)).map((ancestor) => ancestor.id)).toEqual(expected);
|
||||
expect((await svc.getAncestors(fixture.issue.id, { parentId: fixture.parent.id })).map((ancestor) => ancestor.id)).toEqual(expected);
|
||||
await ctx.db.update(issues).set({ parentId: fixture.blocker.id }).where(eq(issues.id, fixture.blocker.id));
|
||||
expect(await svc.getAncestors(fixture.blocker.id)).toEqual([]);
|
||||
}, 60_000);
|
||||
it("answers the interactions poll without reading the issue again", async () => {
|
||||
const census = createStatementCensus(ctx.db);
|
||||
try {
|
||||
const fixture = await seed();
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const path = `/api/issues/${fixture.issue.id}/interactions`;
|
||||
await request(app).get(path).expect(200);
|
||||
let response: request.Response | undefined;
|
||||
const measured = await census.measure(async () => {
|
||||
response = await request(app).get(path).expect(200);
|
||||
});
|
||||
const expected = await issueThreadInteractionService(ctx.db).listForIssue(fixture.issue.id);
|
||||
expect(response!.body).toEqual(JSON.parse(JSON.stringify(expected)));
|
||||
expect(measured.shapes.filter((shape) => shape.shape.startsWith('select "status", "company_id", "execution_workspace_id" from "issues"'))).toEqual([]);
|
||||
expect(measured.statements, formatStatementCensus(path, measured, 20)).toBeLessThanOrEqual(10);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -872,7 +872,7 @@ describe("issue thread interaction routes", () => {
|
||||
.get("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/interactions")
|
||||
.expect(200, []);
|
||||
|
||||
expect(mockInteractionService.listForIssue).toHaveBeenCalledExactlyOnceWith(ISSUE_ID);
|
||||
expect(mockInteractionService.listForIssue).toHaveBeenCalledExactlyOnceWith(ISSUE_ID, expect.objectContaining({ id: ISSUE_ID, status }));
|
||||
expect(mockInteractionService.expireRequestConfirmationsSupersededByHistoricalComments).not.toHaveBeenCalled();
|
||||
expect(mockInteractionService.expirePendingInteractionsForTerminalIssue).not.toHaveBeenCalled();
|
||||
expect(mockLogActivity).not.toHaveBeenCalled();
|
||||
|
||||
@@ -312,7 +312,7 @@ describe("issue goal context routes", () => {
|
||||
);
|
||||
expect(mockIssueService.findMentionedProjectIds).toHaveBeenCalledWith(
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
{ includeCommentBodies: false },
|
||||
{ includeCommentBodies: false, issue: expect.objectContaining({ id: "11111111-1111-4111-8111-111111111111" }) },
|
||||
);
|
||||
expect(mockGoalService.getDefaultCompanyGoal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -76,6 +76,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"inbox-agent-policy.ts": "/api",
|
||||
"inbox-dismissals.ts": "/api",
|
||||
"instance-database-backups.ts": "/api",
|
||||
"instance-server-metrics.ts": "/api",
|
||||
"instance-settings.ts": "/api",
|
||||
"issues.ts": "/api",
|
||||
"issue-tree-control.ts": "/api",
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { EventLoopUtilization } from "node:perf_hooks";
|
||||
import {
|
||||
activeServerMetrics,
|
||||
recordMissedLeaseRenewal,
|
||||
recordRunEventCommitted,
|
||||
ServerMetricsCollector,
|
||||
serverMetricsEnabledFromEnv,
|
||||
startServerMetrics,
|
||||
stopServerMetrics,
|
||||
type ServerMetricsProbes,
|
||||
} from "../services/server-metrics.js";
|
||||
|
||||
const FIXTURE = fileURLToPath(new URL("../../../scripts/scale-ramp/server-metrics.fixture.json", import.meta.url));
|
||||
|
||||
function fakeProbes() {
|
||||
const state = { now: 0, wall: Date.parse("2026-11-14T12:00:00.000Z"), idle: 0, active: 0, cpuMicros: 0, mainMs: 0, statements: 0, uptime: 100 };
|
||||
const elu = (): EventLoopUtilization => ({ idle: state.idle, active: state.active, utilization: 0 });
|
||||
const probes: ServerMetricsProbes = {
|
||||
now: () => state.now,
|
||||
wallNow: () => state.wall,
|
||||
eventLoopUtilization: (current?: EventLoopUtilization, previous?: EventLoopUtilization) => {
|
||||
if (!current) return elu();
|
||||
const idle = current.idle - (previous?.idle ?? 0);
|
||||
const active = current.active - (previous?.active ?? 0);
|
||||
return { idle, active, utilization: idle + active > 0 ? active / (idle + active) : 0 };
|
||||
},
|
||||
processCpuMicros: () => state.cpuMicros,
|
||||
mainThreadCpuMs: () => state.mainMs,
|
||||
statementCount: () => state.statements,
|
||||
uptimeSec: () => state.uptime,
|
||||
dedicatedConnections: () => ({ limit: 24, inUse: 3, peakInUse: 9, waiting: 1, queued: 12, overLimit: 0, nestedOverLimit: 0 }),
|
||||
};
|
||||
const advance = (ms: number, load: { busy: number; cpu?: number; statementsPerSecond?: number }) => {
|
||||
state.now += ms;
|
||||
state.wall += ms;
|
||||
state.uptime += ms / 1000;
|
||||
state.active += ms * load.busy;
|
||||
state.idle += ms * (1 - load.busy);
|
||||
state.mainMs += ms * load.busy;
|
||||
state.cpuMicros += ms * (load.cpu ?? load.busy) * 1000;
|
||||
state.statements += (ms / 1000) * (load.statementsPerSecond ?? 0);
|
||||
};
|
||||
return { probes, advance };
|
||||
}
|
||||
|
||||
const collectors: ServerMetricsCollector[] = [];
|
||||
function collector(probes: ServerMetricsProbes) {
|
||||
const created = new ServerMetricsCollector({ probes, bucketMs: 10_000, buckets: 6, buildRevision: "0123456789abcdef0123456789abcdef01234567",
|
||||
monitorEventLoop: false, processId: "a1b2c3d4e5f60718" });
|
||||
collectors.push(created);
|
||||
return created;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const created of collectors.splice(0)) created.stop();
|
||||
const active = activeServerMetrics();
|
||||
if (active) stopServerMetrics(active);
|
||||
});
|
||||
|
||||
describe("server metrics collector", () => {
|
||||
it("reports rates and utilization over the sliding window, dropping buckets older than the window", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.9, statementsPerSecond: 500 });
|
||||
metrics.rotate();
|
||||
}
|
||||
const busy = metrics.snapshot();
|
||||
expect(busy.windowMs).toBe(50_000);
|
||||
expect(busy.eventLoopUtilization).toBeCloseTo(0.9, 4);
|
||||
expect(busy.mainThreadCpu).toBeCloseTo(0.9, 4);
|
||||
expect(busy.statementsPerSecond).toBeCloseTo(500, 2);
|
||||
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.1, statementsPerSecond: 20 });
|
||||
metrics.rotate();
|
||||
}
|
||||
const quiet = metrics.snapshot();
|
||||
expect(quiet.eventLoopUtilization).toBeCloseTo(0.1, 4);
|
||||
expect(quiet.statementsPerSecond).toBeCloseTo(20, 2);
|
||||
});
|
||||
|
||||
it("expires buckets by elapsed time when the rotation timer fires late", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.1, statementsPerSecond: 10 });
|
||||
metrics.rotate();
|
||||
}
|
||||
metrics.recordRunEventLatenessMs(5_000);
|
||||
advance(35_000, { busy: 0.5, statementsPerSecond: 100 });
|
||||
metrics.rotate();
|
||||
const late = metrics.snapshot();
|
||||
expect(late.windowMs).toBe(55_000);
|
||||
expect(late.statementsPerSecond).toBeCloseTo((20 * 10 + 35 * 100) / 55, 2);
|
||||
expect(late.runEventLatenessSamples).toBe(1);
|
||||
});
|
||||
|
||||
it("reports the real window after a block longer than the window, and the block shows in it", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.1 });
|
||||
metrics.rotate();
|
||||
}
|
||||
metrics.recordRunEventLatenessMs(20);
|
||||
advance(300_000, { busy: 1 });
|
||||
metrics.rotate();
|
||||
const blocked = metrics.snapshot();
|
||||
expect(blocked.windowMs).toBe(300_000);
|
||||
expect(blocked.eventLoopUtilization).toBeCloseTo(1, 4);
|
||||
expect(blocked.runEventLatenessSamples).toBe(1);
|
||||
advance(10_000, { busy: 0.2 });
|
||||
metrics.rotate();
|
||||
expect(metrics.snapshot()).toMatchObject({ windowMs: 10_000, runEventLatenessSamples: 0 });
|
||||
for (let bucket = 0; bucket < 5; bucket += 1) {
|
||||
advance(10_000, { busy: 0.2 });
|
||||
metrics.rotate();
|
||||
}
|
||||
const recovered = metrics.snapshot();
|
||||
expect(recovered.windowMs).toBe(50_000);
|
||||
expect(recovered.eventLoopUtilization).toBeCloseTo(0.2, 4);
|
||||
});
|
||||
|
||||
it("reports latency percentiles only for the window and absent when nothing was recorded", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
expect(metrics.snapshot()).toMatchObject({ runEventLatenessP99Ms: null, runEventLatenessSamples: 0,
|
||||
agentApiPreHandlerP99Ms: null, agentApiPreHandlerSamples: 0 });
|
||||
for (let index = 0; index < 100; index += 1) metrics.recordRunEventLatenessMs(index < 98 ? 20 : 2_000);
|
||||
metrics.recordAgentApiPreHandlerMs(3.5);
|
||||
const recorded = metrics.snapshot();
|
||||
expect(recorded.runEventLatenessSamples).toBe(100);
|
||||
expect(recorded.runEventLatenessP99Ms).toBeGreaterThan(1_900);
|
||||
expect(recorded.agentApiPreHandlerP99Ms).toBeCloseTo(3.5, 1);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0 });
|
||||
metrics.rotate();
|
||||
}
|
||||
expect(metrics.snapshot()).toMatchObject({ runEventLatenessP99Ms: null, runEventLatenessSamples: 0, agentApiPreHandlerSamples: 0 });
|
||||
});
|
||||
|
||||
it("counts missed lease renewals since start and never resets them with the window", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
metrics.recordMissedLeaseRenewal();
|
||||
metrics.recordMissedLeaseRenewal();
|
||||
for (let bucket = 0; bucket < 8; bucket += 1) {
|
||||
advance(10_000, { busy: 0 });
|
||||
metrics.rotate();
|
||||
}
|
||||
expect(metrics.snapshot().leaseRenewalsMissed).toBe(2);
|
||||
});
|
||||
|
||||
it("records into the process collector only while it runs", () => {
|
||||
recordRunEventCommitted(new Date(Date.now() - 500).toISOString(), Date.now());
|
||||
recordMissedLeaseRenewal();
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
const started = startServerMetrics();
|
||||
expect(startServerMetrics()).toBe(started);
|
||||
recordRunEventCommitted(new Date(Date.now() - 500).toISOString(), Date.now());
|
||||
recordRunEventCommitted("not a time", Date.now());
|
||||
recordMissedLeaseRenewal();
|
||||
const snapshot = started.snapshot();
|
||||
expect(snapshot.runEventLatenessSamples).toBe(1);
|
||||
expect(snapshot.runEventLatenessP99Ms).toBeGreaterThanOrEqual(450);
|
||||
expect(snapshot.leaseRenewalsMissed).toBe(1);
|
||||
stopServerMetrics(started);
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
});
|
||||
|
||||
it("reads the kill switch strictly and defaults it off", () => {
|
||||
expect(serverMetricsEnabledFromEnv({})).toBe(false);
|
||||
expect(serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "true" })).toBe(true);
|
||||
expect(serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "0" })).toBe(false);
|
||||
expect(() => serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "yes" })).toThrow(/PAPERCLIP_SERVER_METRICS/);
|
||||
});
|
||||
|
||||
it("serializes exactly the fixture the scale-ramp harness parses", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.42, cpu: 0.55, statementsPerSecond: 180 });
|
||||
metrics.rotate();
|
||||
}
|
||||
for (let index = 0; index < 50; index += 1) metrics.recordRunEventLatenessMs(120);
|
||||
for (let index = 0; index < 50; index += 1) metrics.recordAgentApiPreHandlerMs(15);
|
||||
metrics.recordMissedLeaseRenewal();
|
||||
const snapshot = JSON.parse(JSON.stringify(metrics.snapshot()));
|
||||
if (process.env.UPDATE_SERVER_METRICS_FIXTURE === "1") writeFileSync(FIXTURE, `${JSON.stringify(snapshot, null, 2)}\n`);
|
||||
expect(snapshot).toEqual(JSON.parse(readFileSync(FIXTURE, "utf8")));
|
||||
});
|
||||
});
|
||||
+17
-1
@@ -1,3 +1,4 @@
|
||||
import { authorizationReadScope } from "./services/authorization-read-scope.js";
|
||||
import type { IdleDeadlineOwners } from "./services/idle-deadline-types.js";
|
||||
import { startMcpClientMirrorSync } from "./services/public-mcp/client-mirror-sync.js";
|
||||
import { registerIdleMcpOwners } from "./services/public-mcp/idle-sleep-proof.js";
|
||||
@@ -11,7 +12,7 @@ import { finishServiceShutdown } from "./shutdown.js";
|
||||
import { promptInjectionPreventionRoutes } from "./routes/prompt-injection-prevention.js";
|
||||
import { voiceSessionRoutes, voiceWebhookRoutes } from "./routes/voice-sessions.js";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { chatEndpoints } from "@paperclipai/db";
|
||||
import { chatEndpoints, dedicatedDbConnectionStats } from "@paperclipai/db";
|
||||
import { fastResponseRoutes } from "./routes/fast-responses.js";
|
||||
import { fastResponseService } from "./services/fast-responses.js";
|
||||
import { createDeliveryWorkCoordinator } from "./services/delivery-work-coordinator.js";
|
||||
@@ -253,6 +254,14 @@ import {
|
||||
import { COMPANY_IMPORT_API_PATH } from "./routes/company-import-paths.js";
|
||||
import { apiCompression } from "./middleware/api-compression.js";
|
||||
import { apiServerTiming } from "./middleware/api-server-timing.js";
|
||||
import { instanceServerMetricsRoutes } from "./routes/instance-server-metrics.js";
|
||||
import {
|
||||
serverMetricsAgentPreHandler,
|
||||
serverMetricsArrival,
|
||||
serverMetricsEnabledFromEnv,
|
||||
startServerMetrics,
|
||||
stopServerMetrics,
|
||||
} from "./services/server-metrics.js";
|
||||
import { chatWebhookBodyParser } from "./middleware/chat-webhook-body.js";
|
||||
import { createChatWebhookDiagnostics } from "./services/chat-webhook-diagnostics.js";
|
||||
|
||||
@@ -491,9 +500,12 @@ export async function createApp(
|
||||
managedPluginAutoInstall?: readonly string[] | null;
|
||||
/** Test override for the bundled plugin catalog root. */
|
||||
bundledPluginCatalogRoot?: string;
|
||||
serverMetricsEnabled?: boolean;
|
||||
},
|
||||
) {
|
||||
const app = express();
|
||||
const serverMetrics = (opts.serverMetricsEnabled ?? serverMetricsEnabledFromEnv(process.env)) ? startServerMetrics(() => dedicatedDbConnectionStats(db)) : null;
|
||||
if (serverMetrics) app.use("/api", serverMetricsArrival());
|
||||
// First, so the reported server time includes admission and database waits.
|
||||
app.use("/api", apiServerTiming());
|
||||
app.use(databaseOperationMiddleware);
|
||||
@@ -624,6 +636,7 @@ export async function createApp(
|
||||
// REPLACES whatever actor the request otherwise resolved to, and only on
|
||||
// the one endpoint it authorizes (see the middleware for the contract).
|
||||
app.use(cloudControlMiddleware());
|
||||
app.use(authorizationReadScope);
|
||||
app.use(runnerCallOutcomeMiddleware(db));
|
||||
app.use(connectionEventWakeRoutes(db));
|
||||
app.use(skillAccessRequestContext);
|
||||
@@ -886,6 +899,7 @@ export async function createApp(
|
||||
if (opts.databaseBackupService) {
|
||||
api.use(instanceDatabaseBackupRoutes(opts.databaseBackupService));
|
||||
}
|
||||
if (serverMetrics) api.use(instanceServerMetricsRoutes(serverMetrics));
|
||||
const pluginRegistry = pluginRegistryService(db);
|
||||
const eventBus = createPluginEventBus();
|
||||
setPluginEventBus(eventBus);
|
||||
@@ -1084,6 +1098,7 @@ export async function createApp(
|
||||
|
||||
api.use(museBoardRoutes(db, opts.authPublicBaseUrl));
|
||||
api.use(museQualificationRoutes(db));
|
||||
if (serverMetrics) app.use("/api", serverMetricsAgentPreHandler(serverMetrics));
|
||||
app.use("/api", api);
|
||||
app.use("/api", (_req, res) => {
|
||||
res.status(404).json({ error: "API route not found" });
|
||||
@@ -1448,6 +1463,7 @@ export async function createApp(
|
||||
// caller stops the database and the provider. A lease release that
|
||||
// fails stays a durable record for the startup reaper.
|
||||
await setupTokenLoginService?.shutdown();
|
||||
if (serverMetrics) stopServerMetrics(serverMetrics);
|
||||
});
|
||||
});
|
||||
return appServicesShutdown;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Router } from "express";
|
||||
import type { ServerMetricsCollector } from "../services/server-metrics.js";
|
||||
import { assertInstanceAdmin } from "./authz.js";
|
||||
|
||||
export function instanceServerMetricsRoutes(collector: ServerMetricsCollector) {
|
||||
const router = Router();
|
||||
|
||||
router.get("/instance/server-metrics", (req, res) => {
|
||||
assertInstanceAdmin(req);
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.json(collector.snapshot());
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -8478,9 +8478,9 @@ export function issueRoutes(
|
||||
companyId: string;
|
||||
projectId: string | null;
|
||||
goalId: string | null;
|
||||
}) {
|
||||
}, options: { workspaceProvider?: boolean } = {}) {
|
||||
const projectPromise = issue.projectId
|
||||
? projectsSvc.getById(issue.projectId)
|
||||
? projectsSvc.getById(issue.projectId, options)
|
||||
: Promise.resolve(null);
|
||||
const directGoalPromise = issue.goalId
|
||||
? goalsSvc.getById(issue.goalId)
|
||||
@@ -10157,20 +10157,20 @@ export function issueRoutes(
|
||||
workProducts,
|
||||
createdFrom,
|
||||
] = await Promise.all([
|
||||
timing.time("project_goal", () => resolveIssueProjectAndGoal(issue)),
|
||||
timing.time("ancestors", () => svc.getAncestors(issue.id)),
|
||||
timing.time("mentions", () => svc.findMentionedProjectIds(issue.id, { includeCommentBodies: false })),
|
||||
timing.time("project_goal", () => resolveIssueProjectAndGoal(issue, { workspaceProvider: false })),
|
||||
timing.time("ancestors", () => svc.getAncestors(issue.id, { parentId: issue.parentId })),
|
||||
timing.time("mentions", () => svc.findMentionedProjectIds(issue.id, { includeCommentBodies: false, issue })),
|
||||
timing.time("documents", () => documentsSvc.getIssueDocumentPayload(issue)),
|
||||
timing.time("relations", () => svc.getRelationSummaries(issue.id)),
|
||||
timing.time("relations", () => svc.getRelationSummaries(issue.id, { companyId: issue.companyId })),
|
||||
timing.time("blockers", () => svc
|
||||
.listBlockerAttention(issue.companyId, [issue])
|
||||
.then((map) => map.get(issue.id) ?? null)),
|
||||
timing.time("review", () => svc
|
||||
.listReviewAttention(issue.companyId, [issue])
|
||||
.then((map) => map.get(issue.id) ?? null)),
|
||||
timing.time("references", () => issueReferencesSvc.listIssueReferenceSummary(issue.id)),
|
||||
timing.time("references", () => issueReferencesSvc.listIssueReferenceSummary(issue.id, undefined, { companyId: issue.companyId })),
|
||||
timing.time("handoff", () => listSuccessfulRunHandoffStates(db, issue.companyId, [issue.id])),
|
||||
timing.time("retry", () => svc.getCurrentScheduledRetry(issue.id)),
|
||||
timing.time("retry", () => svc.getCurrentScheduledRetry(issue.id, { companyId: issue.companyId })),
|
||||
timing.time("recovery", () => recoveryActionsSvc.getActiveForIssue(issue.companyId, issue.id)),
|
||||
inboxArchiveFieldsPromise,
|
||||
timing.time("channel", () => getExternalChannelBindingSummary(db, issue.companyId, issue.id)),
|
||||
@@ -18402,7 +18402,7 @@ export function issueRoutes(
|
||||
if (!issue) return;
|
||||
if (!(await assertIssueReadAllowed(req, res, issue))) return;
|
||||
const interactions =
|
||||
await issueThreadInteractionService(db).listForIssue(id);
|
||||
await issueThreadInteractionService(db).listForIssue(issue.id, issue);
|
||||
if (req.actor.type === "agent" && req.actor.agentId && req.actor.runId) {
|
||||
await recordDeclinedInteractionRead(db, { companyId: issue.companyId, agentId: req.actor.agentId, runId: req.actor.runId,
|
||||
issue, interactions: interactions as Parameters<typeof recordDeclinedInteractionRead>[1]["interactions"] })
|
||||
|
||||
@@ -1642,6 +1642,7 @@ const INSTANCE_ADMIN_OPERATIONS = new Set([
|
||||
"POST /api/companies",
|
||||
"POST /api/plugins/install",
|
||||
"POST /api/instance/database-backups",
|
||||
"GET /api/instance/server-metrics",
|
||||
"POST /api/admin/users/{userId}/promote-instance-admin",
|
||||
"POST /api/admin/users/{userId}/demote-instance-admin",
|
||||
"PUT /api/admin/users/{userId}/company-access",
|
||||
@@ -10391,6 +10392,17 @@ registry.registerPath({
|
||||
responses: { 201: r.ok(), 401: r.unauthorized, 403: r.forbidden },
|
||||
});
|
||||
|
||||
// ─── Instance server metrics ──────────────────────────────────────────────────
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/instance/server-metrics",
|
||||
tags: ["instance"],
|
||||
summary: "Get this server process's load metrics",
|
||||
description: "Instance admins only: agent credentials and company members receive 403. Returns numbers for the one server process that answers: CPU, event-loop utilization and delay, statements per second, run event lateness and agent API pre-handler p99, missed lease renewals and dedicated database connection use, over about the last minute (windowMs). It returns 404 unless the operator set PAPERCLIP_SERVER_METRICS=true.",
|
||||
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
|
||||
});
|
||||
|
||||
// ─── LLM text endpoints ───────────────────────────────────────────────────────
|
||||
|
||||
registry.registerPath({
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
};
|
||||
}
|
||||
+2
@@ -107,6 +107,8 @@ export const runnerCodexDynamicToolsFit = runner.runnerCodexDynamicToolsFit;
|
||||
export const admitToolInputSchema = runner.admitToolInputSchema;
|
||||
export const TOOL_INPUT_SCHEMA_MAX_BYTES = runner.TOOL_INPUT_SCHEMA_MAX_BYTES;
|
||||
export const canonicalToolInputSchema = runner.canonicalToolInputSchema;
|
||||
export const runnerLaunchPreparationDigest = runner.runnerLaunchPreparationDigest;
|
||||
export const runnerLaunchRunDigest = runner.runnerLaunchRunDigest;
|
||||
export const inspectWarmRunTransition = runner.inspectWarmRunTransition;
|
||||
export const inspectStagedRunAttachment = runner.inspectStagedRunAttachment;
|
||||
export const inspectRetainedRunInstructions = runner.inspectRetainedRunInstructions;
|
||||
|
||||
Reference in new issue
Block a user