139 lines
14 KiB
JavaScript
139 lines
14 KiB
JavaScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import assert from 'node:assert/strict';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { DatabaseSync } from 'node:sqlite';
|
|
import { publicSnapshot, digest } from '../retained-host-state.mjs';
|
|
import { root, origin, read, save, client, sha, compareConfig, compareConnectionDefinitions } from './common.mjs';
|
|
import { inspectorClosed } from './inspector.mjs';
|
|
|
|
const stage = process.argv[2]; assert.ok(['node', 'react', 'python', 'final'].includes(stage));
|
|
const prefix = 'audits/' + stage + '-' + randomUUID(), frozen = read('frozen.json'), compatibility = read('compatibility/result.json');
|
|
const engineering = ['node', 'react', 'python'].filter(kind => fs.existsSync(path.join(root, kind, 'result.json'))).map(kind => ({ kind, ...read(kind + '/result.json') }));
|
|
const sessionIds = new Set(compatibility.results.flatMap(value => value.preflights.map(row => row.sessionId)).concat(engineering.map(value => value.sessionId).filter(Boolean)));
|
|
const projectIds = new Set(compatibility.results.map(value => value.projectId).concat(engineering.map(value => value.projectId).filter(Boolean)));
|
|
const external = fs.existsSync(path.join(root, 'external-observations/declared.json')) ? read('external-observations/declared.json').sources.map(source => {
|
|
assert.match(source.path, /^external-observations\/[a-f0-9-]{36}\/index\.json$/);
|
|
assert.equal(sha(fs.readFileSync(path.join(root, source.path))), source.sha256);
|
|
const value = read(source.path); assert.equal(value.m4Engineering, false); assert.equal(value.requestsReplayed, false);
|
|
assert.equal(sessionIds.has(value.sessionId), false); assert.equal(frozen.baseline.database.sessionIds.includes(value.sessionId), false);
|
|
assert.ok(frozen.originalProjects.some(project => project.id === value.projectId)); return value;
|
|
}) : [];
|
|
const allSessionIds = new Set([...sessionIds, ...external.map(value => value.sessionId)]);
|
|
assert.equal(allSessionIds.size, sessionIds.size + external.length, 'No duplicate declared external sessions.');
|
|
const sessionProjects = new Map(compatibility.results.flatMap(value => value.preflights.map(row => [row.sessionId, value.projectId]))
|
|
.concat(engineering.filter(value => value.sessionId).map(value => [value.sessionId, value.projectId]), external.map(value => [value.sessionId, value.projectId])));
|
|
const diagnosticIds = new Set(compatibility.results.map(value => read('compatibility/' + value.connectionId + '/network-start.json').job.id));
|
|
const expectedRequests = compatibility.requests + engineering.reduce((sum, value) => sum + (value.requests ?? 0), 0);
|
|
const externalRequests = external.reduce((sum, value) => sum + value.requests, 0), databaseRequests = expectedRequests + externalRequests;
|
|
const { api, boot, close } = await client(); let result;
|
|
try {
|
|
await inspectorClosed(); const host = await api('/host/status'); assert.equal(host.activity.active, false);
|
|
assert.equal(host.identity.pid, frozen.host.identity.pid); assert.equal(host.identity.instanceId, frozen.host.identity.instanceId); assert.equal(boot.version, '1.25.13');
|
|
const after = await publicSnapshot(origin, host.identity.dataRoot); save(prefix + '/after.json', after); const before = frozen.baseline;
|
|
assert.deepEqual(new Set(boot.projects.filter(value => !frozen.originalProjects.some(old => old.id === value.id)).map(value => value.id)), projectIds);
|
|
assert.deepEqual(boot.projects.filter(value => !projectIds.has(value.id)), frozen.originalProjects);
|
|
assert.deepEqual(after.database.sessionIds.filter(id => !before.database.sessionIds.includes(id)).sort(), [...allSessionIds].sort());
|
|
const configComparison = compareConfig(frozen.config, boot.config), configDelta = boot.config.configRevision - frozen.config.configRevision;
|
|
assert.equal(configDelta, engineering.filter(value => value.executed).length * 2, 'Exactly one select and restore per new engineering sample.');
|
|
const definitions = compareConnectionDefinitions(frozen.center, after.modelCenter, frozen.config, boot.config);
|
|
assert.deepEqual(after.modelCenter.selected, frozen.center.selected); assert.deepEqual(after.modelCenter.pools, frozen.center.pools);
|
|
const exportMap = new Map(after.exports.map(value => [value.id, value])), artifactMap = new Map(after.persistent.artifacts.map(value => [value.path, value]));
|
|
for (const original of before.exports) assert.deepEqual(exportMap.get(original.id), original, 'Original session export: ' + original.id);
|
|
for (const original of before.persistent.artifacts) assert.deepEqual(artifactMap.get(original.path), original, 'Original artifact byte: ' + original.path);
|
|
for (const value of external) {
|
|
assert.deepEqual(exportMap.get(value.sessionId), value.exports, 'Explicit external session export: ' + value.sessionId);
|
|
for (const artifact of value.artifacts) assert.deepEqual(artifactMap.get(artifact.path), { path: artifact.path, bytes: artifact.bytes, sha256: artifact.sha256 }, 'Explicit external artifact byte: ' + artifact.path);
|
|
}
|
|
const db = new DatabaseSync(path.join(host.identity.dataRoot, 'workbench.sqlite'), { readOnly: true }); const addedRows = {}, metadataChanges = [], sequenceChanges = []; let checkedOriginalRows = 0;
|
|
try {
|
|
assert.deepEqual(Object.keys(after.database.tables), Object.keys(before.database.tables));
|
|
for (const [table, originalTable] of Object.entries(before.database.tables)) {
|
|
const currentTable = after.database.tables[table]; assert.equal(currentTable.schemaSha256, originalTable.schemaSha256); addedRows[table] = currentTable.count - originalTable.count;
|
|
const originals = new Set(originalTable.rows.map(value => (value.kind ?? '') + ':' + value.id)), currentRows = new Map(currentTable.rows.map(value => [(value.kind ?? '') + ':' + value.id, value]));
|
|
for (const value of external) if (value.tables[table]) {
|
|
assert.equal(value.tables[table].schemaSha256, originalTable.schemaSha256);
|
|
for (const row of value.tables[table].rows) {
|
|
assert.equal(originals.has((row.kind ?? '') + ':' + row.id), false, 'External observation cannot replace an original row.');
|
|
assert.deepEqual(currentRows.get((row.kind ?? '') + ':' + row.id), row, 'Every explicitly recorded external row: ' + table + ':' + row.id);
|
|
}
|
|
}
|
|
for (const original of originalTable.rows) {
|
|
if (table === 'projects') {
|
|
const current = db.prepare('SELECT * FROM projects WHERE id=?').get(original.id); assert.ok(current);
|
|
assert.equal(digest({ ...current, position: current.position - projectIds.size }), original.sha256, 'Original project fields and declared front insertion positions.');
|
|
} else if (table === 'sqlite_sequence') {
|
|
const sequences = db.prepare('SELECT * FROM sqlite_sequence').all();
|
|
const current = sequences.find(value => digest({ ...value, seq: original.id }) === original.sha256); assert.ok(current, 'Original sequence authority.');
|
|
const increment = current.name === 'events' ? after.eventCursor - before.eventCursor : current.name === 'model_attempts' ? databaseRequests : NaN;
|
|
assert.ok(Number.isSafeInteger(increment)); assert.equal(current.seq, original.id + increment);
|
|
sequenceChanges.push({ name: current.name, original: original.id, current: current.seq, increment });
|
|
} else if (table === 'metadata' && ['config', 'modelRegistry', 'modelNetworkDiagnostics'].includes(original.id)) {
|
|
const current = db.prepare('SELECT * FROM metadata WHERE key=?').get(original.id), value = JSON.parse(current.value); let normalized;
|
|
if (original.id === 'config') { assert.equal(value.configRevision, boot.config.configRevision); normalized = { ...value, configRevision: frozen.config.configRevision }; }
|
|
else if (original.id === 'modelRegistry') {
|
|
assert.equal(value.revision, frozen.center.revision + configDelta); assert.deepEqual(value.selected, frozen.center.selected);
|
|
normalized = { ...value, revision: frozen.center.revision };
|
|
} else {
|
|
assert.ok(Array.isArray(value)); const additions = value.filter(row => diagnosticIds.has(row.id)); assert.equal(additions.length, diagnosticIds.size);
|
|
normalized = value.filter(row => !diagnosticIds.has(row.id));
|
|
}
|
|
assert.equal(digest({ ...current, value: JSON.stringify(normalized) }), original.sha256, 'Original public metadata bytes after the declared increment: ' + original.id);
|
|
metadataChanges.push({ key: original.id, originalRowSha256: original.sha256, currentRowSha256: digest(current), originalRestoredByDeclaredIncrement: true });
|
|
} else {
|
|
const current = currentRows.get((original.kind ?? '') + ':' + original.id); assert.ok(current, table + ': missing original ' + original.id);
|
|
assert.equal(current.sha256, original.sha256, table + ': changed original ' + original.id);
|
|
}
|
|
checkedOriginalRows++;
|
|
}
|
|
if (['events', 'records', 'sessions'].includes(table)) {
|
|
const columns = table === 'records' ? 'id,kind,session_id,project_id' : table === 'events' ? 'id,session_id,project_id' : 'id,project_id';
|
|
for (const row of db.prepare('SELECT ' + columns + ' FROM ' + table).all()) if (!originals.has((row.kind ?? '') + ':' + row.id)) {
|
|
const sessionId = table === 'sessions' ? row.id : row.session_id;
|
|
assert.ok(allSessionIds.has(sessionId), 'Every new ' + table + ' needs a declared session.'); assert.equal(row.project_id, sessionProjects.get(sessionId));
|
|
const observation = external.find(value => value.sessionId === sessionId);
|
|
if (observation) assert.ok(observation.tables[table].rows.some(value => value.id === row.id && (value.kind ?? '') === (row.kind ?? '')), 'External rows must match their explicit immutable list.');
|
|
}
|
|
} else if (table === 'outbox') {
|
|
for (const row of db.prepare('SELECT outbox.seq,events.session_id FROM outbox JOIN events USING(seq) WHERE outbox.seq>?').all(before.eventCursor)) {
|
|
assert.ok(allSessionIds.has(row.session_id));
|
|
const observation = external.find(value => value.sessionId === row.session_id);
|
|
if (observation) assert.ok(observation.tables.outbox.rows.some(value => value.id === row.seq), 'Explicit external outbox sequence.');
|
|
}
|
|
} else if (table === 'model_attempts') {
|
|
assert.equal(addedRows[table], databaseRequests);
|
|
// The ledger stores session_id; its project authority is the existing
|
|
// sessions relation, not a nonexistent model_attempts.project_id field.
|
|
for (const row of db.prepare('SELECT model_attempts.id,model_attempts.session_id,sessions.project_id FROM model_attempts LEFT JOIN sessions ON sessions.id=model_attempts.session_id').all()) if (!originals.has(':' + row.id)) {
|
|
assert.ok(allSessionIds.has(row.session_id)); assert.equal(row.project_id, sessionProjects.get(row.session_id));
|
|
const observation = external.find(value => value.sessionId === row.session_id);
|
|
if (observation) assert.ok(observation.tables.model_attempts.rows.some(value => value.id === row.id), 'Explicit external request ID.');
|
|
}
|
|
} else if (['metadata', 'sqlite_sequence'].includes(table)) assert.equal(addedRows[table], 0);
|
|
}
|
|
const references = new Map(db.prepare("SELECT payload FROM records WHERE kind='artifact'").all().map(row => { const value = JSON.parse(row.payload); return [value.relative, value]; }));
|
|
const originals = new Set(before.persistent.artifacts.map(value => value.path));
|
|
for (const artifact of after.persistent.artifacts) if (!originals.has(artifact.path)) {
|
|
const reference = references.get(artifact.path); assert.ok(reference && allSessionIds.has(reference.sessionId) && reference.projectId === sessionProjects.get(reference.sessionId), 'New original artifact must be owned or explicitly recorded externally.');
|
|
assert.equal(reference.sha256, artifact.sha256); assert.equal(reference.bytes, artifact.bytes);
|
|
}
|
|
} finally { db.close(); }
|
|
for (const original of before.persistent.files) {
|
|
const current = after.persistent.files.find(value => value.path === original.path); assert.ok(current);
|
|
if (original.path === 'config.json' && current.sha256 !== original.sha256) {
|
|
const value = JSON.parse(fs.readFileSync(path.join(host.identity.dataRoot, original.path), 'utf8'));
|
|
assert.equal(sha(JSON.stringify({ ...value, configRevision: frozen.config.configRevision }, null, 2)), original.sha256, 'Original config file bytes after the exact config revision increment.');
|
|
} else assert.equal(current.sha256, original.sha256, 'Original persistent file: ' + original.path);
|
|
}
|
|
result = { success: true, stage, version: boot.version, pid: host.identity.pid, instanceId: host.identity.instanceId, originalProjects: frozen.originalProjects.length,
|
|
originalSessions: before.database.sessionIds.length, originalModelRequests: before.database.tables.model_attempts.count, originalArtifacts: before.persistent.artifacts.length,
|
|
addedProjects: projectIds.size, addedSessions: sessionIds.size, addedRows, newArtifacts: after.persistent.artifacts.length - before.persistent.artifacts.length, checkedOriginalRows,
|
|
originalSessionExports: 'exact', originalArtifactBytes: 'exact', originalRows: 'exact with explicitly hashed project-position/public-metadata/sequence increments',
|
|
configComparison, definitions, metadataChanges, sequenceChanges, batchModelRequests: expectedRequests, externalModelRequests: externalRequests,
|
|
externalObservations: external.map(value => ({ sessionId: value.sessionId, projectId: value.projectId, requests: value.requests, tables: Object.fromEntries(Object.entries(value.tables).map(([table, source]) => [table, source.count])), artifacts: value.artifacts.length, scope: value.scope })),
|
|
originalCredentialRow: 'exact SHA; never decrypted or copied',
|
|
engineering: engineering.map(value => ({ kind: value.kind, success: value.success, executed: value.executed })), inspectorClosed: true, keysReadOrResaved: false, historicalSamplesReplayed: false, purgeExecuted: false };
|
|
} catch (error) { result = { success: false, stage, error: error.stack, keysReadOrResaved: false, noMutationOrRetry: true }; process.exitCode = 1; }
|
|
finally { save(prefix + '/result.json', result); await close(); }
|
|
console.log(JSON.stringify({ prefix, ...result }));
|