// Local branches pin parent storage. This is lifecycle authority, not a disposable cache. import { canonicalJson } from './hash.ts'; import { createHash, randomUUID } from 'node:crypto'; import { volterHome } from './volter-home.ts'; import { basename, dirname, join, posix, relative, resolve, sep, win32 } from 'node:path'; import { stateDirName } from './storage.ts'; import { getActiveWorldStore, storageLockScope, withStorageLockOperation, type WorldLockOptions, type WorldStore } from './world-store.ts'; type Pin = { child: string; ownerPid: number; committed?: boolean }; type Ancestry = { generation: string; children: Pin[] }; let entered: WeakSet | undefined; export const canonicalStatePath = (path: string): string => getActiveWorldStore().canonicalPath?.(path) ?? resolve(path); const metaPath = (dir: string) => join(dir, 'ancestry.json'); /** The World folder a state path lies in: everything before its `/worlds/` segments, or undefined. */ function worldFolderOf(path: string): string | undefined { const state = stateDirName().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return new RegExp(`^(.*?)[\\\\/]${state}[\\\\/]worlds[\\\\/][^\\\\/]+(?:[\\\\/]|$)`).exec(path)?.[1]; } /** A World folder moved or copied elsewhere is that World, opened where it now is (architecture, "A World is an install", * marks and branches included): a path its records hold under the folder they were written in is read under the folder * `readFrom` lies in. `recorded` is one of the record's paths known to be the reader's own (a history view's owner * directory); null where the folder has not moved. A path under another folder is another World's, read as recorded. */ export function movedStatePaths(recorded: string, readFrom: string): ((path: string) => string) | null { const from = worldFolderOf(recorded); const to = worldFolderOf(canonicalStatePath(readFrom)); if (from === undefined || to === undefined || from === to) return null; // each folder in its own path form (a drive or UNC root is Windows', which separates with \ and /): the part under the // recorded folder is read in its form and joined onto the reader's in the reader's, so a cross-system copy is rebased const formOf = (path: string) => (/^(?:[A-Za-z]:[\\/]|\\\\)/.test(path) ? win32 : posix); const form = formOf(from), reader = formOf(to); // join normalizes, so a recorded path's trailing separator (a directory a file name is later appended to) is kept, // in the reader's form const keepTrailing = (moved: string, path: string): string => ((form === win32 ? /[\\/]$/ : /\/$/).test(path) && !moved.endsWith(reader.sep) ? `${moved}${reader.sep}` : moved); return (path) => { const rel = form.relative(from, path); return rel === '' || (rel !== '..' && !rel.startsWith(`..${form.sep}`) && !form.isAbsolute(rel)) ? keepTrailing(reader.join(to, ...rel.split(form.sep)), path) : path; }; } const inside = (base: string, path: string) => { const rel = relative(canonicalStatePath(base), canonicalStatePath(path)); return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !rel.startsWith(sep)); }; /** Synchronous only; use exclusive acquisition without age-stealing a live owner. * The coordinator lives outside service, instance and hosted World deletion trees. It is held only for ancestry * bookkeeping (generations, pins, branch pointers, removal receipts) and the not-being-removed check: every World * sharing the VOLTER_HOME waits on it, so no append, fold or caller's critical section runs inside it, and no state lock * is taken inside it (`withStateLock` takes its lock first). */ export function withAncestryLock(fn: () => T, options: WorldLockOptions = {}): T { const scope = storageLockScope(options); const store = getActiveWorldStore(); const active = entered ??= new WeakSet(); if (active.has(store)) return fn(); const path = join(volterHome(), 'branch-ancestry.lock'); return store.withLock(path, () => { active.add(store); try { recoverRemovals(path); return fn(); } finally { active.delete(store); } }, { ...scope, retainLiveOwner: true }); } /** The state locks this process holds, per store: taken again inside one, a lock is already ours. */ let heldLocks: WeakMap> | undefined; const heldBy = (store: WorldStore): Set => { const map = heldLocks ??= new WeakMap(); let set = map.get(store); if (!set) { set = new Set(); map.set(store, set); } return set; }; /** Run `fn` holding the cross-process lock at `lockPath`, a lock of the directory it sits in: taken first, then the * coordinator only to check that the directory is not being removed. Re-entrant within a process. */ export function withStateLock(lockPath: string, fn: () => T, options: WorldLockOptions = {}): T { const scope = storageLockScope(options); const store = getActiveWorldStore(); const held = heldBy(store); if (held.has(lockPath)) return fn(); if (entered?.has(store)) throw new Error(`State lock ${lockPath} taken inside the ancestry coordinator: a state lock is taken before it, never inside it`); // A lock taken inside a held lock of the SAME directory asks the coordinator nothing: the outer take checked that // the directory is not being removed, and a removal recorded since waits on that outer lock before it deletes // anything, so this operation finishes first, as a holder that checked before the receipt does. Asked again, each // write took the machine-wide coordinator three times for one directory. const directory = dirname(lockPath); const nested = [...held].some((path) => dirname(path) === directory); return store.withLock(lockPath, () => { // Read the removal receipt while holding this directory's lock. A removal writes its receipt under the // coordinator before waiting for this lock, so a later receipt belongs to a removal that waits for this holder. if (!nested && removalRecorded()) withAncestryLock(() => assertNotBeingRemoved(directory), { operation: 'removal preflight' }); held.add(lockPath); try { return fn(); } finally { held.delete(lockPath); } }, scope); } /** A state directory's history lock: its appends, captures, observation batches and folds. A branch's is taken before * its ancestors'. */ export function withHistoryLock(directory: string, fn: () => T, options: WorldLockOptions = {}): T { return withStateLock(join(canonicalStatePath(directory), 'history.lock'), fn, storageLockScope(options)); } /** A lock file a holder has recorded itself in (`{pid, hostname}`, written before the holder runs anything): a file * that only ends in `.lock` (a yarn.lock) is not one. */ function isHeldLock(text: string | null): boolean { try { const holder = JSON.parse(text ?? '') as { pid?: unknown }; return Number.isInteger(holder.pid); } catch { return false; } } /** Several sibling directories' history locks at once (a World's services, a changeset's targets), in one order. */ export function withHistoryLocks(directories: string[], fn: () => T, options: WorldLockOptions = {}): T { const scope = storageLockScope(options); const sorted = [...new Set(directories.map((d) => canonicalStatePath(d)))].sort(); const take = (i: number): T => (i === sorted.length ? fn() : withHistoryLock(sorted[i]!, () => take(i + 1), scope)); return take(0); } /** The locks inside a tree a removal waits on before deleting it. */ function locksUnder(path: string): string[] { const store = getActiveWorldStore(); const out: string[] = []; const walk = (dir: string): void => { for (const name of store.list(dir)) { if (name === 'node_modules' || name === '.git') continue; const child = join(dir, name); const stat = store.stat(child); if (!stat || stat.isSymbolicLink) continue; if (stat.isDirectory) walk(child); else if (name.endsWith('.lock') && isHeldLock(store.read(child))) out.push(child); } }; if (store.stat(path)?.isDirectory) walk(path); return out.sort(); } function metadata(dir: string): Ancestry | null { const raw = getActiveWorldStore().read(metaPath(dir)); if (raw === null) return null; const value = JSON.parse(raw) as Ancestry; if (!value || typeof value.generation !== 'string' || !Array.isArray(value.children) || value.children.some(p => typeof p.child !== 'string' || !Number.isInteger(p.ownerPid) || p.ownerPid <= 0)) { throw new Error(`Unreadable branch ancestry at ${dir}; retained`); } return value; } /** Create an identity only for an existing parent. A recreated path gets a new identity. */ export function stateGeneration(dir: string): string { return withAncestryLock(() => { const store = getActiveWorldStore(); if (!store.stat(dir)?.isDirectory) throw new Error(`Branch parent is missing: ${dir}`); assertNotBeingRemoved(dir); let meta = metadata(dir); if (!meta) { meta = { generation: randomUUID(), children: [] }; store.writeAtomic(metaPath(dir), JSON.stringify(meta)); } return meta.generation; }, { operation: 'state generation' }); } /** Must be called in the same critical section as child pointer publication. A crash before * publication leaves a pending pin; it can be ignored only once its writer is provably dead. */ export function pinParent(parentDir: string, child: string, expected?: string): string { parentDir = canonicalStatePath(parentDir); child = canonicalStatePath(child); const generation = stateGeneration(parentDir); if (expected !== undefined && generation !== expected) throw new Error(`Branch parent generation changed: ${parentDir}`); const meta = metadata(parentDir)!; if (!meta.children.some(p => p.child === child)) { meta.children.push({ child, ownerPid: process.pid }); getActiveWorldStore().writeAtomic(metaPath(parentDir), JSON.stringify(meta)); } return generation; } /** Mark publication complete only after branch.json exists. */ export function commitParentPin(parentDir: string, child: string): void { parentDir = canonicalStatePath(parentDir); child = canonicalStatePath(child); const meta = metadata(parentDir)!; const pin = meta.children.find(p => p.child === child)!; pin.committed = true; getActiveWorldStore().writeAtomic(metaPath(parentDir), JSON.stringify(meta)); } /** Read-only identity validation. */ export function checkParent(parentDir: string, expected?: string): void { if (!getActiveWorldStore().stat(parentDir)?.isDirectory) throw new Error(`Branch parent is missing: ${parentDir}`); if (expected !== undefined && metadata(parentDir)?.generation !== expected) throw new Error(`Branch parent generation changed: ${parentDir}`); } function filesUnder(path: string): string[] { const store = getActiveWorldStore(); const info = store.stat(path); if (info?.isSymbolicLink) throw new Error(`Symbolic-link branch state retained: ${path}`); if (!info?.isDirectory) return []; const result: string[] = []; const stateSuffix = join(stateDirName(), 'world'); const stateService = dirname(path).endsWith(`${sep}${stateSuffix}`); if (stateService && store.stat(join(path, 'views'))?.isSymbolicLink) throw new Error(`Symbolic-link history views retained: ${path}`); if (stateService) return [...['ancestry.json', 'branch.json'].map(name => join(path, name)), ...store.list(join(path, 'views')).filter(name => /^[a-f0-9]{64}\.json$/.test(name)).map(name => join(path, 'views', name))].filter(file => { const stat = store.stat(file); if (stat?.isSymbolicLink) throw new Error(`Symbolic-link ancestry metadata retained: ${file}`); return stat !== null; }); for (const name of store.list(path)) { if (name === 'node_modules' || name === '.git') continue; const child = join(path, name); if (store.stat(child)?.isSymbolicLink) continue; // recursive removal unlinks this entry; its target survives if (store.stat(child)?.isDirectory) result.push(...filesUnder(child)); } return result; } /** Caller holds the coordinator through the actual deletion. A committed pin with missing * child metadata is uncertainty, not permission: only explicit child removal releases it. */ export function assertStateRemovable(path: string): void { const store = getActiveWorldStore(); for (const file of filesUnder(path).filter(f => f.endsWith(`${sep}ancestry.json`))) { const meta = metadata(dirname(file))!; for (const pin of meta.children) { if (inside(path, pin.child)) continue; // deleting the entire dependent subtree together const raw = store.read(pin.child); if (raw === null) { if (!pin.committed) { try { process.kill(pin.ownerPid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ESRCH') continue; } } throw new Error(`Retained branch parent: dependent branch metadata unavailable at ${pin.child}`); } const retained = JSON.parse(raw) as { dependencies?: Array<{ directory: string; generation: string }> }; if (retained.dependencies !== undefined) { if (createHash('sha256').update(canonicalJson(retained)).digest('hex') + '.json' !== basename(pin.child)) throw new Error(`Invalid retained history ownership ${pin.child}`); if (!Array.isArray(retained.dependencies) || retained.dependencies.some(d => typeof d.directory !== 'string' || typeof d.generation !== 'string')) throw new Error(`Unreadable retained history ${pin.child}`); if (retained.dependencies.some(d => canonicalStatePath(d.directory) === canonicalStatePath(dirname(file)))) throw new Error(`Retained branch parent: dependent history view ${pin.child}`); continue; } const child = JSON.parse(raw) as { parent?: { at?: unknown; position?: unknown; generation?: unknown; directory?: unknown } }; if (!child || !child.parent || typeof child.parent.at !== 'string' || !Number.isInteger(child.parent.position) || Number(child.parent.position) < 0 || (child.parent.generation !== undefined && typeof child.parent.generation !== 'string')) throw new Error(`Unreadable dependent branch ${pin.child}; retained`); if (/^[a-z][a-z0-9+.-]*:\/\//i.test(child.parent.at)) continue; // The pin's child state layout is //world//branch.json. // Derive the real parent from at, never trust an independently edited directory field. const layout = join(stateDirName(), 'world', basename(dirname(pin.child))); const actualParent = canonicalStatePath(join(child.parent.at, layout)); if (actualParent === canonicalStatePath(dirname(file)) || !child.parent.generation || child.parent.directory !== actualParent || metadata(actualParent)?.generation !== child.parent.generation) { throw new Error(`Retained branch parent: dependent branch ${pin.child}. Remove dependent branches first; down without purge can still stop compute.`); } } } } type Outgoing = { child: string; parent?: { directory?: string; generation?: string } }; type Removal = { path: string; outgoing: Outgoing[] }; const removalDir = () => join(volterHome(), 'branch-removals'); function releaseOutgoing(removal: Removal): void { const store = getActiveWorldStore(); for (const { child, parent } of removal.outgoing) { if (!inside(removal.path, child)) throw new Error('Invalid branch removal receipt; retained'); if (!parent?.directory || inside(removal.path, parent.directory)) continue; const meta = metadata(parent.directory); if (!meta || meta.generation !== parent.generation) continue; meta.children = meta.children.filter(p => p.child !== child); store.writeAtomic(metaPath(parent.directory), JSON.stringify(meta)); } } /** A crash after deleting files cannot strand committed child pins. Receipts are replayed * before any subsequent ancestry publication, so path reuse cannot hide completed removal. */ function recoverRemovals(lockPath: string): void { const store = getActiveWorldStore(); const receipts = store.list(removalDir()).filter(n => n.endsWith('.json')); if (!receipts.length) { beingRemoved = []; return; } const pending: string[] = []; withStorageLockOperation(lockPath, 'ancestry removal recovery', () => { for (const name of receipts) { const file = join(removalDir(), name); const removal = JSON.parse(store.read(file)!) as Removal; if (typeof removal.path !== 'string' || !Array.isArray(removal.outgoing)) throw new Error('Invalid branch removal receipt; retained'); if (!store.exists(removal.path)) { releaseOutgoing(removal); store.remove(file); } else pending.push(removal.path); } }); beingRemoved = pending; } /** Whether any removal receipt is recorded now: read without the coordinator (withStateLock). */ function removalRecorded(): boolean { return getActiveWorldStore().list(removalDir()).some((name) => name.endsWith('.json')); } /** State whose removal is recorded and not yet complete: its deletion runs outside the coordinator, so nothing may pin * it as a parent or write into it meanwhile. Read under the coordinator, where recoverRemovals has just refreshed it. */ let beingRemoved: string[] = []; export function assertNotBeingRemoved(path: string): void { const at = beingRemoved.find((p) => inside(p, path)); if (at) throw new Error(`World state is being removed: ${at}`); } /** The coordinator is held to decide and record removal (`check`, the caller's own precondition, runs there too) * and to release it, not through the * deletion: every World on the machine shares the coordinator, and a large tree's deletion outlasts their writes' * patience. The receipt, written first, keeps the path from being pinned or locked while it is deleted; the deletion * then waits on each lock inside the tree in turn, so a holder that checked before the receipt finishes first. */ export function withStateRemoval(path: string, remove: () => T, check?: () => void): T { const store = getActiveWorldStore(); const { removal, receipt } = withAncestryLock(() => { check?.(); assertStateRemovable(path); const outgoing = filesUnder(path).filter(f => !f.endsWith(`${sep}ancestry.json`)).flatMap(child => { const branch = JSON.parse(store.read(child)!) as { parent?: Outgoing['parent']; dependencies?: Array>; previousParents?: Array> }; return (branch.dependencies ?? [...(branch.previousParents ?? []), branch.parent]).map(parent => ({ child: canonicalStatePath(child), parent })); }); const removal = { path: canonicalStatePath(path), outgoing }; const receipt = join(removalDir(), `${randomUUID()}.json`); store.writeAtomic(receipt, JSON.stringify(removal)); beingRemoved = [...beingRemoved, removal.path]; return { removal, receipt }; }, { operation: 'removal preflight' }); // Each lock is waited on alone, taken and let go: a holder that checked before the receipt finishes, and a taker // after it refuses once it holds the lock (withStateLock), so the removal never holds one lock while waiting on // another and no lock order can deadlock it. A wait that fails leaves nothing deleted: the receipt is released. const held = heldBy(store); try { for (const lock of locksUnder(path).filter((l) => !held.has(l))) store.withLock(lock, () => undefined, { operation: 'removal preflight' }); } catch (error) { withAncestryLock(() => { if (store.exists(receipt)) store.remove(receipt); beingRemoved = beingRemoved.filter((p) => p !== removal.path); }, { operation: 'ancestry removal recovery' }); throw error; } const result = remove(); withAncestryLock(() => { if (store.exists(path)) throw new Error(`Branch state removal incomplete: ${path}; receipt retained`); // Another process's recovery may have released it already; both steps are idempotent. releaseOutgoing(removal); if (store.exists(receipt)) store.remove(receipt); }, { operation: 'ancestry removal recovery' }); return result; }