Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ This project uses calendar-style release versions, currently `YYYY.M.D.N`.

- Nothing yet.

### Fixed

- Wait for the existing bounded workspace admission fence before initializing a pristine original document. Ordinary concurrent tree reads no longer turn a first text-document open into a fail-fast lifecycle conflict; current rights and all mutation/receipt safeguards remain enforced.

## [2026.11.8.1] - 2026-11-08

### Added
Expand Down
2 changes: 1 addition & 1 deletion app/lib/collaboration/markdown-file-import-persistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1055,7 +1055,7 @@ async function withOriginalBootstrapTransaction<Frame extends OriginalBootstrapF
owner = connection; ownerIdentity = identity; return connection;
} catch (error) { await connection.close(new Error('Discarding mismatched original bootstrap owner.', { cause: error })); throw error; }
};
return withWorkspaceFileLifecycleGuard({ workspaceId: selection.workspaceId, paths: [selection.path] }, async () => {
return withWorkspaceFileLifecycleGuard({ workspaceId: selection.workspaceId, paths: [selection.path], admissionLock: 'wait' }, async () => {
if (!owner || !ownerIdentity) return fail('MARKDOWN_IMPORT_INVALID_INPUT');
const frame = options.createFrame({ selection, realm, owner, identity: ownerIdentity });
const openMutation = async () => {
Expand Down
72 changes: 72 additions & 0 deletions docs/testing/original-bootstrap-read-fence-2026-11-08.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{
"version": 1,
"scope": "Original-file bootstrap waits at the existing bounded lifecycle admission boundary; no document mutation replay.",
"baseline": {
"sourceCommit": "ce0a7feadc66daca04e5ec83e760a03bee12924c",
"imageDigest": "sha256:d5e545d3f0bf462115e8a6029c4b59a9b3e3d28e09b4ae4fa706bf9ad202649b",
"actualHttpSessionStatus": 409,
"code": "COLLABORATION_FILE_LIFECYCLE_BUSY",
"elapsedMs": 456,
"requests": 1,
"actualSharedPgAdmissionFence": true,
"physicalBytesAndTargetRowsXminUnchanged": true,
"newRegressionFailsBeforeFix": true
},
"implementation": {
"symbol": "withOriginalBootstrapTransaction",
"admissionLock": "wait",
"existingLockTimeout": "4s",
"existingStatementTimeout": "5s",
"mutationRetriesAdded": 0,
"clientRetryHintsAdded": false,
"authorityStillValidatedAfterAdmission": true
},
"validation": {
"originalBootstrap": {
"command": "npm run test:collaboration:pristine-original-bootstrap:postgres",
"exitCode": 0,
"realPostgres18Families": 31,
"newCases": [
"shared reader holds actual owner before any native mutation; release permits one state and one receipt",
"current rights revoked during wait reject without native writes"
],
"strengthenedCase": "an exclusive holder expires with the existing lifecycle Busy code and finite timeout; original bytes and native absence remain unchanged"
},
"apiKeyOriginals": {
"command": "npm run test:api-keys:original-imports:native",
"exitCode": 0,
"principalGroups": 8,
"ownerGroups": 13,
"httpGroups": 8,
"mcpGroups": 11,
"actualTcpRequests": 27,
"jsonRpcRequests": 41,
"includesLostCommitAcknowledgementAndCurrentRevocation": true
},
"managedContainerIdentitiesPreserved": true,
"ciConfiguration": {
"command": "npm run test:api-keys:ci-config",
"exitCode": 0,
"checks": 19,
"privateEnvironmentFallbackInCi": false,
"bootstrapSuiteNowIncludedIn": "npm run test:api-keys:native",
"databaseSelection": "existing shared native-test database config and actual PostgreSQL target/owner validation",
"actualCiRun": "pending"
}
},
"sourceSha256": {
"app/lib/collaboration/markdown-file-import-persistence.ts": "19f2cea10ec87655425c016a317b8ac23620ad389dff53ef4a5213d5e64ca94d",
"scripts/workspace-pristine-original-bootstrap-postgres-test.ts": "65f8f8c770dd0d2ea19852fdb46b371408c23be4601cdc115b598aba2c133fcb"
},
"pending": [
"updated-source production build",
"PR review and CI",
"new exact-tag release-image browser acceptance",
"Control Plane registration and production promotion"
],
"excluded": [
"Review Center",
"file-operation Undo",
"bold plus inline-code schema/client compatibility change"
]
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@
"test:api-keys:sdk:copies:native": "NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-python-sdk-copy-postgres-test.ts",
"test:api-keys:sdk:paths:native": "NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-python-sdk-path-postgres-test.ts",
"test:api-keys:workspaces:native": "NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-workspace-list-principal-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-workspace-browse-principal-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-workspace-list-adapters-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-workspace-browse-adapters-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/mcp-manifest-postgres-test.ts",
"test:api-keys:native": "NODE_ENV=test CANVAS_SHARED_CONNECTION_POSTGRES_TEST=1 tsx --conditions react-server scripts/api-key-management-test.ts --native && NODE_ENV=test CANVAS_SHARED_CONNECTION_POSTGRES_TEST=1 tsx --conditions react-server scripts/api-key-authentication-test.ts --native && npm run test:api-keys:documents:native && npm run test:api-keys:workspaces:native && npm run test:api-keys:edits:native && npm run test:api-keys:creates:native && npm run test:api-keys:copies:native && npm run test:api-keys:paths:native && npm run test:api-keys:original-imports:native && npm run test:api-keys:migration:native",
"test:api-keys:native": "NODE_ENV=test CANVAS_SHARED_CONNECTION_POSTGRES_TEST=1 tsx --conditions react-server scripts/api-key-management-test.ts --native && NODE_ENV=test CANVAS_SHARED_CONNECTION_POSTGRES_TEST=1 tsx --conditions react-server scripts/api-key-authentication-test.ts --native && npm run test:api-keys:documents:native && npm run test:api-keys:workspaces:native && npm run test:api-keys:edits:native && npm run test:api-keys:creates:native && npm run test:api-keys:copies:native && npm run test:api-keys:paths:native && npm run test:collaboration:pristine-original-bootstrap:postgres && npm run test:api-keys:original-imports:native && npm run test:api-keys:migration:native",
"test:api-keys:migration:native": "NODE_ENV=test CANVAS_SHARED_CONNECTION_POSTGRES_TEST=1 CANVAS_POSTGRES_VECTOR_ENABLED=false tsx --conditions react-server scripts/api-key-portable-database-postgres-test.ts",
"test:api-keys:original-imports:native": "NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-original-markdown-import-principal-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-original-markdown-import-owner-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-original-markdown-import-http-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-original-markdown-import-mcp-postgres-test.ts",
"test:api-keys:copies:native": "NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-workspace-copy-principal-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-workspace-copy-origin-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-native-copy-owner-postgres-test.ts && NODE_ENV=test CANVAS_POSTGRES_VECTOR_ENABLED=false node scripts/run-document-read-tool-dispatch-test.mjs scripts/api-key-native-copy-adapters-postgres-test.ts",
Expand Down
87 changes: 76 additions & 11 deletions scripts/workspace-pristine-original-bootstrap-postgres-test.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { mkdir, mkdtemp, readFile, rename, rm, stat, symlink, link, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, readFile, rename, rm, symlink, link, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { parse } from 'dotenv';
import { Client,types } from 'pg';
import { NextRequest } from 'next/server';
import { serializeSignedCookie } from 'better-call';
import type { SqlConnection } from '../app/lib/db';
import type { PristineOriginalWorkspaceFileRequest, MarkdownFileImportResult } from '../app/lib/collaboration/markdown-file-import-persistence';
import { readNativeTestDatabaseConfig, assertNativeTestDatabaseTarget } from './helpers/native-test-database-config';

const privateEnvironment = '/Users/frankalexanderweber/.local/state/canvas-local-team-seat/notebook-host-dev.env';
let stage = 'private configuration';
let stage = 'owned native database configuration';
async function main(): Promise<void> {
assert.equal(process.env.NODE_ENV, 'test');
assert.notEqual(process.env.CANVAS_LEGACY_EPOCH_TIMESTAMP_UNIT?.trim().toLowerCase(), 'seconds');
assert.notEqual(process.env.CANVAS_POSTGRES_VECTOR_ENABLED, 'true');
assert.equal((await stat(privateEnvironment)).mode & 0o077, 0);
const connectionString = parse(await readFile(privateEnvironment, 'utf8')).DATABASE_URL; assert(connectionString);
const url = new URL(connectionString);
assert(['postgres:', 'postgresql:'].includes(url.protocol)); assert(['localhost','127.0.0.1'].includes(url.hostname));
assert.equal(url.port,'55433'); assert.equal(url.pathname,'/canvas_notebook'); assert.equal(url.search,'');
const databaseConfig = await readNativeTestDatabaseConfig(), { connectionString } = databaseConfig;
const schema = `original_bootstrap_${crypto.randomUUID().replaceAll('-','')}`;
assert.match(schema,/^original_bootstrap_[a-f0-9]{32}$/u);
const dataRoot = await mkdtemp(path.join(tmpdir(),'canvas-original-bootstrap-'));
Expand All @@ -38,7 +33,7 @@ async function main(): Promise<void> {
let cases = 0;
try {
await control.connect();
assert.equal(Math.floor(Number((await control.query("SELECT current_setting('server_version_num') AS version")).rows[0].version)/10000),18);
await assertNativeTestDatabaseTarget(control,databaseConfig);
await control.query(`CREATE SCHEMA "${schema}"`); created = true;
// Set node-postgres PGOPTIONS BEFORE importing any runtime DB/Auth module.
// No public fallback, no public-qualified epoch conversion/extension path.
Expand Down Expand Up @@ -207,6 +202,18 @@ async function main(): Promise<void> {
};
const code=(...codes:string[])=>(error:unknown)=>!!error&&typeof error==='object'&&codes.includes(String(Reflect.get(error,'code')));
const check=async(name:string,operation:()=>Promise<void>)=>{stage=name;await operation();cases++;console.log(`Original bootstrap fixture passed: ${name}`);};
const waitForAdmissionOwner=async(owned:ReturnType<typeof factory>,settled:()=>boolean)=>{
let waiting=false;
const deadline=Date.now()+2000;
while(!settled()&&!waiting&&Date.now()<deadline) {
const backend=owned.events.find(event=>event.step==='open')?.backend;
if(backend) waiting=(await admin.query(`SELECT EXISTS(SELECT 1 FROM pg_locks
WHERE pid=$1 AND locktype='advisory' AND mode='ExclusiveLock' AND NOT granted) AS waiting`,[backend])).rows[0].waiting;
if(!waiting&&!settled()) await new Promise(resolve=>setTimeout(resolve,20));
}
assert.equal(settled(),false,'An ordinary read fence must not cause a fail-fast bootstrap denial.');
assert.equal(waiting,true,'The genuine owner must wait on the actual PostgreSQL admission lock.');
};
const pristine=async(filePath:string,marker='never_initialized',provider='yjs',version=0,lineage:string|null=null)=>{
const id=`collab-${crypto.randomUUID()}`;await admin.query(`INSERT INTO collaboration_documents(id,lineage_id,organization_id,workspace_id,workspace_type,path,provider,status,state_version,created_at,updated_at,yjs_state_lifecycle)
VALUES($1,$2,'principal-org',$3,'organization',$4,$5,'active',$6,1,1,$7)`,[id,lineage,workspaceId,filePath,provider,version,marker]);return selection(filePath,{kind:'pristine',documentId:id});
Expand Down Expand Up @@ -304,12 +311,70 @@ async function main(): Promise<void> {
const release=installCollaborationRoomInspector(doc=>doc===id?1:0);try{await assert.rejects(invoke(input),code('MARKDOWN_IMPORT_BUSY'));}finally{release();}
const holder=await ownClient();try{await holder.query('SELECT pg_advisory_lock($1::bigint)',[lockIdentity(id).key]);await assert.rejects(invoke(input),code('MARKDOWN_IMPORT_BUSY'));}finally{await holder.end();clients.delete(holder);}
});
await check('a genuine shared admission reader completes before original bootstrap starts mutation',async()=>{
const input=selection('shared-read-fence.txt'),bytes=Buffer.from('Original bytes behind a read fence\n');
await original(input.path,bytes);
const holder=await ownClient(),owned=factory();
let settled=false;
let pending:Promise<{value?:MarkdownFileImportResult;error?:unknown}>|undefined;
try {
await holder.query('BEGIN READ ONLY');
await holder.query('SELECT pg_advisory_xact_lock_shared($1::bigint)',[collaborationAdmissionLockKey(workspaceId)]);
pending=bootstrap(await request(),input,owned).then(value=>({value}),error=>({error})).finally(()=>{settled=true;});
await waitForAdmissionOwner(owned,()=>settled);
assert(!owned.events.some(event=>['lineage','registry','state','receipt'].includes(event.step)));
await empty(input);
assert((await readFile(path.join(root,input.path))).equals(bytes));
} finally {
await holder.query('ROLLBACK');
await holder.end();clients.delete(holder);
}
const completed=await pending!;
assert.equal(completed.error,undefined);
assert(completed.value);
await roundtrip(completed.value,bytes);
assert.equal(owned.events.filter(event=>event.step==='state').length,1);
assert.equal(owned.events.filter(event=>event.step==='receipt').length,1);
});
await check('rights revoked while admission waits reject before any original document mutation',async()=>{
const input=selection('revoked-read-fence.txt'),bytes=Buffer.from('Preserve the revoked original\n');
await original(input.path,bytes);
const holder=await ownClient(),owned=factory();
let settled=false;
let pending:Promise<{value?:MarkdownFileImportResult;error?:unknown}>|undefined;
try {
await holder.query('BEGIN READ ONLY');
await holder.query('SELECT pg_advisory_xact_lock_shared($1::bigint)',[collaborationAdmissionLockKey(workspaceId)]);
pending=bootstrap(await request(),input,owned).then(value=>({value}),error=>({error})).finally(()=>{settled=true;});
await waitForAdmissionOwner(owned,()=>settled);
await admin.query('UPDATE "user" SET banned=1,ban_expires=1 WHERE id=\'member\'');
await holder.query('ROLLBACK');
const completed=await pending;
assert.equal(completed.value,undefined);
assert(code('SEAT_ACCESS_INACTIVE','PRINCIPAL_ACCESS_DENIED','PRINCIPAL_AUTH_REVOKED')(completed.error));
assert(!owned.events.some(event=>['lineage','registry','state','receipt'].includes(event.step)));
await empty(input);
assert((await readFile(path.join(root,input.path))).equals(bytes));
} finally {
await holder.query('ROLLBACK');
await holder.end();clients.delete(holder);
if(pending) await pending;
await admin.query('UPDATE "user" SET banned=0,ban_expires=NULL WHERE id=\'member\'');
}
});
await check('persisted path reservation and actual exclusive owner are busy',async()=>{
const file='reserved.md';await original(file,'Original\n');const input=selection(file),owned=factory();const admission=createCollaborationAdmissionService(owned);
const actionPayloadText=JSON.stringify({originalBootstrapFixture:true});const reservation={requestId:crypto.randomUUID(),actorId:'member',action:'rename' as const,actionPayloadText,
actionDigest:collaborationAdmissionActionDigest('rename',actionPayloadText),scopes:[{workspaceId,organizationId:'principal-org',path:file,kind:'exact' as const}],expectedDocuments:[]};
const reserved=await admission.reserve(reservation);try{await assert.rejects(invoke(input));}finally{await admission.cancel(reservation,reserved.revision);}
const holder=await ownClient();try{await holder.query('SELECT pg_advisory_lock($1::bigint)',[collaborationAdmissionLockKey(workspaceId)]);await assert.rejects(invoke(input));}finally{await holder.end();clients.delete(holder);}
const holder=await ownClient();
try {
await holder.query('SELECT pg_advisory_lock($1::bigint)',[collaborationAdmissionLockKey(workspaceId)]);
const started=Date.now();
await assert.rejects(invoke(input),code('COLLABORATION_FILE_LIFECYCLE_BUSY'));
assert(Date.now()-started>=3000&&Date.now()-started<10000,'Admission waiting must retain its finite lock timeout.');
assert.equal(await readFile(path.join(root,file),'utf8'),'Original\n');
} finally {await holder.end();clients.delete(holder);}
await empty(input);
});
await check('geared inherited lease and matching owner object never mint bootstrap',async()=>{
Expand Down
15 changes: 14 additions & 1 deletion tests/editor-mobile-block-moves.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
import { expect, test } from '@playwright/test';
import { expect, test, type Locator } from '@playwright/test';
import { randomUUID } from 'node:crypto';
import { authenticateManagedTestPage, enterMarkdownEditMode } from './helpers/managed-test-context';

test.use({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });

function selectedEditorText(editor: Locator) {
return editor.evaluate(element => {
const { state } = (element as HTMLElement & { editor: { state: {
selection: { from: number; to: number };
doc: { textBetween(from: number, to: number, separator: string): string };
} } }).editor;
return { dom: window.getSelection()?.toString() ?? '',
native: state.doc.textBetween(state.selection.from, state.selection.to, '\n') };
});
}

for (const block of ['paragraph', 'code'] as const) {
test(`mobile ${block} moves retain the menu anchor and remain editable after undo`, async ({ page }, info) => {
test.skip(process.env.COLLABORATION_E2E !== '1', 'Requires the managed local Postgres stack.');
Expand Down Expand Up @@ -117,6 +128,7 @@ test('mobile list and table deletion keep structure, history and focus during ba
const range = document.createRange(); range.selectNodeContents(element);
const selection = window.getSelection()!; selection.removeAllRanges(); selection.addRange(range);
});
await expect.poll(() => selectedEditorText(editor)).toEqual({ dom: 'One', native: 'One' });
await page.keyboard.press('Backspace');
await expect(editor.locator('li').first()).toHaveText(' two');
const afterList = await tree();
Expand All @@ -129,6 +141,7 @@ test('mobile list and table deletion keep structure, history and focus during ba
const range = document.createRange(); range.selectNodeContents(paragraph);
const selection = window.getSelection()!; selection.removeAllRanges(); selection.addRange(range);
});
await expect.poll(() => selectedEditorText(editor)).toEqual({ dom: 'Cell value', native: 'Cell value' });
await page.keyboard.press('Backspace'); await expect(cell).toHaveText('');
const afterCell = await tree();
await page.keyboard.press('ControlOrMeta+z'); await expect.poll(tree).toEqual(afterList);
Expand Down
Loading
Loading