Split heartbeat-process-recovery.test.ts into 4 balanced serialized suites (#22955)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Release and master verification run serialized server integration
suites across sharded CI jobs (`release-verify.yml`)
> - `server/src/__tests__/heartbeat-process-recovery.test.ts` (17,926
lines, 466 expanded tests) takes ~6m 28s in a single file, so Vitest
cannot shard it across runners even with 9 serialized shards (#22946)
> - Because one file sets a hard floor on the serialized verification
lane, release readiness stays slower than necessary after every merge
> - This pull request moves the shared suite body into
`server/src/__tests__/heartbeat-process-recovery.helper.ts` with four
disjoint `part` slices and adds four thin test entrypoints
(`heartbeat-process-recovery-part-{1..4}.test.ts`)
> - The benefit is balanced shard distribution across serialized
runners, cutting the single-file serialized ceiling by ~4.5 minutes
while keeping all 466 test cases intact

## Linked Issues or Issue Description

Refs #22946

**Area**
CI / Test Infrastructure

**Current Behavior**
`server/src/__tests__/heartbeat-process-recovery.test.ts` runs as a
single 17,926-line Vitest file (~344s recorded, ~388s in recent release
runs), bounding `Serialized tests` even across 9 shards.

**Proposed Improvement**
Partition the suite into four thin entrypoint files
(`heartbeat-process-recovery-part-{1..4}.test.ts`) backed by a shared
`heartbeat-process-recovery.helper.ts`, with measured proportional shard
weights in `scripts/serialized-shard-durations.json` and
`scripts/ci/nightly-only-suites.json`.

**Motivation / Use Case**
Shorten master and release verification wall-clock latency without
dropping or weakening any recovery test coverage.

## What Changed

- Renamed `server/src/__tests__/heartbeat-process-recovery.test.ts` to
`server/src/__tests__/heartbeat-process-recovery.helper.ts` exporting
`registerHeartbeatProcessRecoverySuite(part: 1 | 2 | 3 | 4)`, hoisting
`withTempPaperclipHome` to shared scope, making `beforeAll`'s
`authUsers` seed `.onConflictDoNothing()` for shared
`PAPERCLIP_TEST_DATABASE_URL` safety, routing dynamic `run-dispatch`
imports through `../modules/run-dispatch/index.js`, and updating the two
stack-trace file-name assertions to `.helper.ts`.
- Added four 3-line entrypoints:
`server/src/__tests__/heartbeat-process-recovery-part-{1,2,3,4}.test.ts`.
- Updated `scripts/run-vitest-stable.mjs`,
`scripts/serialized-shard-durations.json`, and
`scripts/ci/nightly-only-suites.json` with the four part paths and
measured proportional shard weights (`88511`, `102168`, `72141`, `81197`
ms; sum `344017` ms).
- Updated `.github/workflows/runner-chaos-evals.yml` (with
`--no-file-parallelism` to preserve serial execution in that job),
`maps/feature-map/recovery.md`,
`packages/paperclip-runner/spec/evals/stress-workflow-traceability.json`,
and `scripts/ci/test-selection.integration.test.mjs`.

## Verification

- Executed all four split suites locally via Vitest against embedded
Postgres — **466/466 tests passed** (0 failed, 0 skipped):
- `heartbeat-process-recovery-part-1.test.ts`: 116/116 passed (199.67s
under 4-way local contention)
- `heartbeat-process-recovery-part-2.test.ts`: 103/103 passed (230.48s)
  - `heartbeat-process-recovery-part-3.test.ts`: 87/87 passed (162.74s)
- `heartbeat-process-recovery-part-4.test.ts`: 160/160 passed (183.17s)
- Verified brace-depth exhaustiveness across
`heartbeat-process-recovery.helper.ts`: 0 top-level
`it`/`it.each`/`describe` blocks outside `if (part === N)` guards.
- `node scripts/check-module-boundaries.mjs` — passed.
- `node scripts/check-maps.mjs` — passed.
- `node scripts/check-test-budget.mjs --base origin/master` — passed.
- `node --test scripts/check-test-budget.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/ci/test-selection.integration.test.mjs` — passed.

## Risks

- Low risk: test-only partition; zero production runtime files changed.
- Adding a future test to `heartbeat-process-recovery.helper.ts` outside
an `if (part === N)` guard would not register in any part; documented
the placement rule directly on `registerHeartbeatProcessRecoverySuite`.

## Model Used

- Google Gemini (Antigravity agent with 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
- [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)

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-25 12:08:54 -06:00
1 parent 2d06567795
commit 2538dce415
12 files changed
+109 -52

No files matched your search

+5 -2
View File
@@ -69,9 +69,12 @@ jobs:
- name: Run server finalization and recovery suites
run: |
pnpm --filter @paperclipai/server exec vitest run \
pnpm --filter @paperclipai/server exec vitest run --no-file-parallelism \
src/__tests__/native-finalization-recovery.test.ts \
src/__tests__/heartbeat-process-recovery.test.ts \
src/__tests__/heartbeat-process-recovery-part-1.test.ts \
src/__tests__/heartbeat-process-recovery-part-2.test.ts \
src/__tests__/heartbeat-process-recovery-part-3.test.ts \
src/__tests__/heartbeat-process-recovery-part-4.test.ts \
src/__tests__/heartbeat-comment-wake-batching.test.ts \
src/__tests__/heartbeat-dependency-scheduling.test.ts \
src/__tests__/provider-trace-store.test.ts \
+2 -2
View File
@@ -288,7 +288,7 @@ the task becomes done or cancelled. Verify one unchanged action ID, attempt
count, and timestamps; task completion must not authorize copyback. Clear only
the exact receipt after operator stop verification, then confirm stale action
cleanup. The [route regressions](../../server/src/__tests__/issue-recovery-actions.test.ts)
and [heartbeat regression](../../server/src/__tests__/heartbeat-process-recovery.test.ts)
and [heartbeat regression](../../server/src/__tests__/heartbeat-process-recovery-part-1.test.ts)
cover this sequence without a live operator recovery claim.
An intentionally Done onboarding parent can still need its validated
@@ -408,7 +408,7 @@ files, successful lease cleanup, and one bounded continuation. Reload before
checking the successor. Repeat with controller loss: the expired fence must
retain the exact source and require repair, never claim restored files or start
a second executor. The database-backed
[shutdown regression](../../server/src/__tests__/heartbeat-process-recovery.test.ts)
[shutdown regression](../../server/src/__tests__/heartbeat-process-recovery-part-1.test.ts)
checks finalizer joining, release order, durable retry uniqueness, and reload.
The [settlement regressions](../../server/src/services/heartbeat/recovery.test.ts)
cover other-controller fencing and owner loss. Provider boundaries are controlled
@@ -36,7 +36,7 @@
{ "id": "STRESS-017", "classification": "workflow_eval", "workflowIds": ["cancellation-permissions"], "regressionTests": ["../../ui/src/components/task-chat/transcript-adapter.test.ts"] },
{ "id": "STRESS-018", "classification": "workflow_eval", "workflowIds": ["restart-recovery", "completion-robustness"], "regressionTests": ["../../server/src/services/native-runtime/native-session-executor.test.ts"] },
{ "id": "STRESS-019", "classification": "workflow_eval", "workflowIds": ["restart-recovery", "governed-interaction"], "regressionTests": ["src/backends/harness-driver-backend.test.ts"] },
{ "id": "STRESS-020", "classification": "workflow_eval", "workflowIds": ["completion-robustness"], "regressionTests": ["../../server/src/__tests__/heartbeat-process-recovery.test.ts", "../../server/src/__tests__/heartbeat-comment-wake-batching.test.ts"] },
{ "id": "STRESS-020", "classification": "workflow_eval", "workflowIds": ["completion-robustness"], "regressionTests": ["../../server/src/__tests__/heartbeat-process-recovery-part-1.test.ts", "../../server/src/__tests__/heartbeat-process-recovery-part-2.test.ts", "../../server/src/__tests__/heartbeat-process-recovery-part-3.test.ts", "../../server/src/__tests__/heartbeat-process-recovery-part-4.test.ts", "../../server/src/__tests__/heartbeat-comment-wake-batching.test.ts"] },
{ "id": "STRESS-021", "classification": "workflow_eval", "workflowIds": ["governed-interaction"], "regressionTests": ["../../server/src/services/native-runtime/native-session-executor.test.ts"] },
{ "id": "STRESS-022", "classification": "workflow_eval", "workflowIds": ["governed-interaction", "restart-recovery"], "regressionTests": ["src/drivers/acpx/codex-acpx-driver.test.ts"] },
{ "id": "STRESS-023", "classification": "workflow_eval", "workflowIds": ["cancellation-permissions"], "regressionTests": ["../../server/src/services/native-runtime/native-session-executor.test.ts"] },
+21 -3
View File
@@ -164,10 +164,28 @@
"measuredMs": 223420
},
{
"path": "server/src/__tests__/heartbeat-process-recovery.test.ts",
"path": "server/src/__tests__/heartbeat-process-recovery-part-1.test.ts",
"category": "recovery-idle-maintenance-soak",
"reason": "Heavy serialized heartbeat process-crash recovery soak (285 cases, 344s); core heartbeat/recovery.test.ts stays on PRs",
"measuredMs": 344017
"reason": "Heavy serialized heartbeat process-crash recovery soak (part 1/4, 116 cases); core heartbeat/recovery.test.ts stays on PRs",
"measuredMs": 88511
},
{
"path": "server/src/__tests__/heartbeat-process-recovery-part-2.test.ts",
"category": "recovery-idle-maintenance-soak",
"reason": "Heavy serialized heartbeat process-crash recovery soak (part 2/4, 103 cases); core heartbeat/recovery.test.ts stays on PRs",
"measuredMs": 102168
},
{
"path": "server/src/__tests__/heartbeat-process-recovery-part-3.test.ts",
"category": "recovery-idle-maintenance-soak",
"reason": "Heavy serialized heartbeat process-crash recovery soak (part 3/4, 87 cases); core heartbeat/recovery.test.ts stays on PRs",
"measuredMs": 72141
},
{
"path": "server/src/__tests__/heartbeat-process-recovery-part-4.test.ts",
"category": "recovery-idle-maintenance-soak",
"reason": "Heavy serialized heartbeat process-crash recovery soak (part 4/4, 160 cases); core heartbeat/recovery.test.ts stays on PRs",
"measuredMs": 81197
},
{
"path": "server/src/__tests__/heartbeat-retry-scheduling.test.ts",
@@ -234,7 +234,7 @@ test("mixed audited documentation stays graph eligible and large complete source
});
test("refineTestPlan applies nightly exclusions before partitioning while keeping full inventory validation", () => {
const nightlySuite = "server/src/__tests__/heartbeat-process-recovery.test.ts";
const nightlySuite = "server/src/__tests__/heartbeat-process-recovery-part-1.test.ts";
const fastSuite = "server/src/__tests__/issues-service.test.ts";
const entries = [0, 1].map((shard_index) => ({
group: "general-server-without-chat",
+4 -1
View File
@@ -66,7 +66,10 @@ const additionalSerializedServerTests = new Set([
"server/src/__tests__/health.test.ts",
"server/src/__tests__/heartbeat-dependency-scheduling.test.ts",
"server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts",
"server/src/__tests__/heartbeat-process-recovery.test.ts",
"server/src/__tests__/heartbeat-process-recovery-part-1.test.ts",
"server/src/__tests__/heartbeat-process-recovery-part-2.test.ts",
"server/src/__tests__/heartbeat-process-recovery-part-3.test.ts",
"server/src/__tests__/heartbeat-process-recovery-part-4.test.ts",
"server/src/__tests__/invite-accept-existing-member.test.ts",
"server/src/__tests__/invite-accept-gateway-defaults.test.ts",
"server/src/__tests__/invite-accept-replay.test.ts",
+4 -1
View File
@@ -86,7 +86,10 @@
"server/src/__tests__/health.test.ts": 5679,
"server/src/__tests__/heartbeat-dependency-scheduling.test.ts": 78007,
"server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts": 54768,
"server/src/__tests__/heartbeat-process-recovery.test.ts": 344017,
"server/src/__tests__/heartbeat-process-recovery-part-1.test.ts": 88511,
"server/src/__tests__/heartbeat-process-recovery-part-2.test.ts": 102168,
"server/src/__tests__/heartbeat-process-recovery-part-3.test.ts": 72141,
"server/src/__tests__/heartbeat-process-recovery-part-4.test.ts": 81197,
"server/src/__tests__/heartbeat-run-privacy-routes.test.ts": 28486,
"server/src/__tests__/inbox-agent-policy-routes.test.ts": 6628,
"server/src/__tests__/inbox-archive-routes.test.ts": 11396,
@@ -0,0 +1,3 @@
import { registerHeartbeatProcessRecoverySuite } from "./heartbeat-process-recovery.helper.js";
registerHeartbeatProcessRecoverySuite(1);
@@ -0,0 +1,3 @@
import { registerHeartbeatProcessRecoverySuite } from "./heartbeat-process-recovery.helper.js";
registerHeartbeatProcessRecoverySuite(2);
@@ -0,0 +1,3 @@
import { registerHeartbeatProcessRecoverySuite } from "./heartbeat-process-recovery.helper.js";
registerHeartbeatProcessRecoverySuite(3);
@@ -0,0 +1,3 @@
import { registerHeartbeatProcessRecoverySuite } from "./heartbeat-process-recovery.helper.js";
registerHeartbeatProcessRecoverySuite(4);
@@ -532,7 +532,14 @@ const spentRestartRetryAccounting = () => ({
serverRestartWindowStartedAt: new Date().toISOString(),
});
describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
/**
* Registers one of four disjoint partitions of the heartbeat process recovery
* suite so CI can shard them across serialized runners. Every `it` / `it.each`
* (and nested `describe`) in this function MUST live inside an
* `if (part === N)` block; shared helpers stay at top level outside the guards.
*/
export function registerHeartbeatProcessRecoverySuite(part: 1 | 2 | 3 | 4): void {
describeEmbeddedPostgres(`heartbeat orphaned process recovery (part ${part}/4)`, () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<
ReturnType<typeof startEmbeddedPostgresTestDatabase>
@@ -679,7 +686,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
emailVerified: true,
createdAt: now,
updatedAt: now,
});
}).onConflictDoNothing();
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
afterEach(async () => {
@@ -1017,6 +1024,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
return { environmentId, leaseId };
}
if (part === 1) {
it("does not reap active adapter executions started by another heartbeat service instance", async () => {
let releaseAdapter!: () => void;
const adapterRelease = new Promise<void>(resolve => { releaseAdapter = resolve; });
@@ -1105,6 +1113,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
}
// Start alone measures 3-6s locally, before the 5s settle wait.
}, 30_000);
}
async function seedStrandedIssueFixture(input: {
status: "todo" | "in_progress";
@@ -1660,6 +1669,40 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
return { companyId, agentId, runId, wakeupRequestId, issueId };
}
async function withTempPaperclipHome<T>(
fn: (home: string) => Promise<T>,
): Promise<T> {
const home = await fs.mkdtemp(
path.join(os.tmpdir(), "paperclip-hot-restart-"),
);
const previousHome = process.env.PAPERCLIP_HOME;
process.env.PAPERCLIP_HOME = home;
try {
return await fn(home);
} finally {
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME;
else process.env.PAPERCLIP_HOME = previousHome;
// Native dispatch materializes read-only runtime bundles in this owned
// temporary home. Restore directory permissions solely for test cleanup.
const makeDirectoriesWritable = async (
directory: string,
): Promise<void> => {
const stat = await fs.lstat(directory);
if (!stat.isDirectory() || stat.isSymbolicLink()) return;
await fs.chmod(directory, 0o700);
for (const entry of await fs.readdir(directory, {
withFileTypes: true,
})) {
if (entry.isDirectory())
await makeDirectoriesWritable(path.join(directory, entry.name));
}
};
await makeDirectoriesWritable(home);
await fs.rm(home, { recursive: true, force: true });
}
}
if (part === 1) {
it.each(["owned", "forged"] as const)("keeps unresolved-ref recovery and reporting while persisting only owned diagnostics: %s", async provenance => {
const { companyId, agentId, issueId, runId, wakeupRequestId } = await seedQueuedIssueRunFixture();
const repoRoot = await fs.mkdtemp(path.join(os.tmpdir(), "base-ref-heartbeat-"));
@@ -2131,7 +2174,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
const report = await waitForValue(async () => mockCaptureRunFailure.mock.calls.find(([event]) => event.runId === runId)?.[0]);
expect(report?.diagnostics).toMatchObject({
execution: { failurePhase: "setup" },
exceptions: [{ message, stack: expect.stringContaining("heartbeat-process-recovery.test.ts") }, { code: "ECONNRESET" }],
exceptions: [{ message, stack: expect.stringContaining("heartbeat-process-recovery.helper.ts") }, { code: "ECONNRESET" }],
});
const [wakeup] = await db.select().from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, wakeupRequestId));
@@ -2412,8 +2455,8 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
const previous = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!;
await db.insert(heartbeatRuns).values({ id: queuedId, companyId, agentId: previous.agentId,
status: "queued", contextSnapshot: { issueId, wakeReason: "issue_commented" } });
const { createPostgresRunDispatchAdapter } = await import("../modules/run-dispatch/adapters/postgres.js");
expect(await createPostgresRunDispatchAdapter(db).cancelStaleQueuedRun({ companyId, runId: queuedId,
const { createRunDispatch } = await import("../modules/run-dispatch/index.js");
expect(await createRunDispatch(db).cancelStaleQueuedRun({ companyId, runId: queuedId,
expectedStatus: "queued", now: new Date() })).toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
const { settleUnrecoverableExecutions } = await import("../services/execution-recovery-resolution.js");
await settleUnrecoverableExecutions(db);
@@ -2435,8 +2478,8 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
const previous = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!;
await db.insert(heartbeatRuns).values({ id: queuedId, companyId, agentId: previous.agentId,
status: "queued", contextSnapshot: { issueId, wakeReason: "issue_commented" } });
const { createPostgresRunDispatchAdapter } = await import("../modules/run-dispatch/adapters/postgres.js");
expect(await createPostgresRunDispatchAdapter(db).cancelStaleQueuedRun({ companyId, runId: queuedId,
const { createRunDispatch } = await import("../modules/run-dispatch/index.js");
expect(await createRunDispatch(db).cancelStaleQueuedRun({ companyId, runId: queuedId,
expectedStatus: "queued", now: new Date() })).toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
await db.update(environmentLeases).set({ releasedAt: new Date(), status: "released" }).where(eq(environmentLeases.id, lease!.id));
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
@@ -4053,39 +4096,6 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
]);
});
async function withTempPaperclipHome<T>(
fn: (home: string) => Promise<T>,
): Promise<T> {
const home = await fs.mkdtemp(
path.join(os.tmpdir(), "paperclip-hot-restart-"),
);
const previousHome = process.env.PAPERCLIP_HOME;
process.env.PAPERCLIP_HOME = home;
try {
return await fn(home);
} finally {
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME;
else process.env.PAPERCLIP_HOME = previousHome;
// Native dispatch materializes read-only runtime bundles in this owned
// temporary home. Restore directory permissions solely for test cleanup.
const makeDirectoriesWritable = async (
directory: string,
): Promise<void> => {
const stat = await fs.lstat(directory);
if (!stat.isDirectory() || stat.isSymbolicLink()) return;
await fs.chmod(directory, 0o700);
for (const entry of await fs.readdir(directory, {
withFileTypes: true,
})) {
if (entry.isDirectory())
await makeDirectoriesWritable(path.join(directory, entry.name));
}
};
await makeDirectoriesWritable(home);
await fs.rm(home, { recursive: true, force: true });
}
}
it.each([false, true])("settles a failed saved native descriptor without inventing files when workspace access is disabled: %s", async withoutWorkspace => {
await withTempPaperclipHome(async () => {
const f = await seedQueuedIssueRunFixture();
@@ -5154,7 +5164,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
await heartbeat.drainActiveRunExecutions();
}
});
}
if (part === 2) {
it("reports adopted hot-restart runs before startup reap can mark them process_lost", async () => {
const child = spawnAliveProcess();
childProcesses.add(child);
@@ -6958,7 +6970,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
const report = await waitForValue(async () => mockCaptureRunFailure.mock.calls.find(([event]) => event.runId === runId)?.[0]);
expect(report?.diagnostics).toMatchObject({
execution: { failurePhase: "execute" },
exceptions: [{ stack: expect.stringContaining("heartbeat-process-recovery.test.ts") }],
exceptions: [{ stack: expect.stringContaining("heartbeat-process-recovery.helper.ts") }],
});
const interaction = await waitForValue(async () => {
@@ -10132,7 +10144,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
}),
);
});
}
if (part === 3) {
it.each(([
{ mode: "signal", graceful: false, failure: null },
{ mode: "graceful exit", graceful: true, failure: null },
@@ -13458,7 +13472,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
).resolves.toEqual([{ id: runId }]);
},
);
}
if (part === 4) {
async function seedCommittedChatControlStop(
control: "close" | "new" = "close",
) {
@@ -17919,8 +17935,10 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
});
});
}
});
}
enableRunFailureReporting();