fix(server): stop terminal workspace reaper starving on oldest candidates (#11238)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server runs a scheduled reaper that archives terminal workspaces
after it checks their state.
> - The reaper reads candidates in `updatedAt` order and skips
candidates that do not qualify for archive.
> - The fixed page kept the same skipped candidates at the front, so the
reaper did not inspect later eligible workspaces.
> - This pull request adds a keyset cursor and a throttled log for
sweeps that archive no workspace.
> - The benefit is that the reaper inspects all candidates over time and
reports an inert sweep.

## Linked Issues or Issue Description

**What happened?**

The terminal workspace reaper inspected a fixed page of old candidates.
Ineligible candidates stayed in that page, so the reaper skipped later
eligible workspaces on every sweep.

**Expected behavior**

The reaper must inspect each candidate over time and archive every
eligible terminal workspace.

**Steps to reproduce**

1. Create more than 50 terminal workspace candidates.
2. Keep the oldest page ineligible for archive.
3. Place an eligible workspace after that page.
4. Run repeated reaper sweeps.
5. Observe that the later eligible workspace remains unarchived.

**Paperclip version or commit**

Commit `3efdf555e6e14a46747c796c3c554438bfc03261`.

**Deployment mode**

Built from source with the server test suite.

**Installation method**

Built from source.

**Agent adapter(s) involved**

Not adapter-specific (core bug).

**Database mode**

Not database-related.

## What Changed

- Add a keyset cursor that uses `(updatedAt, id)` order across reaper
pages.
- Reset the cursor at the end of the candidate set so the next sweep
starts at the beginning.
- Add a throttled log when a sweep inspects candidates but archives
none.
- Add regression tests for archive delivery and starvation.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/execution-workspaces-service.test.ts` — 45 tests pass.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/server-startup-feedback-export.test.ts` — 16 tests pass.
- `pnpm --filter @paperclipai/server typecheck` — clean.

## Risks

Low risk. The change affects only candidate paging and the related
reaper log. The cursor resets after the candidate set, so the sweep
remains periodic.

## Model Used

Codex, OpenAI GPT-5, extended reasoning, tool use, and code execution.

## 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 (no exact duplicate found; related scheduler PR #10911 is
distinct)
- [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 (no
documentation applies; this is an internal reaper behavior change)
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-08-12 10:21:00 -07:00
1 parent 1a377424db
commit f9bd0438e1
3 files changed
+412 -6

No files matched your search

+87 -6
View File
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { and, asc, desc, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
import { and, asc, desc, eq, gt, inArray, isNull, lte, ne, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
executionWorkspaces,
@@ -1063,6 +1063,29 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
>();
const pullRequestStateCacheTtlMs = 5 * 60 * 1000;
// The terminal-workspace reaper scans the candidate set in fixed-size pages.
// It keeps this keyset cursor between sweeps so each sweep continues after the
// previous page. A skipped candidate keeps its updatedAt, so a cursor is
// required: without it the query re-selects the oldest ineligible rows every
// sweep and starves eligible rows behind them. The cursor resets to the start
// when a sweep reaches the end of the candidate set.
let terminalSweepCursor: { updatedAt: Date; id: string } | null = null;
// The reaper freezes an upper bound on updatedAt at the start of each
// rotation. The scan only reads candidates at or below the bound, so a steady
// stream of newer candidates cannot keep every page full and stop the cursor
// from ever reaching the end. A frozen set is finite, so the cursor always
// reaches a short page and resets, and older candidates that became eligible
// are revisited on the next rotation. The next rotation captures a new bound,
// so candidates updated after the previous bound enter the scan then.
let terminalSweepBoundary: Date | null = null;
// The scheduler starts a sweep on each tick and does not wait for the previous
// sweep to finish. A sweep that outlasts the tick interval overlaps the next
// sweep. Both sweeps share the cursor and the boundary above. Interleaved
// reads and writes can leave a non-null cursor with a null boundary, which
// removes the upper bound and makes the scan chase newer churn again. This
// flag lets only one sweep run at a time, so one sweep owns the shared state.
let terminalSweepInProgress = false;
async function listWorkspaceIssueTree(workspace: Pick<ExecutionWorkspaceRow, "companyId" | "sourceIssueId">) {
if (!workspace.sourceIssueId) return [];
return db
@@ -2033,16 +2056,71 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
},
sweepTerminalWorkspaces: async (limit = 50) => {
// Skip this sweep while another sweep runs. A concurrent sweep would share
// the cursor and the boundary and could corrupt the rotation state. A
// skipped tick is safe: the next tick runs the sweep with intact state.
if (terminalSweepInProgress) {
return {
checked: 0,
eligible: 0,
archived: 0,
cleanupFailed: 0,
skippedActiveRun: 0,
skippedNonTerminalTree: 0,
skippedUndelivered: 0,
skippedRace: 0,
};
}
terminalSweepInProgress = true;
try {
const baseCandidateFilter = and(
inArray(executionWorkspaces.status, ["active", "idle", "in_review"]),
isNull(executionWorkspaces.closedAt),
sql<boolean>`${executionWorkspaces.sourceIssueId} IS NOT NULL`,
);
// Continue the scan after the previous sweep's last row. The keyset
// predicate uses the same (updatedAt, id) order as the query, so each
// sweep advances past the rows it already inspected instead of re-reading
// the oldest ineligible candidates.
const cursor = terminalSweepCursor;
// Freeze an upper bound on updatedAt at the start of each rotation. Without
// a bound, a steady stream of newer candidates keeps every page full, so
// the cursor never reaches the end and never resets, and older candidates
// that became eligible are never revisited. The frozen bound makes the
// rotation cover a finite set, so the cursor always reaches a short page.
if (!cursor) {
terminalSweepBoundary = now();
}
const boundary = terminalSweepBoundary;
const boundaryFilter = boundary
? lte(executionWorkspaces.updatedAt, boundary)
: undefined;
const cursorFilter = cursor
? or(
gt(executionWorkspaces.updatedAt, cursor.updatedAt),
and(
eq(executionWorkspaces.updatedAt, cursor.updatedAt),
gt(executionWorkspaces.id, cursor.id),
),
)
: undefined;
const scanFilter = and(baseCandidateFilter, boundaryFilter, cursorFilter);
const candidates = await db
.select()
.from(executionWorkspaces)
.where(and(
inArray(executionWorkspaces.status, ["active", "idle", "in_review"]),
isNull(executionWorkspaces.closedAt),
sql<boolean>`${executionWorkspaces.sourceIssueId} IS NOT NULL`,
))
.where(scanFilter)
.orderBy(asc(executionWorkspaces.updatedAt), asc(executionWorkspaces.id))
.limit(limit);
// Advance the cursor to this page's last row. A short page means the scan
// reached the end of the bounded candidate set, so reset the cursor and
// the bound to start a new rotation on the next sweep.
if (candidates.length < limit) {
terminalSweepCursor = null;
terminalSweepBoundary = null;
} else {
const lastCandidate = candidates[candidates.length - 1]!;
terminalSweepCursor = { updatedAt: lastCandidate.updatedAt, id: lastCandidate.id };
}
const result = {
checked: candidates.length,
eligible: 0,
@@ -2178,6 +2256,9 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
}
}
return result;
} finally {
terminalSweepInProgress = false;
}
},
create: async (data: typeof executionWorkspaces.$inferInsert) => {