/** Owned-local PostgreSQL regression only. It deliberately changes disposable * runtime SESSION defaults and observes real driver COMMITs; no native traffic. */ import assert from "node:assert/strict" import { randomUUID } from "node:crypto" import type { Pool } from "pg" import type { createConfiguredBandwidthControlSource } from "./bandwidth-control-source.js" import type { BandwidthBinding, BandwidthScope } from "./bandwidth-admission.js" import type { ProbeStorageConnection } from "./server-probe-journal-maintenance.js" import { assertOwnedBandwidthSql, fixtureBinding, completionProof, scope } from "./bandwidth-admission-process.sql-helper.js" assertOwnedBandwidthSql() export async function acceptBandwidthJournalDurability(source: ReturnType, owner: Pool, controlGeneration: string) { assertOwnedBandwidthSql() const { Client } = await import("pg") const { createBandwidthAdmissionSqlJournal } = await import("./bandwidth-admission-storage.js") const connect = source.connect.bind(source), eventProof = source.eventProofOnConnection.bind(source) const originalQuery = Client.prototype.query, pids = new Set(), commitSettings: string[] = [] const held = new Set() let patched = false, allDefaultsRestored = false const acquireFour = async () => { // Retain the completed siblings too if one checkout fails: finally must // never leave a session owned by this helper checked out. const results = await Promise.allSettled(Array.from({ length: 4 }, async () => { const lease = await connect(scope()); held.add(lease); return lease })) for (const result of results) if (result.status === "rejected") throw result.reason return results.map(result => (result as PromiseFulfilledResult).value) } const release = (lease: ProbeStorageConnection) => { held.delete(lease); lease.release() } try { const initial = await acquireFour() for (const lease of initial) { await lease.query("SET SESSION synchronous_commit=off") const row = (await lease.query("SELECT pg_catalog.pg_backend_pid() AS pid,pg_catalog.current_setting('synchronous_commit') AS setting")).rows[0] assert.equal(row.setting, "off"); pids.add(Number(row.pid)) } assert.equal(pids.size, 4) initial.forEach(release) Client.prototype.query = function (this: InstanceType, ...args: unknown[]) { const text = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text ?? "" const pid = (this as unknown as { processID: number }).processID if (!pids.has(pid) || !/^COMMIT\s*;?$/i.test(text.trim())) return Reflect.apply(originalQuery, this, args) // The real same-driver observation runs inside this transaction and // precedes its genuine COMMIT. Neither result is fabricated or replaced. return (async () => { const observation = await Reflect.apply(originalQuery, this, ["SELECT pg_catalog.current_setting('synchronous_commit') AS setting,pg_catalog.pg_backend_pid() AS pid"]) assert.equal(Number(observation.rows[0].pid), pid) assert.equal(observation.rows[0].setting, "on", "journal COMMIT must override the inherited off SESSION default") commitSettings.push(observation.rows[0].setting) return Reflect.apply(originalQuery, this, args) })() } as typeof Client.prototype.query patched = true const prefix = "durability-" + randomUUID(), bindings = [ fixtureBinding(prefix + ":A", prefix + ":B", { controlGeneration }), fixtureBinding(prefix + ":C", prefix + ":D", { controlGeneration }), fixtureBinding(prefix + ":E", prefix + ":F", { controlGeneration }), ] const noSend = new Set() const journalFor = (expected: BandwidthBinding) => { let active: { connection: ProbeStorageConnection; scope: BandwidthScope } | undefined return createBandwidthAdmissionSqlJournal({ now: Date.now, connect: async current => { assert(!active); const connection = await connect(current); held.add(connection); active = { connection, scope: current } return { query: (text, values, options) => connection.query(text, values, options), release(unsafe) { active = undefined; held.delete(connection); connection.release(unsafe) } } }, authorize: async (binding, current) => { assert(Date.now() < current.deadlineAt); current.signal?.throwIfAborted(); assert.deepEqual(binding, expected); assert.equal(binding.controlGeneration, controlGeneration) }, verifyEvidence: async (transition, binding, evidence) => { assert.deepEqual(binding, expected) if (transition === "complete") assert.deepEqual(evidence, { terminalProof: completionProof(binding) }) else if (transition === "release-before-dispatch") { assert(noSend.has(binding.attemptId)); assert.equal((evidence as { proof?: string }).proof, "private-no-send") } else assert.equal(evidence, undefined) }, eventProof: async event => { assert(active); return eventProof(event, active.connection, active.scope) }, }) } const completed = journalFor(bindings[0]) await completed.reserve(bindings[0], scope()); await completed.arm(bindings[0], scope()) await completed.complete(bindings[0], { terminalProof: completionProof(bindings[0]) }, scope()) for (const [index, from] of [[1, "reserved"], [2, "armed"]] as const) { const binding = bindings[index], journal = journalFor(binding); noSend.add(binding.attemptId) await journal.reserve(binding, scope()); if (from === "armed") await journal.arm(binding, scope()) await journal.releaseBeforeDispatch(binding, { from, proof: "private-no-send" }, scope()) } assert.equal(commitSettings.length, 8) const ids = bindings.map(binding => binding.attemptId) const attempts = (await owner.query("SELECT attempt_id::text,state,resolution,terminal_proof FROM mmapp_control.bandwidth_attempts WHERE attempt_id=ANY($1::uuid[])", [ids])).rows assert.equal(attempts.length, 3) for (const binding of bindings) { const row = attempts.find(attempt => attempt.attempt_id === binding.attemptId); assert(row); assert.equal(row.state, "released") assert.equal(row.resolution, binding === bindings[0] ? "remote_completion" : "proven_not_dispatched") assert.equal(row.terminal_proof, binding === bindings[0] ? completionProof(binding) : null) } assert.equal(Number((await owner.query("SELECT count(*) AS n FROM mmapp_control.bandwidth_node_occupancy WHERE attempt_id=ANY($1::uuid[])", [ids])).rows[0].n), 0) const events = (await owner.query("SELECT ack_id::text,attempt_id::text,transition,old_state,new_state,binding_proof,control_generation,evidence_proof FROM mmapp_control.bandwidth_attempt_events WHERE attempt_id=ANY($1::uuid[])", [ids])).rows assert.equal(events.length, 8) const after = await acquireFour(), afterPids = new Set() for (const lease of after) { const row = (await lease.query("SELECT pg_catalog.pg_backend_pid() AS pid,pg_catalog.current_setting('synchronous_commit') AS setting")).rows[0] afterPids.add(Number(row.pid)); assert.equal(row.setting, "off", "SET LOCAL must not change the reusable SESSION default") } assert.deepEqual(afterPids, pids) for (const event of events) { const material = { ackId: event.ack_id, attemptId: event.attempt_id, transition: event.transition, oldState: event.old_state, newState: event.new_state, bindingProof: event.binding_proof, controlGeneration: event.control_generation, terminalProof: event.transition === "complete" ? completionProof(bindings[0]) : null } assert.equal(event.evidence_proof, await eventProof(material, after[0], scope())) } for (const lease of after) { await lease.query("SET SESSION synchronous_commit=on"); release(lease) } allDefaultsRestored = true return { checks: 5, physicalRuntimeSessions: pids.size, actualCommitObservations: commitSettings.length, allCommitSettings: "on", subsequentSessionDefaults: "off", persistedAttempts: attempts.length, persistedEvents: events.length, remainingOccupancy: 0, syntheticPrivateEvidence: true, realNativeCalls: 0 } } finally { if (patched) Client.prototype.query = originalQuery // Also repair the test's SESSION defaults when an assertion fails. Acquire // the entire pool, not four sequential checkouts of the same backend. if (!allDefaultsRestored) { for (const lease of [...held]) { try { await lease.query("SET SESSION synchronous_commit=on") } catch { /* Retired leases are destroyed by their source. */ } finally { held.delete(lease); lease.release(true) } } try { const leases = await acquireFour() for (const lease of leases) { try { await lease.query("SET SESSION synchronous_commit=on") } finally { release(lease) } } } finally { for (const lease of [...held]) { held.delete(lease); lease.release(true) } } } } }