Files
PaperClipAI/tests/runner-e2e/controller-database.test.ts
T
DottaandPaperclip 6987c2f20b test(upgrades): qualify controller replacement with immutable artifacts and phase evidence (#17455)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/105/changes/paperclip/105
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip needs evidence that an admitted execution survives a
main-server replacement.
> - Runner mechanics and server adoption belong to #17097 and #17439.
> - A healthy HTTP endpoint does not prove recovery of the original
execution.
> - Qualification must identify the serving artifact, natural ownership,
authenticated attachment and resumed processing separately.
> - It must also retain failed runs and measure normal-operation costs.
> - This PR extends the existing qualification machinery and acceptance
record.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Operators can assess upgrade continuity from phase evidence tied to
exact artifacts and profiles.

**Current behavior**

A same-artifact restart or synthetic executor pass cannot establish
different-artifact upgrade and rollback support. Idle SQL gates also do
not measure active-run capacity.

**Proposed behavior**

Use immutable A/B artifacts and strict phase receipts through the
existing supervisor. Preserve failed evidence and add measured
before/after workload costs.

Builds on merged #17097 and #17439. The base is now `master`. #17456
follows for review convenience. This PR lands qualification machinery
and the evidence record. The remaining hosted gates stay open for
deployment qualification; merging this machinery does not claim those
experiments passed.

## What Changed

- Extend the main-server supervisor and installed-artifact verification
for actual serving revisions, forward migrations and compatible
rollback.
- Distinguish HTTP readiness, natural ownership, authenticated
attachment, resumed processing and backlog settlement.
- Retain the original reconnect grace and execution identity checks.
Never substitute a new task or edited lease for continuity.
- Reuse real-harness and Daytona qualification paths, with exact profile
and artifact provenance.
- Bind current Copilot attestation inputs in the Daytona image
fingerprint.
- Keep one acceptance record, including both failed file-only stress
phases and the final passing bounded-pool comparison.

## Verification

After retargeting to master, all 158 focused qualification cases across
13 files pass, with E2E typecheck. The first 12-file batch has four
report-lock test failures and 133 passes. Master #17811 had committed
the exact already-approved output lock, while that fixture assumed HEAD
must be the uncorrected input. The fixture now checks both pinned forms,
executes the committed-lock path, and reconstructs the pinned input to
retain all rejection tests. The production helper, policy hashes, patch
and dependency resolution are unchanged. The corrected batch explicitly
includes both process-preservation suites; the prior 146-case receipt
has its own source and selection.

Current candidate `8f1d6ec02f` integrates master `09ad9adce2`, including
the merged server slice. Its diff contains only qualification code and
documentation. The [qualification
record](https://github.com/paperclipai/paperclip/blob/8f1d6ec02f5bf6c90e7b27da8156953cabd9a180/doc/plans/2026-10-22-hot-upgrade-qualification.md)
is the acceptance ledger and retains source-attributed failures and
hosted limits.

On the eighth integration, all 146 cases across 12 focused qualification
files pass, including report-lock preparation, workflow security and
workflow targeting. E2E typecheck passes. The earlier 118-case result
remains attributed to its prior source. The first sandbox invocation has
117 passes and one failure because process inspection was denied during
inert fixture cleanup. The permitted repeat passes all 118 and a
targeted process check finds no remaining fixture daemon. The earlier
96-case receipt remains source-attributed in the ledger. The latest two
review regressions first fail: an intermediate replacement can cite
another runner/session despite a valid final step, and malformed receipt
JSON aborts evidence packaging. Each replacement now binds
run/company/issue/runner/session, and corrupt receipts retain explicit
invalid metadata plus sanitized diagnostics while other logs and
receipts still package. These checks prove qualification machinery with
injected supervisor operations, configuration subprocesses and real
filesystem packaging. They do not qualify a hosted harness.

Three request-reader cases, 14 artifact/configuration/cache/history
cases, and three lost-partial-receipt cases fail before their respective
corrections. The final collector preserves sanitized startup, readiness
and recovery phase receipts through packaging and temporary-root
deletion. Earlier embedded-Postgres initialization, report-catalog
drift, CI scheduling/cleanup failures and fixture collisions remain
recorded with their corrections or limits. The previous Greptile service
error is retained as historical review evidence, not a current review
pass.

The record includes prior source `9bb9d3417e`'s actual Linux
contention/fairness successes and the ordinary-warm regression proof
from the server slice. The historical 300-session component campaign
passes four after phases and retains earlier burst failures. Those
component costs do not establish hosted capacity. The hosted API-only
pair has zero agents/viewers, fails both absolute latency gates and the
candidate memory gate, and does not complete the active-agent/viewer
matrix.

The strict ten-agent same-artifact restart remains attributed to its
original artifact. It does not qualify this updated stack. Actual
A→B/B→A, the normal drain-free Cloud rollout, and other hosted harnesses
remain open. No new provider turn, deployment or hosted qualification
was run during merge preparation.

Prior source `57d3767eac` jobs 122590643944, 122590643983 and
122590644161 ended after runner shutdown/cancellation without final
Vitest results. The shutdown cause is unproven. No retry was issued
before this source was superseded by the required server recovery fix.
These attempts remain failures/incomplete evidence. Fresh exact-head CI,
legacy status, completed Greptile 5/5, resolved feedback and normal
merge eligibility remain required.

## Risks

Different-artifact A→B/B→A, the normal drain-free Cloud rollout path,
other hosted harnesses and the complete concurrency/viewer matrix remain
open. Frozen branch builds are development-build evidence. This PR owns
qualification and evidence; production defects must be fixed in their
earlier owning slice.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, repository tools and code
execution. The runtime does not expose a more specific model ID or
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
- [ ] 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-27 21:58:09 -05:00

80 lines
4.6 KiB
TypeScript

import { spawn } from "node:child_process";
import { once } from "node:events";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import { expect, it } from "vitest";
import { createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "../../packages/db/src/index.js";
import { assertEmbeddedDatabaseIsolation } from "./instance-isolation.js";
import { prepareControllerDatabase } from "./controller-database.js";
import { createRunnerE2ETemporaryRoot, prepareRunnerE2EServerConfig } from "./server-config.js";
it("keeps an unmigrated fixture database alive when its serving client dies", async () => {
const root = await createRunnerE2ETemporaryRoot();
const configPath = path.join(root, "instance", "config.json");
let database: Awaited<ReturnType<typeof prepareControllerDatabase>> | undefined;
let db: ReturnType<typeof createDb> | undefined;
let child: ReturnType<typeof spawn> | undefined;
try {
await (await prepareRunnerE2EServerConfig({ temporaryRoot: root, configPath, serverPort: 3100 }))!.close();
database = await prepareControllerDatabase(configPath, root);
const config = JSON.parse(await readFile(configPath, "utf8"));
expect(config.database.mode).toBe("postgres");
await mkdir(path.dirname(config.secrets.localEncrypted.keyFilePath), { recursive: true });
await writeFile(config.secrets.localEncrypted.keyFilePath, "fixture-key");
await expect(assertEmbeddedDatabaseIsolation(configPath, root)).resolves.toBeUndefined();
db = createDb(config.database.connectionString);
const before = await db.$client`select pg_postmaster_start_time()::text as started`;
expect(await db.$client`select tablename from pg_tables where schemaname = 'public'`).toEqual([]);
const require = createRequire(new URL("../../packages/db/package.json", import.meta.url));
child = spawn(process.execPath, ["--input-type=module", "-e", `
const { default: postgres } = await import(process.argv[1]);
const sql = postgres(process.argv[2]);
await sql.unsafe('select 1');
process.stdout.write('connected');
setInterval(() => {}, 1000);
`, require.resolve("postgres"), config.database.connectionString], { stdio: ["ignore", "pipe", "pipe"] });
let errors = "";
child.stderr!.on("data", chunk => { errors += chunk; });
const connected = await Promise.race([
once(child.stdout!, "data").then(([chunk]) => String(chunk)),
once(child, "exit").then(() => { throw new Error(`Database client exited before connection: ${errors}`); }),
]);
expect(connected).toBe("connected");
const stopped = once(child, "exit");
child.kill("SIGKILL");
await stopped;
expect(await db.$client`select pg_postmaster_start_time()::text as started`).toEqual(before);
await db.$client`create table replacement_probe (id integer primary key)`;
await db.$client`insert into replacement_probe values (1)`;
expect(await db.$client`select count(*)::integer as count from replacement_probe`).toEqual([{ count: 1 }]);
await db.$client.end({ timeout: 1 }); db = undefined;
await database.cleanup(); database = undefined;
// The launcher grades isolation after the supervisor has shut down.
await expect(assertEmbeddedDatabaseIsolation(configPath, root)).resolves.toBeUndefined();
} finally {
if (child && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
await db?.$client.end({ timeout: 1 });
await database?.cleanup();
await rm(root, { recursive: true, force: true });
}
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
it("rejects database directories outside the fixture and leaves external databases alone", async () => {
const root = await createRunnerE2ETemporaryRoot();
const configPath = path.join(root, "config.json");
try {
await (await prepareRunnerE2EServerConfig({ temporaryRoot: root, configPath, serverPort: 3100 }))!.close();
const config = JSON.parse(await readFile(configPath, "utf8"));
config.database.embeddedPostgresDataDir = path.join(root, "..", "unrelated");
await writeFile(configPath, JSON.stringify(config));
await expect(prepareControllerDatabase(configPath, root)).rejects.toThrow("must belong to its qualification fixture");
config.database.mode = "postgres";
config.database.connectionString = "postgres://unused@127.0.0.1:1/never-connect";
const encoded = JSON.stringify(config);
await writeFile(configPath, encoded);
await (await prepareControllerDatabase(configPath, root)).cleanup();
expect(await readFile(configPath, "utf8")).toBe(encoded);
} finally { await rm(root, { recursive: true, force: true }); }
});