db-sync server: interrupted SQLite KVS flush and allocator restart corrupt restored indexes
まだ誰も着手していません。
評価
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 初心者へのやさしさ
- 35/100
調査の方向性
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.
索引モデルが issue の本文から書いたものです。
説明
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-2565a09331bd31a79e25accd7d34a59255f4e28df1338ff4bcd20f12384c39e2c31. - Executed against the actual compiled DataScript and
new-sqlite-storagefunctions withbetter-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
- Save the JavaScript below as
logseq-storage-interrupted-flush-repro.js. - 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 kvswrites. - 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/-storecallsupsert-addr-content!, which upserts each KVS row in adoseqwithout an internal SQL transaction. - worker/handler/sync.cljs:
apply-large-tx-entry!supplies an outerwith-sql-transaction!; the ordinaryapply-tx-entry!branch callsldb/transact!without that wrapper. - db.cljs:
transact-syncinvokes DataScript persistence (dc/store-after-transact!ord/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.
- 主要言語
- 言語のデータがありません
- スター
- 29
- フォーク
- 2
- PR マージ指標
- 30日以内にマージされた PR はありません
環境構築
このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
logseq/db-test のほかの issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
-
難易度 2/5 1〜3時間 初心者へのやさしさ 75/100
-
難易度 2/5 1〜3時間 初心者へのやさしさ 70/100
-
Potential Dataloss: Deleting an entry from the property page's node table has no confirmation dialog対応中かも @tiensonqin が 59 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 75/100
-
Disabling Flashcards in Settings does not disable Flashcard shortcuts or tags対応中かも @tiensonqin が 60 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 75/100
似ている issue
-
kind/enhancement
難易度 2/5 1〜3時間 初心者へのやさしさ 74/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
openminion/openminion#857 ·
メンテナーはふだん 1 日以内に返信
-
bug
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
メンテナーはふだん 1 日以内に返信
-
HTTP `batch.Send` returns nil and inserts no rows when the block does not encode対応中かも @Indian-boult が今日担当しました。 オープンbug queries
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
ClickHouse/clickhouse-go#2155 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
MongoDB: shorten the index creation ERROR line and quiet the test output of grails-data-mongodb-coreオープン
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
apache/grails-core#17129 ·
メンテナーはふだん 1 日以内に返信