Files
MikrotikManager/backend/src/modules/mcp/routing-reservation.sql-helper.ts
T

830 lines
79 KiB
TypeScript

import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import { basename, dirname, join, resolve } from "node:path"
import { readFile, writeFile } from "node:fs/promises"
import type { PoolClient } from "pg"
/** Actual SQL/crypto numbered-schema acceptance only; no public tool registration,
* native callback, controller tick, reservation refund or fixture DELETE. */
export function assertOwnedRoutingReservationSql() {
assert.equal(process.env.MMAPP_OWN_ROUTING_RESERVATIONS, "true")
const url = new URL(process.env.DATABASE_URL ?? "")
assert.equal(url.hostname, "127.0.0.1"); assert.equal(url.pathname, "/postgres")
assert(["postgres:", "postgresql:"].includes(url.protocol))
assert(process.env.MCP_STATE_DIR && basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-"))
}
export async function acceptRoutingReservationSql(options: { runtimeAdmission?: boolean; commonAdmissionOnly?: boolean; forwardChargeOnly?: boolean } = {}) {
assertOwnedRoutingReservationSql()
const { pool } = await import("../../db/index.js")
const { mcpConnectionPolicySchema } = await import("@mmapp/contracts/mcp")
const { routeAiProfileSchema } = await import("@mmapp/contracts/mcp-routing")
const security = await import("./security.js")
const { createRoutingSourceContext, readRoutingEndpoints } = await import("./routing-observation-source.js")
const { resolveRoutingProfileAuthority } = await import("./routing-profile-authority.js")
const { assertAcknowledgedRoutingForwardAttempt, createRoutingReservationStore, withRoutingReservationAdmission, readHistoricalChargesWithinOwner } = await import("./routing-reservation-store.js")
const { RoutingReservationCommitUnknown } = await import("./routing-reservation-transaction.js")
assert.equal((await pool.query("SELECT current_database() AS name")).rows[0].name, "postgres")
assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations WHERE id='0040_mcp_routing_reservations'")).rows[0].n, 1, "Numbered routing reservation enrollment required")
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservations")).rows[0].n, 0, "Acceptance must start with empty enrolled ledgers")
const previousEnabled = (await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled as boolean
const ids: number[] = [], profileIds: string[] = [], names: string[] = []
const store = createRoutingReservationStore()
// Positive historical fixtures explicitly reconstruct every durable record.
const replaceFixtureAnchor = async (id: string, bindingProof: string, createdAt: string) => {
const rows = (await pool.query("SELECT id,payload FROM mcp_audit WHERE action='routing.charge.admitted' AND payload->'anchor'->>'allocationId'=$1", [id])).rows
assert.equal(rows.length, 1)
const anchor = { ...rows[0].payload.anchor, bindingDigest: security.fingerprint(bindingProof), createdAt }
const mac = await security.privateSecretFingerprint(security.fingerprint(anchor), "routing-charge-audit-v1")
await pool.query("UPDATE mcp_audit SET payload=$2::jsonb,created_at=$3 WHERE id=$1", [rows[0].id, JSON.stringify({ anchor, mac }), createdAt])
const file = join(security.mcpStateDirectory(), "routing-charge-journal", anchor.profileId + ".json")
const { body } = JSON.parse(await readFile(file, "utf8"))
const witness = body.witnesses.find((value: { allocationId: string }) => value.allocationId === id)
assert(witness)
Object.assign(witness, { createdAt, auditMac: mac })
const hostMac = await security.privateSecretFingerprint(security.fingerprint(body), "routing-charge-host-journal-v1")
await writeFile(file, JSON.stringify({ body, mac: hostMac }) + "\n")
}
try {
ids.push(...(await pool.query("INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl) VALUES($1,'127.0.0.1',9,true,'SYNTHETIC','SYNTHETIC',false,true) RETURNING id", ["reservation-synthetic-" + randomUUID()])).rows.map(row => Number(row.id)))
await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1")
const contextSources = (await createRoutingSourceContext(await readRoutingEndpoints(ids))).expected
const fixture = async (mutations = 10, maxSwitches = 3, autoRecovery = true) => {
const connectionId = randomUUID(), credentialId = randomUUID(), profileId = randomUUID(), ownerId = "reservation-owner-" + randomUUID()
const now = Date.now(), expiresAt = new Date(now + 600000).toISOString(), generation = await security.accessGeneration()
const permissions = ["mm:network:read", "mm:network:write", "mm:filters:write"]
const policy = mcpConnectionPolicySchema.parse({ id: connectionId, version: 1, status: "active", mode: "approval", permissions, expiresAt,
scope: { serverIds: ids, operationIds: ["routing.analyze", "routing.community.switch", "routing.path.verify", "operations.recover"], allowGlobal: false },
limits: { callsPerMinute: 100, mutationsPerHour: mutations, concurrentReads: 4, serversPerPlan: 2, objectsPerPlan: 20 } })
await pool.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,'synthetic reservation',$2,$3::jsonb,$4::jsonb,$5,$6,$7)", [connectionId, ownerId, JSON.stringify(permissions), JSON.stringify(policy), generation, expiresAt, new Date(now - 1000)])
await pool.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [credentialId, connectionId, randomUUID(), expiresAt])
let profile = routeAiProfileSchema.parse({ name: "Synthetic reserved profile", serverId: ids[0], community: "65000:10", family: "ipv4", table: "tenant", probeVrf: "probe", autoRecovery, maxSwitchesPerHour: maxSwitches,
candidates: ["a", "b"].map((id, index) => ({ id, jumpHostId: ids[0], exitNodeId: ids[0], wanInterface: "synthetic-wan", downstreamInterface: "synthetic-hop", gateway: "192.0.2." + (index + 1),
gatewayRef: { resource: "ipv4_route", id: "*" + (index + 1) }, controlProbe: { targetInterface: "synthetic-exit", expectedHops: [{ serverId: ids[0], interface: "synthetic-exit" }] } })) })
await pool.query("INSERT INTO mcp_routing_profiles(id,connection_id,config,enabled,grant_expires_at,credential_id,generation,policy_version) VALUES($1,$2,$3::jsonb,true,$4,$5,$6,1)", [profileId, connectionId, JSON.stringify(profile), expiresAt, credentialId, generation])
profileIds.push(profileId)
const principal = { connectionId, credentialId, credentialExpiresAt: expiresAt }
let authority = await resolveRoutingProfileAuthority({ profileId, expectedVersion: 1, profile, principal, ownerId, transport: { contextSources } })
const makeSource = async (createOperation = true) => {
const operationId = randomUUID(), planId = randomUUID()
const input: Record<string, unknown> = { serverId: ids[0], profile, principal, ownerId, candidateId: "b", originalCandidateId: "a", persistentProfileAuthority: authority,
contextSources, policyProof: security.fingerprint(policy), connectionGeneration: generation, generation, receiptId: randomUUID(), proofRevision: 3,
nativeId: "*1", dependencyProof: "d".repeat(64), originalTargetProof: "a".repeat(64), desiredTargetProof: "b".repeat(64),
originalRuleCiphertext: await security.encryptSecret("synthetic original command; no native request made"), desiredRuleCiphertext: await security.encryptSecret("synthetic desired command; no native request made"),
rules: [{ community: profile.community, gateway: "192.0.2.2" }], beforeRules: [{ community: profile.community, gateway: "192.0.2.1" }] }
input.requestProof = await security.privateSecretFingerprint(security.fingerprint(input), "route-ai-scoped-request-v3")
const evidence = { target: { scope: "servers", serverIds: ids }, objects: [], snapshots: [], before: input.beforeRules, steps: [{ kind: "service", service: "routing.community.scoped", input }], warnings: [], requiresHuman: true, mutationCost: 2 }
await pool.query("INSERT INTO mcp_plans(id,connection_id,operation_id,operation_version,policy_version,generation,payload,evidence,state,expires_at,approved_by,approved_at) VALUES($1,$2,'routing.community.switch',7,1,$3,$4::jsonb,$5::jsonb,$8,$6,$7,now())", [planId, connectionId, generation, JSON.stringify({ sealed: await security.encryptSecret(JSON.stringify({ profile, candidateId: "b" })) }), JSON.stringify({ sealed: await security.encryptSecret(JSON.stringify(evidence)) }), expiresAt, ownerId, createOperation ? "executing" : "approved"])
if (createOperation) await pool.query("INSERT INTO mcp_operations(id,plan_id,connection_id,idempotency_key,state) VALUES($1,$2,$3,$4,'pending')", [operationId, planId, connectionId, randomUUID()])
return { operationId, planId, input }
}
const renew = async () => {
const row = (await pool.query("SELECT config,version FROM mcp_routing_profiles WHERE id=$1", [profileId])).rows[0]
profile = routeAiProfileSchema.parse(row.config)
authority = await resolveRoutingProfileAuthority({ profileId, expectedVersion: row.version, profile, principal, ownerId, transport: { contextSources } })
}
return { connectionId, credentialId, profileId, principal, makeSource, renew }
}
const used = async (connectionId: string) => Number((await pool.query("SELECT COALESCE(sum(used),0)::int AS used FROM mcp_budget_buckets WHERE connection_id=$1 AND kind='mutations'", [connectionId])).rows[0].used)
if (!options.commonAdmissionOnly && !options.forwardChargeOnly) {
{
const f = await fixture(2, 2), source = await f.makeSource()
const concurrent = await Promise.all([store.reserve(source.operationId), store.reserve(source.operationId)])
assert.equal(concurrent.filter(value => value.created).length, 1)
assert.equal(concurrent[0].reservationId, concurrent[1].reservationId)
assert.equal(concurrent.filter(value => !!value.forwardAllocation).length, 1)
assert.equal((await store.reserve(source.operationId)).forwardAllocation, undefined)
assert.equal((await createRoutingReservationStore().reserve(source.operationId)).forwardAllocation, undefined)
await assert.rejects(store.beginForwardAttempt(JSON.parse(JSON.stringify({ kind: "routing-reserved-forward-allocation" }))), /capability/)
assert.equal(await used(f.connectionId), 2)
const shared = (await pool.query("SELECT mode,slot_phase,source_configuration_proof,reservation_id FROM mcp_scoped_recovery_intents WHERE source_operation_id=$1", [source.operationId])).rows
assert.equal(shared.length, 1); assert.equal(shared[0].mode, "reserved"); assert.equal(shared[0].slot_phase, "reservation-held"); assert.equal(shared[0].source_configuration_proof, null)
assert.equal((await store.read(concurrent[0].reservationId, f.principal)).nativeDispatchAvailable, false)
const newerId = randomUUID()
await pool.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [newerId, f.connectionId, randomUUID(), f.principal.credentialExpiresAt])
await store.read(concurrent[0].reservationId, { ...f.principal, credentialId: newerId })
assert.equal(await used(f.connectionId), 2, "Historical read cannot allocate fresh budget")
// OwnPG-only production-crypto hourly reader acceptance. No native request,
// CONFIG_APPLIED or network receipt is fabricated by these fixtures.
const historicalPrincipal = { ...f.principal, credentialId: newerId }
const charged = () => store.readHourlyCharges(f.profileId, historicalPrincipal)
assert.equal((await charged()).totalCharges, 2)
await pool.query("UPDATE mcp_routing_profiles SET grant_expires_at=now()-interval '1 second',enabled=false,version=version+1 WHERE id=$1", [f.profileId])
await pool.query("UPDATE mcp_credentials SET revoked_at=now() WHERE id=$1", [f.credentialId])
assert.equal((await charged()).totalCharges, 2, "Old grant/credential/profile version never erases charge")
const at = new Date().toISOString()
await pool.query("UPDATE mcp_routing_profiles SET state=$2::jsonb WHERE id=$1", [f.profileId, JSON.stringify({ switches: [at, at] })])
const projected = await charged()
assert.equal(projected.legacyCharges, 2); assert.equal(projected.reservedCharges, 2); assert.equal(projected.totalCharges, 4)
assert.equal(projected.budgetFits, false); assert.equal(projected.dispatchAllowed, false); assert.equal(projected.securityProof, false)
const reservationId = concurrent[0].reservationId
const original = (await pool.query("SELECT * FROM mcp_routing_reservations WHERE id=$1", [reservationId])).rows[0]
const originalShared = (await pool.query("SELECT * FROM mcp_scoped_recovery_intents WHERE reservation_id=$1", [reservationId])).rows[0]
const originalSlots = (await pool.query("SELECT * FROM mcp_routing_reservation_slots WHERE reservation_id=$1 ORDER BY lane", [reservationId])).rows
const restore = async () => {
await pool.query("UPDATE mcp_routing_reservations SET binding_sealed=$2,binding_proof=$3,state_sealed=$4,state_proof=$5,revision=$6,profile_id=$7,deadline=$8,created_at=$9 WHERE id=$1", [reservationId, original.binding_sealed, original.binding_proof, original.state_sealed, original.state_proof, original.revision, original.profile_id, original.deadline, original.created_at])
for (const slot of originalSlots) await pool.query("INSERT INTO mcp_routing_reservation_slots(reservation_id,profile_id,lane,state,created_at) VALUES($1,$2,$3,$4,$5) ON CONFLICT(reservation_id,lane) DO UPDATE SET state=excluded.state,profile_id=excluded.profile_id,created_at=excluded.created_at", [reservationId, slot.profile_id, slot.lane, slot.state, slot.created_at])
await pool.query("UPDATE mcp_scoped_recovery_intents SET intent_sealed=$2,intent_proof=$3,state=$4,slot_phase=$5,source_configuration_proof=$6,recovery_receipt_id=$7,deadline=$8,created_at=$9,inverse_intent_sealed=$10,inverse_intent_proof=$11,inverse_configuration_sealed=$12,inverse_configuration_proof=$13,verified_sealed=$14,verified_proof=$15 WHERE reservation_id=$1", [reservationId, originalShared.intent_sealed, originalShared.intent_proof, originalShared.state, originalShared.slot_phase, originalShared.source_configuration_proof, originalShared.recovery_receipt_id, originalShared.deadline, originalShared.created_at, originalShared.inverse_intent_sealed, originalShared.inverse_intent_proof, originalShared.inverse_configuration_sealed, originalShared.inverse_configuration_proof, originalShared.verified_sealed, originalShared.verified_proof])
await replaceFixtureAnchor(reservationId, original.binding_proof, original.created_at.toISOString())
}
const invalid = async (sql: string, values: unknown[]) => {
try { await pool.query(sql, values); await assert.rejects(charged) } finally { await restore() }
}
await invalid("UPDATE mcp_routing_reservations SET binding_proof=$2 WHERE id=$1", [reservationId, "0".repeat(64)])
await invalid("UPDATE mcp_routing_reservations SET state_proof=$2 WHERE id=$1", [reservationId, "0".repeat(64)])
await invalid("UPDATE mcp_routing_reservation_slots SET state='spent' WHERE reservation_id=$1 AND lane='inverse'", [reservationId])
await invalid("DELETE FROM mcp_routing_reservation_slots WHERE reservation_id=$1 AND lane='inverse'", [reservationId])
await invalid("UPDATE mcp_scoped_recovery_intents SET recovery_receipt_id=$2 WHERE reservation_id=$1", [reservationId, randomUUID()])
await invalid("UPDATE mcp_routing_reservations SET state_sealed=$2 WHERE id=$1", [reservationId, "x".repeat(131073)])
await invalid("UPDATE mcp_routing_reservations SET created_at=clock_timestamp()+interval '1 minute' WHERE id=$1", [reservationId])
const foreign = await fixture()
await invalid("UPDATE mcp_routing_reservations SET profile_id=$2 WHERE id=$1", [reservationId, foreign.profileId])
const overflow: string[] = []
try {
for (let index = 0; index < 11; index++) {
const extra = await f.makeSource(), id = randomUUID(); overflow.push(id)
// Deliberately invalid identity clones: bound refusal must happen
// before loading any ciphertext, not after returning a partial count.
await pool.query(`INSERT INTO mcp_routing_reservations(id,source_plan_id,source_operation_id,source_step_index,profile_id,connection_id,binding_sealed,binding_proof,state_sealed,state_proof,revision,deadline,created_at)
SELECT $2,$3,$4,source_step_index,profile_id,connection_id,binding_sealed,binding_proof,state_sealed,state_proof,revision,deadline,created_at FROM mcp_routing_reservations WHERE id=$1`, [reservationId, id, extra.planId, extra.operationId])
}
await assert.rejects(charged, /count bound/)
} finally { await pool.query("DELETE FROM mcp_routing_reservations WHERE id=ANY($1::uuid[])", [overflow]) }
// Readable old state remains charged under original source inverse slot.
// Signed historical state fixtures exercise integrity ONLY, not success
// of a real forward/inverse or production fault/network verification.
for (const [forward, inverse] of [["held", "held"], ["spent", "spent"], ["spent", "unknown"], ["spent", "proven-unused"]]) {
try {
const outcome = forward === "held" ? undefined : { status: inverse === "proven-unused" ? "passed" : "failed", configurationProof: "c".repeat(64), networkProof: "d".repeat(64) }
const state = { revision: original.revision + 1, forward, inverse, ...(outcome ? { outcome } : {}) }
const stateProof = await security.privateSecretFingerprint(security.fingerprint({ bindingProof: original.binding_proof, state }), "routing-reservation-state-v1")
const phase = inverse === "spent" || inverse === "unknown" ? "reserved-attempt" : outcome ? "reservation-bound" : "reservation-held"
const sharedPacket = { phase, reservationId, bindingProof: original.binding_proof, stateProof }
await pool.query("UPDATE mcp_routing_reservations SET state_sealed=$2,state_proof=$3,revision=$4 WHERE id=$1", [reservationId, await security.encryptSecret(JSON.stringify(state)), stateProof, state.revision])
await pool.query("UPDATE mcp_routing_reservation_slots SET state=CASE lane WHEN 'forward' THEN $2 ELSE $3 END WHERE reservation_id=$1", [reservationId, forward, inverse])
await pool.query("UPDATE mcp_scoped_recovery_intents SET intent_sealed=$2,intent_proof=$3,state=$4,slot_phase=$5,source_configuration_proof=$6 WHERE reservation_id=$1", [reservationId, await security.encryptSecret(JSON.stringify(sharedPacket)), await security.privateSecretFingerprint(security.fingerprint(sharedPacket), "routing-reservation-shared-slot-v1"), inverse === "unknown" ? "unknown" : "intent", phase, outcome?.configurationProof ?? null])
assert.equal((await charged()).reservedCharges, 2)
} finally { await restore() }
}
// Positive historical RECOVERY_VERIFIED verification: real ownSQL rows,
// fixed production encryption/MAC/domains and actual schema verifier.
// Synthetic stored receipt fixture; NOT a completed native recovery.
try {
const start = Date.now() - 3000, until = new Date(start + 1500).toISOString()
const binding = { ...JSON.parse(await security.decryptSecret(original.binding_sealed)), createdAt: new Date(start).toISOString(), deadline: until }
const bindingProof = await security.privateSecretFingerprint(security.fingerprint(binding), "routing-reservation-binding-v1")
const state = { revision: original.revision + 1, forward: "spent", inverse: "spent", outcome: { status: "failed", configurationProof: "c".repeat(64), networkProof: "d".repeat(64) } }
const stateProof = await security.privateSecretFingerprint(security.fingerprint({ bindingProof, state }), "routing-reservation-state-v1")
const packet = { phase: "reserved-attempt", reservationId, bindingProof, stateProof }
const intent = { revision: 1, phase: "RECOVERY_INTENT", mode: "reserved", reservationId, networkProof: state.outcome.networkProof,
sourceOperationId: binding.operationId, sourceStepIndex: 0, sourceReceiptId: binding.sourceReceiptId, sourceProof: binding.sourceEvidenceProof,
configurationProof: state.outcome.configurationProof, operationId: binding.operationId, stepIndex: 0, receiptId: binding.inverseReceiptId,
requestSeal: "e".repeat(64), connectionId: binding.principal.connectionId, ownerId: binding.ownerId, validUntil: until, createdAt: binding.createdAt }
const config = { ...intent, phase: "RECOVERY_CONFIG_APPLIED", serverId: ids[0], nativeId: "*1", candidateId: "a",
originalRule: "synthetic ownSQL historical receipt", targetProof: "a".repeat(64), dependencyProof: "b".repeat(64),
sourceEpochs: [{ serverId: ids[0], proof: "f".repeat(64) }], pathCheckId: null, observedAt: new Date(start + 100).toISOString() }
const verified = { ...config, phase: "RECOVERY_VERIFIED", pathCheckId: randomUUID(), observedAt: new Date(start + 200).toISOString() }
const mac = (value: unknown, kind: string) => security.privateSecretFingerprint(security.fingerprint(value), "route-ai-scoped-recovery-" + kind + "-v1")
await pool.query("UPDATE mcp_routing_reservations SET binding_sealed=$2,binding_proof=$3,state_sealed=$4,state_proof=$5,revision=$6,deadline=$7,created_at=$8 WHERE id=$1", [reservationId, await security.encryptSecret(JSON.stringify(binding)), bindingProof, await security.encryptSecret(JSON.stringify(state)), stateProof, state.revision, until, binding.createdAt])
await pool.query("UPDATE mcp_routing_reservation_slots SET state='spent',created_at=$2 WHERE reservation_id=$1", [reservationId, binding.createdAt])
await pool.query(`UPDATE mcp_scoped_recovery_intents SET intent_sealed=$2,intent_proof=$3,state='verified',slot_phase='reserved-attempt',source_configuration_proof=$4,deadline=$5,created_at=$6,
inverse_intent_sealed=$7,inverse_intent_proof=$8,inverse_configuration_sealed=$9,inverse_configuration_proof=$10,verified_sealed=$11,verified_proof=$12 WHERE reservation_id=$1`,
[reservationId, await security.encryptSecret(JSON.stringify(packet)), await security.privateSecretFingerprint(security.fingerprint(packet), "routing-reservation-shared-slot-v1"), state.outcome.configurationProof, until, binding.createdAt,
await security.encryptSecret(JSON.stringify(intent)), await mac(intent, "intent"), await security.encryptSecret(JSON.stringify(config)), await mac(config, "configuration"), await security.encryptSecret(JSON.stringify(verified)), await mac(verified, "verified")])
assert(Date.parse(until) < Date.now())
await replaceFixtureAnchor(reservationId, bindingProof, binding.createdAt)
assert.equal((await charged()).reservedCharges, 2)
await pool.query("UPDATE mcp_scoped_recovery_intents SET verified_proof=$2 WHERE reservation_id=$1", [reservationId, "0".repeat(64)])
await assert.rejects(charged)
} finally { await restore() }
// RR sees the original coherent catalog despite a real concurrent COMMIT
// moving its raw parent after profile snapshot establishment.
const rr = await fixture(), rrSource = await rr.makeSource(), rrAllocation = await store.reserve(rrSource.operationId)
let committed = false
const rrStore = createRoutingReservationStore(async () => {
const db = await pool.connect(), query = db.query.bind(db)
return { query: async (...args: unknown[]) => {
const result = await (query as (...values: unknown[]) => Promise<unknown>)(...args)
if (String(args[0]).includes("clock_timestamp() AS observed_at FROM mcp_routing_profiles")) {
await pool.query("UPDATE mcp_routing_reservations SET profile_id=$2 WHERE id=$1", [rrAllocation.reservationId, foreign.profileId]); committed = true
}
return result
}, release: (destroy?: boolean) => db.release(destroy) } as unknown as PoolClient
})
try {
assert.equal((await rrStore.readHourlyCharges(rr.profileId, rr.principal)).reservedCharges, 2)
assert.equal(committed, true)
await assert.rejects(store.readHourlyCharges(rr.profileId, rr.principal))
} finally { await pool.query("UPDATE mcp_routing_reservations SET profile_id=$2 WHERE id=$1", [rrAllocation.reservationId, rr.profileId]) }
// Historical boundary uses real stored timestamps/signed binding. Only
// rows older than the complete hour window (all references) disappear.
try {
const old = new Date(Date.now() - 3601000).toISOString(), binding = { ...JSON.parse(await security.decryptSecret(original.binding_sealed)), createdAt: old }
const bindingProof = await security.privateSecretFingerprint(security.fingerprint(binding), "routing-reservation-binding-v1")
const state = JSON.parse(await security.decryptSecret(original.state_sealed))
const stateProof = await security.privateSecretFingerprint(security.fingerprint({ bindingProof, state }), "routing-reservation-state-v1")
const packet = { phase: "reservation-held", reservationId, bindingProof, stateProof }
await pool.query("UPDATE mcp_routing_reservations SET binding_sealed=$2,binding_proof=$3,state_proof=$4,created_at=$5 WHERE id=$1", [reservationId, await security.encryptSecret(JSON.stringify(binding)), bindingProof, stateProof, old])
await pool.query("UPDATE mcp_routing_reservation_slots SET created_at=$2 WHERE reservation_id=$1", [reservationId, old])
await pool.query("UPDATE mcp_scoped_recovery_intents SET intent_sealed=$2,intent_proof=$3,created_at=$4 WHERE reservation_id=$1", [reservationId, await security.encryptSecret(JSON.stringify(packet)), await security.privateSecretFingerprint(security.fingerprint(packet), "routing-reservation-shared-slot-v1"), old])
await replaceFixtureAnchor(reservationId, bindingProof, old)
assert.equal((await charged()).reservedCharges, 0)
assert.equal((await charged()).legacyCharges, 2)
} finally { await restore() }
const beforeRead = (await pool.query("SELECT count(*)::int AS n FROM mcp_operation_steps WHERE operation_id=$1", [source.operationId])).rows[0].n
await charged()
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_operation_steps WHERE operation_id=$1", [source.operationId])).rows[0].n, beforeRead)
assert.equal(await used(f.connectionId), 2, "Read-only projection never allocates/debits/refunds")
await assert.rejects(store.readHourlyCharges(randomUUID(), historicalPrincipal))
// Actual access change after snapshot COMMIT; proxy observes actual SQL,
// never substitutes a row, signer, authority or crypto result.
const lateStore = createRoutingReservationStore(async () => {
const db = await pool.connect(), query = db.query.bind(db)
return { query: async (...args: unknown[]) => {
const result = await (query as (...values: unknown[]) => Promise<unknown>)(...args)
if (args[0] === "COMMIT") await pool.query("UPDATE mcp_credentials SET revoked_at=now() WHERE id=$1", [newerId])
return result
}, release: (destroy?: boolean) => db.release(destroy) } as unknown as PoolClient
})
try { await assert.rejects(lateStore.readHourlyCharges(f.profileId, historicalPrincipal)) }
finally { await pool.query("UPDATE mcp_credentials SET revoked_at=NULL WHERE id=$1", [newerId]) }
const files = await import("node:fs/promises"), paths = await import("node:path")
const keyPath = paths.join(security.mcpStateDirectory(), "encryption-key"), heldKey = keyPath + ".owned-hourly-" + randomUUID()
let keyHeld = false
const missingKeyStore = createRoutingReservationStore(async () => {
const db = await pool.connect(), query = db.query.bind(db)
return { query: async (...args: unknown[]) => {
const result = await (query as (...values: unknown[]) => Promise<unknown>)(...args)
if (args[0] === "COMMIT") { await files.rename(keyPath, heldKey); keyHeld = true }
return result
}, release: (destroy?: boolean) => db.release(destroy) } as unknown as PoolClient
})
try {
await assert.rejects(missingKeyStore.readHourlyCharges(f.profileId, historicalPrincipal))
await assert.rejects(files.access(keyPath), "Historical read must not bootstrap missing encryption key")
} finally {
if (keyHeld) { await files.rm(keyPath, { force: true }); await files.rename(heldKey, keyPath) }
}
const deadlineStore = createRoutingReservationStore(async () => {
const db = await pool.connect(), query = db.query.bind(db)
return { query: async (...args: unknown[]) => {
const result = await (query as (...values: unknown[]) => Promise<unknown>)(...args)
if (args[0] === "COMMIT") await new Promise(done => setTimeout(done, 10050))
return result
}, release: (destroy?: boolean) => db.release(destroy) } as unknown as PoolClient
})
await assert.rejects(deadlineStore.readHourlyCharges(f.profileId, historicalPrincipal), /Hourly ledger read expired/)
names.push("hourly positive historical RECOVERY_VERIFIED production-crypto fixture expired but charged; tampered verified proof refused",
"hourly real parallel COMMIT cannot tear repeatable-read integrity snapshot",
"hourly old complete history window excluded; future drift and actual 10s publication expiry refused")
names.push("hourly authenticated legacy overlap/expired grant/revoked original credential remains charged", "hourly MAC/slot/shared/orphan/size tamper whole refusal", "hourly all charged states and original source inverse slot; no debit or native receipt")
names.push("concurrent exact-fit single reservation/shared source-step slot", "new-credential read never allocates")
}
{
const f = await fixture(2, 2), source = await f.makeSource()
await pool.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'mutations',date_trunc('hour',now()),1)", [f.connectionId])
await assert.rejects(store.reserve(source.operationId), /mutation budget/)
assert.equal(await used(f.connectionId), 1)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservations WHERE source_operation_id=$1", [source.operationId])).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_scoped_recovery_intents WHERE source_operation_id=$1", [source.operationId])).rows[0].n, 0)
names.push("short by one connection mutation rolls back all allocations")
}
{
const f = await fixture(10, 3), first = await f.makeSource(), second = await f.makeSource()
await store.reserve(first.operationId); await assert.rejects(store.reserve(second.operationId), /profile switch slots/)
assert.equal(await used(f.connectionId), 2)
names.push("short by one rolling-hour profile slot across source operations")
}
{
const f = await fixture(10, 3), source = await f.makeSource()
await pool.query("UPDATE mcp_routing_profiles SET state=jsonb_build_object('switches',jsonb_build_array(to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'),to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'))) WHERE id=$1", [f.profileId])
await assert.rejects(store.reserve(source.operationId), /profile switch slots/)
assert.equal(await used(f.connectionId), 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservations WHERE source_operation_id=$1", [source.operationId])).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservation_slots WHERE profile_id=$1", [f.profileId])).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_scoped_recovery_intents WHERE source_operation_id=$1", [source.operationId])).rows[0].n, 0)
names.push("legacy recent two plus held two exceeds max three without debit")
}
{
const f = await fixture(), source = await f.makeSource()
for (const history of [{ switches: ["invalid"] }, { switches: [new Date(Date.now() + 3600000).toISOString()] }, { switches: Array(2049).fill(new Date().toISOString()) }, { unrelated: "x".repeat(131073) }]) {
await pool.query("UPDATE mcp_routing_profiles SET state=$2::jsonb WHERE id=$1", [f.profileId, JSON.stringify(history)])
if ("unrelated" in history) {
await assert.rejects(store.reserve(source.operationId), (error: unknown) => error instanceof security.McpError && error.code === "STATE_CONFLICT" && error.statusCode === 409 && error.message === "Постоянный допуск профиля маршрутизации недоступен или изменён")
} else await assert.rejects(store.reserve(source.operationId), /legacy profile switch history/i)
assert.equal(await used(f.connectionId), 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservation_slots WHERE profile_id=$1", [f.profileId])).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservations WHERE source_operation_id=$1", [source.operationId])).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_scoped_recovery_intents WHERE source_operation_id=$1", [source.operationId])).rows[0].n, 0)
}
names.push("malformed future oversized legacy histories refuse with zero allocations")
}
{
const f = await fixture(), source = await f.makeSource(); let injected = false
const lateStore = createRoutingReservationStore(async () => {
const client = await pool.connect(), original = client.query.bind(client)
return { query: async (...args: unknown[]) => {
if (!injected && typeof args[0] === "string" && args[0].includes("SELECT id FROM mcp_routing_profiles")) { injected = true; await pool.query("UPDATE mcp_routing_profiles SET version=version+1 WHERE id=$1", [f.profileId]) }
return (original as (...values: unknown[]) => Promise<unknown>)(...args)
}, release: (destroy: boolean) => client.release(destroy) } as unknown as PoolClient
})
await assert.rejects(lateStore.reserve(source.operationId)); assert.equal(injected, true); assert.equal(await used(f.connectionId), 0)
names.push("late persistent authority edit before admission leaves zero charge")
}
{
const f = await fixture(), source = await f.makeSource(), destroyed: boolean[] = []; let commitSent = false
const uncertain = createRoutingReservationStore(async () => {
const client = await pool.connect(), original = client.query.bind(client)
return { query: async (...args: unknown[]) => {
assert(!(commitSent && args[0] === "ROLLBACK"), "No rollback after uncertain COMMIT")
const result = await (original as (...values: unknown[]) => Promise<unknown>)(...args)
if (args[0] === "COMMIT") { commitSent = true; throw Error("Owned synthetic lost COMMIT ACK") }
return result
}, release: (destroy: boolean) => { destroyed.push(destroy); client.release(destroy) } } as unknown as PoolClient
})
await assert.rejects(uncertain.reserve(source.operationId), RoutingReservationCommitUnknown)
assert.deepEqual(destroyed, [true]); assert.equal(await used(f.connectionId), 2)
const id = (await pool.query("SELECT id FROM mcp_routing_reservations WHERE source_operation_id=$1", [source.operationId])).rows[0].id
assert.equal((await store.read(id, f.principal)).state.forward, "held")
const restarted = createRoutingReservationStore()
assert.equal((await restarted.reserve(source.operationId)).forwardAllocation, undefined)
await assert.rejects(restarted.beginForwardAttempt(JSON.parse(JSON.stringify(id))), /capability/)
await assert.rejects(restarted.beginForwardAttempt(JSON.parse('{"kind":"routing-reserved-forward-allocation"}')), /capability/)
assert.equal((await store.read(id, f.principal)).state.forward, "held")
assert.equal(await used(f.connectionId), 2)
names.push("lost COMMIT ACK destroys owner; no forward capability after read or repeated reserve")
}
{
const f = await fixture(), source = await f.makeSource(), reservation = await store.reserve(source.operationId)
await pool.query("UPDATE mcp_operations SET state='running' WHERE id=$1", [source.operationId])
await pool.query("INSERT INTO mcp_operation_steps(operation_id,step_index,state,intended_state) VALUES($1,0,'intent',$2::jsonb)", [source.operationId, JSON.stringify(security.redact({ kind: "service", service: "routing.community.scoped", input: source.input }))])
assert(reservation.forwardAllocation)
await assert.rejects(assertAcknowledgedRoutingForwardAttempt(reservation.forwardAllocation, source.operationId, f.principal), /No acknowledged/)
await store.beginForwardAttempt(reservation.forwardAllocation)
assert.equal(await assertAcknowledgedRoutingForwardAttempt(reservation.forwardAllocation, source.operationId, f.principal), Date.parse(reservation.deadline))
await assert.rejects(assertAcknowledgedRoutingForwardAttempt(JSON.parse(JSON.stringify(reservation.forwardAllocation)), source.operationId, f.principal), /No acknowledged/)
await assert.rejects(assertAcknowledgedRoutingForwardAttempt(reservation.forwardAllocation, randomUUID(), f.principal), /attempt changed/)
await assert.rejects(store.beginForwardAttempt(reservation.forwardAllocation), /capability/)
await assert.rejects(store.recordForwardOutcome(reservation.reservationId), /CONFIG_APPLIED/)
await assert.rejects(store.proveUnusedInverse(reservation.reservationId), /terminal applied/)
assert.equal((await store.read(reservation.reservationId, f.principal)).state.outcome, undefined)
assert.equal((await store.read(reservation.reservationId, f.principal)).state.inverse, "held")
await store.markUnknown(reservation.reservationId, "forward")
await assert.rejects(assertAcknowledgedRoutingForwardAttempt(reservation.forwardAllocation, source.operationId, f.principal), /attempt changed/)
assert.equal((await store.read(reservation.reservationId, f.principal)).state.forward, "unknown")
assert.equal(await used(f.connectionId), 2)
await assert.rejects(store.beginForwardAttempt(reservation.forwardAllocation), /capability/)
names.push("spent forward/no genuine checkpoint and preterminal unused-proof refuse; unknown never replays or refunds")
}
if (options.runtimeAdmission) {
const f = await fixture(), source = await f.makeSource(), reservation = await store.reserve(source.operationId)
assert(reservation.forwardAllocation)
await pool.query("UPDATE mcp_operations SET state='running' WHERE id=$1", [source.operationId])
const changedIntent = security.redact({ kind: "service", service: "routing.community.scoped", input: { ...source.input, receiptId: randomUUID() } })
await pool.query("INSERT INTO mcp_operation_steps(operation_id,step_index,state,intended_state) VALUES($1,0,'intent',$2::jsonb)",
[source.operationId, JSON.stringify(changedIntent)])
await assert.rejects(store.beginForwardAttempt(reservation.forwardAllocation), /No exact running reserved intent/)
assert.deepEqual((await store.read(reservation.reservationId, f.principal)).state, reservation.state)
assert.equal(await used(f.connectionId), 2)
names.push("running operation with changed generic intent refuses reserved spend without changing held slots or charge")
}
{
const f = await fixture(), source = await f.makeSource(), reservation = await store.reserve(source.operationId)
const { loadScopedNetworkCheckpoint, saveScopedConfigurationCheckpoint, saveScopedNetworkCheckpoint } = await import("./routing-community-scoped-checkpoint.js")
const { unknownOriginalEffects } = await import("./routing-original-effects.js")
await pool.query("UPDATE mcp_operations SET state='running' WHERE id=$1", [source.operationId])
const step = { kind: "service", service: "routing.community.scoped", input: source.input }
await pool.query("INSERT INTO mcp_operation_steps(operation_id,step_index,state,intended_state) VALUES($1,0,'intent',$2::jsonb)",
[source.operationId, JSON.stringify(security.redact(step))])
await pool.query("INSERT INTO mcp_operation_checkpoints(operation_id,step_index,before_sealed) VALUES($1,0,$2)",
[source.operationId, await security.encryptSecret(JSON.stringify(source.input.beforeRules))])
assert(reservation.forwardAllocation)
await store.beginForwardAttempt(reservation.forwardAllocation)
// Use the actual checkpoint writers for production crypto and SQL, but
// deliberately seed a synthetic failed-forward observation. No PATCH
// or genuine network observation is part of this owned component case.
const requestSeal = String(source.input.requestProof)
const configuration = await saveScopedConfigurationCheckpoint(source.input, requestSeal)
const effects = unknownOriginalEffects("authenticated-log-interval-coverage-unsupported")
await assert.rejects(saveScopedNetworkCheckpoint(source.input, requestSeal, { id: randomUUID(), candidateId: "b",
status: "failed", observedAt: configuration.observedAt }, "0".repeat(64), effects), { code: "STATE_CONFLICT" })
const editor = await pool.connect()
const check = { id: randomUUID(), candidateId: "b", status: "failed" as const, observedAt: configuration.observedAt }
let publication: Promise<void> | undefined
try {
await editor.query("BEGIN")
await editor.query("UPDATE mcp_operation_checkpoints SET configuration_proof=$2 WHERE operation_id=$1",
[source.operationId, "0".repeat(64)])
publication = saveScopedNetworkCheckpoint(source.input, requestSeal, check, configuration.checkpointProof, effects)
void publication.catch(() => {})
const { setTimeout: delay } = await import("node:timers/promises")
const { rows: [{ pid }] } = await editor.query("SELECT pg_backend_pid() AS pid")
let waiting = false
for (let attempt = 0; attempt < 100 && !waiting; attempt++) {
const result = await pool.query("SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)) AND query LIKE '%FOR NO KEY UPDATE OF c'",
[pid])
waiting = Boolean(result.rowCount)
if (!waiting) await delay(15)
}
assert(waiting, "Network checkpoint publication must wait for the configuration row")
await editor.query("COMMIT")
await assert.rejects(publication, { code: "STATE_CONFLICT" })
} finally {
editor.release(true)
await publication?.catch(() => {})
}
assert.equal((await pool.query("SELECT 1 FROM mcp_audit WHERE action='routing.scoped.network-check' AND payload->>'receiptId'=$1",
[source.input.receiptId])).rowCount, 0)
await pool.query("UPDATE mcp_operation_checkpoints SET configuration_proof=$2 WHERE operation_id=$1",
[source.operationId, configuration.checkpointProof])
const publish = () => saveScopedNetworkCheckpoint(source.input, requestSeal, check, configuration.checkpointProof, effects)
await Promise.all([publish(), publish()])
await assert.rejects(saveScopedNetworkCheckpoint(source.input, requestSeal, { ...check, status: "passed" },
configuration.checkpointProof, effects), { code: "STATE_CONFLICT" })
assert.equal((await pool.query("SELECT 1 FROM mcp_audit WHERE action='routing.scoped.network-check' AND payload->>'receiptId'=$1",
[source.input.receiptId])).rowCount, 1)
const network = await loadScopedNetworkCheckpoint(source.input, requestSeal)
assert.equal(network?.status, "failed")
assert.deepEqual(network?.originalEffects, effects)
const before = await store.read(reservation.reservationId, f.principal)
assert.equal(before.state.forward, "spent")
assert.equal(before.state.inverse, "held")
assert.equal(before.state.outcome, undefined)
assert.equal(before.chargedMutationUnits, 2)
assert.equal(before.chargedProfileSlots, 2)
assert.equal(before.refundsAvailable, false)
const sharedSlot = async () => (await pool.query(`SELECT state,slot_phase,inverse_intent_sealed,inverse_configuration_sealed,verified_sealed
FROM mcp_scoped_recovery_intents WHERE reservation_id=$1`, [reservation.reservationId])).rows
const shared = await sharedSlot()
assert.deepEqual(shared, [{ state: "intent", slot_phase: "reservation-held", inverse_intent_sealed: null,
inverse_configuration_sealed: null, verified_sealed: null }])
for (let attempt = 0; attempt < 2; attempt++) {
await assert.rejects(store.recordForwardOutcome(reservation.reservationId), /Authenticated network evidence for automatic recovery unavailable/)
assert.deepEqual((await store.read(reservation.reservationId, f.principal)).state, before.state)
assert.deepEqual(await sharedSlot(), shared)
}
await assert.rejects(store.proveUnusedInverse(reservation.reservationId), /terminal applied/)
assert.equal(await used(f.connectionId), 2)
assert.equal((await store.readHourlyCharges(f.profileId, f.principal)).reservedCharges, 2)
names.push("signed synthetic failed-control checkpoint with REST-only unknown log coverage cannot create an inverse allocation or outcome; original shared slot and both charges stay held without refund")
}
{
const f = await fixture(), source = await f.makeSource(), reservation = await store.reserve(source.operationId)
const saved = (await pool.query("SELECT state_proof FROM mcp_routing_reservations WHERE id=$1", [reservation.reservationId])).rows[0].state_proof
await pool.query("UPDATE mcp_routing_reservations SET state_proof=$2 WHERE id=$1", [reservation.reservationId, "f".repeat(64)])
await assert.rejects(store.read(reservation.reservationId, f.principal), /tampering/)
await pool.query("UPDATE mcp_routing_reservations SET state_proof=$2 WHERE id=$1", [reservation.reservationId, saved])
await pool.query("UPDATE mcp_scoped_recovery_intents SET state='unknown' WHERE source_operation_id=$1", [source.operationId])
assert.equal((await store.read(reservation.reservationId, f.principal)).sharedSlotQuarantined, true)
assert(reservation.forwardAllocation)
await assert.rejects(store.beginForwardAttempt(reservation.forwardAllocation), /quarantined/)
names.push("signed ledger tamper and external shared-slot quarantine fail closed")
}
if (options.runtimeAdmission) {
const { applyPlan, loadPlan } = await import("./runtime.js")
const { withSystemDatabaseOperationLock } = await import("../../db/operation-lock.js")
const { lockRoutingReservationAdmissionSource } = await import("./routing-reservation-runtime.js")
const emptyAllocations = async (f: Awaited<ReturnType<typeof fixture>>, planId: string) => {
assert.equal(await used(f.connectionId), 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_operations WHERE plan_id=$1", [planId])).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservations WHERE profile_id=$1", [f.profileId])).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservation_slots WHERE profile_id=$1", [f.profileId])).rows[0].n, 0)
}
{
const f = await fixture(2, 2), source = await f.makeSource(false), key = randomUUID()
await withSystemDatabaseOperationLock(() => pool.connect(), async () => {
await assert.rejects(applyPlan(f.principal, source.planId, key), { code: "PROTOCOL_STORAGE_BUSY" })
await emptyAllocations(f, source.planId)
})
const operation = await applyPlan(f.principal, source.planId, key)
await new Promise(resolve => setTimeout(resolve, 30))
assert.equal((await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [operation.id])).rows[0].state, "pending", "Reserved native dispatch remains gated")
assert.equal(await used(f.connectionId), 2, "Runtime must not double-charge the store debit")
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservation_slots WHERE profile_id=$1", [f.profileId])).rows[0].n, 2)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_scoped_recovery_intents WHERE source_operation_id=$1", [operation.id])).rows[0].n, 1)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_operation_steps WHERE operation_id=$1", [operation.id])).rows[0].n, 0)
assert.equal((await applyPlan(f.principal, source.planId, key)).id, operation.id)
assert.equal(await used(f.connectionId), 2)
assert.equal((await store.readHourlyCharges(f.profileId, f.principal)).reservedCharges, 2)
const auditCount = await pool.query("SELECT count(*)::int AS n FROM mcp_audit WHERE connection_id=$1 AND action='routing.charge.admitted'", [f.connectionId])
assert.equal(auditCount.rows[0].n, 1, "Idempotent replay retains one audit witness for both slots")
const owner = await pool.connect()
try {
await owner.query("BEGIN")
// An owned disposable database only. Simulate erasure outside the ordinary trigger protections.
for (const table of ["mcp_scoped_recovery_intents", "mcp_routing_reservation_slots", "mcp_routing_reservations"])
await owner.query(`ALTER TABLE ${table} DISABLE TRIGGER USER`)
await owner.query("DELETE FROM mcp_scoped_recovery_intents WHERE source_operation_id=$1", [operation.id])
await owner.query("DELETE FROM mcp_routing_reservation_slots WHERE profile_id=$1", [f.profileId])
await owner.query("DELETE FROM mcp_routing_reservations WHERE source_operation_id=$1", [operation.id])
const current = await (await import("./store.js")).effectiveMcpConnection(f.principal, owner)
await assert.rejects(readHistoricalChargesWithinOwner(owner, f.profileId, current, undefined, Date.now() + 10000), /не совпал с журналом допуска/)
} finally {
try { await owner.query("ROLLBACK") } finally { owner.release() }
}
assert.equal((await store.readHourlyCharges(f.profileId, f.principal)).reservedCharges, 2)
names.push("surviving signed audit refuses an erased reservation family and rollback restores both original slots")
names.push("actual reserved apply refuses during database maintenance without allocating, then records one two-unit hold and returns the same ID on replay without dispatch")
}
for (const scenario of ["short-budget", "cancelled", "authority-disabled"] as const) {
const f = await fixture(scenario === "short-budget" ? 1 : 10), source = await f.makeSource(false)
if (scenario === "cancelled") await pool.query("UPDATE mcp_plans SET state='cancelled' WHERE id=$1", [source.planId])
if (scenario === "authority-disabled") await pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=$1", [f.profileId])
await assert.rejects(applyPlan(f.principal, source.planId, randomUUID()))
await emptyAllocations(f, source.planId)
names.push("actual applyPlan " + scenario + " refuses before operation/budget/profile/shared allocations")
}
{
const f = await fixture(2, 2), source = await f.makeSource(false), released: boolean[] = [], statements: string[] = []
const connect = async () => {
const client = await pool.connect(), original = client.query.bind(client)
let commitSent = false
return { query: async (...args: unknown[]) => {
const sql = String(args[0]); statements.push(sql)
assert(!(commitSent && sql === "ROLLBACK"), "Unknown outer COMMIT must never roll back")
const result = await (original as (...values: unknown[]) => Promise<unknown>)(...args)
if (sql === "COMMIT") { commitSent = true; throw Error("Owned outer admission COMMIT ACK lost") }
return result
}, release: (destroy: boolean) => { released.push(destroy); client.release(destroy) } } as unknown as PoolClient
}
await assert.rejects(withRoutingReservationAdmission(async (db, reserve) => {
await db.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [f.connectionId])
await lockRoutingReservationAdmissionSource(db, await loadPlan(source.planId, db), f.principal)
await db.query("INSERT INTO mcp_operations(id,plan_id,connection_id,idempotency_key,state) VALUES($1,$2,$3,$4,'pending')", [source.operationId, source.planId, f.connectionId, randomUUID()])
await db.query("UPDATE mcp_plans SET state='executing' WHERE id=$1", [source.planId])
await reserve(source.operationId)
}, connect), RoutingReservationCommitUnknown)
assert.deepEqual(released, [true]); assert.equal(statements.filter(sql => sql === "BEGIN").length, 1); assert.equal(statements.filter(sql => sql === "COMMIT").length, 1)
assert.equal(statements.filter(sql => sql.startsWith("INSERT INTO mcp_budget_buckets")).length, 1)
assert.equal(await used(f.connectionId), 2)
const restarted = createRoutingReservationStore(), repeated = await restarted.reserve(source.operationId)
assert.equal(repeated.forwardAllocation, undefined)
assert.equal((await restarted.read(repeated.reservationId, f.principal)).state.forward, "held")
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_operation_steps WHERE operation_id=$1", [source.operationId])).rows[0].n, 0)
names.push("owned outer admission lost actual COMMIT ACK retains atomic operation/hold and emits no forward capability")
}
}
// Same-owner admission consumes the authenticated OBSERVED historical rows,
// not public read access or a second client/transaction. No full-catalog
// deletion anchor, new writer registration or native recovery is claimed.
{
const f = await fixture(10, 4), first = await f.makeSource(), old = await store.reserve(first.operationId), next = await f.makeSource()
const row = (await pool.query("SELECT * FROM mcp_routing_reservations WHERE id=$1", [old.reservationId])).rows[0]
const inverse = (await pool.query("SELECT * FROM mcp_routing_reservation_slots WHERE reservation_id=$1 AND lane='inverse'", [old.reservationId])).rows[0]
const snapshot = async () => ({
used: await used(f.connectionId),
allocations: security.fingerprint((await pool.query("SELECT COALESCE(jsonb_agg(to_jsonb(r) ORDER BY r.id),'[]'::jsonb) AS rows FROM mcp_routing_reservations r WHERE connection_id=$1", [f.connectionId])).rows[0].rows),
slots: security.fingerprint((await pool.query("SELECT COALESCE(jsonb_agg(to_jsonb(s) ORDER BY s.reservation_id,s.lane),'[]'::jsonb) AS rows FROM mcp_routing_reservation_slots s WHERE profile_id=$1", [f.profileId])).rows[0].rows),
shared: security.fingerprint((await pool.query("SELECT COALESCE(jsonb_agg(to_jsonb(s) ORDER BY s.source_operation_id,s.source_step_index),'[]'::jsonb) AS rows FROM mcp_scoped_recovery_intents s WHERE authority_profile_id=$1", [f.profileId])).rows[0].rows),
})
const denials: { before: Awaited<ReturnType<typeof snapshot>>; after: Awaited<ReturnType<typeof snapshot>>; unchanged: true }[] = []
const unchangedRefusal = async (operationId: string, pattern?: RegExp) => {
const before = await snapshot()
if (pattern) await assert.rejects(store.reserve(operationId), pattern)
else await assert.rejects(store.reserve(operationId))
const after = await snapshot()
assert.deepEqual(after, before, "Denied admission must preserve full allocation/slot/shared rows and mutation debit")
denials.push({ before, after, unchanged: true })
}
await pool.query("UPDATE mcp_routing_reservations SET binding_proof=$2 WHERE id=$1", [old.reservationId, "0".repeat(64)])
try { await unchangedRefusal(next.operationId, /tampering/) }
finally { await pool.query("UPDATE mcp_routing_reservations SET binding_proof=$2 WHERE id=$1", [old.reservationId, row.binding_proof]) }
await pool.query("DELETE FROM mcp_routing_reservation_slots WHERE reservation_id=$1 AND lane='inverse'", [old.reservationId])
try { await unchangedRefusal(next.operationId, /allocation ledger/) }
finally { await pool.query("INSERT INTO mcp_routing_reservation_slots(reservation_id,profile_id,lane,state,created_at) VALUES($1,$2,$3,$4,$5)", [inverse.reservation_id, inverse.profile_id, inverse.lane, inverse.state, inverse.created_at]) }
const shared = (await pool.query("SELECT intent_proof FROM mcp_scoped_recovery_intents WHERE reservation_id=$1", [old.reservationId])).rows[0]
await pool.query("UPDATE mcp_scoped_recovery_intents SET intent_proof=$2 WHERE reservation_id=$1", [old.reservationId, "0".repeat(64)])
try { await unchangedRefusal(next.operationId, /allocation proof/) }
finally { await pool.query("UPDATE mcp_scoped_recovery_intents SET intent_proof=$2 WHERE reservation_id=$1", [old.reservationId, shared.intent_proof]) }
await pool.query("UPDATE mcp_routing_profiles SET state=$2::jsonb WHERE id=$1", [f.profileId, JSON.stringify({ switches: [row.created_at.toISOString()] })])
try { await unchangedRefusal(next.operationId, /profile switch slots/) }
finally { await pool.query("UPDATE mcp_routing_profiles SET state='{}'::jsonb WHERE id=$1", [f.profileId]) }
// A signed historical expired deadline remains charged. This does not
// grant execution and never calls live() for historical allocations.
const binding = { ...JSON.parse(await security.decryptSecret(row.binding_sealed)), deadline: new Date(Date.now() - 1000).toISOString() }
const bindingProof = await security.privateSecretFingerprint(security.fingerprint(binding), "routing-reservation-binding-v1")
const state = JSON.parse(await security.decryptSecret(row.state_sealed))
const stateProof = await security.privateSecretFingerprint(security.fingerprint({ bindingProof, state }), "routing-reservation-state-v1")
const packet = { phase: "reservation-held", reservationId: old.reservationId, bindingProof, stateProof }
await pool.query("UPDATE mcp_routing_reservations SET binding_sealed=$2,binding_proof=$3,state_proof=$4,deadline=$5 WHERE id=$1", [old.reservationId, await security.encryptSecret(JSON.stringify(binding)), bindingProof, stateProof, binding.deadline])
await pool.query("UPDATE mcp_scoped_recovery_intents SET intent_sealed=$2,intent_proof=$3,deadline=$4 WHERE reservation_id=$1", [old.reservationId, await security.encryptSecret(JSON.stringify(packet)), await security.privateSecretFingerprint(security.fingerprint(packet), "routing-reservation-shared-slot-v1"), binding.deadline])
await replaceFixtureAnchor(old.reservationId, bindingProof, binding.createdAt)
// Renew actual current profile/credential authority. Old credential and
// original grant/version do not reset the charge of the old allocation.
const newCredential = randomUUID(), expiry = new Date(Date.now() + 540000).toISOString()
await pool.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [newCredential, f.connectionId, randomUUID(), expiry])
await pool.query("UPDATE mcp_credentials SET revoked_at=now() WHERE id=$1", [f.credentialId])
await pool.query("UPDATE mcp_routing_profiles SET grant_expires_at=now()-interval '1 second',enabled=false WHERE id=$1", [f.profileId])
await pool.query("UPDATE mcp_routing_profiles SET grant_expires_at=$2,credential_id=$3,version=version+1,enabled=true WHERE id=$1", [f.profileId, expiry, newCredential])
const currentProfile = (await pool.query("SELECT config,version FROM mcp_routing_profiles WHERE id=$1", [f.profileId])).rows[0]
const owner = (await pool.query("SELECT owner_id FROM mcp_connections WHERE id=$1", [f.connectionId])).rows[0].owner_id
const principal = { ...f.principal, credentialId: newCredential, credentialExpiresAt: expiry }
const authority = await resolveRoutingProfileAuthority({ profileId: f.profileId, expectedVersion: currentProfile.version, profile: routeAiProfileSchema.parse(currentProfile.config), principal, ownerId: owner, transport: { contextSources } })
const plan = (await pool.query("SELECT evidence FROM mcp_plans WHERE id=$1", [next.planId])).rows[0]
const evidence = JSON.parse(await security.decryptSecret(plan.evidence.sealed))
const { requestProof: _oldRequest, ...input } = evidence.steps[0].input
Object.assign(input, { principal, persistentProfileAuthority: authority })
input.requestProof = await security.privateSecretFingerprint(security.fingerprint(input), "route-ai-scoped-request-v3")
evidence.steps[0].input = input
await pool.query("UPDATE mcp_plans SET evidence=$2::jsonb WHERE id=$1", [next.planId, JSON.stringify({ sealed: await security.encryptSecret(JSON.stringify(evidence)) })])
const statements: string[] = [], pids = new Set<number>()
const traced = createRoutingReservationStore(async () => {
const db = await pool.connect(), query = db.query.bind(db); pids.add(Number((await db.query("SELECT pg_backend_pid() AS pid")).rows[0].pid))
return { query: async (...args: unknown[]) => { statements.push(String(args[0])); return (query as (...values: unknown[]) => Promise<unknown>)(...args) },
release: (destroy?: boolean) => db.release(destroy) } as unknown as PoolClient
})
await traced.reserve(next.operationId)
assert.equal(pids.size, 1)
assert.equal(statements.filter(sql => sql === "BEGIN").length, 1); assert.equal(statements.filter(sql => sql === "COMMIT").length, 1)
const profileLock = statements.findIndex(sql => sql === "SELECT id FROM mcp_routing_profiles WHERE id=$1 FOR UPDATE")
const authenticatedRead = statements.findIndex(sql => sql.includes("AS wanted ORDER BY id LIMIT 12"))
const debit = statements.findIndex(sql => sql.startsWith("INSERT INTO mcp_budget_buckets"))
assert(profileLock >= 0 && authenticatedRead > profileLock && debit > authenticatedRead)
assert.equal(await used(f.connectionId), 4)
assert.equal((await store.readHourlyCharges(f.profileId, principal)).reservedCharges, 4)
const over = await f.makeSource() // Original credential is revoked: still no bypass.
await unchangedRefusal(over.operationId)
assert.equal(await used(f.connectionId), 4)
const traceFiles = await import("node:fs/promises")
await traceFiles.writeFile(resolve(process.env.MCP_STATE_DIR!, "..", "owner-admission-query-trace.json"), JSON.stringify({
pids: [...pids], statements, profileLock, authenticatedRead, debit,
beginCount: statements.filter(sql => sql === "BEGIN").length, commitCount: statements.filter(sql => sql === "COMMIT").length,
denials, sourceOwnerOnly: true, publicReadLaneUsedForAdmission: false, nativeRequests: 0,
}, null, 2))
names.push("same-owner admission rejects prior MAC/slot/shared tamper before new debit", "same-owner legacy overlap charged without timestamp dedup",
"same-owner renewed authority and expired historical allocation retain four charges under one transaction/profile lock")
}
}
if (options.commonAdmissionOnly && !options.forwardChargeOnly) {
// Non-reserved persistent forward must join the SAME existing owner lock
// order without acquiring the reserved debit/capability or native rights.
const { lockRoutingReservationAdmissionSource } = await import("./routing-reservation-runtime.js")
const { loadPlan } = await import("./runtime.js")
const f = await fixture(10, 3, false), source = await f.makeSource(false)
await withRoutingReservationAdmission(async db => {
const ownerPid = Number((await db.query("SELECT pg_backend_pid() AS pid")).rows[0].pid)
await db.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [f.connectionId])
const selected = await lockRoutingReservationAdmissionSource(db, await loadPlan(source.planId, db), f.principal)
assert.equal(selected.reserved, false)
const editor = await pool.connect()
try {
assert.notEqual(Number((await editor.query("SELECT pg_backend_pid() AS pid")).rows[0].pid), ownerPid)
await editor.query("SET lock_timeout='100ms'")
await assert.rejects(editor.query("UPDATE mcp_routing_profiles SET version=version+1 WHERE id=$1", [f.profileId]), (error: unknown) => (error as { code?: string }).code === "55P03")
} finally { await editor.query("RESET lock_timeout"); editor.release() }
const other = await fixture(10, 3, false), otherSource = await other.makeSource(false)
await withRoutingReservationAdmission(async separateOwner => {
await separateOwner.query("SET LOCAL lock_timeout='100ms'")
await separateOwner.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [other.connectionId])
assert.equal((await lockRoutingReservationAdmissionSource(separateOwner, await loadPlan(otherSource.planId, separateOwner), other.principal)).reserved, false)
})
assert.equal(await used(other.connectionId), 0)
})
assert.equal(await used(f.connectionId), 0)
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservations WHERE profile_id=$1", [f.profileId])).rows[0].n), 0)
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_operations WHERE plan_id=$1", [source.planId])).rows[0].n), 0)
names.push("non-reserved scoped persistent admission holds existing profile lock against concurrent editor without reserved debit/capability")
names.push("different authenticated profile and connection admit without false profile-lock contention")
await pool.query("UPDATE mcp_routing_profiles SET version=version+1 WHERE id=$1", [f.profileId])
await assert.rejects(withRoutingReservationAdmission(async db => {
await db.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [f.connectionId])
await lockRoutingReservationAdmissionSource(db, await loadPlan(source.planId, db), f.principal)
}))
assert.equal(await used(f.connectionId), 0)
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservation_slots WHERE profile_id=$1", [f.profileId])).rows[0].n), 0)
names.push("non-reserved scoped admission rejects genuinely changed profile authority with zero allocation/debit")
const renewed = await fixture(10, 4, false), oldSource = await renewed.makeSource(false)
const editor = await pool.connect()
await editor.query("BEGIN"); await editor.query("SET LOCAL lock_timeout='1s'"); await editor.query("SET LOCAL statement_timeout='5s'")
const editorPid = Number((await editor.query("SELECT pg_backend_pid() AS pid")).rows[0].pid)
await editor.query("SELECT id FROM mcp_routing_profiles WHERE id=$1 FOR UPDATE", [renewed.profileId])
const pending = withRoutingReservationAdmission(async db => {
await db.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [renewed.connectionId])
await lockRoutingReservationAdmissionSource(db, await loadPlan(oldSource.planId, db), renewed.principal)
})
let pendingError: unknown, raceError: unknown
void pending.catch(() => {})
try {
let waiting = false
for (let attempt = 0; attempt < 150; attempt++) {
waiting = (await pool.query("SELECT pid FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND $1::int=ANY(pg_blocking_pids(pid)) AND query LIKE 'SELECT id FROM mcp_routing_profiles WHERE id=%FOR UPDATE'", [editorPid])).rowCount === 1
if (waiting) break
await new Promise(resolve => setTimeout(resolve, 10))
}
assert(waiting, "The old false-plan must actually wait before current profile renewal")
// Genuine newly signed authority is resolved only AFTER this current
// metadata renewal. False/true are never simultaneously authoritative.
await editor.query("UPDATE mcp_routing_profiles SET config=jsonb_set(config,'{autoRecovery}','true'),version=version+1 WHERE id=$1", [renewed.profileId])
await editor.query("COMMIT")
} catch (error) { raceError = error; try { await editor.query("ROLLBACK") } catch { /* preserve first error */ } }
finally { editor.release(); try { await pending } catch (error) { pendingError = error } }
if (raceError) throw raceError
assert(pendingError, "Changed actual authority must refuse after the profile lock is acquired")
assert.equal(await used(renewed.connectionId), 0)
await renewed.renew()
const currentSource = await renewed.makeSource(), admitted = await store.reserve(currentSource.operationId)
assert.equal(admitted.created, true); assert(admitted.forwardAllocation)
assert.equal(await used(renewed.connectionId), 2)
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_reservation_slots WHERE profile_id=$1", [renewed.profileId])).rows[0].n), 2)
names.push("same-profile stale false-plan refuses after real owner wait and current renewal; newly authenticated auto authority retains original two-slot debit")
}
if (options.forwardChargeOnly) {
console.log(JSON.stringify({stage:"forward-runtime-created"}))
const { applyPlan } = await import("./runtime.js")
const terminal = async (id: string) => {
for (let attempt = 0; attempt < 250; attempt++) {
const value = (await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [id])).rows[0]
if (value && !["pending", "running"].includes(value.state)) return value.state as string
await new Promise(resolve => setTimeout(resolve, 20))
}
throw Error("Owned forward fixture operation did not terminate")
}
const count = async (profileId: string) => Number((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_forward_charges WHERE profile_id=$1", [profileId])).rows[0].n)
const f = await fixture(100, 4, false), source = await f.makeSource(false), key = randomUUID()
const operation = await applyPlan(f.principal, source.planId, key)
await terminal(operation.id) // Synthetic request intentionally has no native SLA witness.
const charge = (await pool.query("SELECT * FROM mcp_routing_forward_charges WHERE source_operation_id=$1", [operation.id])).rows[0]
assert(charge); assert.equal(charge.source_plan_id, source.planId); assert.equal(charge.profile_id, f.profileId)
assert.equal(charge.source_step_index, 0); assert.equal(charge.charge_units, 1)
const signed = JSON.parse(await security.decryptSecretExisting(charge.binding_sealed))
assert.equal(signed.createdAt, charge.created_at.toISOString(), "Signed charge uses the exact observed SQL time")
assert.equal(await used(f.connectionId), 2); assert.equal(await count(f.profileId), 1)
assert.equal((await applyPlan(f.principal, source.planId, key)).id, operation.id)
assert.equal(await used(f.connectionId), 2); assert.equal(await count(f.profileId), 1)
assert.equal((await store.readHourlyCharges(f.profileId, f.principal)).forwardCharges, 1)
names.push("actual runtime-created non-reserved operation atomically owns one signed SQL-time forward charge; same-key read never recharges/replays")
console.log(JSON.stringify({stage:"forward-renewed-reserved"}))
const legacyAt = (await pool.query("SELECT clock_timestamp() AS at")).rows[0].at.toISOString()
await pool.query("UPDATE mcp_routing_profiles SET config=jsonb_set(config,'{autoRecovery}','true'),version=version+1,state=jsonb_build_object('switches',jsonb_build_array($2::text)) WHERE id=$1", [f.profileId, legacyAt])
await f.renew()
const autoSource = await f.makeSource(false)
const automatic = await applyPlan(f.principal, autoSource.planId, randomUUID())
assert.equal((await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [automatic.id])).rows[0].state, "pending", "Existing reserved native dispatch stays closed")
const total = await store.readHourlyCharges(f.profileId, f.principal)
assert.equal(total.forwardCharges, 1); assert.equal(total.reservedCharges, 2); assert.equal(total.legacyCharges, 1); assert.equal(total.totalCharges, 4)
assert.equal(await used(f.connectionId), 4)
names.push("current profile renewal keeps historical forward1 plus original reserved2 plus conservative legacy1; no weak timestamp dedup")
console.log(JSON.stringify({stage:"forward-quota-and-guards"}))
const snapshot = async () => (await pool.query("SELECT jsonb_build_object('charges',(SELECT coalesce(jsonb_agg(to_jsonb(c) ORDER BY c.source_operation_id),'[]') FROM mcp_routing_forward_charges c WHERE profile_id=$1),'slots',(SELECT coalesce(jsonb_agg(to_jsonb(s) ORDER BY s.reservation_id,s.lane),'[]') FROM mcp_routing_reservation_slots s WHERE profile_id=$1),'used',(SELECT coalesce(sum(used),0) FROM mcp_budget_buckets WHERE connection_id=$2 AND kind='mutations')) AS value", [f.profileId, f.connectionId])).rows[0].value
const before = security.fingerprint(await snapshot()), deniedSource = await f.makeSource(false)
await assert.rejects(applyPlan(f.principal, deniedSource.planId, randomUUID()), (error: unknown) => error instanceof security.McpError && error.code === "STATE_CONFLICT")
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_operations WHERE plan_id=$1", [deniedSource.planId])).rows[0].n), 0)
assert.equal(security.fingerprint(await snapshot()), before)
for (const sql of ["DELETE FROM mcp_routing_forward_charges WHERE source_operation_id=$1", "UPDATE mcp_routing_forward_charges SET created_at=clock_timestamp() WHERE source_operation_id=$1"])
await assert.rejects(pool.query(sql, [operation.id]), (error: unknown) => (error as { code?: string }).code === "P0001")
await assert.rejects(pool.query("TRUNCATE mcp_routing_forward_charges"), (error: unknown) => (error as { code?: string }).code === "P0001")
assert.equal(security.fingerprint(await snapshot()), before)
names.push("over-budget runtime admission rolls back operation/debit/all rows; recent deletion/time edits/truncate cannot refund a charge")
console.log(JSON.stringify({stage:"forward-profile-delete"}))
const orphan = await fixture(100, 4, false), orphanSource = await orphan.makeSource(false)
const retained = await applyPlan(orphan.principal, orphanSource.planId, randomUUID()); await terminal(retained.id)
assert.equal(await count(orphan.profileId), 1)
await pool.query("DELETE FROM mcp_routing_profiles WHERE id=$1", [orphan.profileId])
assert.equal(await count(orphan.profileId), 1, "Profile-family deletion cannot erase retained hourly charge")
names.push("ordinary profile removal has no new lifetime FK blockage and leaves its actual operation charge retained")
console.log(JSON.stringify({stage:"forward-lost-return"}))
const lost = await fixture(100, 4, false), lostSource = await lost.makeSource(false), lostKey = randomUUID()
const observedClient = await pool.connect(), prototype = Object.getPrototypeOf(observedClient) as PoolClient
const originalQuery = prototype.query; observedClient.release()
const chargedOwners = new WeakSet<object>(); let committedReturnLost = false
// Transparent fault after the REAL charge INSERT and REAL COMMIT on its
// exact owner. No invented COMMIT, rows, operation, crypto or authority.
prototype.query = function (this: PoolClient, ...args: unknown[]) {
const sql = typeof args[0] === "string" ? args[0] : String((args[0] as { text?: unknown })?.text)
const result = (originalQuery as (...values: unknown[]) => unknown).apply(this, args)
if (!(result instanceof Promise)) return result
return result.then(value => {
if (sql.startsWith("INSERT INTO mcp_routing_forward_charges") && (args[1] as unknown[] | undefined)?.[2] === lost.profileId) chargedOwners.add(this)
if (sql === "COMMIT" && chargedOwners.has(this)) { chargedOwners.delete(this); committedReturnLost = true; throw Error("Owned actual forward admission COMMIT return lost") }
return value
})
} as PoolClient["query"]
try { await assert.rejects(applyPlan(lost.principal, lostSource.planId, lostKey), RoutingReservationCommitUnknown) }
finally { prototype.query = originalQuery }
assert(committedReturnLost)
const saved = (await pool.query("SELECT id,state,error_code,verification,result FROM mcp_operations WHERE plan_id=$1", [lostSource.planId])).rows[0]
assert(saved)
console.log(JSON.stringify({stage:"forward-lost-persistent-observation",realCommitReturnLost:committedReturnLost,
state:saved.state,errorCode:saved.error_code,verification:saved.verification,chargeCount:await count(lost.profileId),mutationUsed:await used(lost.connectionId)}))
// The REAL runtime retires its original admission on an uncertain COMMIT.
// Lower-level store-only fixtures have no such owner to quarantine them.
assert.equal(saved.state, "unknown"); assert.equal(saved.error_code, "PROCESS_INTERRUPTED"); assert.equal(saved.verification, "inconclusive")
assert.equal(saved.result.automaticRetry, false); assert.equal(saved.result.needsReview, true)
assert.equal(await count(lost.profileId), 1); assert.equal(await used(lost.connectionId), 2)
assert.equal((await applyPlan(lost.principal, lostSource.planId, lostKey)).id, saved.id)
await new Promise(resolve => setTimeout(resolve, 30))
assert.equal((await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [saved.id])).rows[0].state, "unknown")
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_operation_steps WHERE operation_id=$1", [saved.id])).rows[0].n), 0)
assert.equal(await count(lost.profileId), 1); assert.equal(await used(lost.connectionId), 2)
names.push("real forward admission COMMIT plus injected lost application return leaves one charge and no dispatch; same-key observation cannot replay")
}
return { cases: names.length, names, actualSql: true, productionHmac: true, sourcePlans: "synthetic encrypted source and historical recovery receipt fixtures; no native recovery or genuine network checkpoint claimed",
numberedSchemaEnrollment: true, schemaMigration: "0040_mcp_routing_reservations", proposalDdlOnly: false, runtimeRegistered: false, runtimeAdmissionAccepted: !!options.runtimeAdmission, reservedNativeDispatchEnabled: false,
nativeRequests: 0, refundsAvailable: false, fullReservedInverseLifecycleAccepted: false }
} finally {
if (profileIds.length) await pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=ANY($1::uuid[])", [profileIds])
if (ids.length) await pool.query("UPDATE servers SET enabled=false WHERE id=ANY($1::int[])", [ids])
await pool.query("UPDATE mcp_settings SET enabled=$1 WHERE id=1", [previousEnabled])
}
}