db-sync server: interrupted SQLite KVS flush and allocator restart corrupt restored indexes

Aperta
#1,525 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
35/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
clojure, sqlite
Ambito
database

Direzione di ricerca

Read deps/db-sync/src/logseq/db_sync/storage.cljs, deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs, and deps/db/src/logseq/db.cljs at the cited revision. Trace the ordinary transaction path and the per-row KVS upserts, then compare how the large-transaction path wraps SQL writes. Done means a fix or recovery strategy accounts for partial durable rows and allocator high-water together, with the supplied interruption and control reproduction passing.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

What happened

An interrupted SQLite KVS flush can leave durable index-node rows beyond the allocator high-water recorded in root metadata. After allocator recovery as in a fresh process, later writes can reuse those durable addresses and corrupt the restored DataScript indexes. Native traversal then throws Cannot read properties of null (reading 'keys'), although SQLite PRAGMA quick_check remains ok.

This report tracks the db-sync server storage adapter / partial-durable-flush branch separately from logseq/logseq#13911, so this branch remains tracked until that PR or another change is verified against it.

Environment and reproduction boundary

  • Exact exercised self-host image: ghcr.io/yshalsager/logseq-selfhost-sync:20260808-862ea7b.
  • Image digest: sha256:a20744c9e3f49cf34e46199d514f9e81daea824c680564429c6b6ab1235b0d4f.
  • Bundle: /app/worker/dist/node-adapter.js, SHA-256 5a09331bd31a79e25accd7d34a59255f4e28df1338ff4bcd20f12384c39e2c31.
  • Executed against the actual compiled DataScript and new-sqlite-storage functions with better-sqlite3, generated integer datoms and SQLite :memory:. Only entrypoint export injection and an SQL-adapter interruption hook are used. The store/restore/index algorithms are not reimplemented.
  • This is a deterministic storage-layer reproduction, not an HTTP push or OS process-kill reproduction. It resets the compiled allocator before restoring to model fresh-process allocator recovery. It does not run the production tx-log listener.
  • The original deployed-server incident had unreadable indexes; its original writer/failure trigger has not been established. Do not infer disk-full, OOM or a specific client from this fixture. The matching symptom does not prove this was the historical trigger.
  • The reproduction is pinned to the older deployed server bundle, not a claim that the current desktop 2.0.2 bundle or PR head was exercised.

Reproduce the bug

  1. Save the JavaScript below as logseq-storage-interrupted-flush-repro.js.
  2. Run it using the exact deployed image/module context:
docker run --rm -v "$PWD/logseq-storage-interrupted-flush-repro.js:/app/repro.js:ro" \
  ghcr.io/yshalsager/logseq-selfhost-sync:20260808-862ea7b \
  sh -lc 'cd /app && node /app/repro.js /app/worker/dist/node-adapter.js'

The fixture runs failure and no-interruption control:

  • Store 3,000 baseline datoms on indexed synthetic attribute :x.
  • Append 2,000 datoms, injecting one error after 136 insert into kvs writes.
  • Record root and durable SQL address watermarks.
  • Reset the allocator, restore the old persisted root, and append 400 datoms.
  • Restore/traverse EAVT and check SQLite integrity / index leaf depths.

A 2,000-item direct storage call is used to create enough KVS rows; this is not the normal server large-transaction handler, which has its own SQL wrapper. The fixture therefore tests the adapter branch rather than claiming an end-to-end 2,000-item HTTP failure.

Complete synthetic reproduction (no graph, auth, network or personal content)
#!/usr/bin/env node
/*
 Synthetic in-memory reproduction for Logseq db-sync interrupted SQLite flush / root-only allocator recovery.
 Privacy: generated datoms + SQLite :memory: only. No graph path, auth, server URL, or user data.

 This is the preserved deployed-bundle harness with only path configurability added. It must be run from a
 checkout/image where better-sqlite3 resolves exactly as the bundle expects.

 Maintainer one-command against the deployed self-host bundle image:
   docker run --rm -v "$PWD/logseq-storage-interrupted-flush-repro.js:/app/repro.js:ro" \
     ghcr.io/yshalsager/logseq-selfhost-sync:20260808-862ea7b \
     sh -lc 'cd /app && node /app/repro.js /app/worker/dist/node-adapter.js'

 Equivalent form if mounted elsewhere:
   docker run --rm -v "$PWD/logseq-storage-interrupted-flush-repro.js:/repro.js:ro" \
     ghcr.io/yshalsager/logseq-selfhost-sync:20260808-862ea7b \
     sh -lc 'cd /app && NODE_PATH=/app/node_modules node /repro.js /app/worker/dist/node-adapter.js'
*/
const fs=require('fs'),SQLite=require('better-sqlite3');
const bundlePath=process.argv[2]||'/app/worker/dist/node-adapter.js';
let text=fs.readFileSync(bundlePath,'utf8');const entry='qd.g($$,process.argv.slice(2));';const injected="globalThis.__sqlProof={read:IW,js:Zk,arr:nN,init:Voa,datom:IO,adapter:mQ,store:pQ,restore:fpa,conn:wQ,transact:kpa,get:p,vector:ji,sqlite:x9,eavt:tD,maxAddr:kQ};";if(text.split(entry).length!==2)throw Error('unexpected entrypoint');
new Function('require',text.replace(/^#!.*\n/,'').replace(entry,injected))(require);const D=globalThis.__sqlProof;
function run(interrupt){D.maxAddr.ad(null,1000000);const sqldb=new SQLite(':memory:');sqldb.exec('create table kvs (addr INTEGER primary key,content TEXT,addresses JSON)');const sql={_db:sqldb,exec(statement,...args){const normalized=statement.trim().toLowerCase();if(args.length){const prepared=sqldb.prepare(statement);if(normalized.startsWith('select'))return prepared.all(...args);prepared.run(...args);return null;}if(normalized.startsWith('select'))return sqldb.prepare(statement).all();sqldb.exec(statement);return null;}};const storage=new D.sqlite(sql,null);const kw=D.read(JSON.stringify('~:x')),add=D.read(JSON.stringify('~:db/add'));const schema=D.read(JSON.stringify(['^ ','~:x',['^ ','~:db/index',true]]));const db=D.init(Array.from({length:3000},(_,i)=>D.datom(i+1,kw,i,536870913)),schema);D.store(db,D.adapter(storage));const conn=D.conn(db);const original=sql.exec;let inserts=0;sql.exec=function(statement,...args){if(statement.startsWith('insert into kvs')){if(interrupt&&inserts++===136)throw Error('injected SQLite write interruption');}return original.call(this,statement,...args)};let firstError=null;try{D.transact(conn,D.vector(...Array.from({length:2000},(_,i)=>D.vector(add,i+3001,kw,i+3000))))}catch(e){firstError=e.message}sql.exec=original;const rootBefore=D.js(D.read(sqldb.prepare('select content from kvs where addr=0').get().content)),diskMax=sqldb.prepare('select max(addr) as max from kvs').get().max;D.maxAddr.ad(null,1000000);const reopen=D.arr(D.restore(storage,null))[0],c2=D.conn(reopen);let secondError=null;try{D.transact(c2,D.vector(...Array.from({length:400},(_,i)=>D.vector(add,i+6001,kw,i+6000))))}catch(e){secondError=e.message}const root=D.js(D.read(sqldb.prepare('select content from kvs where addr=0').get().content));const audit={shift:root['eavt-metadata'].shift,leafDepths:{},missing:0,cycles:0};function walk(addr,depth,path){if(path.has(addr)){audit.cycles++;return}const row=sqldb.prepare('select addresses from kvs where addr=?').get(addr);if(!row){audit.missing++;return}if(row.addresses){for(const ch of JSON.parse(row.addresses))walk(ch,depth+1,new Set([...path,addr]));}else audit.leafDepths[depth]=(audit.leafDepths[depth]||0)+1;}walk(root.eavt,0,new Set());let restoredCount=null,restoreError=null;try{restoredCount=D.arr(D.eavt.h(D.arr(D.restore(storage,null))[0])).length}catch(e){restoreError=e.message}const out={interrupt,firstError,secondError,restoreError,restoredCount,rootWatermarkBeforeRestart:rootBefore['max-addr'],diskWatermarkBeforeRestart:diskMax,quickCheck:sqldb.pragma('quick_check'),audit};sqldb.close();return out;}console.log(JSON.stringify({bundlePath,failure:run(true),control:run(false)},null,2));

Observed result

Preserved output of the actual deployed-bundle exercise:

{
  "failure": {
    "interrupt": true,
    "firstError": "injected SQLite write interruption",
    "secondError": null,
    "restoreError": "Cannot read properties of null (reading 'keys')",
    "restoredCount": null,
    "rootWatermarkBeforeRestart": 1000393,
    "diskWatermarkBeforeRestart": 1000526,
    "quickCheck": [
      {
        "quick_check": "ok"
      }
    ],
    "audit": {
      "shift": 2,
      "leafDepths": {
        "1": 5,
        "2": 194,
        "3": 22
      },
      "missing": 0,
      "cycles": 0
    }
  },
  "control": {
    "interrupt": false,
    "firstError": null,
    "secondError": null,
    "restoreError": null,
    "restoredCount": 5400,
    "rootWatermarkBeforeRestart": 1000792,
    "diskWatermarkBeforeRestart": 1000792,
    "quickCheck": [
      {
        "quick_check": "ok"
      }
    ],
    "audit": {
      "shift": 2,
      "leafDepths": {
        "2": 275
      },
      "missing": 0,
      "cycles": 0
    }
  }
}

Before restart the failed flush leaves root max-addr=1000393 but durable SQL max(addr)=1000526. The later write returns without a second error, but restore/traversal fails; EAVT leaves occur at depths 1, 2 and 3 despite root shift 2, with no missing rows or cycles counted. The control restores 5,400 datoms, has equal watermarks, and leaves at depth 2 only.

The exact leaf counts are observed output, not a promised invariant across builds. Mixed depths, failed native traversal and successful no-interruption control are the relevant behavior.

Expected behavior

An interrupted store must not leave reusable durable addresses that can corrupt indexes after reopening. Either the complete KVS flush commits atomically, or recovery must safely account for partial durability before accepting new writes. Reopening a previously committed state must remain structurally valid; an unsuccessful edit must not corrupt later successful edits.

Source evidence and relation to PR #13911

At deployed source revision 862ea7b:

  • storage.cljs: new-sqlite-storage/-store calls upsert-addr-content!, which upserts each KVS row in a doseq without an internal SQL transaction.
  • worker/handler/sync.cljs: apply-large-tx-entry! supplies an outer with-sql-transaction!; the ordinary apply-tx-entry! branch calls ldb/transact! without that wrapper.
  • db.cljs: transact-sync invokes DataScript persistence (dc/store-after-transact! or d/transact!) before callbacks, without supplying the missing ordinary-path SQL transaction.

PR logseq/logseq#13911 describes a related rollback / memory nodes marked stored / later missing-row mechanism and reload-on-store-failure in ldb/transact! / ldb/batch-transact!. This fixture instead retains partially durable rows, restarts the allocator from an older root, and produces invalid topology without missing references. I have not applied that PR to the deployed server or run this fixture on its head. It may mitigate some paths, but is not yet verified as a fix for this branch.

Please evaluate the server row-set atomicity and allocator-recovery high-water together; this separate issue can be closed once the server branch is demonstrably covered. No additional retry/diagnostic bug is being alleged here.

Safety / verification limits

The exercise contains generated datoms and SQLite :memory: only; no production graph/snapshot, note text, credentials, external server access or asset content is attached. The preserved deployed-image run supplies the output above. A later attempt against a different local advanced bundle failed at symbol setup (D.maxAddr.ad is not a function); the Docker daemon on that workstation was unavailable, so no additional run on that different build is claimed. No source fix or PR-head validation is claimed.

Lingua principale
Nessun dato sulla lingua
Stelle
29
Fork
2
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di logseq/db-test

Tutte le issue di logseq/db-test

Issue simili

Altre issue su Databases

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.