mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-09 16:02:36 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Background services own future checks, retries, and recovery work. > - An idle tenant can stop only when a durable wake covers its remaining duties. > - The current alarm catalog covers several domains but leaves these owners blocked. > - A saved future timestamp alone cannot prove that reconstruction or admitted work has settled. > - This pull request binds durable domain snapshots to the actual registered worker revisions. > - The tenant can hand off supported future duties and retain all checks for uncertain or active work. ## Linked Issues or Issue Description No matching public issue was found. Related work: [domain deadline handoff #18656](https://github.com/paperclipai/paperclip/pull/18656), [owned blocker diagnostics #18632](https://github.com/paperclipai/paperclip/pull/18632), and [completed history proof #18646](https://github.com/paperclipai/paperclip/pull/18646). The separate [native idle-session change #18988](https://github.com/paperclipai/paperclip/pull/18988) covers runtime retirement. [Far-future retry re-probes #13534](https://github.com/paperclipai/paperclip/pull/13534) changes recovery responsiveness after an upstream success; this change preserves existing retry decisions. **What happened?** Future status-card, external-object, skill-sync, watchdog, retry, and quota duties lacked complete owner-bound coverage in the idle deadline proof. A completed quota task could also retain its monitor policy and timestamp and remain blocked after the scheduler had disarmed it. **Expected behavior** A settled registered owner can hand off its exact supported future deadline. Active work, dirty reconstruction, transaction uncertainty, changed revisions, claims, unknown state, and unsupported duties keep the tenant awake. Completed history retains its data and stops recurring work when the owner has no remaining duty. **Steps to reproduce** 1. Produce a supported future duty through its normal service. 2. Let the registered worker finish reconstruction and admitted work. 3. Request an owned idle report with the negotiated domain deadline catalog. 4. Check the saved earliest deadline and generation before durable alarm registration. 5. Stop and reconstruct the worker. Check that ordinary admission and claims resume useful work once due. 6. Complete a quota task. Keep its saved policy and timestamp. Check that linked unfinished work still blocks sleep and that settled history does not. **Paperclip version or commit** The owned patch was qualified at `699c8569fa34338dd75cdc5731381ec1e2efdb45`. Publication head `491fac368ee72eaac8ae105d53e6bf6b305d8a6a` normally merges actual master `039e0dad2c51c80251e1302a19c5566e039c357a`. All 43 owned files are byte-identical. All 29 new upstream paths are preserved. The later normal current-master integration is `8c912e1ba4fc66397a7341ade59373af8075068f`, described separately below. **Deployment mode** Source checkout with real PostgreSQL 17 and a controlled local Node process. No deployed alarm, tenant suspension, database suspension, or fleet result is claimed. ## What Changed - Add registered-worker reconciliation revisions and invalidate them on stop. - Keep status-card, external-object, and skill deadline interpretation with their owners. - Reuse the watchdog classifier against the supplied database snapshot. - Validate the exact saved retry run and paired queued wake. - Validate legacy quota source bindings and the current assignee or reviewer policy. - Preserve common issue scope, dependency, sibling, and state checks for covered waits. - Compose normalized owner snapshots within the existing bounded deadline proof and recheck revisions after inspection. - Bind actual service and worker instances from server startup. Missing bindings preserve existing blockers. - Retain completed quota policy and timestamps while independently rejecting linked unfinished runs or wakes. - Block unconsumed budget evaluation inputs through the owning queue predicate. Accounting policy and settlement stay unchanged. - Bind completed quota history through fixed-size UUID-array parameters, preserve exact company/task/source associations, and guard external references before the run-ID join. - Batch watchdog subtrees and shared classifier facts without changing the 64-query or two-second proof budget; preserve exact company pairing for first-run evidence. - Extend production-path regression controls and document supported coverage and limits. ## Verification Current integration head: `688abc6cac6016b9fb50e5832f81e2975ed5d49f`. Fresh exact-head checks completed with **58 successes, three intentional skips and one neutral review**, including aggregate `ci / verify`. The complete current Greptile review is **5/5**. The complete current Ponytail verdict is **Ship (4/5)**, with only optional cleanup of an unused MCP proof input; both prior correctness findings are resolved. All review threads and nested pages were inspected. The normal master merges preserve the registered retry deadline owner and current startup completion log after the same readiness await. The earlier focused evidence below remains tied to its tested source revisions. Current-master integration `8c912e1ba4fc66397a7341ade59373af8075068f`: - Normally merge actual master `46fb933b0155d183ce64a8bdc4950d1b58c926f6`. Every nonoverlapping tree blob retains its owning parent across 14,044 paths. All 42 owner-only files and 15 critical binding/proof/readiness files remain byte-identical. Three automatic overlaps preserve the existing watchdog binding, conservative unavailable-reader fallback and optional actual owner arguments. The two scoped-deadline conflicts retain the entire upstream resource-reservation/mid-pass admission/abort algorithm inside the existing reconciliation revision/running/failure fence, with both parent test sets. - Actual TypeScript 7.0.2 server noEmit passed in 9.434 seconds, normal source declaration layers in 12.102 seconds, and four selected test/helper/config layers extending the actual CI configuration in 3.167 seconds. No compiler option weakening, heap override, donor declarations or SDK replacement stub. - Focused PG0 controls passed: 102 scheduler/proof/owner controls in 16.451 seconds, including all 21 scoped-deadline cases; 121 startup controls; and all 107 unchanged instance-settings route cases in 6.456 seconds. The latter first hit a local prewire-guard listener-registration race. Only the ignored guard was corrected to register the same actual OS-bound server port immediately after native listen returns. Closed, unknown, foreign, offhost and PG destinations remain blocked. Original failure evidence is retained; product code and assertions were unchanged. - The exact current UI policy command now reports zero findings (0.362 seconds); its seven scanner controls pass. The earlier dependent PR used an old scanner/source baseline under a newly enforcing trusted workflow and reported 397 findings. Carrying the genuine current master resolves that mismatch without editing unrelated UI sites or relaxing the gate. - Every meaningful worker checked its executing PID/thread/preload hash and matching receipt. PG0 controls opened no PostgreSQL sockets; all owned processes exited. Original dependency-cache/DNS, ignored-harness syntax/type and guard failures remain separate from product results. - This is fresh semantic and focused runtime qualification, not a local whole-repository or current-head PostgreSQL acceptance rerun. The upstream workspace-busy parked-retry/terminal-holder notification path remains unchanged by this merge and needs its separate current-graph producer check. Historical six-case/scale results below stay tied to their measured sources. A matching controlled default-cadence follow-up is in #19191; no fresh current-head two-cycle or deployed suspension claim follows from this merge. - All 59 exact-head check contexts now pass (55 success, one neutral, three intentional skips), plus the legacy security status. The complete edited Greptile review is 5/5 for this exact commit, with all root/nested pages inspected and no unresolved threads. Ponytail stopped without completing its new turn; it supplied no new verdict or finding. Prior actual findings remain addressed. Earlier scores/checks below belong to their explicit earlier commits. On frozen clean merged source `699c8569fa`: - Real PostgreSQL acceptance: **6/6 passed**,83.483 seconds wall. Actual retry producer creates the exact saved run/wake; stopped and reconstructed owner resumes through current admission, one durable start, real local process output and normal task completion. Includes cancellation, drain arrival, retained quota history with queued-run/wake negatives, watchdog review settlement and budget-input empty/pending/consumed control using the actual owner. - Affected coordinator, deadline, scoped-deadline, recovery and composed-proof controls: **78/78 in five files passed**,32.114 seconds wall, worker 1/no file parallelism. - `pnpm exec tsc --noEmit -p server/tsconfig.json`: **passed**,17.467 seconds. Native TypeScript 7.0.2 and Node 24.22.2. - PostgreSQL tests use one dedicated test database, matching fixture/admin URLs, pool limit four, one worker, and no embedded fallback. Every run recorded unchanged source hashes and a clean checkout. - The eight-second real-clock retry is a domain execution check. It is below the Cloud minimum wake lead and is not a positive accepted hosted sleep cycle. - The completed quota-history product failure and original fixture/protocol failures were preserved; the owning-reader fix passed a real PostgreSQL red/green regression before the fresh merged six-case pass. - After runtime completion, the dedicated database had zero other clients and no owned runtime processes. All three qualification process PIDs exited. The coordinator independently audits and drops the database. - Comment-only cleanup has equal strict TypeScript parser ASTs across 15 files. The final lexical audit finds no added comments relative to actual master. `git diff --check` passed. - Earlier retry fixtures omitted responsible-user membership, advanced JavaScript time past the real PostgreSQL lease clock, or produced stdout without normal task completion. Corrected fixtures use real membership, an eight-second real deadline, and ordinary task comment/completion. The last case exposed legitimate disposition repair rather than duplicate retry promotion. - The quota and watchdog controls first ran before admitted work or the existing 30-second reconstruction duty settled. The stronger tests require an interim blocked report and then exact settled-owner proof. Production deadlines were not changed. The separate completed-quota-history defect was fixed in its reader and verified with linked unfinished-run and wake controls. - The status/object and skill owners reviewed the actual final startup, route and post-backup bindings. Their domain source evidence carries where token-equivalent. The master coordinator coalescing change was reviewed separately. Historical domain PostgreSQL results are not presented as fresh full-suite results on this head. The later master merge adds retry predecessor cleanup checks under the existing issue claim lock. The source audit confirms unchanged saved deadlines and run/wake identities. The three actual retry lifecycle/cancellation/drain cases passed on the batched candidate with this parent (31.817 seconds). Those local dependency controls preceded the current exact-head remote run. Native backup preservation and TestOps changes from master are retained. No pass is inferred for changed dependency behavior solely from unchanged owned files. Review repair published as `643f1e7400`: - The original reader returned `unknown` after seven actual watchdog reviews settled across seven companies. The unchanged composed-report regression passed after batching; the final reader passed in 61.841 seconds, including active queued-work and stopped-owner rejection. - A separate two-company red/green control rejects terminal-run context from another company as first-run grace evidence. Shared facts are serialized once, with per-root IDs and review summaries. - The affected recovery, proof and diagnostic unit controls passed 47/47 (14.575 seconds). Startup owner-contract fixtures passed 121/121 (10.589 seconds). - Diagnostic PostgreSQL controls passed7/7 (12.406 seconds), including the normal budget-input producer and its exact blocker reason. Initial empty-state setup uses the same cleanup as per-case teardown when a dedicated test database is reused. - Actual repository `pnpm exec tsc --noEmit -p server/tsconfig.json` passed 12.710 seconds with no heap override. Final source has no added code comments; whitespace checks pass. - The original query-budget failure, two-company discriminator, initial cross-suite fixture failure and an interrupted incorrect local-driver selector are retained separately. The interrupted run is not a pass. Independent cleanup found zero owned clients or runtime processes. Quota-scale repair published as `6696a37f8a`: - The exact 10,000-row completed-history case reproduced `MAX_PARAMETERS_EXCEEDED`:90,002 bound parameters exceeded the driver's 65,534 limit, and the composed report returned `unknown` despite settled owners. Original failure and actual driver diagnostics are retained. - Fixed pending-work queries use three typed UUID-array parameters plus the result limit, keeping exact company/issue/source tuple bindings. The primary run-ID column stays uncast; a guarded CASE validates the raw external reference before conversion. The 10,000-row cap and 64-query/two-second proof budget are unchanged. - The same 10,000-row composed-report case passed 18.860 seconds, with unfinished run/wake rejection, malformed-reference safety and conservative 10,001-row overflow. Its fixture derives retained history from the actual quota producer and normal task completion, expands valid persisted issue/source pairs, then starts the actual registered owners. - The existing actual quota producer case passed 14.187 seconds, including exact future deadline, retained completion history, unfinished work, real foreign-company source references and noncanonical/malformed references. - Affected owner/proof controls passed 22/22 (26.444 seconds). Production server noEmit passed 16.039 seconds. - CI on 643 identified TS7034/TS7005 in the settled-watchdog fixture's initially untyped collection. It is now explicitly typed. A separate affected-entry semantic check extending the repository's actual `server/src/__tests__/tsconfig.json` passed 15.093 seconds: six affected tests, two owner files, ambient declarations and current imported source, with unchanged strict/module/lib/path settings. The production server config excludes that test directory and is not presented as test-layer proof. No custom suppression or replacement SDK stub was added. - All runs were sequential with pool max 4, worker 1, source/config/command hashes and cleared inherited provider/LIVE/other-database variables. Cleanup found zero owned database clients or local runtime processes. At prior head `6696a37f8a5718cd0f79054969a0084462d41d47`, all required CI gates pass. The exact-head inventory has 55 successes, one neutral review and three intentional skips. Greptile is 5/5. The complete latest Ponytail verdict confirms the quota finding is fixed; its only remaining note is optional unused MCP proof state, not a behavior defect. All three review threads are resolved. The earlier 643 result remains historical. The repository-wide typecheck, tests, build and browser gates passed in the prior `6696a37f8a5718cd0f79054969a0084462d41d47` CI run. The new `8c912e1ba4fc66397a7341ade59373af8075068f` full CI also passes. They were not run as a full local workspace command in the focused PostgreSQL lease. Local evidence above uses bounded external databases and does not claim embedded-cluster, live-provider or deployed-alarm qualification. ## Risks - An unsupported or uncertain owner state must remain blocked. An optimistic exemption could lose work while compute is stopped. - Changes during reconstruction or inspection must invalidate the proof. A memory-only timer is not durable alarm coverage. - Current authorization, budgets, cancellation, accounting, and resource ownership still apply on dispatch. The proof does not grant execution authority. - The supported writer model uses in-process transaction signals and startup/resume reconstruction. Independent SQL writers and other replicas need an explicit wake contract. - Native, review, coalesced, and taskless retry variants remain conservative until their owner cases qualify. Reviewer quota and hosted alarm qualification remain open. - The shared catalog remains opt-in. Legacy callers and missing owner bindings retain their old blockers. ## Model Used OpenAI `gpt-6.1-sol` was the configured model for the delegated service implementations and reviews. OpenAI Codex, based on GPT-6, performed managing review and integration. Both used repository tools and code execution. The exact served backend snapshots and context-window limits were not exposed. ## 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 and contains no internal Paperclip ticket id - [x] I have run tests locally and they pass on the final merged head - [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 — exact current-head run passes - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups — complete current-head review and all paginated threads inspected - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
341 lines
18 KiB
TypeScript
341 lines
18 KiB
TypeScript
import { resolveExternalTestDatabaseUrl } from '../__tests__/helpers/external-test-database.js';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { promises as fs } from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
import { eq, sql } from 'drizzle-orm';
|
|
import { companies, companySkills, companySkillSources, createDb, applyPendingMigrations, projects, projectWorkspaces, projectSkillSources } from '@paperclipai/db';
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from '../__tests__/helpers/embedded-postgres.js';
|
|
import { githubFixture } from '../__tests__/helpers/github-skills.js';
|
|
import { skillSourceSyncService } from './skill-source-sync.js';
|
|
import { readIdleSkillSourceSchedule } from './skill-source-idle-schedule.js';
|
|
import { skillSourceService, type SkillSourceContext } from './skill-sources.js';
|
|
import { enqueueProjectSkillSource, detachProjectSkillSource } from './project-skill-source-bindings.js';
|
|
import { createDeliveryWorkCoordinator } from './delivery-work-coordinator.js';
|
|
import { idleWorkSnapshot } from './task-admission.js';
|
|
import { readIdleSleepSafety } from './idle-sleep-safety.js';
|
|
import { companyService } from './companies.js';
|
|
|
|
const externalUrl = resolveExternalTestDatabaseUrl('PAPERCLIP_SKILL_SYNC_TEST_DATABASE_URL');
|
|
const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
|
const setup = { refreshUserId: null, refreshAgentId: null, refreshLocalTrusted: true, connectionId: null, refreshGrantId: null };
|
|
|
|
describe.skipIf(!support.supported)('skill source committed work and deadlines', () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator>;
|
|
let service: ReturnType<typeof skillSourceSyncService>;
|
|
let home: string;
|
|
const oldHome = process.env.PAPERCLIP_HOME;
|
|
let companyId: string;
|
|
let draining: boolean;
|
|
let standby: boolean;
|
|
let calls: string[];
|
|
let errors: unknown[];
|
|
let context: SkillSourceContext;
|
|
let contextFor: ReturnType<typeof vi.fn<() => Promise<SkillSourceContext>>>;
|
|
let reads: ReturnType<typeof vi.fn>;
|
|
let failDeadline: boolean;
|
|
beforeAll(async () => {
|
|
if (externalUrl) await applyPendingMigrations(externalUrl);
|
|
else database = await startEmbeddedPostgresTestDatabase('skill-sync-work-');
|
|
db = createDb(externalUrl ?? database.connectionString, { maxConnections: 4 });
|
|
home = await fs.mkdtemp(path.join(os.tmpdir(), 'skill-sync-work-home-'));
|
|
process.env.PAPERCLIP_HOME = home;
|
|
});
|
|
beforeEach(async () => {
|
|
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'], shouldAdvanceTime: true });
|
|
draining = false; standby = false; calls = []; errors = []; failDeadline = false;
|
|
companyId = randomUUID();
|
|
await db.insert(companies).values({ id: companyId, name: 'Skill sync', issuePrefix: 'SSW' });
|
|
const reader = githubFixture({ 'test/SKILL.md': '---\nname: test\ndescription: Test workflow\n---\nFollow the workflow.\n' });
|
|
reads = vi.fn(reader);
|
|
Object.assign(reads, reader);
|
|
context = { actor: { type: 'system' }, setup: { userId: null, localTrusted: true },
|
|
read: () => reads as unknown as ReturnType<SkillSourceContext['read']>, authorize: async () => {}, audit: async () => {} };
|
|
contextFor = vi.fn(async () => context);
|
|
});
|
|
afterEach(async () => {
|
|
await service?.stop();
|
|
await coordinator?.stop();
|
|
vi.useRealTimers();
|
|
await db.execute(sql`TRUNCATE TABLE companies CASCADE`);
|
|
});
|
|
afterAll(async () => {
|
|
if (oldHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = oldHome;
|
|
await db?.$client.end({ timeout: 1 });
|
|
await database?.cleanup();
|
|
if (home) await fs.rm(home, { recursive: true, force: true });
|
|
});
|
|
async function workspace(ref = 'main', projectId?: string) {
|
|
if (!projectId) {
|
|
const [project] = await db.insert(projects).values({ companyId, name: ref }).returning();
|
|
projectId = project.id;
|
|
}
|
|
const [row] = await db.insert(projectWorkspaces).values({ companyId, projectId, name: ref,
|
|
repoUrl: 'https://github.com/acme/skills', defaultRef: ref }).returning();
|
|
return row;
|
|
}
|
|
async function source(overrides: Partial<typeof companySkillSources.$inferInsert> = {}) {
|
|
const [row] = await db.insert(companySkillSources).values({ companyId, repositoryUrl: 'https://github.com/acme/skills',
|
|
fullName: 'acme/skills', trackingRef: 'main', refreshLocalTrusted: true, ...overrides }).returning();
|
|
return row;
|
|
}
|
|
async function start() {
|
|
const observed = new Proxy(db, { get(target, key) {
|
|
if (!['select', 'update', 'insert', 'delete', 'execute', 'transaction'].includes(String(key))) return Reflect.get(target, key);
|
|
return (...args: unknown[]) => {
|
|
calls.push(String(key));
|
|
if (key === 'execute' && failDeadline) { failDeadline = false; throw new Error('deadline read failed'); }
|
|
return Reflect.apply(Reflect.get(target, key), target, args);
|
|
};
|
|
} });
|
|
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining && !standby,
|
|
canReconcile: () => !standby, onError: error => errors.push(error) });
|
|
service = skillSourceSyncService(observed, { context: contextFor });
|
|
await service.start(coordinator).ready;
|
|
}
|
|
async function settle() {
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(0));
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(0));
|
|
}
|
|
async function quiet(ms = 60_000) {
|
|
const baseline = [...calls];
|
|
await vi.advanceTimersByTimeAsync(ms);
|
|
expect(calls).toEqual(baseline);
|
|
}
|
|
async function imported(id: string) {
|
|
await vi.waitFor(async () => {
|
|
const [row] = await db.select().from(projectSkillSources).where(eq(projectSkillSources.id, id));
|
|
expect(row.sourceId).not.toBeNull();
|
|
});
|
|
await settle();
|
|
}
|
|
async function sleepSafety() {
|
|
const ownerId = randomUUID(), now = Date.now();
|
|
return readIdleSleepSafety(db, () => ({ ownerId, draining: true, activeRuns: 0, pendingWakes: 0,
|
|
startedAt: new Date(now - 1000), expiresAt: new Date(now + 60_000) }), () => now, ownerId, async () => 'none');
|
|
}
|
|
|
|
it('stays SQL-quiet empty and with paused sources and retained bindings', async () => {
|
|
await start(); await quiet();
|
|
expect(service.reconciliationSnapshot().reconciled).toBe(true);
|
|
expect(await readIdleSkillSourceSchedule(db, Date.now(), service.reconciliationSnapshot)).toMatchObject({ blocked: false, deadlines: [] });
|
|
await coordinator.stop(); await service.stop();
|
|
const row = await source({ automaticUpdates: false });
|
|
const ws = await workspace();
|
|
await db.insert(projectSkillSources).values({ companyId, projectId: ws.projectId, workspaceId: ws.id,
|
|
sourceId: row.id, repositoryUrl: row.repositoryUrl, trackingRef: 'main', active: false, status: 'ready' });
|
|
await start(); await quiet(600_000);
|
|
expect(coordinator.nextWakeAt()).toBeNull();
|
|
expect(reads).not.toHaveBeenCalled();
|
|
expect((await sleepSafety()).backgroundWork).toBe('none');
|
|
});
|
|
|
|
it('reconciles a direct tick and invalidates its certificate on coordinator stop', async () => {
|
|
await start(); await settle();
|
|
const before = service.reconciliationSnapshot();
|
|
expect(before.reconciled).toBe(true);
|
|
await service.tick();
|
|
expect(service.reconciliationSnapshot().reconciled).toBe(false);
|
|
await settle();
|
|
expect(service.reconciliationSnapshot().reconciled).toBe(true);
|
|
expect(service.reconciliationSnapshot().revision).not.toBe(before.revision);
|
|
await quiet();
|
|
await coordinator.stop();
|
|
expect(service.reconciliationSnapshot().reconciled).toBe(false);
|
|
});
|
|
|
|
it('imports the first real attachment after quiet only when its outer transaction commits', async () => {
|
|
const ws = await workspace(); await start(); await quiet();
|
|
let release!: () => void, written!: () => void;
|
|
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
const ready = new Promise<void>(resolve => { written = resolve; });
|
|
let bindingId = '';
|
|
const transaction = db.transaction(async tx => {
|
|
bindingId = (await enqueueProjectSkillSource(tx as unknown as typeof db, ws, setup))!.id;
|
|
written(); await gate;
|
|
});
|
|
await ready;
|
|
expect(contextFor).not.toHaveBeenCalled();
|
|
expect(idleWorkSnapshot().active).toBeGreaterThan(0);
|
|
release(); await transaction;
|
|
await imported(bindingId);
|
|
expect(await db.select().from(companySkills)).toHaveLength(1);
|
|
expect(coordinator.nextWakeAt()).toBeGreaterThan(Date.now() + 250_000);
|
|
await quiet();
|
|
expect(service.reconciliationSnapshot().reconciled).toBe(true);
|
|
const deadline = await readIdleSkillSourceSchedule(db, Date.now(), service.reconciliationSnapshot);
|
|
expect(deadline.blocked).toBe(false);
|
|
expect(deadline.deadlines).toHaveLength(1);
|
|
expect((await sleepSafety()).backgroundWork).toBe('present');
|
|
});
|
|
|
|
it('does not import a rolled-back attachment and returns to quiet', async () => {
|
|
const ws = await workspace(); await start();
|
|
await expect(db.transaction(async tx => {
|
|
await enqueueProjectSkillSource(tx as unknown as typeof db, ws, setup);
|
|
throw new Error('rollback');
|
|
})).rejects.toThrow('rollback');
|
|
await settle(); await quiet();
|
|
expect(contextFor).not.toHaveBeenCalled();
|
|
expect(coordinator.nextWakeAt()).toBeNull();
|
|
});
|
|
|
|
it.each(['drain', 'standby'] as const)('retains startup and first attachment during %s', async state => {
|
|
draining = state === 'drain'; standby = state === 'standby';
|
|
const ws = await workspace(); await start();
|
|
const binding = await enqueueProjectSkillSource(db, ws, setup);
|
|
if (state === 'drain') await settle();
|
|
else expect(idleWorkSnapshot().active).toBeGreaterThan(0);
|
|
await quiet(20_000);
|
|
expect(contextFor).not.toHaveBeenCalled();
|
|
expect(service.reconciliationSnapshot().reconciled).toBe(false);
|
|
draining = false; standby = false;
|
|
await vi.advanceTimersByTimeAsync(5_000); await imported(binding!.id);
|
|
expect(service.reconciliationSnapshot().reconciled).toBe(true);
|
|
});
|
|
|
|
it('recovers a failed sweep after drain without losing its request', async () => {
|
|
const ws = await workspace();
|
|
const binding = await enqueueProjectSkillSource(db, ws, setup);
|
|
await db.update(projectSkillSources).set({ nextSyncAt: new Date(Date.now() + 60_000) }).where(eq(projectSkillSources.id, binding!.id));
|
|
failDeadline = true; await start();
|
|
expect(errors).toHaveLength(1);
|
|
draining = true; await vi.advanceTimersByTimeAsync(5_000); await settle(); await quiet(20_000);
|
|
draining = false; await vi.advanceTimersByTimeAsync(5_000); await settle();
|
|
expect(coordinator.nextWakeAt()).not.toBeNull();
|
|
await vi.advanceTimersByTimeAsync(60_000); await imported(binding!.id);
|
|
});
|
|
|
|
it('restores retry and lease deadlines on restart without polling between attempts', async () => {
|
|
const ws = await workspace();
|
|
const binding = await enqueueProjectSkillSource(db, ws, setup);
|
|
const leaseAt = Date.now() + 60_000;
|
|
await db.update(projectSkillSources).set({ leaseToken: randomUUID(), leaseExpiresAt: new Date(leaseAt) }).where(eq(projectSkillSources.id, binding!.id));
|
|
contextFor.mockRejectedValueOnce(new Error('temporary provider failure'));
|
|
await start();
|
|
expect(coordinator.nextWakeAt()).toBe(leaseAt);
|
|
await quiet(50_000); await vi.advanceTimersByTimeAsync(11_000); await settle();
|
|
const [failed] = await db.select().from(projectSkillSources).where(eq(projectSkillSources.id, binding!.id));
|
|
expect(failed.status).toBe('error'); expect(failed.failureCount).toBe(1);
|
|
await service.stop(); await coordinator.stop(); await start();
|
|
expect(coordinator.nextWakeAt()).toBe(failed.nextSyncAt.getTime());
|
|
await quiet(60_000); await vi.advanceTimersByTimeAsync(240_000); await imported(binding!.id);
|
|
});
|
|
|
|
it('preempts a later deadline on settings and cancels refreshes when paused', async () => {
|
|
const row = await source({ nextSyncAt: new Date(Date.now() + 600_000) });
|
|
await start(); await quiet();
|
|
const sources = skillSourceService(db);
|
|
await sources.settings(companyId, row.id, { revision: row.revision, importNewSkills: true }, context);
|
|
await settle();
|
|
expect(contextFor).toHaveBeenCalled();
|
|
const current = await sources.detail(companyId, row.id);
|
|
await sources.settings(companyId, row.id, { revision: current.revision, automaticUpdates: false }, context);
|
|
await settle(); await quiet(600_000);
|
|
expect(coordinator.nextWakeAt()).toBeNull();
|
|
});
|
|
|
|
it('replaces a manual refresh lease with its committed retry deadline', async () => {
|
|
const row = await source({ nextSyncAt: new Date(Date.now() + 3_600_000) });
|
|
await start();
|
|
let rejectRead!: (error: Error) => void, reading!: () => void;
|
|
const ready = new Promise<void>(resolve => { reading = resolve; });
|
|
const response = new Promise<never>((_, reject) => { rejectRead = reject; });
|
|
const refresh = skillSourceService(db).refresh(companyId, row.id, {
|
|
...context, read: () => Object.assign(async () => { reading(); return response; }, { openSnapshot: context.read(null).openSnapshot }),
|
|
});
|
|
const rejected = expect(refresh).rejects.toThrow('provider unavailable');
|
|
await ready; await settle();
|
|
const [leased] = await db.select().from(companySkillSources).where(eq(companySkillSources.id, row.id));
|
|
expect(leased.leaseToken).not.toBeNull();
|
|
rejectRead(new Error('provider unavailable')); await rejected; await settle();
|
|
const [failed] = await db.select().from(companySkillSources).where(eq(companySkillSources.id, row.id));
|
|
expect(failed.leaseToken).toBeNull();
|
|
expect(coordinator.nextWakeAt()).toBe(failed.nextSyncAt.getTime());
|
|
await quiet(60_000);
|
|
await vi.advanceTimersByTimeAsync(240_000); await settle();
|
|
const [refreshed] = await db.select().from(companySkillSources).where(eq(companySkillSources.id, row.id));
|
|
expect(refreshed.failureCount).toBe(0);
|
|
expect(refreshed.lastSuccessAt).not.toBeNull();
|
|
await quiet(60_000);
|
|
});
|
|
|
|
it('aborts provider work on shutdown and leaves the import recoverable', async () => {
|
|
const ws = await workspace(); await start();
|
|
const reader = githubFixture({});
|
|
let reading!: () => void;
|
|
const ready = new Promise<void>(resolve => { reading = resolve; });
|
|
reader.openSnapshot = async (_input, options) => new Promise((_, reject) => {
|
|
options!.signal!.addEventListener('abort', () => reject(options!.signal!.reason), { once: true });
|
|
reading();
|
|
});
|
|
context.read = () => reader;
|
|
const binding = await enqueueProjectSkillSource(db, ws, setup);
|
|
await vi.advanceTimersByTimeAsync(0); await ready;
|
|
await service.stop(); await coordinator.stop();
|
|
const [pending] = await db.select().from(projectSkillSources).where(eq(projectSkillSources.id, binding!.id));
|
|
expect(pending).toMatchObject({ status: 'pending', leaseToken: null, failureCount: 0, sourceId: null });
|
|
await quiet(600_000);
|
|
context.read = () => githubFixture({});
|
|
await start(); await imported(binding!.id);
|
|
});
|
|
|
|
it('admits deferred imports after a full batch frees capacity', async () => {
|
|
context.read = () => githubFixture({});
|
|
const ws = await workspace('ref0');
|
|
const bindings = [];
|
|
for (let i = 0; i < 21; i++) {
|
|
const row = i === 0 ? ws : await workspace(`ref${i}`, ws.projectId);
|
|
bindings.push(await enqueueProjectSkillSource(db, row, setup));
|
|
}
|
|
expect(bindings.at(-1)!.active).toBe(false);
|
|
await start(); await settle();
|
|
await vi.advanceTimersByTimeAsync(15_000); await imported(bindings.at(-1)!.id);
|
|
expect(await db.select().from(projectSkillSources).where(eq(projectSkillSources.status, 'ready'))).toHaveLength(21);
|
|
});
|
|
|
|
it('preserves a new committed attachment during an active sweep', async () => {
|
|
const first = await workspace('first'), second = await workspace('second');
|
|
await enqueueProjectSkillSource(db, first, setup);
|
|
contextFor.mockImplementationOnce(async () => {
|
|
await enqueueProjectSkillSource(db, second, setup);
|
|
return context;
|
|
});
|
|
await start(); await settle();
|
|
await vi.advanceTimersByTimeAsync(5_000); await settle();
|
|
expect(await db.select().from(projectSkillSources).where(eq(projectSkillSources.status, 'ready'))).toHaveLength(2);
|
|
});
|
|
|
|
it('wakes saved work on company reactivation and cancels detached imports', async () => {
|
|
const ws = await workspace();
|
|
const binding = await enqueueProjectSkillSource(db, ws, setup);
|
|
await db.update(companies).set({ status: 'paused' }).where(eq(companies.id, companyId));
|
|
await start(); await quiet();
|
|
expect(coordinator.nextWakeAt()).toBeNull();
|
|
await companyService(db).update(companyId, { status: 'active' });
|
|
await imported(binding!.id);
|
|
const later = await workspace('later');
|
|
draining = true;
|
|
const pending = await enqueueProjectSkillSource(db, later, setup);
|
|
await detachProjectSkillSource(db, companyId, later.id);
|
|
draining = false; await settle();
|
|
const [detached] = await db.select().from(projectSkillSources).where(eq(projectSkillSources.id, pending!.id));
|
|
expect(detached.active).toBe(false); expect(detached.sourceId).toBeNull();
|
|
});
|
|
|
|
it('blocks host sleep for a future import until it is detached', async () => {
|
|
const ws = await workspace();
|
|
const binding = await enqueueProjectSkillSource(db, ws, setup);
|
|
await db.update(projectSkillSources).set({ nextSyncAt: new Date(Date.now() + 600_000) }).where(eq(projectSkillSources.id, binding!.id));
|
|
await start();
|
|
expect((await sleepSafety()).backgroundWork).toBe('present');
|
|
await detachProjectSkillSource(db, companyId, ws.id); await settle();
|
|
expect((await sleepSafety()).backgroundWork).toBe('none');
|
|
});
|
|
});
|