fix(workspaces): let one online source scope hold as many locks as its alias bound admits (#22724)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted server moves each local workspace to shared storage in
bounded online passes while it serves work
> - A Git workspace moves online only while one transaction holds the
source lock of every task and project that can write its repository
> - On staging, one stack keeps 46 workspaces blocked with
`workspaces:source_scope_source_keys_exceeded`
> - The proof refuses a scope above 128 lock keys, but the same proof
admits up to 256 alias records, and each record adds a task key
> - The fence must hold every key at the same time, so it cannot page
across passes: a writer that took a released key could change the
repository during the capture
> - This pull request raises the key bound to 512 in one shared
constant, and makes the capture's Git source root bound follow it
> - The benefit is that a repository shared by many tasks moves online
with the same fence as a small one

## Linked Issues or Issue Description

Refs #22644

**What happened?**
After repeated online passes on staging (Core 4434d12e), one stack
reports `source_scope_source_keys_exceeded` x46.

**Expected behavior**
A source scope that the alias bound admits (256 records) can take all of
its source locks. The offline move has no lock bound, because all
writers are stopped.

**Steps to reproduce**
1. Create a managed Git checkout with 133 task records that point at it.
2. Run `inventoryRemoteWorkspaceMigration` online. It reports
`source_keys_exceeded`.

**Is 128 a safety bound or a budget?**
- It cannot be a budget that pages across passes. The keys fence writers
only while one transaction holds all of them. Each pass releases its
locks.
- It bounds the advisory locks that one transaction takes. Each key is
one entry in the PostgreSQL shared lock table. That table holds
`max_locks_per_transaction` (default 64) times `max_connections`
entries, which is 6,400 with the defaults. 512 keys are 8% of that, and
one server runs one workspace migration at a time.
- The capture's Git source root bound (384) was three roots per key at
the old bound, and it would refuse the larger scope. It is now three
roots per key at the new bound.

## What Changed

- New `workspace-source-key-limit.ts` exports
`WORKSPACE_SOURCE_KEY_LIMIT = 512`.
- `withWorkspaceSourceLocks` (new scope and joined scope) and the online
proof (`source_keys_exceeded`) use the constant.
- The capture's Git source root bound is 1536 (three roots per key). The
capture code runs in a worker from its own source text and cannot import
the constant. A test ties the two values together.

## Verification

- Red on `origin/master` (b908678ea3):
  - 512 keys in one scope throw `workspace_source_scope_limit`.
  - A 133-record Git closure reports `source_keys_exceeded`.
- A capture with 1536 owned Git source roots fails with
`online_source_git_requires_shared_fence`.
- Green with the fix:
- 512 keys are held at once (`pg_locks` shows 512 advisory locks), and
513 are refused before a connection is reserved.
- The 133-record closure is eligible, its scope has 133 task keys, the
migration publishes, and the files stay in place.
  - The capture accepts 1536 roots and refuses 1537.
- `cd server && npx vitest run
src/services/remote-workspace-migration.test.ts
src/services/remote-workspace-online-source.test.ts
src/services/remote-workspace-cohort-migration.test.ts
src/services/remote-workspace-migration-concurrency.test.ts
src/services/remote-workspace-snapshot-archive.test.ts
src/services/isolated-remote-workspace-source-lock.test.ts` (embedded
PostgreSQL): 6 files, 493 tests passed.
- `cd server && pnpm typecheck`: passed.

## Risks

- Low to medium. A large scope holds up to 512 advisory locks in one
transaction. This is within the default lock table with a wide margin,
and only one workspace migration runs at a time per server.
- Lock acquisition takes one round trip per key, so a 512-key scope adds
roughly half a second at 1 ms per round trip.
- Scopes above 256 alias records are still refused (`members_exceeded`).

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.

## 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>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-23 19:39:56 -06:00
1 parent 6a642a9316
commit f0bbd4ada9
6 files changed
+34 -5

No files matched your search

@@ -6,6 +6,7 @@ import { executionWorkspaces, heartbeatRuns, issueRecoveryActions, type Db } fro
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { explainOnlineOrdinarySource, inspectImportedWorkspaceSourcePaths, physicalPath, requiresOnlineOrdinarySource, type WorkspaceSourceScope } from "./remote-workspace-migration-tree.js";
import { workspaceSourceIdentities } from "./workspace-source-lock.js";
import { WORKSPACE_SOURCE_KEY_LIMIT } from "./workspace-source-key-limit.js";
import { readNestedWorkspaceGitSourceRoots, readWorkspaceGitLinkedRoots, readWorkspaceGitSourceRoots, type WorkspaceGitSourceRoots } from "./workspace-git-source-roots.js";
import { inspectOnlineLegacyWorkspaceRecoveryHold, inspectOnlineLegacyWorkspaceRecoverySource, type OnlineLegacyWorkspaceRecoveryHold } from "./online-legacy-workspace-recovery.js";
import type { LegacyWorkspaceRecoverySource } from "./legacy-workspace-recovery-migration.js";
@@ -199,7 +200,7 @@ export async function explainOnlineWorkspaceSource(db: ReadDb, workspace: Worksp
if ([...linkedSources.values()].some(proof => proof.links.some(link => !registeredRoots.some(root =>
link.root.path === root || link.root.path.startsWith(root + path.sep))))) return unproven("git_link_unregistered");
const issueIds = [...new Set([...physicalIssueIds, ...included.map(node => node.row.sourceIssueId!)])].sort();
if (issueIds.length + projectIds.size > 128) return unproven("source_keys_exceeded");
if (issueIds.length + projectIds.size > WORKSPACE_SOURCE_KEY_LIMIT) return unproven("source_keys_exceeded");
const instance = await physicalPath(resolvePaperclipInstanceRoot());
const gitSourceRoots = [...[...projectIds].map(id => path.join(instance, "projects", workspace.companyId, id)),
...issueIds.flatMap(id => ["isolated-workspaces", "isolated-workspace-attempts", "isolated-repository-sources"].map(kind =>
@@ -420,9 +420,25 @@ describe.skipIf(!support.supported)("online ordinary physical source fence", ()
} finally { release(); await owner; }
});
it("bounds source-lock closures before reserving a connection", async () => {
await expect(withWorkspaceSourceLocks(db, { companyId: randomUUID(), issueIds: Array.from({ length: 129 }, () => randomUUID()) },
await expect(withWorkspaceSourceLocks(db, { companyId: randomUUID(), issueIds: Array.from({ length: 513 }, () => randomUUID()) },
async () => { throw new Error("scope must not be admitted"); })).rejects.toThrow("workspace_source_scope_limit");
await expect(withWorkspaceSourceLocks(db, { companyId: randomUUID(), issueIds: Array.from({ length: 511 }, () => randomUUID()),
projectIds: [randomUUID()] }, async lock => (await lock.execute(sql`select count(*)::int as held from pg_locks
where locktype='advisory' and pid=pg_backend_pid()`))[0]?.held)).resolves.toBe(512);
});
it("moves a Git folder online when its alias closure needs more than 128 source locks", async () => {
const f = await fixture(), repoUrl = "https://example.invalid/wide-closure.git";
await git(f.cwd, "init", "-q", "-b", "main"); await git(f.cwd, "add", "."); await git(f.cwd, "commit", "-qm", "Saved legacy work");
const extra = Array.from({ length: 130 }, () => randomUUID());
await db.insert(issues).values(extra.map((id, n) => ({ id, companyId: f.companyId, projectId: f.projectId, title: `Wide alias ${n}` })));
await db.insert(executionWorkspaces).values(extra.map((id, n) => ({ companyId: f.companyId, projectId: f.projectId, sourceIssueId: id,
name: `Wide alias ${n}`, mode: "shared_workspace" as const, strategyType: "project_primary", providerType: "local_fs", cwd: f.cwd, providerRef: f.cwd })));
await db.update(executionWorkspaces).set({ repoUrl, branchName: "main" }).where(eq(executionWorkspaces.companyId, f.companyId));
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: true, reasons: [] });
expect((await inspectOnlineWorkspaceSource(db, await stored(f.workspaceId)))?.issueIds).toHaveLength(133);
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).resolves.toMatchObject({ applied: true });
expect(await fs.readFile(path.join(f.cwd, "saved.txt"), "utf8")).toBe("saved legacy edits\n");
}, 120_000);
it.each(["task", "operation", "foreign", "descendant"] as const)("retains the %s guard across the complete alias closure", async kind => {
const f = await fixture(), alias = f.aliases[2];
if (kind === "task") {
@@ -7,6 +7,7 @@ import path from "node:path";
import { promisify } from "node:util";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { workspaceArchive, readRemoteWorkspaceArchiveDirectories, remoteWorkspaceArchiveScript, remoteWorkspaceCaptureFailureMessage } from "./remote-workspace-snapshot-archive.js";
import { WORKSPACE_SOURCE_KEY_LIMIT } from "./workspace-source-key-limit.js";
const archiveIo = vi.hoisted(() => ({
afterChmod: undefined as ((target: string, mode: number) => void) | undefined,
@@ -118,6 +119,15 @@ describe("portable remote workspace archives", () => {
expect(await fs.readFile(path.join(restored, "new.txt"), "utf8")).toBe("untracked\n");
await git(restored, "fsck", "--connectivity-only", "--no-dangling");
});
it("accepts the Git source roots of a source-lock scope at its key bound and refuses more", async () => {
const cwd = await source(); await git(cwd, "init", "-q", "-b", "main");
await fs.writeFile(path.join(cwd, "work.txt"), "saved\n"); await git(cwd, "add", "."); await git(cwd, "commit", "-qm", "base");
const owned = await fs.realpath(root), others = (count: number) => Array.from({ length: count }, (_, n) => path.join(owned, "unrelated", String(n)));
await expect(captureRemoteWorkspaceDirectory({ cwd, archivePath: path.join(root, "bounded.pcws"), singlePass: true,
gitSourceRoots: [owned, ...others(WORKSPACE_SOURCE_KEY_LIMIT * 3 - 1)] })).resolves.toMatchObject({ manifestDigest: expect.any(String) });
await expect(captureRemoteWorkspaceDirectory({ cwd, archivePath: path.join(root, "unbounded.pcws"), singlePass: true,
gitSourceRoots: [owned, ...others(WORKSPACE_SOURCE_KEY_LIMIT * 3)] })).rejects.toThrow("online_source_git_requires_shared_fence");
});
it.each([".", "nested"])("requires a shared Git fence before reading included %s Git storage", async location => {
const cwd = await source(), repository = path.join(cwd, location);
await fs.mkdir(repository, { recursive: true });
@@ -309,7 +309,7 @@ export async function workspaceArchive(input: {
};
const assertGitSourceFence = async (repo: string) => {
if (!input.gitSourceRoots) return null;
if (!input.gitSourceRoots.length || input.gitSourceRoots.length > 384
if (!input.gitSourceRoots.length || input.gitSourceRoots.length > 1536
|| input.gitSourceRoots.some(root => !path.isAbsolute(root) || path.resolve(root) !== root)) fail("online_source_git_requires_shared_fence");
const directory = async (target: string) => {
const actual = await fs.realpath(target), entry = await fs.lstat(target, { bigint: true });
@@ -0,0 +1 @@
export const WORKSPACE_SOURCE_KEY_LIMIT = 512;
+3 -2
View File
@@ -6,6 +6,7 @@ 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";
import { WORKSPACE_SOURCE_KEY_LIMIT } from "./workspace-source-key-limit.js";
type SourceTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
type SourceLockScope = { db: Db; companyId: string; keys: Set<string>; transaction: SourceTransaction; active: boolean };
@@ -85,7 +86,7 @@ export async function withWorkspaceSourceLocks<T>(db: Db,
...(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");
if (keys.length > WORKSPACE_SOURCE_KEY_LIMIT) throw new Error("workspace_source_scope_limit");
const held = heldScope();
if (wait && held?.db === db) throw new Error("workspace_source_wait_requires_independent_scope");
const acquire = async (scope: SourceLockScope, nonblocking: boolean) => {
@@ -99,7 +100,7 @@ export async function withWorkspaceSourceLocks<T>(db: Db,
}
};
if (held?.db === db) {
if (new Set([...held.keys, ...keys]).size > 128) throw new Error("workspace_source_scope_limit");
if (new Set([...held.keys, ...keys]).size > WORKSPACE_SOURCE_KEY_LIMIT) 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:"));