23f7624596
ADR-166 MCP Bridge Security Lock / Static-source security lock (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / Compose default binds loopback + Mongo has auth (push) Failing after 2s
CodeQL Advanced / Analyze (rust) (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / plugin-agent-federation bindHost default (push) Failing after 1s
ADR-166 MCP Bridge Security Lock / Runtime behavior — 401 + terminal gate + fail-closed (push) Failing after 4s
business-pods-smoke / smoke (push) Failing after 1s
all-plugins-smoke / smoke-all (push) Failing after 2s
CI/CD Pipeline / Security & Code Quality (push) Failing after 1s
CI/CD Pipeline / Test Suite (ubuntu-latest) (push) Failing after 1s
CI/CD Pipeline / Build & Package (macos-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (ubuntu-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (windows-latest) (push) Has been skipped
CI/CD Pipeline / Documentation & Examples (push) Failing after 1s
Clone Tracker (14-day rolling) / Snapshot clones for ruflo ecosystem (push) Failing after 1s
CodeQL Advanced / Analyze (actions) (push) Failing after 1s
CodeQL Advanced / Analyze (javascript-typescript) (push) Failing after 1s
federation-peer-rust / stable-noop (push) Failing after 1s
metaharness-ci / score (push) Failing after 1s
metaharness-ci / router-compat (push) Failing after 0s
metaharness-ci / similarity-tests (push) Failing after 0s
no-agentbbs-smoke / smoke-without-agentbbs (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (windows-latest) (push) Has been skipped
codex-integration-audit / Codex integration audit (push) Failing after 1s
helpers-manifest-guard / guard (push) Failing after 1s
🔗 Cross-Agent Integration Tests / 🤝 Agent Coordination Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🧠 Memory Sharing Integration (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🛡️ Fault Tolerance Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / ⚡ Performance Integration Tests (push) Has been skipped
metaharness-ci / mcp-scan (push) Failing after 1s
metaharness-ci / eject-dryrun (push) Failing after 1s
metaharness-ci / metaharness-real-data (push) Failing after 0s
no-cli-optdep-bloat-2561 / guard (push) Failing after 1s
no-metaharness-smoke / smoke-without-metaharness (push) Failing after 1s
no-phantom-agentic-flow-subpath / guard (push) Failing after 1s
🔄 Automated Rollback Manager / 🚨 Failure Detection (push) Failing after 1s
V3 CI/CD Pipeline / Plugin hooks smoke / ubuntu-latest / Node 22 (push) Failing after 1s
V3 CI/CD Pipeline / ruflo-graph-intelligence build + test smoke (#2044, ADR-123) (push) Failing after 1s
CVE Audit Gate / Audit root (critical-blocking) (push) Failing after 2s
cost-tracker-smoke / smoke (push) Failing after 3s
oia-audit-weekly / audit (push) Failing after 2s
ruflo-agent-smoke / ruflo-agent structural smoke (push) Failing after 1s
📊 Status Badges Update / 📊 Update Status Badges (push) Failing after 1s
V3 CI/CD Pipeline / Static regression guards (#2267 YAML + (push) Failing after 1s
V3 CI/CD Pipeline / Test V3 Packages (push) Failing after 0s
V3 CI/CD Pipeline / agent_execute provider routing smoke (#2042) (push) Failing after 0s
CVE Audit Gate / Audit v3 (critical-blocking) (push) Failing after 1s
federation-peer-rust / stable-native (push) Failing after 2s
🔗 Cross-Agent Integration Tests / 🚀 Integration Test Setup (push) Failing after 2s
neural-trader-smoke / runtime-smoke (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (macos-latest) (push) Has been skipped
V3 CI/CD Pipeline / Build V3 (ubuntu-latest) (push) Has been skipped
V3 CI/CD Pipeline / Type Check V3 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 24 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 22 (push) Failing after 2s
V3 CI/CD Pipeline / browser rvf create flag smoke (#2015) (push) Failing after 0s
V3 CI/CD Pipeline / Dependency review (#2046) (push) Has been skipped
V3 CI/CD Pipeline / Supply-chain audit (#2046) (push) Failing after 0s
V3 CI/CD Pipeline / witness marker drift smoke (#2021) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader portfolio CG smoke (#2068, ADR-126 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader backtest signing smoke (#2068, ADR-126 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / kg-extract type-import classification smoke (#2049) (push) Failing after 0s
V3 CI/CD Pipeline / witness verify precondition smoke (#1880) (push) Failing after 2s
V3 CI/CD Pipeline / neural-trader pipeline risk-gate smoke (#2068, ADR-126 Phase 5) (push) Failing after 0s
V3 CI/CD Pipeline / neural-trader feature attribution smoke (#2068, ADR-126 Phase 6) (push) Failing after 0s
V3 CI/CD Pipeline / plugin-registry signature verification smoke (#1922, CWE-347) (push) Failing after 4s
V3 CI/CD Pipeline / memory stats legacy-DB smoke (#2120) (push) Failing after 4s
V3 CI/CD Pipeline / github deprecated actions smoke (#2089, ADR-127 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / graph query + pathfinder smoke (ADR-130 P2+P5) (push) Has been skipped
V3 CI/CD Pipeline / graph trajectory hooks smoke (ADR-130 P3) (push) Has been skipped
V3 CI/CD Pipeline / graph plugin adapter smoke (ADR-130 P4) (push) Has been skipped
V3 CI/CD Pipeline / graph benchmark (ADR-130 P6) (push) Has been skipped
V3 CI/CD Pipeline / statusline generator delegation smoke (#2195) (push) Failing after 1s
V3 CI/CD Pipeline / wizard init regression guard (#2206 (push) Failing after 1s
V3 CI/CD Pipeline / memory no-stray-db smoke (ADR-125 P7) (push) Failing after 1s
V3 CI/CD Pipeline / github-safe injection smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github actions pin smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github attribution opt-in smoke (#2089, ADR-127 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / pre-bash hook safety smoke (#2017) (push) Failing after 1s
V3 CI/CD Pipeline / Memory import smoke / ubuntu-latest (push) Failing after 0s
V3 CI/CD Pipeline / MCP protocol smoke / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / ruvllm WASM auto-init smoke (#2086) (push) Failing after 4s
V3 CI/CD Pipeline / MCP paired-tool round-trip smoke (#1889) (push) Failing after 1s
V3 CI/CD Pipeline / Plugin package install-safety (#1902/#1903/#1904) (push) Failing after 1s
V3 CI/CD Pipeline / Tool description discoverability (ADR-112) (push) Failing after 3s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (22) (push) Failing after 1s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (24) (push) Failing after 1s
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Vector-index dimension audit (#1947) (push) Failing after 0s
V3 CI/CD Pipeline / Hook-command install safety (#1921) (push) Failing after 1s
V3 CI/CD Pipeline / ToolOutputGuardrail smoke (ADR-131, (push) Failing after 1s
V3 CI/CD Pipeline / init-bundle invariants smoke (#2095, ADR-128 Phase 5) (push) Failing after 1s
V3 CI/CD Pipeline / wasm provider bridge smoke (ADR-129 P1) (push) Failing after 2s
V3 CI/CD Pipeline / wasm gallery CRUD smoke (ADR-129 P3) (push) Failing after 1s
V3 CI/CD Pipeline / wasm plugin bridge smoke (ADR-129 P4) (push) Failing after 0s
V3 CI/CD Pipeline / wasm compose smoke (ADR-129 P2) (push) Failing after 4s
V3 CI/CD Pipeline / graph schema smoke (ADR-130 P1) (push) Failing after 0s
Validate Marketplace / validate (push) Failing after 1s
🔍 Verification Pipeline / 🚀 Setup Verification (push) Failing after 1s
🔍 Verification Pipeline / 🛡️ Security Verification (push) Has been skipped
🔍 Verification Pipeline / 📝 Code Quality (push) Has been skipped
🔍 Verification Pipeline / 🧪 Test Verification (${{ matrix.os }}, Node ${{ matrix.node }}) (push) Has been skipped
🔍 Verification Pipeline / 🏗️ Build Verification (push) Has been skipped
🔍 Verification Pipeline / 📚 Documentation Verification (push) Has been skipped
CVE Audit Gate / High-severity report (warn only) (push) Has been cancelled
🔄 Automated Rollback Manager / 🔄 Execute Rollback (push) Has been cancelled
🔄 Automated Rollback Manager / ✅ Post-Rollback Verification (push) Has been cancelled
🔄 Automated Rollback Manager / 📊 Rollback Monitoring (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / windows-latest (push) Has been cancelled
🔄 Automated Rollback Manager / ⏳ Manual Rollback Approval (push) Has been cancelled
V3 CI/CD Pipeline / MCP protocol smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Memory import smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / ubuntu-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Publish to npm (alpha) (push) Has been cancelled
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / macos-latest / Node 22 (push) Has been cancelled
V3 CI/CD Pipeline / Plugin hooks smoke / macos-latest / Node 22 (push) Has been cancelled
CI/CD Pipeline / Deploy & Release (push) Has been cancelled
CI/CD Pipeline / CI Status (push) Has been cancelled
🔗 Cross-Agent Integration Tests / 📊 Integration Test Report (push) Has been cancelled
🔄 Automated Rollback Manager / 🔍 Pre-Rollback Validation (push) Has been cancelled
🔍 Verification Pipeline / ⚡ Performance Verification (push) Has been cancelled
🔍 Verification Pipeline / 📊 Verification Report (push) Has been cancelled
375 lines
13 KiB
TypeScript
375 lines
13 KiB
TypeScript
/**
|
|
* LongMemEval Benchmark Harness for AgentDB
|
|
*
|
|
* ADR-088: Full LongMemEval benchmark implementation
|
|
*
|
|
* Usage:
|
|
* npx tsx harness.ts --mode raw --limit 50 # Quick test (50 questions)
|
|
* npx tsx harness.ts --mode raw # Full benchmark (500 questions)
|
|
* npx tsx harness.ts --mode hybrid # With Haiku reranking
|
|
* npx tsx harness.ts --mode baseline # Plain cosine baseline
|
|
*/
|
|
|
|
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
|
import { join, dirname } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import type {
|
|
Session,
|
|
Question,
|
|
QuestionResult,
|
|
CategoryResult,
|
|
BenchmarkReport,
|
|
BenchmarkMode,
|
|
MemoryAdapter,
|
|
QuestionType,
|
|
} from './types.js';
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
|
|
// ── CLI Args ──────────────────────────────────────────────────
|
|
|
|
function parseArgs(): { mode: BenchmarkMode; limit: number; dataDir: string; adapter: string } {
|
|
const args = process.argv.slice(2);
|
|
let mode: BenchmarkMode = 'raw';
|
|
let limit = 0; // 0 = all
|
|
let dataDir = join(__dirname, 'data');
|
|
let adapter = 'agentdb';
|
|
|
|
for (let i = 0; i < args.length; i++) {
|
|
switch (args[i]) {
|
|
case '--mode': mode = (args[++i] as BenchmarkMode) || 'raw'; break;
|
|
case '--limit': limit = parseInt(args[++i], 10) || 0; break;
|
|
case '--data': dataDir = args[++i]; break;
|
|
case '--adapter': adapter = args[++i]; break;
|
|
}
|
|
}
|
|
|
|
return { mode, limit, dataDir, adapter };
|
|
}
|
|
|
|
// ── Dataset Loading ───────────────────────────────────────────
|
|
|
|
function loadDataset(dataDir: string): { sessions: Session[]; questions: Question[] } {
|
|
const oracleFile = join(dataDir, 'longmemeval_oracle.json');
|
|
if (!existsSync(oracleFile)) {
|
|
console.error(`Dataset not found at ${oracleFile}`);
|
|
console.error('Run: bash scripts/download-dataset.sh');
|
|
process.exit(1);
|
|
}
|
|
|
|
const raw = JSON.parse(readFileSync(oracleFile, 'utf-8'));
|
|
|
|
// LongMemEval format: array of items with sessions + question
|
|
const sessions: Session[] = [];
|
|
const questions: Question[] = [];
|
|
const seenSessions = new Set<string>();
|
|
|
|
for (const item of raw) {
|
|
// Extract sessions
|
|
if (item.sessions) {
|
|
for (const sess of item.sessions) {
|
|
if (!seenSessions.has(sess.session_id)) {
|
|
seenSessions.add(sess.session_id);
|
|
sessions.push(sess);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Extract question
|
|
if (item.question) {
|
|
questions.push({
|
|
question_id: item.question_id ?? item.id ?? `q-${questions.length}`,
|
|
question: item.question,
|
|
answer: item.answer ?? item.answers ?? '',
|
|
question_type: mapQuestionType(item.question_type ?? item.type ?? ''),
|
|
evidence_session_ids: item.evidence_session_ids ?? [],
|
|
num_hops: item.num_hops ?? 1,
|
|
});
|
|
}
|
|
}
|
|
|
|
return { sessions, questions };
|
|
}
|
|
|
|
function mapQuestionType(raw: string): QuestionType {
|
|
const normalized = raw.toLowerCase().replace(/[^a-z-]/g, '-');
|
|
const mapping: Record<string, QuestionType> = {
|
|
'single-session-single-hop': 'single-session-single-hop',
|
|
'single-session-multi-hop': 'single-session-multi-hop',
|
|
'multi-session-single-hop': 'multi-session-single-hop',
|
|
'multi-session-multi-hop': 'multi-session-multi-hop',
|
|
'knowledge-update': 'knowledge-update',
|
|
'temporal-reasoning': 'temporal-reasoning',
|
|
};
|
|
return mapping[normalized] ?? 'single-session-single-hop';
|
|
}
|
|
|
|
// ── Answer Evaluation ─────────────────────────────────────────
|
|
|
|
function evaluateAnswer(predicted: string, gold: string | string[]): boolean {
|
|
const normalize = (s: string) => s.toLowerCase().trim().replace(/[^\w\s]/g, '');
|
|
const pred = normalize(predicted);
|
|
|
|
const golds = Array.isArray(gold) ? gold : [gold];
|
|
|
|
for (const g of golds) {
|
|
const ng = normalize(g);
|
|
// Exact match
|
|
if (pred === ng) return true;
|
|
// Contains match (lenient — official eval is more nuanced)
|
|
if (pred.includes(ng) || ng.includes(pred)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ── Answer Generation ─────────────────────────────────────────
|
|
|
|
async function generateAnswer(
|
|
question: string,
|
|
context: Array<{ content: string; score: number }>,
|
|
mode: BenchmarkMode
|
|
): Promise<string> {
|
|
// Raw mode: extract answer directly from top retrieved chunk
|
|
if (mode === 'raw' || mode === 'baseline') {
|
|
// Simple extractive: return the most relevant chunk
|
|
// A real system would use an LLM here, but raw mode = zero API
|
|
return context.length > 0 ? context[0].content : '';
|
|
}
|
|
|
|
// Hybrid / Full mode: use Haiku for answer generation
|
|
if (mode === 'hybrid' || mode === 'full') {
|
|
const contextText = context
|
|
.slice(0, 5)
|
|
.map((c, i) => `[${i + 1}] ${c.content}`)
|
|
.join('\n\n');
|
|
|
|
try {
|
|
const { default: Anthropic } = await import('@anthropic-ai/sdk');
|
|
const client = new Anthropic();
|
|
|
|
const response = await client.messages.create({
|
|
model: 'claude-haiku-4-5-20251001',
|
|
max_tokens: 256,
|
|
messages: [
|
|
{
|
|
role: 'user',
|
|
content: `Based on the following conversation excerpts, answer the question concisely.\n\nContext:\n${contextText}\n\nQuestion: ${question}\n\nAnswer (be concise, just the answer):`,
|
|
},
|
|
],
|
|
});
|
|
|
|
const block = response.content[0];
|
|
return block.type === 'text' ? block.text.trim() : '';
|
|
} catch (err) {
|
|
console.warn(`[Haiku] Failed: ${(err as Error).message}`);
|
|
return context.length > 0 ? context[0].content : '';
|
|
}
|
|
}
|
|
|
|
return '';
|
|
}
|
|
|
|
// ── Percentile Calculation ────────────────────────────────────
|
|
|
|
function percentile(arr: number[], p: number): number {
|
|
if (arr.length === 0) return 0;
|
|
const sorted = [...arr].sort((a, b) => a - b);
|
|
const idx = Math.ceil((p / 100) * sorted.length) - 1;
|
|
return sorted[Math.max(0, idx)];
|
|
}
|
|
|
|
// ── Main Benchmark ────────────────────────────────────────────
|
|
|
|
async function main() {
|
|
const { mode, limit, dataDir, adapter: adapterName } = parseArgs();
|
|
|
|
console.log('=== LongMemEval Benchmark for AgentDB ===');
|
|
console.log(`Mode: ${mode}`);
|
|
console.log(`Adapter: ${adapterName}`);
|
|
console.log(`Limit: ${limit || 'all'}`);
|
|
console.log('');
|
|
|
|
// Load dataset
|
|
console.log('[1/5] Loading dataset...');
|
|
const { sessions, questions } = loadDataset(dataDir);
|
|
const evalQuestions = limit > 0 ? questions.slice(0, limit) : questions;
|
|
console.log(` Sessions: ${sessions.length}, Questions: ${evalQuestions.length}/${questions.length}`);
|
|
|
|
// Initialize adapter
|
|
console.log(`[2/5] Initializing ${adapterName} adapter...`);
|
|
let adapter: MemoryAdapter;
|
|
|
|
if (adapterName === 'baseline') {
|
|
const { BaselineAdapter } = await import('./adapters/baseline-adapter.js');
|
|
adapter = new BaselineAdapter();
|
|
} else {
|
|
const { AgentDBAdapter } = await import('./adapters/agentdb-adapter.js');
|
|
adapter = new AgentDBAdapter();
|
|
}
|
|
|
|
await adapter.init();
|
|
|
|
// Ingest sessions
|
|
console.log('[3/5] Ingesting sessions...');
|
|
const ingestStart = performance.now();
|
|
let totalMessages = 0;
|
|
|
|
for (let i = 0; i < sessions.length; i++) {
|
|
await adapter.ingestSession(sessions[i]);
|
|
totalMessages += sessions[i].messages.length;
|
|
if ((i + 1) % 50 === 0 || i === sessions.length - 1) {
|
|
process.stdout.write(` Ingested ${i + 1}/${sessions.length} sessions (${totalMessages} messages)\r`);
|
|
}
|
|
}
|
|
const ingestMs = performance.now() - ingestStart;
|
|
console.log(`\n Ingestion complete in ${(ingestMs / 1000).toFixed(1)}s`);
|
|
|
|
// Evaluate questions
|
|
console.log('[4/5] Evaluating questions...');
|
|
const results: QuestionResult[] = [];
|
|
let correct = 0;
|
|
|
|
for (let i = 0; i < evalQuestions.length; i++) {
|
|
const q = evalQuestions[i];
|
|
|
|
// Retrieve
|
|
const retStart = performance.now();
|
|
const retrieved = await adapter.retrieve(q.question);
|
|
const retrievalMs = performance.now() - retStart;
|
|
|
|
// Generate answer
|
|
const genStart = performance.now();
|
|
const predicted = await generateAnswer(q.question, retrieved, mode);
|
|
const generationMs = performance.now() - genStart;
|
|
|
|
// Evaluate
|
|
const isCorrect = evaluateAnswer(predicted, q.answer);
|
|
if (isCorrect) correct++;
|
|
|
|
results.push({
|
|
question_id: q.question_id,
|
|
question_type: q.question_type,
|
|
predicted_answer: predicted.slice(0, 200),
|
|
gold_answer: q.answer,
|
|
correct: isCorrect,
|
|
retrieval_time_ms: Math.round(retrievalMs * 100) / 100,
|
|
generation_time_ms: Math.round(generationMs * 100) / 100,
|
|
retrieved_chunks: retrieved.length,
|
|
});
|
|
|
|
if ((i + 1) % 25 === 0 || i === evalQuestions.length - 1) {
|
|
const pct = ((correct / (i + 1)) * 100).toFixed(1);
|
|
process.stdout.write(` ${i + 1}/${evalQuestions.length} — ${correct}/${i + 1} correct (${pct}%)\r`);
|
|
}
|
|
}
|
|
|
|
const overallAccuracy = (correct / evalQuestions.length) * 100;
|
|
console.log(`\n Overall: ${correct}/${evalQuestions.length} (${overallAccuracy.toFixed(1)}%)`);
|
|
|
|
// Per-category breakdown
|
|
const categories = new Map<QuestionType, { total: number; correct: number; retMs: number[]; genMs: number[] }>();
|
|
for (const r of results) {
|
|
const cat = categories.get(r.question_type) ?? { total: 0, correct: 0, retMs: [], genMs: [] };
|
|
cat.total++;
|
|
if (r.correct) cat.correct++;
|
|
cat.retMs.push(r.retrieval_time_ms);
|
|
cat.genMs.push(r.generation_time_ms);
|
|
categories.set(r.question_type, cat);
|
|
}
|
|
|
|
const byCategory: CategoryResult[] = [...categories.entries()].map(([type, cat]) => ({
|
|
question_type: type,
|
|
total: cat.total,
|
|
correct: cat.correct,
|
|
accuracy: Math.round((cat.correct / cat.total) * 10000) / 100,
|
|
avg_retrieval_ms: Math.round(cat.retMs.reduce((a, b) => a + b, 0) / cat.retMs.length * 100) / 100,
|
|
avg_generation_ms: Math.round(cat.genMs.reduce((a, b) => a + b, 0) / cat.genMs.length * 100) / 100,
|
|
}));
|
|
|
|
// Latency stats
|
|
const allRetMs = results.map(r => r.retrieval_time_ms);
|
|
const allGenMs = results.map(r => r.generation_time_ms);
|
|
|
|
// Storage stats
|
|
const stats = await adapter.getStats();
|
|
|
|
// Build report
|
|
const report: BenchmarkReport = {
|
|
timestamp: new Date().toISOString(),
|
|
mode,
|
|
system: adapter.name,
|
|
version: '3.5.78',
|
|
overall: {
|
|
total: evalQuestions.length,
|
|
correct,
|
|
accuracy: Math.round(overallAccuracy * 100) / 100,
|
|
},
|
|
by_category: byCategory,
|
|
latency: {
|
|
retrieval_p50_ms: percentile(allRetMs, 50),
|
|
retrieval_p95_ms: percentile(allRetMs, 95),
|
|
retrieval_p99_ms: percentile(allRetMs, 99),
|
|
generation_p50_ms: percentile(allGenMs, 50),
|
|
generation_p95_ms: percentile(allGenMs, 95),
|
|
},
|
|
storage: {
|
|
sessions_ingested: sessions.length,
|
|
total_messages: totalMessages,
|
|
db_size_bytes: stats.sizeBytes,
|
|
index_size_bytes: 0,
|
|
},
|
|
config: {
|
|
embedding_model: 'all-MiniLM-L6-v2',
|
|
embedding_dims: 384,
|
|
hnsw_m: 16,
|
|
hnsw_ef_search: 100,
|
|
top_k: 10,
|
|
similarity_threshold: 0.3,
|
|
},
|
|
};
|
|
|
|
// Save report
|
|
console.log('[5/5] Saving report...');
|
|
const resultsDir = join(__dirname, 'results');
|
|
mkdirSync(resultsDir, { recursive: true });
|
|
|
|
const reportFile = join(resultsDir, `report-${mode}-${new Date().toISOString().slice(0, 10)}.json`);
|
|
writeFileSync(reportFile, JSON.stringify(report, null, 2) + '\n', 'utf-8');
|
|
console.log(` Report: ${reportFile}`);
|
|
|
|
// Save detailed results
|
|
const detailFile = join(resultsDir, `details-${mode}-${new Date().toISOString().slice(0, 10)}.json`);
|
|
writeFileSync(detailFile, JSON.stringify(results, null, 2) + '\n', 'utf-8');
|
|
console.log(` Details: ${detailFile}`);
|
|
|
|
// Print summary table
|
|
console.log('');
|
|
console.log('=== Results ===');
|
|
console.log(`System: ${adapter.name}`);
|
|
console.log(`Mode: ${mode}`);
|
|
console.log(`Overall: ${report.overall.accuracy}% (${correct}/${evalQuestions.length})`);
|
|
console.log('');
|
|
console.log('By Category:');
|
|
console.log(' Type | Total | Correct | Accuracy');
|
|
console.log(' ------------------------------|-------|---------|--------');
|
|
for (const cat of byCategory) {
|
|
const name = cat.question_type.padEnd(30);
|
|
console.log(` ${name}| ${String(cat.total).padStart(5)} | ${String(cat.correct).padStart(7)} | ${cat.accuracy.toFixed(1)}%`);
|
|
}
|
|
console.log('');
|
|
console.log('Latency:');
|
|
console.log(` Retrieval p50: ${report.latency.retrieval_p50_ms.toFixed(1)}ms`);
|
|
console.log(` Retrieval p95: ${report.latency.retrieval_p95_ms.toFixed(1)}ms`);
|
|
console.log(` Retrieval p99: ${report.latency.retrieval_p99_ms.toFixed(1)}ms`);
|
|
|
|
// Cleanup
|
|
await adapter.close();
|
|
console.log('');
|
|
console.log('Benchmark complete.');
|
|
}
|
|
|
|
main().catch(err => {
|
|
console.error('Benchmark failed:', err);
|
|
process.exit(1);
|
|
});
|