Files
PaperClipAI/server/src/services/workspace-source-lock.ts
T
DottaandClaude Opus 5.5 c97c0dd248 fix(workspaces): give run preparation its own source lock scope (#19734)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A run prepares its task workspace under per-source advisory locks
(`workspace-source-lock.ts`). The locks live in a transaction on a
dedicated connection. An `AsyncLocalStorage` scope lets nested calls
reuse that transaction.
> - Timers and detached promises keep the async context that created
them. A native recovery timer or dispatch can start a run from inside
another operation's source scope.
> - When that run prepares its workspace, it sees the other scope as
"held". If that scope already committed, its dedicated connection is
closed. The lock query then fails with `Failed query: select
pg_try_advisory_xact_lock(...)` and cause `CONNECTION_CLOSED`. If that
scope is still open, the run's lock is tied to the other transaction and
is released early.
> - In a restart chaos wave, a reattached follow-up run failed setup
this way 50 ms after "Recovering the existing native runner process".
The setup-failure log did not show the driver cause.
> - This pull request makes only a live scope count as held, and makes
run workspace preparation take its locks in an independent scope.
> - The benefit is that a recovered or dispatched run gets its own
source lock, and a lost-connection failure is diagnosable from the log.

## Linked Issues or Issue Description

**What happened?**
After a control-plane restart, a native run was reattached
(`reattach_remote_runner`). Its workspace preparation failed at once
with `Failed query: select
pg_try_advisory_xact_lock(hashtextextended($1, 0)) as acquired params:
isolated_repository_source:<company>:<issue>`. The run ended
`failed`/`setup_failed`. The stack showed the "already held scope"
branch of `withWorkspaceSourceLocks`, not a new acquisition. The same
failure occurred earlier in the same wave on a different issue without a
restart.

**Steps to reproduce**
1. Call `withIsolatedRepositorySourceLock` for issue A. In its action,
start a detached promise that later calls
`withIsolatedRepositorySourceLock` for issue B.
2. Let the outer action return so its transaction commits.
3. Let the detached call run. It fails with `Failed query ...
pg_try_advisory_xact_lock`, cause `CONNECTION_CLOSED`.

**Expected behavior**
Work that starts after a source scope ends, or independent work such as
a run's preparation, acquires its own locks on its own connection.

**Environment**
Restart chaos campaign on Daytona (OpenCode, workload C1, fault K1,
comment trigger), embedded Postgres. Reproduced locally on embedded
Postgres by the new tests.

Related: #14910 (deferred comment wake reopens a closed issue). This PR
does not change wake promotion.

## What Changed

- `server/src/services/workspace-source-lock.ts`: a scope has an
`active` flag. The flag is cleared when its transaction ends.
`withWorkspaceSourceLocks`, `retainManagedProjectSource`,
`retainCurrentWorkspaceSource`, and `assertCurrentWorkspaceSourceHeld`
use only a live scope.
- `server/src/services/workspace-source-lock.ts`: new
`withIndependentWorkspaceSourceLocks`. It acquires locks in a new scope
and ignores an inherited one.
- `server/src/services/heartbeat/workspace-preparation.ts`: run
workspace preparation uses `withIndependentWorkspaceSourceLocks`.
- `server/src/services/heartbeat/run-completion.ts`: the "heartbeat
execution setup failed" log records a bounded driver `causeCode` (for
example `CONNECTION_CLOSED` or a SQLSTATE). It does not log the cause
text.
- Tests: two embedded-Postgres tests in
`isolated-remote-workspace-source-lock.test.ts`, one unit test in
`run-completion.test.ts`.

## Verification

- `cd server && npx vitest run
src/services/isolated-remote-workspace-source-lock.test.ts` — 4 passed.
- Red (old scope rule): "gives work detached from a finished scope its
own source lock" failed with `Failed query: select
pg_try_advisory_xact_lock(...)`, cause `CONNECTION_CLOSED`. This is the
production error.
- Red: "keeps an independent preparation's lock after the scope that
started it commits" failed because the lock was released with the other
transaction.
- `cd server && npx vitest run
src/services/heartbeat/run-completion.test.ts` — 95 passed.
- `cd server && npx vitest run
src/services/remote-workspace-online-source.test.ts
src/services/heartbeat/workspace-preparation.test.ts
src/services/isolated-repository-rehome.test.ts
src/services/isolated-task-directory-retention.test.ts
src/services/isolated-task-directory.test.ts
src/__tests__/execution-workspace-reopen.test.ts` — all passed.
- `cd server && npx tsc --noEmit` — clean.
- No live Daytona replay was run.

## Risks

- Low. A nested call inside a live scope behaves as before.
- A call that inherited an ended scope now opens its own dedicated
connection and lock transaction. Before, it failed.
- Run preparation never joins another operation's lock scope. No caller
relies on that today. If one did, it would now take a second,
independent lock and could see `workspace_source_busy` instead of
silently sharing.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edit, embedded Postgres tests).

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 23:08:57 -06:00

136 lines
7.7 KiB
TypeScript

import { AsyncLocalStorage } from "node:async_hooks";
import { withDedicatedDbConnection, type Db } from "@paperclipai/db";
import { sql } from "drizzle-orm";
import path from "node:path";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { canonicalRepositoryRoot } from "./execution-workspace-source-roots.js";
import { readWorkspaceGitSourceRoots } from "./workspace-git-source-roots.js";
import { withWorkspaceLockKeepalive } from "./native-runtime/native-workspace-lock-keepalive.js";
type SourceTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
type SourceLockScope = { db: Db; companyId: string; keys: Set<string>; transaction: SourceTransaction; active: boolean };
const sourceLocks = new AsyncLocalStorage<SourceLockScope>();
export class IsolatedRepositorySourceBusy extends Error {}
// Timers and detached promises keep the async context that created them, so
// work can see a scope whose transaction has committed and whose dedicated
// connection is closed. Only a live scope holds locks.
function heldScope(): SourceLockScope | undefined {
const scope = sourceLocks.getStore();
return scope?.active ? scope : undefined;
}
/** Acquires source locks in a new owner scope and ignores an inherited one.
* Use it at the root of independent work, such as a run's workspace
* preparation, that can start inside another operation's source scope.
* Joining that scope would tie these locks to the other transaction. */
export function withIndependentWorkspaceSourceLocks<T>(db: Db,
input: { companyId: string; issueIds?: readonly string[]; projectIds?: readonly string[] },
action: (transaction: SourceTransaction) => Promise<T>, tryOnly = false): Promise<T> {
return sourceLocks.exit(() => withWorkspaceSourceLocks(db, input, action, tryOnly));
}
export function withIsolatedRepositorySourceLock<T>(db: Db, companyId: string, issueId: string,
action: () => Promise<T>, tryOnly = false): Promise<T> {
return withWorkspaceSourceLocks(db, { companyId, issueIds: [issueId] }, action, tryOnly);
}
export async function withWorkspaceSourceLocks<T>(db: Db,
input: { companyId: string; issueIds?: readonly string[]; projectIds?: readonly string[] },
action: (transaction: SourceTransaction) => Promise<T>, tryOnly = false): Promise<T> {
const keys = [...new Set([
...(input.issueIds ?? []).map(id => `isolated_repository_source:${input.companyId}:${id}`),
...(input.projectIds ?? []).map(id => `managed_project_source:${input.companyId}:${id}`),
])].sort();
if (keys.length > 128) throw new Error("workspace_source_scope_limit");
const held = heldScope();
const acquire = async (scope: SourceLockScope, nonblocking: boolean) => {
for (const key of keys) {
if (scope.keys.has(key)) continue;
const lock = nonblocking ? sql`pg_try_advisory_xact_lock(hashtextextended(${key}, 0))`
: sql`pg_advisory_xact_lock(hashtextextended(${key}, 0))`;
const rows = await scope.transaction.execute(sql`select ${lock} as acquired`);
if (nonblocking && !rows[0]?.acquired) throw new IsolatedRepositorySourceBusy("workspace_source_busy");
scope.keys.add(key);
}
};
if (held?.db === db) {
if (new Set([...held.keys, ...keys]).size > 128) throw new Error("workspace_source_scope_limit");
if (held.companyId !== input.companyId) throw new Error("workspace_source_company_mismatch");
const onlyProjectKeys = keys.filter(key => !held.keys.has(key)).every(key => key.startsWith("managed_project_source:"));
const alreadyHasProject = [...held.keys].some(key => key.startsWith("managed_project_source:"));
await acquire(held, !onlyProjectKeys || alreadyHasProject);
return action(held.transaction);
}
return withDedicatedDbConnection(db, connection => connection.transaction(async transaction => {
const scope: SourceLockScope = { db, companyId: input.companyId, transaction, keys: new Set<string>(), active: true };
try {
await acquire(scope, tryOnly);
const rows = await transaction.execute(sql`select setting::bigint as idle_timeout_ms from pg_settings where name = 'idle_in_transaction_session_timeout'`);
return await withWorkspaceLockKeepalive(transaction, Number(rows[0]?.idle_timeout_ms),
() => sourceLocks.run(scope, () => action(transaction)));
} finally {
scope.active = false;
}
}));
}
export async function managedProjectSourceIdentity(companyId: string, cwd: string): Promise<string | null> {
const root = await canonicalRepositoryRoot(path.join(resolvePaperclipInstanceRoot(), "projects"));
const target = await canonicalRepositoryRoot(cwd);
const relative = path.relative(root, target);
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return null;
const [owner, projectId] = relative.split(path.sep);
if (owner !== companyId) throw new Error("workspace_source_company_mismatch");
return projectId && /^[a-f0-9-]{36}$/.test(projectId) ? projectId : null;
}
export async function isolatedTaskSourceIdentity(companyId: string, cwd: string): Promise<string | null> {
const root = await canonicalRepositoryRoot(resolvePaperclipInstanceRoot());
const relative = path.relative(root, await canonicalRepositoryRoot(cwd)).split(path.sep);
if (!["isolated-workspaces", "isolated-workspace-attempts", "isolated-repository-sources"].includes(relative[0])) return null;
if (relative[0] === "isolated-repository-sources" && relative[3] !== "checkout") return null;
if (relative[1] !== companyId) throw new Error("workspace_source_company_mismatch");
return relative[2] && /^[a-f0-9-]{36}$/.test(relative[2]) ? relative[2] : null;
}
export async function retainManagedProjectSource(db: Db, companyId: string, cwd: string): Promise<void> {
const projectId = await managedProjectSourceIdentity(companyId, cwd);
if (!projectId) return;
if (heldScope()?.db !== db) throw new Error("workspace_source_admission_scope_required");
await withWorkspaceSourceLocks(db, { companyId, projectIds: [projectId] }, async () => undefined, true);
}
export async function workspaceSourceIdentities(companyId: string, cwd: string) {
cwd = await canonicalRepositoryRoot(cwd);
const git = await readWorkspaceGitSourceRoots(cwd, { ancestors: true });
const roots = [cwd, ...(git ? [git.root, git.gitDirectory.path, git.commonDirectory.path,
...git.objectDirectories.map(directory => directory.path)] : [])];
const projectIds = new Set<string>(), issueIds = new Set<string>(), unownedPaths: string[] = [];
for (const target of new Set(roots)) {
const projectId = await managedProjectSourceIdentity(companyId, target);
const issueId = await isolatedTaskSourceIdentity(companyId, target);
if (projectId) projectIds.add(projectId);
if (issueId) issueIds.add(issueId);
if (!projectId && !issueId) unownedPaths.push(target);
}
return { projectIds: [...projectIds].sort(), issueIds: [...issueIds].sort(), unownedPaths, git };
}
export async function retainCurrentWorkspaceSource(cwd: string): Promise<void> {
const scope = heldScope();
if (!scope) return;
const identities = await workspaceSourceIdentities(scope.companyId, cwd);
await withWorkspaceSourceLocks(scope.db, { companyId: scope.companyId, ...identities }, async () => undefined, true);
}
export async function assertCurrentWorkspaceSourceHeld(cwd: string): Promise<void> {
const scope = heldScope();
if (!scope) throw new Error("workspace_source_admission_scope_required");
const identities = await workspaceSourceIdentities(scope.companyId, cwd);
if (identities.projectIds.some(id => !scope.keys.has(`managed_project_source:${scope.companyId}:${id}`))
|| identities.issueIds.some(id => !scope.keys.has(`isolated_repository_source:${scope.companyId}:${id}`))) {
throw new IsolatedRepositorySourceBusy("workspace_source_busy");
}
}