102 lines
9.1 KiB
TypeScript
102 lines
9.1 KiB
TypeScript
/** Production engine/SQL acceptance on one private disposable database only. */
|
|
import assert from "node:assert/strict"
|
|
import { basename, dirname, isAbsolute } from "node:path"
|
|
import { setTimeout as delay } from "node:timers/promises"
|
|
import type { PoolClient } from "pg"
|
|
|
|
async function main() {
|
|
assert.equal(process.env.MMAPP_OWN_FLOW_QUALITY,"true");assert.equal(process.env.MMAPP_OWN_SQL_DB,"postgres");assert.equal(process.env.NODE_ENV,"test")
|
|
const endpoint=new URL(process.env.DATABASE_URL??"postgresql://invalid")
|
|
assert(["postgres:","postgresql:"].includes(endpoint.protocol));assert.equal(endpoint.hostname,"127.0.0.1");assert.equal(endpoint.username,"mcp_test");assert(endpoint.password)
|
|
assert.equal(endpoint.pathname,"/postgres");assert.equal(endpoint.search,"");assert.equal(endpoint.hash,"");assert(Number(endpoint.port)>0)
|
|
assert(process.env.MCP_STATE_DIR&&isAbsolute(process.env.MCP_STATE_DIR));assert.equal(basename(process.env.MCP_STATE_DIR),"state");assert(basename(dirname(process.env.MCP_STATE_DIR)).startsWith("mm-mcp-test-"))
|
|
const {pool,closePool}=await import("../db/index.js")
|
|
const {applySqlMigrations}=await import("../db/migrate.js")
|
|
const {ensurePartitionsAround}=await import("../db/partitions.js")
|
|
const engine=await import("./traffic-flow-engine.js")
|
|
const {FlowCommitUnknown}=await import("./traffic-flow-write-transaction.js")
|
|
const {getServerCatalog,loadFlowTopology}=await import("./traffic-flow-topology.js")
|
|
const {pauseRipeBackgroundWork}=await import("./traffic-flow-ripe.js")
|
|
const originalConnect=pool.connect
|
|
let triggerCreated=false
|
|
const groups:string[]=[]
|
|
try {
|
|
await applySqlMigrations(pool);await ensurePartitionsAround(pool)
|
|
const id=Number((await pool.query("INSERT INTO servers(name,host,port,use_ssl,password,type) VALUES('own-flow-quality','127.0.0.1',9,false,'synthetic-unused','home-router') RETURNING id")).rows[0].id)
|
|
await getServerCatalog();await loadFlowTopology()
|
|
const base={src:"10.144.0.1",dst:"10.144.0.2",proto:6,srcPort:12345,dstPort:443,bytes:128,packets:1,inIface:"ether1",outIface:""}
|
|
const feed=(flows:Parameters<typeof engine.queueParsedFlows>[1])=>engine.queueParsedFlows(id,flows)
|
|
const drain=()=>engine.strictDrainEngine(async()=>{},[id])
|
|
const receipts=async()=>(await pool.query("SELECT batch_id,source_proof,result FROM flow_write_receipts WHERE kind='ingest' ORDER BY committed_at,batch_id")).rows
|
|
const mass=async()=>(await pool.query("SELECT coalesce(sum(bytes),0)::bigint AS bytes,coalesce(sum(packets),0)::bigint AS packets FROM flow_minute_stats WHERE server_id=$1",[id])).rows[0]
|
|
const reset=()=>engine.resetEngineAfterDatabaseRestore()
|
|
const installFailure=async()=>{
|
|
await pool.query("CREATE FUNCTION public.mcp_flow_quality_fixture_fail() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'owned quality receipt failure'; END $$")
|
|
await pool.query("CREATE TRIGGER mcp_flow_quality_fixture_fail BEFORE INSERT ON flow_write_receipts FOR EACH ROW EXECUTE FUNCTION public.mcp_flow_quality_fixture_fail()")
|
|
triggerCreated=true
|
|
}
|
|
const removeFailure=async()=>{await pool.query("DROP TRIGGER mcp_flow_quality_fixture_fail ON flow_write_receipts");await pool.query("DROP FUNCTION public.mcp_flow_quality_fixture_fail()");triggerCreated=false}
|
|
|
|
reset();for(let i=0;i<2049;i++)feed([{...base,inIface:"ether"+i}])
|
|
const pressure=engine.getEngineStats().dataQuality
|
|
assert.equal(pressure.records,"2");assert.equal(pressure.bytes,"256");assert.equal(pressure.packets,"2");assert.equal(pressure.reasons["ring-capacity"],true)
|
|
assert.equal(engine.peekPendingFlows().reduce((n,row)=>n+row.bytes,0),2047*128)
|
|
await drain();assert.deepEqual(await mass(),{bytes:2047*128,packets:2047})
|
|
assert.deepEqual((await receipts())[0].result.ingestQuality,pressure)
|
|
assert.equal(engine.observeFlowRing(id).available,false);assert.throws(()=>engine.getRingMbps(id),/incomplete|unobserved/)
|
|
groups.push("ring pressure admits2047/rejects2 before aggregates; genuine SQL minute mass and quantified receipt conserve all input")
|
|
|
|
reset();feed([{...base,bytes:Number.MAX_SAFE_INTEGER+1}]);const beforeLossMass=await mass(),beforeLossReceipts=(await receipts()).length
|
|
assert.equal(engine.peekPendingFlows().length,0);await drain()
|
|
const lossOnly=(await receipts()).at(-1)!.result
|
|
assert.equal((await receipts()).length,beforeLossReceipts+1);assert.equal(lossOnly.buckets,0);assert.equal(lossOnly.ingestQuality.bytes,null);assert.equal(lossOnly.ingestQuality.localAdmission,"loss-quantity-unknown")
|
|
assert.deepEqual(await mass(),beforeLossMass)
|
|
const countBeforeIdle=(await receipts()).length
|
|
await delay(15100);await engine.flushPending({prune:false})
|
|
assert.equal((await receipts()).length,countBeforeIdle,"Persisted quality warning is not perpetual dirty stats creating empty receipts")
|
|
groups.push("unsafe quantity is null; loss-only receipt persists atomically without flow mass and idle warning creates no empty receipt")
|
|
|
|
reset();feed([base,{...base,inIface:"x".repeat(257)}]);const rollbackMass=await mass(),rollbackReceipts=(await receipts()).length
|
|
await installFailure();await assert.rejects(drain(),/owned quality receipt failure/)
|
|
assert.deepEqual(await mass(),rollbackMass);assert.equal((await receipts()).length,rollbackReceipts)
|
|
feed([{...base,srcPort:12346,bytes:64},{...base,bytes:64,inIface:"x".repeat(257)}])
|
|
await removeFailure();await drain()
|
|
let written=await receipts();assert.equal(written.at(-1)!.result.ingestQuality.bytes,"128")
|
|
assert.equal(engine.peekPendingFlows().reduce((n,row)=>n+row.bytes,0),64)
|
|
await drain();written=await receipts();assert.equal(written.at(-1)!.result.ingestQuality.bytes,"64")
|
|
assert.equal(written.length,rollbackReceipts+2)
|
|
groups.push("real receipt failure rolls back every SQL cube; captured/live loss deltas remain separate through explicit retry")
|
|
|
|
reset();feed([base,{...base,inIface:"x".repeat(257)}]);let lost=false,quarantined=false
|
|
pool.connect=(function(this:typeof pool,...args:unknown[]){
|
|
if(args.length)return (originalConnect as (...args:unknown[])=>unknown).apply(pool,args)
|
|
return (originalConnect as()=>Promise<PoolClient>).call(pool).then(client=>new Proxy(client,{get(target,key){
|
|
if(key==="query")return async(...queryArgs:unknown[])=>{const result=await(target.query as(...args:unknown[])=>Promise<unknown>).apply(target,queryArgs);if(queryArgs[0]==="COMMIT"&&!lost){lost=true;throw Error("owned lost flow COMMIT ACK")}return result}
|
|
if(key==="release")return(destroy=false)=>{quarantined ||= destroy;target.release(destroy)}
|
|
const value=Reflect.get(target,key);return typeof value==="function"?value.bind(target):value
|
|
}})as PoolClient)
|
|
})as typeof pool.connect
|
|
try{await assert.rejects(drain(),FlowCommitUnknown)}finally{pool.connect=originalConnect}
|
|
assert(lost&&quarantined);const committed=(await receipts()).at(-1)!,genuineResult=structuredClone(committed.result),unknownMass=await mass()
|
|
feed([{...base,srcPort:12347,bytes:64},{...base,bytes:NaN}])
|
|
await assert.rejects(drain(),/unknown/i);assert.deepEqual(await mass(),unknownMass)
|
|
await pool.query("UPDATE flow_write_receipts SET result=result-'ingestQuality' WHERE batch_id=$1",[committed.batch_id])
|
|
await assert.rejects(engine.reconcileEnginePendingWrite(),/receipt quality/)
|
|
await pool.query("UPDATE flow_write_receipts SET result=$2::jsonb WHERE batch_id=$1",[committed.batch_id,JSON.stringify({...genuineResult,ingestQuality:{...genuineResult.ingestQuality,bytes:"999"}})])
|
|
await assert.rejects(engine.reconcileEnginePendingWrite(),/receipt quality/)
|
|
await pool.query("UPDATE flow_write_receipts SET result=$2::jsonb WHERE batch_id=$1",[committed.batch_id,JSON.stringify(genuineResult)])
|
|
assert.equal((await engine.reconcileEnginePendingWrite()).state,"committed")
|
|
assert.deepEqual(await mass(),unknownMass);assert.equal(engine.peekPendingFlows().reduce((n,row)=>n+row.bytes,0),64)
|
|
await drain();const latest=(await receipts()).at(-1)!.result.ingestQuality
|
|
assert.equal(latest.records,"1");assert.equal(latest.bytes,null);assert.equal(latest.knownLowerBounds.bytes,"0")
|
|
assert.deepEqual((await pool.query("SELECT result FROM flow_write_receipts WHERE batch_id=$1",[committed.batch_id])).rows[0].result,genuineResult)
|
|
groups.push("actual COMMIT ACK loss quarantines old backend; missing/tampered receipt quality cannot ACK; genuine receipt reconciles without replay and new arrivals keep separate delta")
|
|
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM flow_ip_meta")).rows[0].n),0,"Private synthetic flows never enqueue RIPE metadata")
|
|
console.log(JSON.stringify({accepted:groups.length,groups,actualSql:true,actualCommitAckLost:lost,realRouters:false,wrappedClientOnlyForExplicitCommitAckFault:true,wholeInstallation2GbAccepted:false}))
|
|
}finally{
|
|
pool.connect=originalConnect
|
|
try{if(triggerCreated){await pool.query("DROP TRIGGER IF EXISTS mcp_flow_quality_fixture_fail ON flow_write_receipts");await pool.query("DROP FUNCTION IF EXISTS public.mcp_flow_quality_fixture_fail()")};await pauseRipeBackgroundWork()}finally{await closePool()}
|
|
}
|
|
}
|
|
await main()
|