Files
PaperClipAI/server/src/__tests__/terminal-workspace-work.test.ts
T
DottaandPaperclip 7c016c049b perf(workspaces): wake terminal cleanup from committed changes (#16282)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents use execution workspaces to retain their files and Git
branches.
> - A reaper closes eligible workspaces after their task tree is
terminal.
> - The reaper scanned every heartbeat tick and read Git before cheap
eligibility checks.
> - Permanent scans also query idle databases when no cleanup work
exists.
> - This pull request wakes cleanup after transaction settlement and
restores bounded work at startup.
> - The benefit is fewer scans while fresh cleanup guards continue to
protect retained work.

## Linked Issues or Issue Description

Related work: Refs #13619, Refs #11753. Those PRs bound scans or back
off unchanged candidates. This PR uses the transaction work coordinator
to remove the permanent reaper tick. It overlaps their early
terminal-state filtering but does not change their runtime restart
behavior or introduce a second Git scheduler cache.

**What existing behavior does this improve?**

Terminal workspace cleanup and Git inspection for workspace detail
reads.

**Subsystem affected**

Server orchestration, execution workspaces, and idle sleep admission.

**Current behavior**

The heartbeat tick scans workspace candidates every thirty seconds. It
runs Git before rejecting nonterminal trees, cooldowns, and active runs.
Display inspections expire after five seconds.

**Proposed behavior**

Recover workspace rows in bounded startup pages. Wake after relevant
issue, workspace, and pull-request work-product transactions settle.
Schedule the terminal tree cooldown or a five-minute eligibility retry.
Back off unchanged candidates across unrelated wakes, and invalidate
their backoff after relevant committed changes. Park empty and
nonterminal-only lanes. Reuse display inspections for thirty seconds.
Read fresh Git before destructive cleanup.

**Reason and benefit**

Avoid recurring database and Git work when no cleanup is possible.
Retain transaction admission holds, restart recovery, and fresh deletion
checks. Retention eligibility can wait for the next host wake; active
and failed recovery work still blocks sleep.

**Breaking changes**

No schema or API shape changes. Display Git state can lag by thirty
seconds. Cleanup eligibility retries can take five minutes.

## What Changed

- Add a terminal-workspace worker to the existing transaction work
coordinator and scheduler.
- Signal relevant writes before mutation on the owning transaction.
Outer transaction settlement wakes cleanup.
- Derive cooldown deadlines from the full company-scoped terminal task
tree. Continue bounded recovery pages without a permanent sweep.
- Bound unchanged candidate inspections to five minutes, retain at most
256 entries, and invalidate affected entries with scoped transaction
hints. Repeated wakes preserve the earliest inspection deadline.
- Collect deadlines from task trees already read by bounded pages.
Restore the cursor after a failed page and rescan commits received
during a rotation.
- Check terminal state, cooldown, and active runs before Git. Preserve
lifecycle locks, generation fences, and fresh final checks.
- Keep failed or incomplete recovery visible to idle admission. Preserve
the passive retention exception.
- Extend the bounded display cache to thirty seconds and document the
scheduling and wake limits.

## Verification

- Focused workspace, coordinator, cache, and local sleep suites: 111
tests passed with real local PostgreSQL and Git worktrees where
applicable.
- Final worker, display cache, and local sleep suites: 28 tests passed.
- The regressions prove three ineligible workspaces invoke zero Git
scans, cached clean display state cannot remove new untracked files, and
real producer notifications wait for outer transaction settlement.
- `pnpm -r typecheck` and `pnpm build` passed locally. Map and
module-boundary checks passed.
- Work-product and sleep-safety suites: 221 tests passed. Reopen and
issue-tree control suites: 46 tests passed. Final backoff, workspace,
worker, and work-product suites: 87 tests passed.
- Final workspace and worker suites: 81 tests passed. Deadline selection
performs zero database reads. A failed full page retries its unread
terminal workspace before recovery can park.
- Full CI coverage passed on head `2c397970f7`: general tests,
serialized server suites, runner verification, E2E shards, typecheck,
build, and the final verification gate. The duplicate serial local `pnpm
test:run` was stopped after full CI coverage passed; it is not reported
as a completed local pass.
- Greptile: 5/5 with both findings resolved. The security scan also
passed. No failing or pending PR checks remain.

## Risks

- Display state can be stale for thirty seconds. Destructive guards
bypass the display cache.
- Undelivered or otherwise ineligible terminal work retries after five
minutes instead of each heartbeat tick.
- Transaction signals cover the owning `createDb` scope. Direct SQL and
independent server processes require startup recovery.
- Local cooldown timers are maintenance hints. They do not establish an
external wake alarm or whole-instance sleep safety. Existing blockers
remain in force; failed bounded recovery keeps the host awake.

## Model Used

OpenAI GPT-6, model ID `gpt-6`, through Codex. Reasoning, repository
inspection, shell execution, and browser tools assisted the change. The
runtime does not expose the context-window size.

## 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
- [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>
2026-10-14 08:28:45 -05:00

131 lines
6.0 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { notifyTerminalWorkspaceWork, registerTerminalWorkspaceWork, TERMINAL_WORKSPACE_RETRY_MS } from "../services/terminal-workspace-work.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
const coordinators: ReturnType<typeof createDeliveryWorkCoordinator>[] = [];
afterEach(async () => {
for (const coordinator of coordinators.splice(0)) await coordinator.stop();
vi.useRealTimers();
});
function setup() {
vi.useFakeTimers();
const execute = vi.fn(async () => [{ xid: "42", status: "committed" }]);
const owner = installDatabaseWorkSignals({ execute, async transaction(callback: (tx: any) => Promise<any>) {
return callback({ execute });
} });
const enabled = vi.fn(() => true), primary = vi.fn(() => true), onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner,
canRun: () => enabled() && primary(), canReconcile: primary, onError,
});
coordinators.push(coordinator);
const service = {
sweepTerminalWorkspaces: vi.fn(async (_limit?: number, _signal?: AbortSignal) => ({ checked: 0 })),
hasTerminalWorkspaceSweepContinuation: vi.fn(() => false),
nextTerminalWorkspaceSweepAt: vi.fn(async (): Promise<number | null> => null),
};
return { owner, coordinator, service, enabled, primary, onError,
start: () => registerTerminalWorkspaceWork(coordinator, service, enabled) };
}
describe("terminal workspace work", () => {
it("recovers once at startup and makes no scans or SQL for an empty lane", async () => {
const s = setup();
const worker = s.start();
await worker.ready;
await vi.advanceTimersByTimeAsync(3_600_000);
expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(1);
expect(s.service.nextTerminalWorkspaceSweepAt).toHaveBeenCalledTimes(1);
expect(s.coordinator.nextWakeAt()).toBeNull();
expect(vi.getTimerCount()).toBe(0);
expect(idleWorkSnapshot().active).toBe(0);
expect(worker.hasUnrecoveredWork()).toBe(false);
});
it("restores the cooldown deadline, lets commits preempt it, and parks after cleanup", async () => {
const s = setup(), due = Date.now() + 86_400_000;
s.service.nextTerminalWorkspaceSweepAt.mockResolvedValue(due);
const worker = s.start();
await worker.ready;
expect(worker.hasUnrecoveredWork()).toBe(false);
await vi.advanceTimersByTimeAsync(3_600_000);
expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(1);
await s.owner.transaction(tx => notifyTerminalWorkspaceWork(tx));
await s.owner.transaction(tx => notifyTerminalWorkspaceWork(tx));
await vi.advanceTimersByTimeAsync(1);
expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(2);
expect(s.coordinator.nextWakeAt()).toBe(due);
s.service.nextTerminalWorkspaceSweepAt.mockResolvedValue(null);
await vi.advanceTimersByTimeAsync(due - Date.now());
expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(3);
expect(vi.getTimerCount()).toBe(0);
});
it("finishes bounded recovery pages then retries only existing overdue work", async () => {
const s = setup();
s.service.hasTerminalWorkspaceSweepContinuation.mockReturnValueOnce(true);
s.service.nextTerminalWorkspaceSweepAt.mockResolvedValue(Date.now() - 1);
await s.start().ready;
expect(s.coordinator.nextWakeAt()).toBe(Date.now() + 1000);
await vi.advanceTimersByTimeAsync(1000);
expect(s.coordinator.nextWakeAt()).toBe(Date.now() + TERMINAL_WORKSPACE_RETRY_MS);
s.service.nextTerminalWorkspaceSweepAt.mockResolvedValue(null);
await vi.advanceTimersByTimeAsync(TERMINAL_WORKSPACE_RETRY_MS);
expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(3);
expect(vi.getTimerCount()).toBe(0);
});
it("keeps failed recovery visible to sleep admission until a successful empty pass", async () => {
const s = setup();
s.service.sweepTerminalWorkspaces.mockRejectedValueOnce(new Error("database unavailable"));
const worker = s.start();
await worker.ready;
expect(s.onError).toHaveBeenCalledTimes(1);
expect(worker.hasUnrecoveredWork()).toBe(true);
await vi.advanceTimersByTimeAsync(TERMINAL_WORKSPACE_RETRY_MS);
expect(worker.hasUnrecoveredWork()).toBe(false);
expect(vi.getTimerCount()).toBe(0);
});
it("defers scans and deadline SQL during standby and drain", async () => {
const s = setup();
s.primary.mockReturnValue(false);
await s.start().ready;
s.primary.mockReturnValue(true);
s.enabled.mockReturnValue(false);
await s.owner.transaction(tx => notifyTerminalWorkspaceWork(tx));
await vi.advanceTimersByTimeAsync(1);
expect(s.service.sweepTerminalWorkspaces).not.toHaveBeenCalled();
expect(s.service.nextTerminalWorkspaceSweepAt).not.toHaveBeenCalled();
s.enabled.mockReturnValue(true);
await vi.advanceTimersByTimeAsync(TERMINAL_WORKSPACE_RETRY_MS);
expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
});
it("holds admission until accepted cleanup finishes and waits for it during stop", async () => {
const s = setup();
let release!: () => void;
s.service.sweepTerminalWorkspaces.mockImplementationOnce(async (_limit, signal) => {
await new Promise<void>(resolve => { release = resolve; });
expect(signal?.aborted).toBe(true);
return { checked: 1 };
});
const worker = s.start();
await vi.advanceTimersByTimeAsync(1);
expect(idleWorkSnapshot().active).toBe(1);
let stopped = false;
const stopping = s.coordinator.stop().then(() => { stopped = true; });
await vi.advanceTimersByTimeAsync(1);
expect(stopped).toBe(false);
release();
await stopping;
await worker.ready;
expect(idleWorkSnapshot().active).toBe(0);
expect(s.service.nextTerminalWorkspaceSweepAt).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
});
});