Files
MikrotikManager/backend/src/services/server-poll-storage.sql.test.ts
T

223 lines
24 KiB
TypeScript

import assert from "node:assert/strict"
import { createHash,randomUUID } from "node:crypto"
import { MIGRATION_MANIFEST } from "../db/migration-manifest.js"
import { readFile,writeFile } from "node:fs/promises"
import { basename,dirname,resolve } from "node:path"
import type { ProbeStorageSql,ProbeStorageOptions } from "./server-probe-journal-maintenance.js"
import type { PollStorageScope } from "./server-poll-storage-model.js"
assert.equal(process.env.MMAPP_OWN_SERVER_POLL_STORAGE,"true")
const endpoint=new URL(process.env.DATABASE_URL??"")
assert.equal(endpoint.hostname,"127.0.0.1");assert.equal(endpoint.pathname,"/postgres")
assert(process.env.MCP_STATE_DIR&&basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-"))
const {pool,closePool}=await import("../db/index.js")
const {applyLegacyPollStorageFixtureMigrations:applySqlMigrations}=await import("../db/legacy-poll-storage-fixture.js")
const {connectProbeStorage}=await import("./server-probe-storage-connection.js")
const {createServerPollStorage,createServerPollStorageForTests,PollStorageUnknown}=await import("./server-poll-storage.js")
const {collectExpiredServerPollStorage,collectExpiredServerPollStorageForTests}=await import("./server-poll-storage-retention.js")
const {PollStorageRefused}=await import("./server-poll-storage-model.js")
const proof="a".repeat(64),contextProof="b".repeat(64),cases:string[]=[]
const options=():ProbeStorageOptions=>({deadlineAt:Date.now()+20000})
function scope(ownerId="owned-"+randomUUID(),expiresAt=Date.now()+180000):PollStorageScope{return {receiptId:randomUUID(),kind:"rest",executionId:randomUUID(),ownerId,bindingProof:proof,contextProof,issuedAt:Date.now()-1000,expiresAt}}
function binding(value=scope()){return {scope:value,connectionId:null,maxStages:8,authorize:async()=>{assert(Date.now()<value.expiresAt)}}}
const anchor=async(sql:ProbeStorageSql,value:PollStorageScope)=>{
await sql.query("INSERT INTO server_poll_executions(receipt_id,identity_kind,execution_id,binding_proof,context_ciphertext,context_proof) VALUES($1,$2,$3,$4,'SYNTHETIC-CIPHERTEXT',$5)",[value.receiptId,value.kind,value.executionId,value.bindingProof,value.contextProof])
}
const usage=async(ownerId:string)=>(await pool.query("SELECT admissions::int,reserved_rows::int,reserved_bytes::bigint::text FROM server_poll_storage_usage WHERE scope=$1",["owner:"+ownerId])).rows[0]
const historical:PollStorageScope[]=[],connectionId=randomUUID(),pendingOperation=randomUUID(),pendingPlan=randomUUID(),workerConnection=randomUUID(),workerOperation=randomUUID(),workerPlan=randomUUID()
try{
await applySqlMigrations(pool)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations")).rows[0].n,38)
// The actual migration runs on ONE backend/transaction. Synthetic aged
// records are seeded between table DDL and guard installation. Every file
// statement, including its real terminal marker, executes unchanged.
const proposal=await readFile(new URL("../../drizzle/0039_server_poll_storage.sql",import.meta.url),"utf8")
const boundary=proposal.indexOf("-- Every guard");assert(boundary>0)
const setup=await pool.connect()
try{
await setup.query(proposal.slice(0,boundary))
const old=new Date(Date.now()-40*86400000),issued=new Date(old.getTime()-3600000)
await setup.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,created_at) VALUES($1,'SYNTHETIC','historical-mcp','[]','{}','synthetic',$2)",[connectionId,issued])
await setup.query("INSERT INTO mcp_plans(id,connection_id,operation_id,operation_version,policy_version,generation,payload,evidence,state,expires_at,created_at) VALUES($1,$2,'servers.poll',1,1,'synthetic','{}','{}','approved',$3,$4)",[pendingPlan,connectionId,old,issued])
await setup.query("INSERT INTO mcp_operations(id,plan_id,connection_id,idempotency_key,state,created_at) VALUES($1,$2,$3,$5,'running',$4)",[pendingOperation,pendingPlan,connectionId,issued,pendingOperation])
await setup.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,created_at) VALUES($1,'SYNTHETIC','historical-worker','[]','{}','synthetic',$2)",[workerConnection,issued])
await setup.query("INSERT INTO mcp_plans(id,connection_id,operation_id,operation_version,policy_version,generation,payload,evidence,state,expires_at,created_at) VALUES($1,$2,'servers.poll',1,1,'synthetic','{}','{}','approved',$3,$4)",[workerPlan,workerConnection,old,issued])
await setup.query("INSERT INTO mcp_operations(id,plan_id,connection_id,idempotency_key,state,created_at) VALUES($1,$2,$3,$5,'pending',$4)",[workerOperation,workerPlan,workerConnection,issued,workerOperation])
for(const owner of ["historical-rest","historical-mcp","historical-missing-source","historical-recent","historical-worker"]){
const value={...scope(owner),issuedAt:issued.getTime(),expiresAt:old.getTime()}
if(owner.includes("mcp")||owner.includes("missing")){value.kind="mcp";value.executionId=owner.includes("missing")?randomUUID():pendingOperation}
if(owner==="historical-worker"){value.kind="mcp";value.executionId=workerOperation}
historical.push(value)
await setup.query("INSERT INTO server_poll_storage_admissions(receipt_id,identity_kind,execution_id,connection_id,owner_id,binding_proof,context_proof,authority_issued_at,authority_expires_at,max_stages,claim_token,claim_attempted_at,created_at,retention_days,safety_ms,gc_not_before) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,8,NULL,$9,$8,30,60000,$9::timestamptz+interval '30 days 60 seconds')",[value.receiptId,value.kind,value.executionId,owner==="historical-worker"?workerConnection:value.kind==="mcp"?connectionId:null,owner,proof,contextProof,issued,old])
await setup.query("INSERT INTO server_poll_storage_usage(scope,admissions,reserved_rows,reserved_bytes) VALUES($1,1,4019,8421376)",["owner:"+owner])
}
await setup.query("UPDATE server_poll_storage_usage SET admissions=5,reserved_rows=5*4019,reserved_bytes=5*8421376 WHERE scope='global'")
const value=historical[0]
await setup.query("INSERT INTO server_poll_executions(receipt_id,identity_kind,execution_id,binding_proof,context_ciphertext,context_proof,created_at) VALUES($1,'rest',$2,$3,'SYNTHETIC',$4,$5)",[value.receiptId,value.executionId,proof,contextProof,old])
await setup.query("INSERT INTO server_poll_intents(receipt_id,stage,before_proof,effect_proof,intent_proof,created_at) VALUES($1,'native.identity',$2,$2,$2,$3)",[value.receiptId,proof,old])
await setup.query("INSERT INTO server_poll_acks(receipt_id,stage,result_proof,outcome,ack_proof,created_at) VALUES($1,'native.identity',$2,'confirmed',$2,$3)",[value.receiptId,proof,old])
await setup.query("INSERT INTO server_poll_receipts(receipt_id,receipt_ciphertext,receipt_proof,created_at) VALUES($1,'SYNTHETIC',$2,$3)",[value.receiptId,proof,old])
await setup.query("INSERT INTO server_poll_quarantines(receipt_id,identity_kind,execution_id,context_proof,created_at) VALUES($1,'rest',$2,$3,clock_timestamp())",[historical[3].receiptId,historical[3].executionId,contextProof])
await setup.query(proposal.slice(boundary))
}catch(error){await setup.query("ROLLBACK");throw error}finally{setup.release()}
assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations")).rows[0].n,39)
cases.push("owned historical synthetic rows inserted BEFORE guards; no clock alteration, trigger disabling or normal migration marker fabrication")
// Preserve the historical 0039 proof, then run current code only against the
// normal current schema. No synthetic marker or quota backfill is installed.
const addedAdmission=["storage_state","compact_at","archive_bytes","original_activity_at","compaction_claim","compaction_claimed_at","compaction_claim_xid"]
const {POLL_STORAGE_TABLE_KEYS}=await import("./server-poll-storage-restore-evidence.sql-helper.js")
const captureHistorical=async()=>{
const client=await pool.connect(),tables:Record<string,{rows:unknown[];sha256:string}>={}
try{
await client.query("BEGIN READ ONLY");await client.query("SET LOCAL TimeZone='UTC'")
for(const [name,keys] of Object.entries(POLL_STORAGE_TABLE_KEYS)){
if(name==="server_poll_archives")continue
const omitted=name==="server_poll_storage_admissions"?addedAdmission:name==="server_poll_storage_usage"?["compacted_admissions","archive_bytes"]:[]
const rows=(await client.query(`SELECT to_jsonb(t)-$1::text[] AS value FROM ${name} t ORDER BY ${keys}`,[omitted])).rows
tables[name]={rows,sha256:createHash("sha256").update(JSON.stringify(rows)).digest("hex")}
}
await client.query("COMMIT");return tables
}finally{client.release(true)}
}
const historicalBefore=await captureHistorical()
await(await import("../db/migrate.js")).applySqlMigrations(pool)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations")).rows[0].n,MIGRATION_MANIFEST.length)
assert.deepEqual(await captureHistorical(),historicalBefore,"Current normal migrations preserve every historical full admission/journal/counter field and hash")
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions WHERE storage_state<>'full' OR compact_at IS NOT NULL OR archive_bytes IS NOT NULL OR original_activity_at IS NOT NULL OR compaction_claim IS NOT NULL OR compaction_claimed_at IS NOT NULL OR compaction_claim_xid IS NOT NULL")).rows[0].n,0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_usage WHERE compacted_admissions<>0 OR archive_bytes<>0")).rows[0].n,0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_archives")).rows[0].n,0)
cases.push("genuine staged historicalPrefix39 upgraded by normal current migrations; all seven old tables and exact opaque fields/hashes preserved with only new default columns")
const value=scope(),store=createServerPollStorage(binding(value))
await store.claim(options(),sql=>anchor(sql,value))
assert.equal((await usage(value.ownerId)).admissions,1)
assert.equal((await pool.query("SELECT used_rows FROM server_poll_storage_admissions WHERE receipt_id=$1",[value.receiptId])).rows[0].used_rows,1)
await assert.rejects(createServerPollStorage(binding(value)).claim(options(),async()=>assert.fail("spent identity cannot recreate anchor")),PollStorageRefused)
await assert.rejects(store.claim(options(),async()=>assert.fail("same factory never claims twice")),PollStorageRefused)
await store.write(options(),async sql=>{await sql.query("INSERT INTO server_poll_intents(receipt_id,stage,before_proof,effect_proof,intent_proof,created_at) VALUES($1,'native.identity',$2,$2,$2,'2000-01-01')",[value.receiptId,proof])})
assert((await pool.query("SELECT created_at>clock_timestamp()-interval '1 minute' AS fresh FROM server_poll_intents WHERE receipt_id=$1",[value.receiptId])).rows[0].fresh)
await assert.rejects(store.write(options(),sql=>sql.query("INSERT INTO server_poll_intents(receipt_id,stage,before_proof,effect_proof,intent_proof) VALUES($1,'publish.4',$2,$2,$2)",[value.receiptId,proof])),PollStorageRefused)
const before=(await pool.query("SELECT used_rows,used_bytes FROM server_poll_storage_admissions WHERE receipt_id=$1",[value.receiptId])).rows[0]
await store.quarantine();const marked=(await pool.query("SELECT used_rows,used_bytes FROM server_poll_storage_admissions WHERE receipt_id=$1",[value.receiptId])).rows[0]
assert.equal(marked.used_rows,before.used_rows+1)
await pool.query("INSERT INTO server_poll_quarantines(receipt_id,identity_kind,execution_id,context_proof) VALUES($1,'rest',$2,$3) ON CONFLICT DO NOTHING",[value.receiptId,value.executionId,contextProof])
assert.deepEqual((await pool.query("SELECT used_rows,used_bytes FROM server_poll_storage_admissions WHERE receipt_id=$1",[value.receiptId])).rows[0],marked)
await assert.rejects(store.write(options(),sql=>sql.query("INSERT INTO server_poll_intents(receipt_id,stage,before_proof,effect_proof,intent_proof) VALUES($1,'native.resource',$2,$2,$2)",[value.receiptId,proof])),PollStorageRefused)
cases.push("two-phase claim, exact reservation, durable spent identity, normalized activity, plan stage cap and idempotent quarantine actual-row metering")
const owner="concurrent-"+randomUUID(),claims=await Promise.allSettled(Array.from({length:10},async()=>{const s=scope(owner);return createServerPollStorage(binding(s)).claim(options(),sql=>anchor(sql,s))}))
assert.equal(claims.filter(row=>row.status==="fulfilled").length,8)
assert.deepEqual(await usage(owner),{admissions:8,reserved_rows:8*4019,reserved_bytes:String(8*8421376)})
cases.push("ten concurrent independent factories atomically admit eight owner attempts, refuse two, never partially charge counters")
const uncertain=scope(),b=binding(uncertain);let loss=true,callbacks=0
const lost=createServerPollStorageForTests(b,{now:Date.now,async connect(opts){const c=await connectProbeStorage(opts);return {release:v=>c.release(v),async query(text,values,queryOptions){const result=await c.query(text,values,queryOptions);if(text==="COMMIT"&&loss){loss=false;throw Error("SYNTHETIC lost admission commit acknowledgement")};return result}}}})
await assert.rejects(lost.claim(options(),async()=>{callbacks++}),PollStorageUnknown)
assert.equal(callbacks,0);assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_executions WHERE receipt_id=$1",[uncertain.receiptId])).rows[0].n,0)
await assert.rejects(createServerPollStorage(b).claim(options(),async()=>assert.fail("unknown admission cannot restart")),PollStorageRefused)
await lost.quarantine()
assert.equal((await usage(uncertain.ownerId)).admissions,1)
cases.push("real acknowledged-on-server admission COMMIT with lost client ACK never dispatches anchor, remains spent on new factory and supports charged orphan quarantine")
for(const phase of ["consume","write"] as const){
const s=scope();let commit=0,revoked=false
const bound={...binding(s),authorize:async()=>{assert(!revoked)}}
const attempt=createServerPollStorageForTests(bound,{now:Date.now,async connect(opts){const c=await connectProbeStorage(opts);return {release:v=>c.release(v),async query(text,values,queryOptions){const result=await c.query(text,values,queryOptions);if(text==="COMMIT"&&++commit===(phase==="consume"?2:3))throw Error("SYNTHETIC lost "+phase+" commit ACK");return result}}}})
if(phase==="consume")await assert.rejects(attempt.claim(options(),sql=>anchor(sql,s)),PollStorageUnknown)
else{
await attempt.claim(options(),sql=>anchor(sql,s))
await assert.rejects(attempt.write(options(),sql=>sql.query("INSERT INTO server_poll_intents(receipt_id,stage,before_proof,effect_proof,intent_proof) VALUES($1,'native.identity',$2,$2,$2)",[s.receiptId,proof])),PollStorageUnknown)
}
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_executions WHERE receipt_id=$1",[s.receiptId])).rows[0].n,1)
if(phase==="write")assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_intents WHERE receipt_id=$1",[s.receiptId])).rows[0].n,1)
revoked=true;await attempt.quarantine()
await assert.rejects(attempt.write(options(),async()=>assert.fail("poisoned writer cannot restart")),PollStorageRefused)
await assert.rejects(createServerPollStorage(binding(s)).claim(options(),async()=>assert.fail("spent attempt cannot renew")),PollStorageRefused)
assert.equal((await usage(s.ownerId)).admissions,1)
}
cases.push("real consume/anchor and intent COMMIT ACK losses preserve committed rows, destroy owner before fresh quarantine despite revocation and never reopen or recharge the attempt")
await assert.rejects(pool.query("INSERT INTO server_poll_quarantines(receipt_id,identity_kind,execution_id,context_proof) VALUES($1,'rest',$2,$3)",[randomUUID(),randomUUID(),contextProof]))
await assert.rejects(pool.query("UPDATE server_poll_executions SET context_ciphertext='REPLACED' WHERE receipt_id=$1",[historical[0].receiptId]))
const gc=await pool.connect()
try{await gc.query("BEGIN");await gc.query("SET LOCAL mm.poll_storage_gc='on'");await assert.rejects(gc.query("DELETE FROM server_poll_executions WHERE receipt_id=$1",[value.receiptId]));await gc.query("ROLLBACK")}finally{gc.release()}
const predicate=await pool.connect(),settingWriter=await pool.connect()
try{
await predicate.query("BEGIN");await predicate.query("SET LOCAL mm.poll_storage_gc='on'")
assert.equal((await predicate.query("SELECT server_poll_storage_gc_allowed($1) AS allowed",[historical[0].receiptId])).rows[0].allowed,true)
await settingWriter.query("BEGIN");await settingWriter.query("SET LOCAL lock_timeout='100ms'")
await assert.rejects(settingWriter.query("UPDATE mcp_settings SET requests_retention_days=365 WHERE id=1"),(error:unknown)=>(error as{code?:string}).code==="55P03")
}finally{await settingWriter.query("ROLLBACK");settingWriter.release();await predicate.query("ROLLBACK");predicate.release()}
cases.push("direct GC predicate itself locks current retention until transaction end; concurrent retention increase cannot race a GUC-enabled delete")
await pool.query("UPDATE mcp_settings SET requests_retention_days=365 WHERE id=1")
assert.equal((await collectExpiredServerPollStorage()).collected,0)
await pool.query("UPDATE mcp_settings SET requests_retention_days=30 WHERE id=1")
let failDelete=true
await assert.rejects(collectExpiredServerPollStorageForTests({now:Date.now,async connect(opts){const c=await connectProbeStorage(opts);return {release:v=>c.release(v),async query(text,values,queryOptions){const result=await c.query(text,values,queryOptions);if(failDelete&&text.startsWith("DELETE FROM server_poll_storage_admissions")){failDelete=false;throw Error("SYNTHETIC rollback after actual admission deletion and refund")};return result}}}}),PollStorageRefused)
assert.equal((await usage("historical-rest")).admissions,1)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_executions WHERE receipt_id=$1",[historical[0].receiptId])).rows[0].n,1)
let loseGcAck=true
await assert.rejects(collectExpiredServerPollStorageForTests({now:Date.now,async connect(opts){const c=await connectProbeStorage(opts);return {release:v=>c.release(v),async query(text,values,queryOptions){const result=await c.query(text,values,queryOptions);if(text==="COMMIT"&&loseGcAck){loseGcAck=false;throw Error("SYNTHETIC lost actual GC commit ACK")};return result}}}}),PollStorageUnknown)
assert.equal(await usage("historical-rest"),undefined)
assert.throws(()=>createServerPollStorage(binding(historical[0])),PollStorageRefused,"Original expired identity cannot recreate a reservation even after complete GC")
for(const table of ["server_poll_executions","server_poll_intents","server_poll_acks","server_poll_receipts","server_poll_quarantines","server_poll_storage_admissions"]){assert.equal((await pool.query(`SELECT count(*)::int AS n FROM ${table} WHERE receipt_id=$1`,[historical[0].receiptId])).rows[0].n,0)}
assert.equal((await usage("historical-mcp")).admissions,1)
assert.equal((await collectExpiredServerPollStorage()).collected,0,"Next maintenance pass must not refund the already committed unknown cleanup twice")
await pool.query("UPDATE mcp_operations SET state='unknown',finished_at=now()-interval '40 days' WHERE id=$1",[pendingOperation])
assert.equal((await collectExpiredServerPollStorage()).collected,1)
assert.equal(await usage("historical-mcp"),undefined)
assert.equal((await usage("historical-missing-source")).admissions,1)
assert.equal((await usage("historical-recent")).admissions,1)
cases.push("GUC alone cannot erase live data; increased current retention, recent quarantine and missing/running original MCP operation prevent GC; real terminal owner-linked operation permits atomic whole-journal deletion and exact refund")
cases.push("injected failure after real DELETE/refund rolls back all child rows and both counters together")
cases.push("lost acknowledgement after real GC COMMIT is explicit UNKNOWN; a later fresh pass refunds nothing twice, never repeats the spent identity")
await pool.query("UPDATE mcp_operations SET state='unknown',finished_at=now()-interval '40 days' WHERE id=$1",[workerOperation])
assert.equal((await usage("historical-worker")).admissions,1)
assert.equal((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled,false)
await(await import("../modules/mcp/workers.js")).tickMcpWorkers()
assert.equal(await usage("historical-worker"),undefined)
cases.push("actual existing worker tick collects an eligible original terminal poll admission and refunds quota while MCP is disabled")
await (await import("./server-poll-storage-execution.sql-helper.js")).acceptServerPollStorageExecutionSql()
cases.push("actual quota-bound full production poll: all four native GETs observe committed consumed admission, every maintenance publication/ACK metered, known replay no new native or quota")
const globalBefore=Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions)
const fill=await Promise.allSettled(Array.from({length:130-globalBefore},async()=>{const s=scope();return createServerPollStorage(binding(s)).claim({deadlineAt:Date.now()+60000},sql=>anchor(sql,s))}))
assert.equal(fill.filter(row=>row.status==="fulfilled").length,128-globalBefore)
assert.equal(Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions),128)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_usage WHERE scope<>'global' AND admissions=0")).rows[0].n,0,"Refused owner reservations leave no zero counter rows")
cases.push("global 128-attempt cap holds across independent owners and concurrent actual commits; failed admissions leave no orphan counters")
{
const {readServerPollCapacity}=await import("./server-poll-capacity.js")
const fullOwner=(await pool.query("SELECT scope FROM server_poll_storage_usage WHERE scope<>'global' AND admissions=8 LIMIT 1")).rows[0]
assert(fullOwner)
const ownerId=String(fullOwner.scope).slice("owner:".length)
const before=(await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows
const readOnly=await pool.connect()
try{
await readOnly.query("BEGIN READ ONLY")
const capacity=await readServerPollCapacity(readOnly,ownerId,true)
assert.equal(capacity.status,"observed")
if(capacity.status!=="observed")assert.fail("Expected actual full retained capacity")
assert.deepEqual(capacity.owner,{used:8,limit:8,remaining:0})
assert.deepEqual(capacity.global,{exhausted:true,usage:{used:128,limit:128,remaining:0}})
const privateCapacity=await readServerPollCapacity(readOnly,ownerId,false)
assert.equal(privateCapacity.status,"observed")
if(privateCapacity.status!=="observed")assert.fail("Expected scoped private capacity")
assert.deepEqual(privateCapacity.global,{exhausted:true,usage:null})
assert.equal(JSON.stringify(privateCapacity).includes(ownerId),false)
const emptyOwner=await readServerPollCapacity(readOnly,"unallocated-"+randomUUID(),false)
assert.equal(emptyOwner.status,"observed")
if(emptyOwner.status!=="observed")assert.fail("Expected unallocated owner capacity")
assert.deepEqual(emptyOwner.owner,{used:0,limit:8,remaining:8})
assert.equal(emptyOwner.global.exhausted,true)
await readOnly.query("COMMIT")
}finally{readOnly.release()}
assert.deepEqual((await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows,before)
cases.push("portal retained capacity uses real READ ONLY snapshot of owner8/global128, hides non-admin global numbers, never claims unallocated owner bypasses full global cap, and changes no quota row")
}
const evidence=await(await import("./server-poll-storage-restore-evidence.sql-helper.js")).pollStorageRestoreEvidence(pool)
await writeFile(resolve(process.env.MCP_STATE_DIR!,"poll-storage-owned-restore-evidence.json"),JSON.stringify(evidence),{flag:"wx",mode:0o600})
console.log("Owned poll storage SQL:",JSON.stringify({cases:cases.length,names:cases,historicalPrefix39:39,currentMigrations:MIGRATION_MANIFEST.length,actualMigrationFileStagedForOwnedHistoricalFixtures:true,allFileStatementsAndRealTerminalMarker:true,historicalRowsAndHashesPreserved:true,realPgTransactions:true,realQuotaTriggers:true,historicalFixtureBeforeGuards:true,providerOrClockOverrides:false,simulatedCommitAckLossAfterRealCommit:true,publicRoutesRegistered:false,journalAdapterIntegrated:true,productionDatabaseTouched:false,externalNetwork:false}))
}finally{await closePool()}