/** * GridStamp — 3,000,000 Operation Fleet Stress Test * * 100 robots × 30,000 ops = 3,000,000 total operations. * * 10x scale over stress-300k. Same scenario mix, same security invariants. * * SLOs (must pass): * - totalOps >= 3,000,000 * - all replay/adversarial frames caught * - all 100 proof chains valid * - heap growth < 8.0x (slightly relaxed vs 300k's 6.0x) * - throughput > 200 ops/sec * - p99 latency < 500 ms * * Test runtime budget: 120 minutes. */ import { describe, it, expect } from 'vitest'; import { generateSpatialProof, verifySpatialProofIntegrity, createSettlement, } from '../../src/verification/spatial-proof.js'; import { ReplayDetector, FrameIntegrityChecker, } from '../../src/antispoofing/detector.js'; import { ProofChain } from '../../src/verification/proof-chain.js'; import { signFrame, generateNonce } from '../../src/utils/crypto.js'; import { computeSpatialCode, PlaceCellPopulation, GridCellSystem, } from '../../src/memory/place-cells.js'; import { ShortTermMemory } from '../../src/memory/spatial-memory.js'; import type { CameraFrame, Pose, RenderedView, Vec3, SpatialProof, } from '../../src/types/index.js'; const SECRET = 'a]9#kL2$mP7xQ4vB8nR1wF5yH3jT6dG0'; const ROBOT_COUNT = 100; const OPS_PER_ROBOT = 30_000; // 100 × 30,000 = 3,000,000 const FRAME_W = 16; const FRAME_H = 16; const FRAME_PIXELS = FRAME_W * FRAME_H; const MIX_SEE = 0.30; const MIX_REMEMBER = 0.25; const MIX_VERIFY = 0.20; const MIX_NAVIGATE = 0.15; // MIX_SETTLE = 0.10 (implicit) const REPLAY_INJECTION_RATE = 0.05; const ADVERSARIAL_FRAME_RATE = 0.02; const GPS_DRIFT_SIGMA = 0.5 / 3; const CLOCK_SKEW_MS = 500; const MOVEMENT_SPEED_MPS = 2.0; const FRAME_RATE_HZ = 60; const DISPLACEMENT_PER_FRAME = MOVEMENT_SPEED_MPS / FRAME_RATE_HZ; function gaussianRandom(mean: number, sigma: number): number { let u1 = 0, u2 = 0; while (u1 === 0) u1 = Math.random(); while (u2 === 0) u2 = Math.random(); const z = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(2.0 * Math.PI * u2); return mean + z * sigma; } function driftPosition(pos: Vec3): Vec3 { return { x: pos.x + gaussianRandom(0, GPS_DRIFT_SIGMA), y: pos.y + gaussianRandom(0, GPS_DRIFT_SIGMA), z: pos.z + gaussianRandom(0, GPS_DRIFT_SIGMA * 0.3), }; } function makePose(robotId: number, frameIdx: number, baseTs: number): Pose { const angle = (robotId / ROBOT_COUNT) * 2 * Math.PI; const dist = frameIdx * DISPLACEMENT_PER_FRAME; const baseX = 10 + robotId * 2; const baseY = 10 + (robotId * 7) % 200; const position = driftPosition({ x: baseX + Math.cos(angle) * dist, y: baseY + Math.sin(angle) * dist, z: 0, }); const skew = (Math.random() - 0.5) * 2 * CLOCK_SKEW_MS; const timestamp = baseTs + frameIdx * (1000 / FRAME_RATE_HZ) + skew; return { position, orientation: { w: 1, x: 0, y: 0, z: 0 }, timestamp }; } function makeFrame( robotId: number, seqNum: number, frameIdx: number, baseTs: number, tamper: 'none' | 'wrong-hmac' | 'modified-pose' = 'none', ): CameraFrame { const seed = robotId * 10000 + frameIdx; const rgb = new Uint8Array(FRAME_PIXELS * 3); for (let i = 0; i < rgb.length; i++) rgb[i] = (i * 17 + seed * 31 + robotId * 13) % 256; const depth = new Float32Array(FRAME_PIXELS); for (let i = 0; i < depth.length; i++) depth[i] = 1.0 + (seed % 5) * 0.5; const pose = makePose(robotId, frameIdx, baseTs); const ts = pose.timestamp; let hmac = signFrame(rgb, ts, seqNum, SECRET); if (tamper === 'wrong-hmac') { hmac = signFrame(rgb, ts, seqNum, 'WRONG_SECRET_WRONG_SECRET_WRONG_SE'); } else if (tamper === 'modified-pose') { for (let i = 0; i < 100 && i < rgb.length; i++) rgb[i] = 0xFF; } return { id: `r${robotId}-f${frameIdx}-${generateNonce(4)}`, timestamp: ts, rgb, width: FRAME_W, height: FRAME_H, depth, pose, hmac, sequenceNumber: seqNum, }; } function makeRender(frame: CameraFrame): RenderedView { return { rgb: frame.rgb, depth: frame.depth ?? new Float32Array(FRAME_PIXELS), width: frame.width, height: frame.height, pose: frame.pose!, renderTimeMs: 0.5, }; } function percentile(arr: number[], p: number): number { if (arr.length === 0) return 0; const sorted = [...arr].sort((a, b) => a - b); const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length)); return sorted[idx]!; } function heapMB(): number { if (typeof process !== 'undefined' && process.memoryUsage) { return process.memoryUsage().heapUsed / (1024 * 1024); } return 0; } interface RobotResult { ops: { see: number; remember: number; verify: number; navigate: number; settle: number }; security: { replayAttempts: number; replayCaught: number; adversarialAttempts: number; adversarialCaught: number }; proofChainLength: number; proofChainValid: boolean; proofChainIntegrity: number; latencies: number[]; } async function runRobot( robotIdx: number, placeCells: PlaceCellPopulation, gridCells: GridCellSystem, ): Promise { const robotId = `fleet3m-robot-${robotIdx.toString().padStart(3, '0')}`; const baseTs = Date.now(); const integrityChecker = new FrameIntegrityChecker(SECRET, FRAME_RATE_HZ); const proofChain = new ProofChain(); const shortTerm = new ShortTermMemory(200, 60_000); const result: RobotResult = { ops: { see: 0, remember: 0, verify: 0, navigate: 0, settle: 0 }, security: { replayAttempts: 0, replayCaught: 0, adversarialAttempts: 0, adversarialCaught: 0 }, proofChainLength: 0, proofChainValid: false, proofChainIntegrity: 0, latencies: [], }; let seqNum = 0; let lastGoodFrame: CameraFrame | undefined; let lastProof: SpatialProof | undefined; let replaySourceFrame: CameraFrame | undefined; for (let i = 0; i < OPS_PER_ROBOT; i++) { const roll = Math.random(); const t0 = performance.now(); if (roll < MIX_SEE) { seqNum++; const isReplay = Math.random() < REPLAY_INJECTION_RATE && replaySourceFrame; const isAdversarial = !isReplay && Math.random() < ADVERSARIAL_FRAME_RATE; let frame: CameraFrame; if (isReplay && replaySourceFrame) { result.security.replayAttempts++; frame = { ...replaySourceFrame, id: `replay-${robotIdx}-${i}`, sequenceNumber: replaySourceFrame.sequenceNumber, timestamp: baseTs + i * (1000 / FRAME_RATE_HZ) + 50, }; const integrity = integrityChecker.check(frame); if (!integrityChecker.isSafe(integrity)) result.security.replayCaught++; } else if (isAdversarial) { result.security.adversarialAttempts++; const tamperType = (['wrong-hmac', 'modified-pose', 'wrong-hmac'] as const)[ Math.floor(Math.random() * 3) ]!; frame = makeFrame(robotIdx, seqNum, i, baseTs, tamperType); const integrity = integrityChecker.check(frame); if (!integrityChecker.isSafe(integrity)) result.security.adversarialCaught++; } else { frame = makeFrame(robotIdx, seqNum, i, baseTs, 'none'); shortTerm.add(frame, []); lastGoodFrame = frame; if (i % 20 === 0) replaySourceFrame = frame; } result.ops.see++; } else if (roll < MIX_SEE + MIX_REMEMBER) { if (!lastGoodFrame) { seqNum++; lastGoodFrame = makeFrame(robotIdx, seqNum, i, baseTs, 'none'); shortTerm.add(lastGoodFrame, []); } const render = makeRender(lastGoodFrame); const proof = generateSpatialProof( robotId, lastGoodFrame.pose!, lastGoodFrame, render, `merkle-root-${robotIdx}`, [], SECRET, ); if (proofChain.length === 0) proofChain.append(proof); else proofChain.append({ ...proof, prevProofHash: proofChain.tipHash }); lastProof = proof; result.ops.remember++; } else if (roll < MIX_SEE + MIX_REMEMBER + MIX_VERIFY) { // At 3M scale, `lastProof` may be thousands of ops old; SDK rejects // stale proofs (correct). Generate and verify a fresh proof instead // so we're testing verify throughput, not freshness-window retention. if (!lastGoodFrame) { seqNum++; lastGoodFrame = makeFrame(robotIdx, seqNum, i, baseTs, 'none'); } const freshRender = makeRender(lastGoodFrame); const freshProof = generateSpatialProof( robotId, lastGoodFrame.pose!, lastGoodFrame, freshRender, `merkle-root-${robotIdx}`, [], SECRET, ); const check = verifySpatialProofIntegrity(freshProof, SECRET); expect(check.valid).toBe(true); result.ops.verify++; } else if (roll < MIX_SEE + MIX_REMEMBER + MIX_VERIFY + MIX_NAVIGATE) { const pos: Vec3 = lastGoodFrame?.pose?.position ?? { x: robotIdx * 2, y: robotIdx * 3, z: 0 }; const code = computeSpatialCode(pos, placeCells, gridCells); expect(code).toBeDefined(); result.ops.navigate++; } else { if (!lastGoodFrame) { seqNum++; lastGoodFrame = makeFrame(robotIdx, seqNum, i, baseTs, 'none'); } const render = makeRender(lastGoodFrame); const proof = generateSpatialProof( robotId, lastGoodFrame.pose!, lastGoodFrame, render, `merkle-root-${robotIdx}`, [], SECRET, ); if (proof.passed) { const settlement = createSettlement( proof, parseFloat((Math.random() * 100 + 1).toFixed(2)), 'USD', `merchant-${i % 50}`, SECRET, ); expect(settlement).toBeDefined(); } result.ops.settle++; } // Sample 1:50 at 3M scale to cap latency-array memory. if (i % 50 === 0) { result.latencies.push(performance.now() - t0); } } const chainResult = proofChain.verify(); result.proofChainLength = proofChain.length; result.proofChainValid = chainResult.valid; result.proofChainIntegrity = chainResult.chainIntegrity; return result; } describe('GridStamp 3M Fleet Stress Test', () => { it( 'executes 3,000,000 operations across 100 concurrent robots with full security guarantees', async () => { const heapBefore = heapMB(); const wallStart = performance.now(); const placeCells = new PlaceCellPopulation(1.5); placeCells.coverRegion({ x: 0, y: 0, z: 0 }, { x: 220, y: 220, z: 0 }, 4.0, 4.0); const gridCells = new GridCellSystem(0.5, Math.SQRT2, 4, 16); const robotPromises = Array.from({ length: ROBOT_COUNT }, (_, idx) => runRobot(idx, placeCells, gridCells), ); const results = await Promise.all(robotPromises); const wallElapsed = performance.now() - wallStart; const heapAfter = heapMB(); const heapGrowth = heapAfter / Math.max(heapBefore, 1); let totalSee = 0, totalRemember = 0, totalVerify = 0, totalNavigate = 0, totalSettle = 0; let totalReplayAttempts = 0, totalReplayCaught = 0; let totalAdversarialAttempts = 0, totalAdversarialCaught = 0; let totalChainLinks = 0, chainsValid = 0; const allLatencies: number[] = []; for (const r of results) { totalSee += r.ops.see; totalRemember += r.ops.remember; totalVerify += r.ops.verify; totalNavigate += r.ops.navigate; totalSettle += r.ops.settle; totalReplayAttempts += r.security.replayAttempts; totalReplayCaught += r.security.replayCaught; totalAdversarialAttempts += r.security.adversarialAttempts; totalAdversarialCaught += r.security.adversarialCaught; totalChainLinks += r.proofChainLength; if (r.proofChainValid) chainsValid++; allLatencies.push(...r.latencies); } const totalOps = totalSee + totalRemember + totalVerify + totalNavigate + totalSettle; const opsPerSec = Math.round(totalOps / (wallElapsed / 1000)); const p50 = percentile(allLatencies, 50); const p95 = percentile(allLatencies, 95); const p99 = percentile(allLatencies, 99); const replayRate = totalReplayAttempts > 0 ? (totalReplayCaught / totalReplayAttempts * 100).toFixed(1) : 'N/A'; const advRate = totalAdversarialAttempts > 0 ? (totalAdversarialCaught / totalAdversarialAttempts * 100).toFixed(1) : 'N/A'; console.log(''); console.log('================================================================'); console.log(' GridStamp — 3,000,000 OP FLEET STRESS TEST REPORT'); console.log('================================================================'); console.log(` Wall clock: ${(wallElapsed / 1000).toFixed(2)}s`); console.log(` Total operations: ${totalOps.toLocaleString()}`); console.log(` Throughput: ${opsPerSec.toLocaleString()} ops/sec`); console.log(` Robots: ${ROBOT_COUNT}`); console.log(''); console.log(' Operation breakdown:'); console.log(` see() (30%): ${totalSee.toLocaleString()}`); console.log(` remember() (25%): ${totalRemember.toLocaleString()}`); console.log(` verify() (20%): ${totalVerify.toLocaleString()}`); console.log(` navigate() (15%): ${totalNavigate.toLocaleString()}`); console.log(` settle() (10%): ${totalSettle.toLocaleString()}`); console.log(''); console.log(` Latency (sampled 1:50): p50=${p50.toFixed(3)}ms p95=${p95.toFixed(3)}ms p99=${p99.toFixed(3)}ms`); console.log(` Security: replay ${totalReplayCaught}/${totalReplayAttempts} (${replayRate}%) adv ${totalAdversarialCaught}/${totalAdversarialAttempts} (${advRate}%)`); console.log(` Chains: ${chainsValid}/${ROBOT_COUNT} valid, ${totalChainLinks.toLocaleString()} links`); console.log(` Heap: ${heapBefore.toFixed(1)}MB → ${heapAfter.toFixed(1)}MB (${heapGrowth.toFixed(2)}x)`); console.log('================================================================'); expect(totalOps).toBeGreaterThanOrEqual(3_000_000); expect(totalReplayCaught).toBe(totalReplayAttempts); expect(totalReplayAttempts).toBeGreaterThan(0); expect(totalAdversarialCaught).toBe(totalAdversarialAttempts); expect(totalAdversarialAttempts).toBeGreaterThan(0); expect(chainsValid).toBe(ROBOT_COUNT); expect(heapGrowth).toBeLessThan(8.0); expect(opsPerSec).toBeGreaterThan(200); expect(p99).toBeLessThan(500); }, 120 * 60 * 1000, ); });