mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-28 20:21:50 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Cloud requests synchronize a human user's profile and company membership. > - Concurrent requests repeated the same writes before the debounce could record success. > - Upserts also updated unchanged rows and caused avoidable tuple work. > - This pull request shares identical pending writes and guards unchanged updates. > - Each request still reads current authority. Bounded profile lookup also reaches older memberships. > - The benefit is less database work during request bursts with the same actor results. ## Linked Issues or Issue Description **What happened?** A burst of 20 trusted Cloud requests issued 20 membership upserts and 40 profile plus membership tuple updates for one unchanged user. The completed-write debounce did not share in-flight work. **Expected behavior** Identical in-flight requests share persistence work. Distinct contexts retain their order. Failures remain retryable. Each request resolves its own current company and role authority. **Steps to reproduce** Run the synthetic PostgreSQL comparison below at baseline `db70c5acd92f50fa37fb4f0dea3da0e7685089a2`. The harness imports the real resolvers and counts actual writes with database triggers. Related work: #17663 covers adjacent Cloud authorization and projection behavior. This change preserves fresh imported memberships, owner-elevation settings and stale administrator removal. ## What Changed - Serialize synchronization per database client and user. Share only the last identical queued context. Preserve A/B/A transitions and retry after partial failure. - Guard user and membership updates with null-safe value comparisons. Retain default-grant repair when `RETURNING` is empty. - Keep authority reads outside the write debounce. - Resolve exact principal IDs through the existing index, then use at most one company-scoped alias query. This prevents both the old 200-row profile cutoff and repeated membership-page scans. Exact IDs take precedence over namesake aliases. - Add concurrency tests, PostgreSQL tests, a reproducible benchmark and behavior documentation. - Accept both Git 2.55 and 2.56 diagnostic messages in an existing workspace safety assertion, after full CI exposed that portability failure. No expiration behavior changes. ## Verification - Five focused suites passed, 63 tests total. These include Cloud actor concurrency, transient database retry, company provisioning, real PostgreSQL synchronization and the user profile route. - The auth-to-profile regression returned 404 before the lookup repair and 200 after it. The final fixture has 601 memberships and tests raw and normalized non-UUID IDs, missing slugs, alias ordering and exact-ID priority. A counterfactual with the old paging repair performs four membership queries for a missing slug; the final code performs two, each returning at most one row. Cross-company access returns 403 before lookup. - Local PostgreSQL 17.11 benchmark uses two warmup pairs and five alternating measured pairs. Each pair starts a fresh debounce scope. All 20 complete actor results match on every sample. - Burst median: 51.07 ms before, 25.71 ms after. Ranges: 47.21–63.25 ms and 24.17–29.32 ms. Membership statements: 20 to one. Tuple updates: 40 to zero. - Reproduce: `pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-cloud-membership-sync.ts --baseline-ref=db70c5acd92f50fa37fb4f0dea3da0e7685089a2 --docker-postgres=17`. - Real PostgreSQL tests compare all four alias fields with the route's own JavaScript canonical slug output across 76 fixtures. Exhaustive Unicode lowercase inspection validates the special SQL mappings. - A real SQL_ASCII database reproduces the previous en-dash alias 404. The final whole-character replacements precede ASCII-only translation. Four alias fields and ten multibyte edge cases pass, including rejection of a false euro-to-k alias. The disposable database is migrated normally, then removed. - Server TypeScript passed with no diagnostics. - PostgreSQL tests used the normal migrations with a temporary Docker startup override because this host's native PostgreSQL semaphore allocation is exhausted. No tracked test infrastructure changed. - The first full CI run had an unrelated CLI company-import/export health-start timeout. Review also identified repeated profile scans; this follow-up repairs that finding. A later run passed 3,882 tests in server shard 4/12 and failed one existing assertion because Git 2.56 changed its error wording for a missing gitfile target. The safety behavior still refused expiration and preserved the workspace. The assertion now accepts both valid messages; the actual Git/PostgreSQL regression passes locally. Final head `3a644e600ab0ae7315f9828b1ea9dffdef407e4a` passed [full CI](https://github.com/paperclipai/paperclip/actions/runs/40537153522), including the previously failing shard. There are 55 successful checks/statuses, two skipped and one neutral. Fresh Greptile and Paperclip reviews are both 5/5 on this exact head, with zero unresolved threads. GitHub reports mergeable and CLEAN. - Full repository typecheck and build passed on the integrated final source. The local full test command was stopped after native PostgreSQL initialization failed repeatedly, producing 16 failures and skipped database suites. It is incomplete, not a pass. Focused real-database suites used disposable Docker PostgreSQL. Current-head CI runs the full gates separately. ## Risks - Coalescing is local to one process and database client. Other replicas can still take conflict locks. - `updated_at` now records actual profile and membership changes. Access lists sorted by it can show a different order. Profile resolution no longer depends on the first 200 entries. Exact principal IDs take precedence over namesake aliases. The single alias fallback still scans company candidates; no constant-CPU claim is made. - Default role grants retain their existing additive semantics. This change does not define a new demotion policy. - Local synthetic service timings exclude HTTP and network latency. No hosted deployment or production speedup is claimed. - No migration, startup job, polling change or deployment is included. ## Model Used OpenAI Codex, configured model `gpt-6.1-sol` with xhigh reasoning, tool use and code execution. Independent blast-radius review also used `gpt-6-astra` and `gpt-6.1-sol`. The runtime context window was 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 (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 - [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>
168 lines
10 KiB
TypeScript
168 lines
10 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { execFileSync } from "node:child_process";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
import {
|
|
agents, applyPendingMigrations, authUsers, companyMemberships, createDb, startEmbeddedPostgresTestDatabase, type Db,
|
|
} from "../packages/db/src/index.js";
|
|
import { cloudActorHeaderSourceFromHeaders, resolveCloudTenantActor } from "../server/src/middleware/auth.js";
|
|
|
|
// All databases, identities and probes are disposable. This never reads DATABASE_URL.
|
|
const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15);
|
|
const dockerPostgres = process.argv.includes("--docker-postgres=17");
|
|
const repoRoot = fileURLToPath(new URL("../", import.meta.url));
|
|
assert.ok(baselineRef, "Pass an explicit --baseline-ref=<pre-fix commit>");
|
|
const baselineRevision = execFileSync("git", ["rev-parse", "--verify", `${baselineRef}^{commit}`], { encoding: "utf8", cwd: repoRoot }).trim();
|
|
const treatmentRevision = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8", cwd: repoRoot }).trim();
|
|
const treatmentDiff = execFileSync("git", ["diff", "--", "server/src/middleware/auth.ts"], { encoding: "utf8", cwd: repoRoot });
|
|
const keepAlive = setInterval(() => {}, 1_000);
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
|
let baselineDir: string | undefined;
|
|
const clients = new Set<Db>();
|
|
|
|
async function startDatabase() {
|
|
if (!dockerPostgres) return startEmbeddedPostgresTestDatabase("cloud-membership-benchmark-");
|
|
const container = `paperclip-cloud-membership-${randomUUID()}`;
|
|
const docker = (...args: string[]) => execFileSync("docker", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
|
docker("run", "--detach", "--rm", "--name", container, "--label", "paperclip.benchmark=cloud-membership",
|
|
"--publish", "127.0.0.1::5432", "--env", "POSTGRES_USER=paperclip", "--env", "POSTGRES_PASSWORD=paperclip",
|
|
"--env", "POSTGRES_DB=paperclip", "postgres:17");
|
|
const cleanup = async () => { docker("rm", "--force", container); };
|
|
try {
|
|
let ready = false;
|
|
for (let attempt = 0; attempt < 100; attempt++) {
|
|
try {
|
|
docker("exec", container, "pg_isready", "-h", "127.0.0.1", "-U", "paperclip");
|
|
ready = true;
|
|
break;
|
|
} catch { await new Promise(resolve => setTimeout(resolve, 100)); }
|
|
}
|
|
assert.ok(ready, "Disposable PostgreSQL did not become ready");
|
|
const port = docker("port", container, "5432/tcp").split(":").at(-1);
|
|
const connectionString = `postgres://paperclip:paperclip@127.0.0.1:${port}/paperclip`;
|
|
await applyPendingMigrations(connectionString);
|
|
return { connectionString, cleanup };
|
|
} catch (error) { await cleanup(); throw error; }
|
|
}
|
|
|
|
try {
|
|
database = await startDatabase();
|
|
function freshDb() {
|
|
const db = createDb(database!.connectionString);
|
|
clients.add(db);
|
|
return db;
|
|
}
|
|
const db = freshDb();
|
|
baselineDir = await fs.mkdtemp(path.join(fileURLToPath(new URL("../server/scripts/", import.meta.url)), ".cloud-auth-baseline-"));
|
|
const original = new URL("../server/src/middleware/auth.ts", import.meta.url);
|
|
const source = execFileSync("git", ["show", `${baselineRevision}:server/src/middleware/auth.ts`], { encoding: "utf8" });
|
|
const rewritten = source.replace(/from "(\.{1,2}\/[^\"]+)"/g,
|
|
(_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, original)))}`);
|
|
const baselineFile = path.join(baselineDir, "auth.ts");
|
|
await fs.writeFile(baselineFile, rewritten);
|
|
const baseline = (await import(pathToFileURL(baselineFile).href)).resolveCloudTenantActor as typeof resolveCloudTenantActor;
|
|
|
|
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "synthetic-membership-benchmark";
|
|
process.env.PAPERCLIP_MANAGED_CONFIG = JSON.stringify({ v: 1, mode: "cloud", catalogVersion: "synthetic", features: { enableOwnerInstanceAdmin: false }, plugins: { autoInstall: [] } });
|
|
const userId = randomUUID();
|
|
const headers = cloudActorHeaderSourceFromHeaders({
|
|
"x-paperclip-cloud-tenant-token": "synthetic-membership-benchmark",
|
|
"x-paperclip-cloud-user-id": userId,
|
|
"x-paperclip-cloud-user-email": `${userId}@example.test`,
|
|
"x-paperclip-cloud-stack-id": `stack-${randomUUID()}`,
|
|
"x-paperclip-cloud-stack-role": "owner",
|
|
});
|
|
const seeded = await baseline(db, headers);
|
|
const companyId = seeded!.companyIds![0]!;
|
|
await db.insert(agents).values({ companyId, name: "Synthetic observer", adapterType: "codex_local" });
|
|
await db.$client.unsafe("CREATE TABLE cloud_sync_probe (relation text, operation text)");
|
|
await db.$client.unsafe(`CREATE FUNCTION cloud_sync_probe() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
BEGIN INSERT INTO cloud_sync_probe VALUES (TG_TABLE_NAME, TG_OP); RETURN NEW; END $$`);
|
|
await db.$client.unsafe('CREATE TRIGGER cloud_sync_probe AFTER INSERT OR UPDATE ON "user" FOR EACH ROW EXECUTE FUNCTION cloud_sync_probe()');
|
|
await db.$client.unsafe("CREATE TRIGGER cloud_sync_probe AFTER INSERT OR UPDATE ON company_memberships FOR EACH ROW EXECUTE FUNCTION cloud_sync_probe()");
|
|
const [version] = await db.$client.unsafe("SELECT version(), current_setting('max_connections') AS max_connections");
|
|
|
|
function observe(client: Db) {
|
|
const statements: Array<{ table: string; sql: string; params: unknown[]; returnedRows: number }> = [];
|
|
const observed = new Proxy(client, { get(target, key) {
|
|
if (key !== "insert") return Reflect.get(target, key);
|
|
return (...args: Parameters<Db["insert"]>) => {
|
|
const builder = target.insert(...args);
|
|
const values = builder.values.bind(builder);
|
|
builder.values = ((...input: Parameters<typeof values>) => {
|
|
const query = values(...input);
|
|
const execute = query.execute.bind(query);
|
|
query.execute = (async () => {
|
|
const result = await execute();
|
|
if (args[0] === authUsers || args[0] === companyMemberships) {
|
|
statements.push({ table: args[0] === authUsers ? "user" : "company_memberships", ...query.toSQL(), returnedRows: result.length });
|
|
}
|
|
return result;
|
|
}) as typeof query.execute;
|
|
return query;
|
|
}) as typeof builder.values;
|
|
return builder;
|
|
};
|
|
}});
|
|
return { db: observed, statements };
|
|
}
|
|
|
|
const burstSize = 20;
|
|
async function sample(resolve: typeof resolveCloudTenantActor) {
|
|
const client = freshDb();
|
|
const observed = observe(client); // same fixture; a fresh debounce scope
|
|
try {
|
|
await db.$client.unsafe("TRUNCATE cloud_sync_probe");
|
|
const start = performance.now();
|
|
const actors = await Promise.all(Array.from({ length: burstSize }, () => resolve(observed.db, headers)));
|
|
const durationMs = performance.now() - start;
|
|
for (const actor of actors) assert.deepEqual(actor, seeded);
|
|
const writes = await db.$client.unsafe("SELECT relation, operation, count(*)::int AS writes FROM cloud_sync_probe GROUP BY relation, operation ORDER BY relation, operation");
|
|
return { durationMs, statements: observed.statements, writes: [...writes], equalActors: actors.length };
|
|
} finally {
|
|
await client.$client.end({ timeout: 0 });
|
|
clients.delete(client);
|
|
}
|
|
}
|
|
const results: { before: Awaited<ReturnType<typeof sample>>[]; after: Awaited<ReturnType<typeof sample>>[] } = { before: [], after: [] };
|
|
// Alternate order; first two pairs are warmups, then five measured pairs.
|
|
for (let index = 0; index < 7; index += 1) {
|
|
const order = index % 2 === 0 ? ["before", "after"] as const : ["after", "before"] as const;
|
|
for (const variant of order) {
|
|
const result = await sample(variant === "before" ? baseline : resolveCloudTenantActor);
|
|
if (index >= 2) results[variant].push(result);
|
|
}
|
|
}
|
|
for (const before of results.before) {
|
|
assert.equal(before.statements.filter(statement => statement.table === "company_memberships").length, burstSize);
|
|
assert.deepEqual(before.writes, [{ relation: "company_memberships", operation: "UPDATE", writes: burstSize }, { relation: "user", operation: "UPDATE", writes: burstSize }]);
|
|
}
|
|
for (const after of results.after) {
|
|
assert.equal(after.statements.filter(statement => statement.table === "company_memberships").length, 1);
|
|
assert.deepEqual(after.writes, []);
|
|
assert.equal(after.statements.find(statement => statement.table === "company_memberships")!.returnedRows, 0);
|
|
}
|
|
function summarize(samples: typeof results.before) {
|
|
const timings = samples.map(sample => sample.durationMs).sort((left, right) => left - right);
|
|
return { medianMs: timings[2], rangeMs: [timings[0], timings.at(-1)], samplesMs: samples.map(sample => sample.durationMs),
|
|
membershipStatementsPerBurst: samples[0].statements.filter(statement => statement.table === "company_memberships").length,
|
|
tupleWritesPerBurst: samples[0].writes, equalActorsPerBurst: burstSize, statements: samples[0].statements };
|
|
}
|
|
const before = summarize(results.before), after = summarize(results.after);
|
|
const treatmentSources = await Promise.all(["server/src/middleware/auth.ts", "server/src/middleware/cloud-tenant-sync.ts"].map(async file => ({
|
|
file, sha256: createHash("sha256").update(await fs.readFile(new URL(`../${file}`, import.meta.url))).digest("hex"),
|
|
})));
|
|
console.log(JSON.stringify({ baselineRevision, treatmentRevision, treatmentHasUncommittedChanges: treatmentDiff.length > 0,
|
|
treatmentSources, version, fixture: { users: 1, memberships: 1, agents: 1, burstSize, warmupPairs: 2, measuredPairs: 5 },
|
|
scope: "Local real-service burst including SQL and authority reads; excludes HTTP/network. No production latency claim.",
|
|
before, after, speedup: before.medianMs / after.medianMs }, null, 2));
|
|
} finally {
|
|
try {
|
|
await Promise.all([...clients].map(db => db.$client.end({ timeout: 0 })));
|
|
await database?.cleanup();
|
|
if (baselineDir) await fs.rm(baselineDir, { recursive: true, force: true });
|
|
} finally { clearInterval(keepAlive); }
|
|
}
|