mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
fix(runs): honor offset when listing company heartbeat runs (#15669)
<!-- Write all pull request text in Simplified Technical English (ASD-STE100): short sentences, one instruction per sentence, simple approved vocabulary, and the active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board and external tools read agent runs through the REST API > - The company heartbeat runs endpoint returns the run history for a company > - The endpoint accepted a limit value, but it ignored the offset value > - A caller that paged through the runs received the first page again and again, and tools that count runs or tokens silently over-counted > - This pull request adds offset support to the route, to the run list service, and to the OpenAPI entry > - The benefit is correct paging through the full run history of a company ## Linked Issues or Issue Description Fixes #15318 ## What Changed - The `GET /api/companies/:companyId/heartbeat-runs` route now reads the `offset` query parameter, clamps it at zero, and passes it to the heartbeat run list - `listRuns` in the heartbeat run state service accepts `options.offset` and applies it in the database query; an absent or zero offset keeps the current behavior - `listRuns` now orders by `createdAt` descending and then by `id` descending, so page boundaries stay stable when runs share a timestamp - The OpenAPI entry for the endpoint now documents the `agentId`, `limit`, `offset`, and `summary` query parameters - Tests: a mock-level test proves the offset reaches the query only when one is set, and an embedded-Postgres test proves limit and offset page in newest-first order ## Verification - `vitest run server/src/services/heartbeat/run-state.test.ts` — 4 passed, 6 skipped in my sandbox. The PostgreSQL suite self-skips when the tests run as root; the new paging test is in that suite and runs in CI. The mock-level offset test runs everywhere - Negative control: with the source change stashed, the new offset test fails on the unmodified code - `tsc --noEmit -p server/tsconfig.json` passes ## Risks - Low risk. The default behavior does not change when a caller sends no offset - Rows with equal `createdAt` values now have a deterministic order. The old order for equal timestamps was not specified, so no caller could rely on it ## Model Used - Provider: Meta - Model: Muse Spark 1.3 (Muse model family) - Capabilities: tool use, code execution, extended reasoning ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Signed-off-by: Josh Cox <joshuacox@users.noreply.github.com> Co-authored-by: Review <review@local>
This commit is contained in:
1 parent
2eea950c2e
commit
511c9cc5f7
5 files changed
+53
-6
No files matched your search
@@ -93,7 +93,7 @@ describe("heartbeat list connection recovery", () => {
|
||||
for (const attempt of test.attempts) {
|
||||
expect(attempt.params).toEqual(options.agent ? [companyId, agentId] : [companyId]);
|
||||
expect(attempt.limit).toBe(options.limit ?? 200);
|
||||
expect(attempt.order).toEqual(['"heartbeat_runs"."created_at" desc']);
|
||||
expect(attempt.order).toEqual(['"heartbeat_runs"."created_at" desc', '"heartbeat_runs"."id" desc']);
|
||||
expect("resultSummary" in attempt.fields).toBe(!options.summary && options.encoding === "UTF8");
|
||||
expect(attempt.fields).toEqual(test.attempts[0].fields);
|
||||
}
|
||||
|
||||
@@ -7362,8 +7362,10 @@ export function agentRoutes(
|
||||
const limit = limitParam
|
||||
? Math.max(1, Math.min(HEARTBEAT_RUN_LIST_MAX_LIMIT, parseInt(limitParam, 10) || HEARTBEAT_RUN_LIST_DEFAULT_LIMIT))
|
||||
: HEARTBEAT_RUN_LIST_DEFAULT_LIMIT;
|
||||
const offsetParam = req.query.offset as string | undefined;
|
||||
const offset = offsetParam ? Math.max(0, parseInt(offsetParam, 10) || 0) : undefined;
|
||||
const summary = req.query.summary === "true" || req.query.summary === "1";
|
||||
const recentRuns = await heartbeat.list(companyId, agentId, limit, { summary });
|
||||
const recentRuns = await heartbeat.list(companyId, agentId, limit, { summary, offset });
|
||||
const runs = req.query.latestFailuresOnly === "true" ? latestFailedRunsByAgent(recentRuns) : recentRuns;
|
||||
const readDecisions = await getHeartbeatRunReadDecisions(db, access, req.actor, runs);
|
||||
res.json(await runRedactions.redactForRuns(companyId, runs.map((run, index) =>
|
||||
|
||||
@@ -8353,6 +8353,7 @@ registry.registerPath({
|
||||
query: z.object({
|
||||
agentId: z.string().optional(),
|
||||
limit: z.coerce.number().int().min(1).max(1000).default(200),
|
||||
offset: z.coerce.number().int().min(0).optional(),
|
||||
summary: z.enum(["true", "false", "1", "0"]).optional(),
|
||||
latestFailuresOnly: z.enum(["true", "false"]).optional().describe("Return failures only when the agent's latest run within the bounded result failed or timed out. Applied before read redaction."),
|
||||
}),
|
||||
|
||||
@@ -28,6 +28,7 @@ import { STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_HELD_MESSAGE, STORAGE_UNA
|
||||
function readingDatabase(serverEncoding: string, ...results: unknown[][]) {
|
||||
const scopes: unknown[][] = [];
|
||||
const columns: Record<string, unknown>[] = [];
|
||||
const offsets: number[] = [];
|
||||
const execute = vi.fn(async () => [{ server_encoding: serverEncoding }]);
|
||||
const select = vi.fn((projection: Record<string, unknown> = {}) => {
|
||||
columns.push(projection);
|
||||
@@ -41,11 +42,15 @@ function readingDatabase(serverEncoding: string, ...results: unknown[][]) {
|
||||
},
|
||||
orderBy: () => query,
|
||||
limit: () => query,
|
||||
offset: (value: number) => {
|
||||
offsets.push(value);
|
||||
return query;
|
||||
},
|
||||
then: (resolve: (rows: unknown[]) => unknown) => Promise.resolve(rows).then(resolve),
|
||||
};
|
||||
return query;
|
||||
});
|
||||
return { db: { execute, select } as unknown as Db, execute, select, columns, scopes };
|
||||
return { db: { execute, select } as unknown as Db, execute, select, columns, scopes, offsets };
|
||||
}
|
||||
|
||||
describe("heartbeat run state module", () => {
|
||||
@@ -76,6 +81,19 @@ describe("heartbeat run state module", () => {
|
||||
expect(second.scopes[0]).toEqual(["company-two", "agent-two", "claude_local", "task-two"]);
|
||||
});
|
||||
|
||||
it("passes offset through to the run list query only when one is set", async () => {
|
||||
const paged = readingDatabase("UTF8", [{ id: "run-3" }]);
|
||||
const pagedState = extracted.createHeartbeatRunState(paged.db);
|
||||
const page = await pagedState.listRuns("company-one", undefined, 2, { offset: 2 });
|
||||
expect(page.map((row) => row.id)).toEqual(["run-3"]);
|
||||
expect(paged.offsets).toEqual([2]);
|
||||
|
||||
const unpaged = readingDatabase("UTF8", [{ id: "run-1" }]);
|
||||
const unpagedState = extracted.createHeartbeatRunState(unpaged.db);
|
||||
await unpagedState.listRuns("company-one");
|
||||
expect(unpaged.offsets).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps encoding caches local to each factory and preserves full-result reads", async () => {
|
||||
const ascii = readingDatabase("SQL_ASCII");
|
||||
const utf8 = readingDatabase("UTF8");
|
||||
@@ -483,6 +501,23 @@ describePostgres("heartbeat run state database wiring", () => {
|
||||
expect((await state.listRuns(companyId)).map((row) => row.id)).toEqual([run.id]);
|
||||
});
|
||||
|
||||
it("pages listRuns with limit and offset in newest-first order", async () => {
|
||||
const { companyId, agent, state } = await fixture();
|
||||
const insertRun = async (createdAt: string) =>
|
||||
(await db.insert(heartbeatRuns).values({
|
||||
companyId, agentId: agent.id, invocationSource: "assignment", status: "succeeded",
|
||||
createdAt: new Date(createdAt),
|
||||
}).returning())[0];
|
||||
const oldest = await insertRun("2026-01-01T00:00:00Z");
|
||||
const middle = await insertRun("2026-01-02T00:00:00Z");
|
||||
const newest = await insertRun("2026-01-03T00:00:00Z");
|
||||
|
||||
expect((await state.listRuns(companyId)).map((row) => row.id)).toEqual([newest.id, middle.id, oldest.id]);
|
||||
expect((await state.listRuns(companyId, undefined, 2)).map((row) => row.id)).toEqual([newest.id, middle.id]);
|
||||
expect((await state.listRuns(companyId, undefined, 2, { offset: 2 })).map((row) => row.id)).toEqual([oldest.id]);
|
||||
expect((await state.listRuns(companyId, undefined, undefined, { offset: 1 })).map((row) => row.id)).toEqual([middle.id, oldest.id]);
|
||||
});
|
||||
|
||||
it("subtracts prior cumulative usage while excluding the current run", async () => {
|
||||
const { companyId, agent, state } = await fixture();
|
||||
await db.insert(heartbeatRuns).values({
|
||||
|
||||
@@ -1804,10 +1804,16 @@ export function createHeartbeatRunState(db: Db) {
|
||||
companyId: string,
|
||||
agentId?: string,
|
||||
limit?: number,
|
||||
options: { summary?: boolean } = {},
|
||||
options: { summary?: boolean; offset?: number } = {},
|
||||
) => {
|
||||
const safeForLegacyEncoding = await hasUnsafeTextProjectionDatabase();
|
||||
const summary = options.summary === true;
|
||||
const offset =
|
||||
typeof options.offset === "number" &&
|
||||
Number.isFinite(options.offset) &&
|
||||
options.offset > 0
|
||||
? Math.floor(options.offset)
|
||||
: 0;
|
||||
const rows = await retryIdempotentDatabaseOperation(async () => {
|
||||
const query = db
|
||||
.select(
|
||||
@@ -1838,12 +1844,15 @@ export function createHeartbeatRunState(db: Db) {
|
||||
)
|
||||
: eq(heartbeatRuns.companyId, companyId),
|
||||
)
|
||||
.orderBy(desc(heartbeatRuns.createdAt));
|
||||
// The id tiebreak keeps page boundaries stable when runs share a
|
||||
// createdAt timestamp, so offset paging cannot repeat or skip rows.
|
||||
.orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id));
|
||||
|
||||
const boundedLimit = Number.isFinite(limit)
|
||||
? Math.max(1, Math.min(HEARTBEAT_RUN_LIST_MAX_LIMIT, Math.trunc(limit!)))
|
||||
: HEARTBEAT_RUN_LIST_DEFAULT_LIMIT;
|
||||
return await query.limit(boundedLimit);
|
||||
const limited = query.limit(boundedLimit);
|
||||
return offset ? await limited.offset(offset) : await limited;
|
||||
});
|
||||
return rows.map((row) => {
|
||||
const {
|
||||
|
||||
Reference in new issue
Block a user