diff --git a/backend/src/db/migrations/153_node_lookup_heap_locality.sql b/backend/src/db/migrations/153_node_lookup_heap_locality.sql new file mode 100644 index 00000000..534dcb2f --- /dev/null +++ b/backend/src/db/migrations/153_node_lookup_heap_locality.sql @@ -0,0 +1,7 @@ +-- Keep ordered map reads local without adding another per-ingest index. +-- This is a one-time physical rewrite; later DEV bulk loads finalize layout +-- in prepareSampleDataset. CLUSTER preserves the relation and its row values. +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '60s'; +CLUSTER core.nodes USING nodes_normalized_lookup_idx; +ANALYZE core.nodes; diff --git a/backend/src/db/migrations/README.md b/backend/src/db/migrations/README.md index 797deb45..fa4260a6 100644 --- a/backend/src/db/migrations/README.md +++ b/backend/src/db/migrations/README.md @@ -2,6 +2,14 @@ Place additive, versioned SQL migrations here. Do not put whole-table historical backfills in this folder. +`153_node_lookup_heap_locality.sql` performs one bounded physical layout +upgrade of `core.nodes` using its existing normalized lookup index. It preserves +row values and adds no index. The migration owner uses a 5-second lock timeout +and 60-second statement timeout; failure rolls back atomically. Later DEV bulk +imports finalize layout in `sample:prepare`, after loading and convergence. +This is explicit initialization/import maintenance, not a runtime clustering loop +or a guarantee that later writes will preserve physical order indefinitely. + The immutable `016_private_prefixes.sql` has a PostgreSQL ambiguity in its historical rollup query. Environments that already applied it retain and verify its checksum. A completely empty database records an explicit diff --git a/backend/src/tools/prepareSampleDataset.ts b/backend/src/tools/prepareSampleDataset.ts index c5a71d98..45ccb940 100644 --- a/backend/src/tools/prepareSampleDataset.ts +++ b/backend/src/tools/prepareSampleDataset.ts @@ -15,7 +15,7 @@ export async function prepareSampleDataset(databaseUrl: string): Promise { // Share the runtime analytical admission boundary before changing any // fixture state. The retained admission client leaves one of max2 clients // for the sequential preparation helpers below. - await withHeavyWorkAdmission({ pool, workload: 'fixture-prepare', task: async () => { + await withHeavyWorkAdmission({ pool, workload: 'fixture-prepare', task: async maintenance => { // Freeze local lifecycle/background policies for comparable runs. This does // not add, remove or activate compression/retention on any external DB. const jobs = await pool.query<{ job_id: number }>('SELECT job_id FROM timescaledb_information.jobs WHERE job_id >= 1000'); @@ -69,6 +69,21 @@ export async function prepareSampleDataset(databaseUrl: string): Promise { // the earlier join statistics. Refresh them before releasing chart admission. await pool.query(`ANALYZE mesh.packets; ANALYZE mesh.packet_paths; ANALYZE mesh.multibyte_path_facts`); + // Migration153 organizes populated upgrades. Explicit bulk imports can + // populate an initially empty migrated table, so finish their layout here. + // CLUSTER requires a short exclusive lock; use the pinned admission + // session so the transaction and its local deadlines cannot cross clients. + await maintenance.query('BEGIN'); + try { + await maintenance.query(`SET LOCAL lock_timeout = '5s'; + SET LOCAL statement_timeout = '60s'; + CLUSTER core.nodes USING nodes_normalized_lookup_idx; + ANALYZE core.nodes`); + await maintenance.query('COMMIT'); + } catch (error) { + await maintenance.query('ROLLBACK'); + throw error; + } const counts = await pool.query(`SELECT 'nodes' AS relation, COUNT(*)::text AS rows FROM core.nodes UNION ALL SELECT 'packets', COUNT(*)::text FROM mesh.packets UNION ALL SELECT 'paths', COUNT(*)::text FROM mesh.packet_paths diff --git a/backend/src/tools/samplePipeline.integration.test.ts b/backend/src/tools/samplePipeline.integration.test.ts index f10c7a24..ab7de58e 100644 --- a/backend/src/tools/samplePipeline.integration.test.ts +++ b/backend/src/tools/samplePipeline.integration.test.ts @@ -46,6 +46,11 @@ test('synthetic loader and derived-state preparation work on the complete migrat await generateSampleDataset(['--data-dir', directory, '--count', '25']); const args = ['--data-dir', directory, '--database-url', url.href]; await loadSampleDataset([...args, '--reset', '--fast']); + const nodeRows = async () => (await pool.query( + 'SELECT jsonb_agg(to_jsonb(n) ORDER BY node_id) AS value FROM core.nodes n', + )).rows[0].value; + const loadedNodes = await nodeRows(); + const loadedHeap = (await pool.query("SELECT pg_relation_filenode('core.nodes') AS value")).rows[0].value; assert.equal((await pool.query('SELECT COUNT(*)::int AS n FROM mesh.packets')).rows[0].n, 25); assert.equal((await pool.query('SELECT COUNT(*)::int AS n FROM mesh.packets WHERE raw_hex IS NOT NULL AND observation_id IS NOT NULL')).rows[0].n, 25); assert.equal((await pool.query(`SELECT COUNT(*)::int AS n FROM mesh.packets p WHERE ${publicPacketPrivacySql('p')}`)).rows[0].n, 0, @@ -166,6 +171,10 @@ test('synthetic loader and derived-state preparation work on the complete migrat finally { await Promise.allSettled([openingChart, ...(preparing ? [preparing] : []), ...(closingChart ? [closingChart] : [])]); } } }); + assert.deepEqual(await nodeRows(), loadedNodes, 'bulk finalization preserves every raw node field'); + assert.notEqual((await pool.query("SELECT pg_relation_filenode('core.nodes') AS value")).rows[0].value, loadedHeap, + 'a populated import receives physical maintenance after the empty-table migration'); + assert.equal((await pool.query("SELECT indisclustered FROM pg_index WHERE indexrelid='core.nodes_normalized_lookup_idx'::regclass")).rows[0].indisclustered, true); assert.equal((await pool.query(`SELECT COUNT(*)::int AS n FROM mesh.packets p WHERE ${publicPacketPrivacySql('p')}`)).rows[0].n, 25); assert.equal((await pool.query('SELECT COUNT(*)::int AS n FROM mesh.multibyte_path_facts WHERE fully_decoded AND visibility_ok')).rows[0].n, 25); assert.ok(await readPublicResponseGeneration((sql) => pool.query(sql)) > 0); diff --git a/plans/lean-runtime/decisions.md b/plans/lean-runtime/decisions.md index d5e79263..ea217c7c 100644 --- a/plans/lean-runtime/decisions.md +++ b/plans/lean-runtime/decisions.md @@ -2004,3 +2004,41 @@ qualification. Do not change workloads, timing or acceptance limits. - Preserve all query parameters, fields, caps, ordering, memory, admission, deadlines and publication/privacy fences. Verify the compiled SQL, existing region checks and real producer tests before rollout and fresh qualification. + +## Keep the node lookup heap local without another write-heavy index + +- The six-window10x read collection on6f362fe failed its final candidate + C8/warm trial1 map page at565ms p95/813ms p99. All earlier candidate modes + passed and all13 resource checks passed over1,384.8s. Preserve that failure; + neither sampling cadence nor acceptance changes. Its timeline shows the + fixture observer probe reading packet history before the map's cold reads; + region-worker CPU was idle during this particular failure. +- The ordered normalized lookup touched1,514 buffers for1,022 heap rows. + Heap/key correlation was0.0034. Existing migrations148/150 deliberately + removed an extra map index to meet the ingest WAL allowance. Avoid adding a + covering index: it would add write cost and indexed unbounded text can reject + previously valid node values. The hidden dependency is physical heap locality. +- Guarded owned10x CLUSTER using the existing normalized index took1.74s, + preserving all49,542 rows by SHA256 and every index definition. Heap bytes + fell21,553,152→14,204,928 and key correlation became1. The action committed + once; its wrapper's JSON parse failure is retained separately from the + successful native action and43-service/37-log closure. Evidence: + final-evidence/owned-node-cluster-6f362fe-3zqn2_e5/closure.json. +- The existing candidate window then passed all4 modes/3 trials, with C8 warm + p95≤74.69ms and13 resource checks passing. All36 compared HTTP case/trial + data digests and entry counts matched. A separate same-SQL/parameters cold + map probe after the same regional read needed103 disk blocks/~11.6ms, + compared with1,137 blocks/162ms before clustering. These are diagnostic + results, not fresh paired qualification. The original stores are untouched. +- Put the populated-store upgrade in migration153 under the existing finite + db-migrate owner. Keep5s lock and60s statement bounds and atomic rollback. + Later DEV bulk loads belong to the existing sample preparation finalizer, + including scaleLookupFixture which already calls it. Finalize node layout + there on the existing admitted/pinned maintenance session, in its own bounded + transaction; never in an HTTP handler, retention tool or background loop. + An empty-table migration alone does not organize rows loaded later. +- This is one-time upgrade plus explicit bulk finalization, not perpetual + physical ordering. Preserve row values, schema/roles, indexes, freshness, + pools, resource limits and privacy fences. Main configuration must own this + maintenance before any fresh matched evidence is collected at either scale; + fixture-only conditioning cannot substitute for the final runtime.