diff --git a/docs/architecture/search.md b/docs/architecture/search.md index 0838552d..1222e81d 100644 --- a/docs/architecture/search.md +++ b/docs/architecture/search.md @@ -2,7 +2,7 @@ Search uses `vault-search` and canonical Turso reads. `Vault` owns one indexer and a session registry. App Lock retains the Vault; closing it cancels jobs, drops every reader and joins the indexer before closing the store. The index lives under `derived/search-index/`, with the archive's encryption mode and a derived search key. -The indexer reads ordered outbox prefixes, loads current page documents and profile memberships, commits the highest sequence with `SearchIndex::apply`, then removes acknowledged rows with a Batch write. Reopen resumes from the durable index sequence. Reapplying a page replaces it. Missing, incompatible and corrupt generations rebuild from canonical page IDs. Healthy rebuilds publish a new generation only after its source scan and outbox tail are complete. Existing sessions retain their old reader until released. Initial builds publish increasing prefixes; every response identifies incomplete coverage. +The indexer reads ordered outbox prefixes, loads current page documents and profile memberships, commits the highest sequence with `SearchIndex::apply`, then removes acknowledged rows with a Batch write. It prunes after each applied batch, and once at its first poll after opening, for rows a crash left between publishing and pruning; a poll that finds nothing new writes nothing. Until 2026-11-13 every poll deleted from the outbox, ten times a second, and even a delete of no rows makes the archive writer checkpoint, hold readers back and empty their page caches. Reopen resumes from the durable index sequence. Reapplying a page replaces it. Missing, incompatible and corrupt generations rebuild from canonical page IDs. Healthy rebuilds publish a new generation only after its source scan and outbox tail are complete. Existing sessions retain their old reader until released. Initial builds publish increasing prefixes; every response identifies incomplete coverage. Normalization remains in vault-core: ICU NFKC, accent folding, OpenCC, aliases, compact text and CJK segmentation. Visible titles from different profiles retain phrase boundaries. Date/profile/browser predicates apply to the same canonical visit. Selective dates use the visible time indexes; other searches resolve posting batches through page→URL→visible-visit indexes. Hydration verifies current visibility and, once the archive has moved past the session's index snapshot, rechecks each page's current text against the query, so revoked visits and text never reach a result. Writes during a session never restart it: an earlier version restarted membership and counting on every canonical change, and a steady stream of writes (a backup, link previews, page-text fetching) then kept a search from ever finishing. diff --git a/docs/architecture/semantic-index-control.md b/docs/architecture/semantic-index-control.md index c103f1da..962cad59 100644 --- a/docs/architecture/semantic-index-control.md +++ b/docs/architecture/semantic-index-control.md @@ -294,6 +294,17 @@ lose the job's counts. Unchanged chunks still advance through the normal ledger rebuild retains its captured archive boundary; an incremental resume against another lineage starts at the beginning of that lineage's needs, including changed low-id visits. +A fresh build counts what is left to index before its first request, for the progress +denominator. The count reads visit ids 10,000 at a time, one short read each with a stop check in +between, and names `idx_ai_embeddings_lineage_history`. Left to itself Turso searches +`ai_embeddings` by provider, model and lineage, which every row of a lineage shares, so it reads +the whole lineage once per visit. The count was one unhinted statement, and from the lineage +column (2026-11-08) until 2026-11-13 it ran that way: 0.35 s for 2,000 synthetic visits already +indexed, 22.7 s for 16,000, hours for a real archive, and nothing could stop it. The same +8,000 visits took 6 ms on the schema before the lineage column. Any statement that joins +`ai_embeddings` on `history_id` needs the hint; `ai/tests_native/indexing/start.rs` checks the +plans of a build over an existing index. + The lease/closure audit covers status, query/staleness reads, related pages, topics, similar searches, grouping `Prepared._generation`, grouping event/opened-page reads, snapshot signatures and snapshot publication. `Prepared` stays on its caller, including the equal-digest warm branch; diff --git a/docs/architecture/turso-migration-design.md b/docs/architecture/turso-migration-design.md index e5d28e6d..b892abdc 100644 --- a/docs/architecture/turso-migration-design.md +++ b/docs/architecture/turso-migration-design.md @@ -69,7 +69,7 @@ - 每條連線只屬於一個執行緒。 - **寫入執行緒:** 每個資料庫一條,處理寫入佇列。佇列有兩個優先級:「互動」(星號、筆記、標籤、設定、預覽狀態)和「批次」(備份、匯入、重建)。每個批次交易結束後,先處理互動寫入,再開下一批。 -- **讀取執行緒池:** 大小由記憶體量測決定。每條讀取只開短交易,以免卡住 checkpoint。 +- **讀取執行緒池:** 大小由記憶體量測決定。每條讀取只開短交易,以免卡住 checkpoint。要數或走遍整個存檔的讀取分頁做:每頁一個交易,頁與頁之間檢查取消。 - 對外是同步的 request/reply 介面,接上 Tauri 的 `spawn_blocking`。不把 async 往上傳。 **取消:** 長操作(匯出、搜尋 collector、regex 掃描、批次寫入)每批之間檢查取消旗標。Turso 沒有公開的中斷介面。 @@ -80,6 +80,8 @@ - 每個批次之後做 PASSIVE。 - 寫入佇列空下來,而且讀取都結束時,做 TRUNCATE。 + - 為了等到「讀取都結束」,writer 先擋住新的讀取,再等進行中的讀取離開。這一等最多 50 ms:短讀取在這之內都會結束。有一條讀取跑得久而等不到時,writer 放行新的讀取,改在最後一條讀取離開時再做。那次等的時候在裡面的讀取,只要還有一條沒走,writer 就不再擋第二次:不管是之後又有寫入,還是它聽說有別的讀取走了(那個通知可能是它忙的時候留下的)。這條規則記在閘門裡(`vault-store/src/checkpoint.rs` 的 `Gate`),writer 的迴圈只問閘門。`Metrics::truncates_put_off` 數 writer 放棄了幾次,測試靠它判斷,不量時間。 + - 所以跑得久的讀取只會延後 TRUNCATE(它的 snapshot 本來就讓 WAL 截不掉),不會讓別的讀取或後面的寫入等它。延後的期間 WAL 會隨寫入長大:Turso 的 PASSIVE 不會讓 WAL 從頭寫起(量過:100 批都沒截時,WAL 就是整個匯入的大小),要等那條讀取結束才截掉。2026-11-13 以前這一等沒有上限:一條跑了幾小時的語句,加上任何一次寫入,讓 Archive 與 Intelligence 的所有讀取跟著等了幾小時(`vault-store/tests/admission.rs`)。 - 不依賴自動 checkpoint 的設定,0.8.1 會忽略它。 **Migration:** @@ -89,6 +91,8 @@ **引擎日誌:** Turso 在 B-tree 和 VDBE 的每一步都開 `tracing` span。行程裡沒有 `tracing` dispatcher 時,`tracing` 會把每個 span 轉給 `log`,app 的 logger 開在 Debug,於是每一步都要問一次 logger 的逐模組過濾。2026-10-07 量到,同一份兩萬多筆訪問的資料,Insights 重建在測試裡 7 秒,在 app 裡超過一分鐘。所以 app 啟動時用 `vault_store::route_engine_diagnostics_to_log()` 設一個只要 warning 和 error 的 dispatcher:span 在呼叫點就被關掉,引擎的警告照樣進 app 的日誌。 +**跑得久的語句:** 一條語句跑超過 30 秒,`vault-store` 在 log 裡點名它:哪個資料庫的哪條連線、跑了多久、語句的開頭(引號裡的字換成 `?`、註解拿掉;綁定的值本來就不在語句裡)。之後每翻一倍(60 秒、120 秒…)再記一次,結束時也記一行。它停不了那條語句(SDK 沒有中斷介面),只讓它不再無聲:讀取不再互相等之後,一條跑不完的語句唯一的跡象是佔住一條連線與一個核心、WAL 一直長大。2026-11-13 那條跑了幾小時,log 裡一個字也沒有。做法:每條連線記下自己正在跑的語句,`store-watch` 執行緒每 5 秒看一次(`vault-store/src/running.rs`)。工作跑語句的每一條路都經過 `Session::watch`:`Session` 的 `execute`、`query`、`for_each`,先 `prepare` 再 `execute` 或逐列讀的,還有 `integrity_check`。逐列讀的語句讀到最後一列就算結束,不等游標被丟掉。`vault-store` 自己跑的不看:BEGIN 與 COMMIT、checkpoint、migration 的版本紀錄、查詢計劃、複製資料庫。成本是每條語句多一次鎖和複製語句開頭的 300 bytes:最便宜的那種語句(prepare 好的單列 INSERT,約 620 ns)多約 20 ns,在各次量測的起伏之內。 + **錯誤:** 引擎的錯誤轉成 PathKeep 的分類:鎖定中、忙碌、損毀、金鑰錯誤、取消。前端遇到忙碌會自己恢復。 ## 5. 寫入模型 diff --git a/docs/plan/BACKLOG.md b/docs/plan/BACKLOG.md index f3cf3eea..a9eb9441 100644 --- a/docs/plan/BACKLOG.md +++ b/docs/plan/BACKLOG.md @@ -9,6 +9,39 @@ > 2026-10-25:清掉已完成或前提已不存在的 block(v0.3 Paper 前端、已移除的 coverage / mutation gate、已修好的 flaky 測試等,清單見 CHANGELOG 同日)。2026-04 到 2026-06 的收尾註記也一併移除,要看去 git 歷史或 CHANGELOG。 +- [ ] **WORK-SLOW-READ-ALARM** — 跑得久的語句現在會進 log,但 E2E 不會因此失敗、畫面上看不到、也停不了它(2026-11-13 `WORK-LONG-READ-OUTAGE` 做了 log 的部分) + - 讀先:`docs/architecture/turso-migration-design.md` §4(跑得久的語句)、`vault-store/src/running.rs`、`scripts/run-playwright.mjs`、`docs/design/ux-principles.md`。 + - 現況:一條語句跑超過 30 秒,`rust.log` 會點名它,之後每翻倍再記一次。要有人去看 log 才知道。 + - 要做: + - E2E 跑完檢查 app 沒有記這種行。測資只有兩萬多筆造訪,任何一句跑到 30 秒都是計劃選錯:這次的 COUNT 在測資大小上要 40 秒左右,E2E 的 120 秒等待沒擋下來。Rust 的警告會轉到瀏覽器的 console 再印到 runner 的輸出,但 `run-playwright.mjs` 現在是 `stdio: 'inherit'`,沒有在看;做的時候要先證明這條路真的把 `vault_store` 的行帶出來。 + - 畫面:後台任務頁說出「有一個讀取已經跑了多久」,要先過 `ux-principles`。 + - 停下它:`turso_core` 0.8.3 有 `Connection::interrupt`,SDK(`turso`)沒有露出來。查清楚能不能用,能的話暫停與取消就可以停掉跑到一半的語句,而不是等它自己結束。 + +- [ ] **WORK-INDEX-UPDATE-WALKS-ARCHIVE** — 每次備份後的索引更新都把整個存檔走一遍,只有幾十筆新造訪也一樣(2026-11-13 `WORK-LONG-READ-OUTAGE` 驗收時量到) + - 讀先:`docs/architecture/semantic-index-control.md`、`vault-core/src/ai/indexing/backfill.rs`(`run_embedding_backfill` 從游標 0 開始)、`candidates.rs`、`store_rows.rs` 的 `cleanup_stale_embeddings`。 + - 現象:增量建置每次從第一筆造訪讀到最後一筆(每 64 筆一塊:讀造訪、比內容雜湊、讀 enrichment),再把整個 lineage 的列走一遍找已撤銷的造訪,開跑前還要數一次剩多少。幾十萬筆造訪的存檔上,一次更新光是走完就要幾十秒到一兩分鐘,每小時一次;14.4M 是它的三十倍。都是分頁的短讀取,不會擋別人,只是白做。 + - 方向(先設計、先量):備份知道自己寫了哪些造訪、改了哪些頁面;讓更新只讀那些,整個走一遍留給「重新檢查」這種明確的操作。要處理:enrichment 之後才抓到內容的頁面、撤銷與還原、進度的分母。 + +- [ ] **WORK-UNBOUNDED-READS** — 還有一批「一句讀完整張表」的語句(2026-11-13 `WORK-LONG-READ-OUTAGE` 掃程式碼列出,多數沒跑 `EXPLAIN`) + - 讀先:`docs/architecture/turso-migration-design.md` §4、`vault-core/tests/intelligence_read_plans.rs`(計劃測試怎麼寫)、下面的 `WORK-TURSO-MINMAX-WRAPPER-AUDIT` 與 `WORK-SEMANTIC-VISIT-SIDECAR`(已經各自列管的不重複)。 + - 現象:這些各佔一條讀取連線(每個資料庫只有兩條)直到跑完,中途不能取消;`WORK-LONG-READ-OUTAGE` 之後不再讓別的讀取等。照「多常跑」排: + - Insights 建置開頭(每次有變動的備份之後):`intelligence/build_pipeline.rs:22-34` 一個讀取裡每個 profile 一句 `COUNT(*) FROM search_terms`。 + - 後台任務頁開著時每 2 秒:`intelligence_runtime/snapshot.rs:94-100`(`page_content_enrichments` 上沒有索引的 `COUNT`)、`enrichment/content_fetch_api.rs:172-178`。 + - 清單與卡片:`intelligence/search_queries.rs:70-85`(視窗函數掃範圍內所有關鍵字搜尋)、`ai/similar_searches.rs:216-238`、`archive/history/og_images.rs:84-90`(幾乎整張 `urls` 的 `COUNT(DISTINCT)`)、`ai/working_set.rs:190-194`。 + - Doctor 與修復:`archive/doctor.rs:76-115` 一個讀取跑二十幾句整表語句(其中 `DAMAGED_PAGES` 每頁一個沒有提示的相關子查詢,計劃沒驗過)、`doctor_derived.rs:59-110`、`intelligence_schema.rs:52-108`;`doctor.rs:176-184` 與 `:282-287` 是整表的寫入工作,會佔住唯一的 writer。 + - 沒有前端呼叫、計劃沒驗過的 IPC 命令:`intelligence_navigation.rs:84-95`、`phase_four.rs:284-303`、`intelligence_explain.rs:138-146`。 + - 方向:每一條先 `EXPLAIN QUERY PLAN`(在 14.4M 的種子資料上量),再決定分頁、加索引提示或加索引;常跑的先做。凡是拿 join 的鍵去查、表上又有「以常數欄開頭」的索引的語句都要看:Turso 沒有統計資料時會挑常數那個索引(這次的 COUNT 就是)。 + +- [ ] **WORK-STALE-WHEN-BACKEND-SILENT** — 後端不回的時候,畫面照樣顯示舊資料,按鈕沒有反應也沒有說明;IPC 與排程都沒有逾時(2026-11-13 `WORK-LONG-READ-OUTAGE` 查的時候確認) + - 讀先:`docs/design/ux-principles.md`、`docs/architecture/owner-process.md`(§請求不設期限的理由)、`src/features/settings/background/`、`src/lib/ipc/bridge.ts`、`vault-owner-ipc/src/client.rs`。 + - 現象:那天所有讀取都不回。後台任務頁停在點「繼續」之前的那一列(已暫停、舊的錯誤訊息,還給 ▶ 與 ✕),標題卻是「1 項運行中」:列與標題是兩個查詢,一個先回了;之後的輪詢都掛在同一個沒回的請求上,沒有轉圈也沒有錯誤。暫停、取消、開關按下去就一直停在 pending。排程備份的 worker 送出請求後無限等,launchd 的工作也沒有 `TimeOut`,於是之後每小時的備份都不會啟動。 + - 方向:先分清楚「慢」和「不回」。畫面:資料超過一段時間沒更新要看得出來(不是把舊資料當新的);一個動作送出後沒回,要說明並讓人能重試。排程:worker 等 owner 要有上限,逾時記成一次失敗的嘗試再退出,下一個小時才會再跑。設計要先過 `ux-principles`;`owner-process.md` 寫了請求不設期限的理由,要改先寫 trade-off。 + +- [ ] **WORK-EMPTY-WRITE-CHECKPOINT** — 什麼都沒改的寫入工作也讓 writer 做一次 checkpoint(2026-11-13 `WORK-LONG-READ-OUTAGE` 看到;搜尋索引器那個每 100 ms 一次的已經拿掉) + - 讀先:`vault-store/src/worker.rs`(writer 迴圈的 `dirty`)、`checkpoint.rs`。 + - 現象:writer 做完任何一個工作就當自己有東西要截,於是擋住新讀取(最多 50 ms)再做 TRUNCATE。改了 0 列的工作也一樣:`og_images.rs:255-257`、`enrichment/search_text.rs:15`、`stars`/`annotations` 沒變動的儲存。 + - 方向:WAL 裡沒有 frame 就不用截。先確認 Turso 的 `wal_checkpoint(PASSIVE)` 在空的 WAL 上回報的 frame 數可以拿來判斷,再改。 + - [ ] **WORK-BACKUP-INTEGRITY-SCALE** — 原生備份的新身分與讀法在 14.4M 和目標機上的量測(2026-11-01 PR #18 只量了 100 萬筆、M5 Max) - 要量:14.4M 的 v1 存檔更新(migration 2–21,含開啟者 backfill 與重建列號索引)的時間與峰值記憶體;更新後第一次備份(整個重讀、給每筆時間);之後每小時與每週的備份。目標機 4 核 / 8 GB,冷快取。 - 另外量一份 Sync 從新到舊寫的大檔(開啟者大多在子造訪之後):讀完才找到的開啟者分批寫,量它的時間。 @@ -107,10 +140,11 @@ - 根因:Turso 0.8.1 `translate/optimizer/mod.rs` 的 `detect_simple_aggregate` 只在結果欄「正好是」聚合式時走 MIN/MAX 捷徑(沿索引或 rowid 直接走到極值);外面包 `COALESCE`、`+1` 都不算,就退回掃描。Intelligence v2 遷移因此每批掃一次越長越大的新表,1M / 4M 量到 26.5 s / 129 s;改成不包、在 Rust 裡處理 NULL 之後 16.4 s / 66.9 s(`semantic-index-control.md`)。 - 要查(14.4M 時每次都掃一遍的優先):`intelligence/build_pipeline.rs:24`(每次 intelligence 建置掃 `visits`)、`ai/indexing/backfill.rs:413` 與 `:539`、`ai/generations/build.rs:145`、`ai/similar_searches.rs:198`、`ai/indexing/store_rows.rs:91`、`archive/doctor_derived.rs:76`,以及 `intelligence_runtime/enqueue.rs`、`job_control.rs` 的 `MAX(list_order)+1`(小表,可能不用改)。 - 做法:先用 `EXPLAIN` 確認每一條真的掃表,再改成不包的 `MAX(...)` 並在 Rust 裡處理 NULL;有 WHERE 的要確認存取路徑能直接走到極值。結果記進 `turso-review-ledger.md`。 + - 2026-11-13(`WORK-LONG-READ-OUTAGE`):增量建置開頭的三條在真實存檔的本機副本上確認是掃描(`SCAN ai_embeddings`、`SCAN visits`、`SCAN visits USING INDEX idx_visits_visible_time_id`),幾十萬筆造訪時合計約 2.5 秒,其中 `store_rows.rs` 那條掃整張 `ai_embeddings` 就佔 2 秒。`backfill.rs` 的 `max_candidate_history_id` 的註解說它「cheap」,不對。 - [ ] **WORK-SEMANTIC-VISIT-SIDECAR** — 語意搜尋每次都讀一遍範圍內的所有造訪:100 萬次 385 ms,14.4M 估 5.5 秒(M5 Max),目標機更慢(2026-10-17 做完 `WORK-SEMANTIC-PIPELINE` 量到) - 現況:一次語意搜尋 100 萬次造訪 500 ms,其中 385 ms 是一條 SQL 串流範圍內每次造訪(算頁面成員、最新時間與每頁最高分)。向量掃描只要 6 ms。 - - 串流是一次讀取,整段佔住 archive 兩條讀取連線中的一條;writer 做 WAL truncate checkpoint 前要等進行中的讀取結束(`vault-store/src/checkpoint.rs` 的 `wait_for_readers`,`worker.rs` 呼叫),這段時間進來的寫入也跟著等。14.4M 時一次語意搜尋可能讓匯入、備份的寫入延後數秒。以前的逐批回查是很多次短讀取,不會這樣;日期篩選的全文搜尋(`eligibility::load`)本來就是同一種長讀取。 + - 串流是一次讀取,整段佔住 archive 兩條讀取連線中的一條;writer 做 WAL truncate checkpoint 前要等進行中的讀取結束(`vault-store/src/checkpoint.rs` 的 `wait_for_readers`,`worker.rs` 呼叫)。2026-11-13 以前這一等沒有上限,這段時間進來的讀取與寫入都跟著等;現在最多等 50 ms(`WORK-LONG-READ-OUTAGE`),長讀取只佔一條讀取連線、延後 WAL 的截斷。以前的逐批回查是很多次短讀取,不會這樣;日期篩選的全文搜尋(`eligibility::load`)本來就是同一種長讀取。 - 方向(先設計、先量):建索引時把每次造訪的頁面與時間投影到索引旁(跟 `.pkpos` 同一份或並排),加上撤銷造訪的集合;沒有篩選或只有日期篩選時,頁面成員與每頁分數在記憶體裡算完,用到網站、標籤、筆記、星號、profile 等篩選才走 SQL 串流。要處理:索引之後才進來的造訪(成員與最新時間仍要算到它們)、撤銷與還原、App Lock 時放掉記憶體、`semantic_stage_bench` 量 1M / 4M。 - [!] **WORK-VECTOR-MEMORY-AT-SCALE** — 大語料時完整 int8 排序放不進 8 GB(等用戶在研究文件「What this means」的 A / B / C 中選) diff --git a/docs/plan/CHANGELOG.md b/docs/plan/CHANGELOG.md index e322f2f7..31ad455a 100644 --- a/docs/plan/CHANGELOG.md +++ b/docs/plan/CHANGELOG.md @@ -3095,3 +3095,11 @@ that held up when checked against the code. - `WORK-JS-DEPS-2026-11-10` (2026-11-10). Refreshed 30 direct JS and TS dependencies to current stable releases and kept typed ESLint on Microsoft's supported compiler API alongside the TypeScript 7 compiler. Aligned both Tauri plugin pairs, added a daily Bun Dependabot schedule and placed the lockfile audit in the normal gate. The original graph matched 19 packages and 88 distinct advisories on Bun 1.4.4. The refreshed graph passed across 532 checked packages. React Router now mounts a separate provider after onboarding. The Insights tests query Radix's `radiogroup` role and retain the original behavior assertions. Linux `bun run check` passed with 134 E2E cases and one platform skip. The Modal environment now sets `CI=true` for Tauri, and the desktop debug build and combined supply-chain checks passed in that environment. Local frontend checks passed with 107 tests. Validation is recorded in `docs/plan/releases/v0.5.0/dependency-refresh.json`. - PR #20 review and fresh RustSec scan (2026-11-13). A queued search frame could restore cleared rows before passive cleanup; the subscription now ends during commit and queued state updates check ownership. Three React race cases were written before the fix, with the cleared-search case failing under the old code. Modal setup could report success after an installation failed because the runner's conditional subshell suppressed errexit; a separate Bash process now preserves failure (injected exit 17 stops both later commands). The subsequent GitHub audit found newly issued RUSTSEC-2026-0486 after its full check passed. Updated the existing rustix 1.x dependency to 1.1.6, retaining compatible Windows bindings and adding no exception. The patched source passed `bun run verify` and `bun run check:supply-chain`: 110 frontend tests, 91 Rust test groups, 134 E2E cases and one platform skip, desktop debug build, zero JavaScript advisories and the same eight documented Rust exceptions. Both lockfiles stayed unchanged. Receipt: `docs/plan/releases/v0.5.0/pr20-review.json`. + +- `WORK-LONG-READ-OUTAGE` (2026-11-13). The user pressed Continue on a paused index build and the app stopped loading anything new: History showed only what it already had, Insights stayed on its skeletons and Background work kept a row from before the click. Three things combined, each confirmed on the stuck process (sampling and disassembly of the installed build), on synthetic data and on a local copy of the real archive. The statement that counts what a build has left to index had been planned differently since the lineage column of 2026-11-08: Turso searched `ai_embeddings` by provider, model and lineage, which every row of a lineage shares, and read the whole lineage once per visit (0.35 s for 2,000 synthetic visits, 22.7 s for 16,000; 6 ms for 8,000 on the schema before). A writer that had just committed kept new readers out until the readers already running had left, with no limit, so that one statement held up every read and every later write of Intelligence, and of Archive, which it also read. And the search indexer ended each 100 ms poll with a delete from its outbox whether or not there was anything to delete, so the archive writer checkpointed nine times a second and any archive read slower than a poll set that wait off. The count now names the index, reads 10,000 visit ids at a time and checks for a stop between reads; the writer waits 50 ms for readers and otherwise lets them back in, truncates when the last one leaves, and does not hold readers back again for the same read; the indexer writes only when it has something to prune. Until that read ends the WAL grows with what is written, since a passive checkpoint does not let Turso start it over. Ten tests were written before the changes (`vault-store/tests/admission.rs`, two in `search/recovery_tests.rs`, three in `ai/tests_native/indexing/start.rs`). Five fail on the old code: a read, a read of another database and a write each waiting for a read still running, the idle indexer writing, and the plans of a build over an existing index. The rest guard what the changes could break, or need the new code to compile. On the copy of the real archive the whole incremental build now runs: six seconds to its first embedding request (the count is 0.8 s of it; before, an estimated ten hours or more), and nine thousand other reads made meanwhile took at most 52 ms. One thing changes with the idle writes gone: each of them had emptied the readers' page caches, which now fill to their configured size (8 MiB a connection) and stay; `export_heap_stays_bounded_as_archive_grows` had passed only because they never filled, and now measures an export once they have (0.9 MiB at 10,000 visits and at 100,000). Follow-ups are in BACKLOG (`WORK-SLOW-READ-ALARM`, `WORK-INDEX-UPDATE-WALKS-ARCHIVE`, `WORK-UNBOUNDED-READS`, `WORK-STALE-WHEN-BACKEND-SILENT`, `WORK-EMPTY-WRITE-CHECKPOINT`). + +- `WORK-LONG-READ-OUTAGE`, the log line (2026-11-13). With reads no longer waiting for each other, a statement that never ends has no symptom left: one connection and one core stay busy, the WAL grows, and nothing says so. `vault-store` now names in the log any statement that has run for 30 seconds (which connection, for how long, and the start of the statement with whatever stands between quotes replaced by `?`), again each time that age doubles and once more when it ends; a `store-watch` thread looks every five seconds, and a statement costs one more lock and a 300-byte copy. It cannot stop the statement. `html5ever`'s "foster parenting not implemented" warnings, which were the only lines left in `rust.log` that day, are no longer logged. The test (`vault-store/tests/long_statement.rs`) was written first and failed with no line in the log. Still open in `WORK-SLOW-READ-ALARM`: making an E2E run fail on such a line, showing it in the app, and whether `turso_core`'s interrupt can stop a statement. + +- `WORK-LONG-READ-OUTAGE`, review of PR #24 (2026-11-13). ChatGPT Pro and CodeRabbit found nothing that blocks merging and five things to fix; each was checked against the code and held, and they come down to three causes. The writer's loop remembered the reader it had given up waiting for, one reader only, and forgot it on hearing that the last reader had left, which may have been said while it was busy and before that reader came in: the same long read then cost new readers a second 50 ms (reproduced on the real writer thirty times out of thirty), and a second long read inside at the first wait cost another once the first had left (found while checking). The gate now remembers the newest reader there was when the writer gave up and gives it no guard while any reader that old is still inside; the loop keeps no such state. The suggested one-line fix would have left the second case and a test that could only measure time. That test had counted twenty writes' disk time against 500 ms; `Metrics::truncates_put_off` now says how often the writer gave up, the admission tests read it, time nothing and wait for no fixed delay, and the gate's rule has two unit tests in which no time passes. The long-statement watch was attached to one of the ways a job runs a statement: prepared statements (most of Insights' heavy queries and the index build) and `integrity_check` went unnamed. All of them now pass through `Session::watch`, and a cursor counts as ended once its last row is read; the cost on the cheapest statement there is, a prepared single-row insert of about 620 ns, is about 20 ns, inside the spread between runs. The line's redactor did not know SQL comments, so an apostrophe in one turned the literals after it inside out; no statement in the app writes a value into its text, so nothing had leaked. It now tells comments and the four kinds of quotes apart as `sql::tokens` does and leaves comments out. The tests were written first, and those the earlier code could compile failed on it: two waits where one is right, no line for a prepared cursor, the value in the line. The gate's two unit tests need the new code to compile. `integrity_check`'s registration has no test of its own, since nothing can hold it open. + +- RUSTSEC-2026-0538 (2026-11-13). The advisory was issued the day PR #24 was opened and failed its supply-chain audit after the full check had passed on GitHub. It concerns `quinn-udp` 0.5.14, which is in the lockfile only through `reqwest`'s `http3` feature. PathKeep does not enable that feature and never compiles the crate. Updated to the fixed 0.5.16 by changing that package's version and checksum alone, since `cargo update` would also have moved nine other packages to older `windows-sys` releases; `cargo metadata --locked` accepts the result. No exception added. diff --git a/docs/plan/STATUS.md b/docs/plan/STATUS.md index 61259a8d..96a742f5 100644 --- a/docs/plan/STATUS.md +++ b/docs/plan/STATUS.md @@ -9,6 +9,27 @@ ## CURRENT FOCUS +- [x] **WORK-LONG-READ-OUTAGE** — 一條跑不完的讀取讓整個 app 讀不到新資料(用戶 2026-11-13 回報:在 AI 設定點「繼續」建立索引之後,歷史只剩已載入的、洞察永遠載入中,後台任務停在舊狀態)。 + - 讀先:`docs/architecture/turso-migration-design.md` §4(讀取池與 Checkpoint)、`semantic-index-control.md`、`search.md`、`docs/plan/program/quality-matrix.md`(什麼時候才寫 unit test)。 + - 原因有三層,在卡住的進程(採樣、反組譯)、合成資料與真實存檔的本機副本上都確認了: + 1. `10f05828`(11 月 8 日)給 `ai_embeddings` 加了 `lineage` 欄與索引。建置開跑前數「還有多少造訪沒建索引」的那句 `COUNT`,Turso 從此改用「provider、model、lineage」那個索引:每筆造訪把整個 lineage 讀一遍。合成資料 2,000 筆 0.35 秒、16,000 筆 22.7 秒(平方成長);同樣 8,000 筆在加欄之前的 schema 上是 6 ms。那次改動替另一句查詢加了索引提示並寫了測試,漏了這一句。升級後第一個真的開跑的建置就是用戶這一個。 + 2. `vault-store` 的 writer 寫完要截 WAL 時先擋住新讀取,再等進行中的讀取離開,沒有上限。一條長讀取加上任何一次寫入,那個資料庫所有新的讀取與後面的寫入就等到它結束;Intelligence 的讀取讀 `archive.*` 時,Archive 也一樣。 + 3. 搜尋索引器每 100 ms 輪詢一次,結尾無條件刪一次 outbox(刪 0 列也是一個寫入工作)。閒置時 archive 每秒九次以上 checkpoint,任何超過 0.1 秒的 archive 讀取都會碰上第 2 點。Intelligence 那邊是任務每 30 秒的心跳。 + - 修正:`COUNT` 指定 `idx_ai_embeddings_lineage_history`、照造訪 id 每 10,000 一頁、頁與頁之間看有沒有被要求停;writer 等讀取最多 50 ms,等不到就放行,最後一條讀取離開時再截,那條讀取還在的期間不再為它擋;索引器沒有新東西就不寫(開啟後第一次輪詢仍清一次當機留下的列)。 + - 測試十個,寫在修正之前:`vault-store/tests/admission.rs` 五個、`search/recovery_tests.rs` 兩個、`ai/tests_native/indexing/start.rs` 三個。其中五個在舊實作上失敗:讀取、跨資料庫的讀取、寫入不等還在跑的讀取;閒置的索引器不寫 archive;在既有索引上建置的查詢計劃。其餘守的是這次改動可能弄壞的地方(延後的截斷在長讀取結束後補做、當機留下的 outbox 列下次啟動清掉、計數的值、同一條長讀取不再反覆擋讀取:拿掉那條規則它會失敗),或要新程式碼才編得過(計數到一半可以停)。這些 E2E 重現不了:要幾十萬列才看得出來,或要一條被按住的讀取。 + - 驗收:真實存檔的本機副本(embedding 指向本機的假服務)上跑完整個增量建置。開跑到第一個 embedding 請求 6 秒,其中計數 0.8 秒;修之前同一句在同一份資料上每筆造訪要 70–150 ms,估計十幾個小時。建置期間另外跑的九千多次 Archive 與 Intelligence 讀取,中位數不到 0.1 ms,最慢 53 ms。`bun run check` 通過:前端 110 個測試,Rust 92 組,E2E 135 過。 + - 連帶的改變:讀取連線的頁面快取以前被那每秒十次的空寫入一再清空,現在會留著,長到設定的上限為止(每條連線 8 MiB;10 萬筆造訪的匯出跑幾次後兩條共約 14 MB,之後不再長)。`export_heap_stays_bounded_as_archive_grows` 原本靠快取被清空才量得到 2 MiB 以下,改成快取暖了再量:匯出本身在 1 萬與 10 萬筆都是 0.9 MiB。 + - 畫面上看到的「已暫停+舊錯誤」是點「繼續」之前的快照(列與標題是兩個查詢,之後的都沒回);「44 項失敗」是十月中的舊紀錄。 + - 同一天追加(第二個 commit):讀取不再互相等之後,一條跑不完的語句就沒有任何症狀了,所以讓它進 log。一條語句跑超過 30 秒,`vault-store` 點名它(連線、多久、語句開頭,引號裡的字換成 `?`),每翻倍再記一次,結束時也記;`html5ever` 的警告不再進 `rust.log`(那天的 log 只剩它)。測試 `vault-store/tests/long_statement.rs` 先寫,在沒有這個功能時失敗。 + - PR #24 的審查(ChatGPT Pro 與 CodeRabbit,2026-11-13,都說沒有擋合併的)。五條意見逐條對照程式碼,都成立,是三個原因;另一條是驗證時自己發現的。一起改: + 1. 「已經等過的讀取」記在 writer 的迴圈裡,而且只記一條。迴圈一聽到「最後一條讀取走了」就把它忘掉,但那個通知可能是 writer 忙的時候留下的,之後又有讀取進來,於是同一條長讀取多擋一次 50 ms(ChatGPT;在真的 writer 上重現,30 次都重現)。另外,等的時候裡面有兩條長讀取,只記了待最久的那條,它走了之後又為另一條擋一次(自己發現,同一個原因)。改成記在閘門裡:放棄時記下當時最新的讀取編號,編號不比它大的讀取還有一條在,就不讓 writer 擋。迴圈不再有這個狀態。審查建議只刪掉「忘掉」那一行;沒有照做,因為第二種情況還在,而且測試仍然只能靠計時。 + 2. `later_writes…` 把二十次寫入的磁碟時間算進 500 ms 的上限,磁碟慢就誤判(ChatGPT)。新增 `Metrics::truncates_put_off`(writer 放棄了幾次),`admission.rs` 改成讀它:不量時間,也沒有固定的等待,截止時間只用來不讓壞掉的版本卡住整個 suite。閘門的規則另有兩個不花時間的 unit test(等待上限設成零)。 + 3. 慢語句的記錄只接在 `Session::with_statement`。先 `prepare` 再跑的語句(Insights 的重查詢與索引建置多半這樣寫)和 `integrity_check` 都沒被看(ChatGPT、CodeRabbit)。現在每條路都經過 `Session::watch`,逐列讀的語句讀到最後一列就算結束。成本量過:prepare 好的單列 INSERT 約 620 ns,多約 20 ns,在各次量測的起伏之內。 + 4. log 那一行遮字串的程式不認得 SQL 註解:註解裡一個撇號,就讓後面的字串被當成語句本文印出來(CodeRabbit)。app 的語句裡有帶撇號的註解,但沒有把值寫進語句的地方,所以還沒有東西漏過。改成跟 `sql::tokens` 一樣分辨註解與四種引號,註解不印。 + - 測試先寫、先失敗:過期通知與兩條長讀取的兩個(各在改之前的版本上得到 2 次放棄,應為 1)、`long_statement.rs` 的 prepare 兩段(拿掉 `execute` 的登記、或讓讀完的游標繼續算,各自失敗)、遮字串的一個。閘門的兩個 unit test 要新程式碼才編得過。`integrity_check` 的登記沒有自己的測試:沒有辦法讓它停在半路。 + - GitHub 上這個 PR 的主要檢查(lint、建置、Rust、E2E,Ubuntu)通過,之後的供應鏈稽核失敗,跟這裡的改動無關:11 月 13 日發布的 RUSTSEC-2026-0538 影響 `quinn-udp` 0.5.14。它只因為 `reqwest` 的 `http3`(沒開)而列在 lockfile 裡,app 不編它(跑完整個 gate 的 target 裡沒有它的產物)。更新到修正版 0.5.16:lockfile 只改它自己的版本與 checksum,保留既有 Windows bindings(`cargo update` 會順手把另外九個套件的 `windows-sys` 換成舊版),不新增 advisory 例外。 + - 進 BACKLOG:`WORK-SLOW-READ-ALARM`(剩下的部分:E2E 檢查、畫面、中斷語句)、`WORK-INDEX-UPDATE-WALKS-ARCHIVE`、`WORK-UNBOUNDED-READS`、`WORK-STALE-WHEN-BACKEND-SILENT`、`WORK-EMPTY-WRITE-CHECKPOINT`;`WORK-TURSO-MINMAX-WRAPPER-AUDIT` 補了量測。 + - [x] **WORK-RUSTIX-2026-11-13** — 新發布的 RUSTSEC-2026-0486 擋下 PR #20 的供應鏈 gate,更新既有間接依賴後重新驗證。 - 讀先:`docs/architecture/dependency-maintenance.md`、RustSec 官方公告與 crates.io 的版本/依賴資料。 - 11 月 11 日發布的公告影響 rustix 1.1.4;更新至最新修正版 1.1.6。保留既有 Windows bindings,不新增 advisory 例外。GitHub 的完整 `bun run check` 已過,失敗的是隨後的新公告掃描。 diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 008bde7f..66587c1d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -5298,9 +5298,9 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.14" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", diff --git a/src-tauri/crates/vault-core/src/ai/indexing/backfill.rs b/src-tauri/crates/vault-core/src/ai/indexing/backfill.rs index 61344c9b..a6a02481 100644 --- a/src-tauri/crates/vault-core/src/ai/indexing/backfill.rs +++ b/src-tauri/crates/vault-core/src/ai/indexing/backfill.rs @@ -434,48 +434,80 @@ fn scan_target_for(connection: &Session<'_>, start_history_id: i64) -> Result, provider_id: &str, model: &str, rebuild: bool, lineage: &str, + after: i64, + through: i64, ) -> Result { let count: i64 = connection .query_one( "SELECT COUNT(*) FROM archive.visits AS visits - WHERE visits.reverted_at IS NULL + WHERE visits.id > ?5 AND visits.id <= ?6 + AND visits.reverted_at IS NULL AND (?3 = 1 OR NOT EXISTS ( - SELECT 1 FROM ai_embeddings AS e - WHERE e.provider_id = ?1 AND e.model = ?2 AND e.lineage=?4 AND e.history_id = visits.id + SELECT 1 FROM ai_embeddings AS e INDEXED BY idx_ai_embeddings_lineage_history + WHERE e.history_id = visits.id + AND e.provider_id = ?1 AND e.model = ?2 AND e.lineage = ?4 ))", - params![provider_id, model, i64::from(rebuild), lineage], + params![provider_id, model, i64::from(rebuild), lineage, after, through], |row| Ok(row.get(0)?), ) .context("counting candidate pages needing embedding for the index embed target")?; Ok(count.max(0) as u64) } -/// Resolves the embed-progress denominator to REPORT this run: the captured candidate count on a -/// fresh build, else 0 ("unknown — preserve the stored target"). Mirrors [`scan_target_for`] so a -/// resume never recounts a corpus that grew (or got partially embedded) under the build. +/// Resolves the embed-progress denominator to REPORT this run: the visits still missing from this +/// pair on a fresh build, else 0 ("unknown — preserve the stored target"). Mirrors +/// [`scan_target_for`] so a resume never recounts a corpus that grew (or got partially embedded) +/// under the build. Runs once, in the background, before the first request; `scan_target` is the +/// highest id to count through. +#[allow(clippy::too_many_arguments)] fn embed_target_for( - connection: &Session<'_>, + vault: &crate::Vault, provider_id: &str, model: &str, start_history_id: i64, rebuild: bool, lineage: &str, + scan_target: i64, + run_control: Option<&Arc>, ) -> Result { if start_history_id > 0 { return Ok(0); } - candidate_visit_count(connection, provider_id, model, rebuild, lineage) + let mut total = 0; + let mut after = 0; + while after < scan_target { + checkpoint_ai_run(run_control, COUNT_STOPPED)?; + let through = after.saturating_add(COUNT_PAGE_IDS).min(scan_target); + let (provider_id, model, lineage) = + (provider_id.to_owned(), model.to_owned(), lineage.to_owned()); + total += vault.read(Db::Intelligence, move |s| { + candidate_visit_count(s, &provider_id, &model, rebuild, &lineage, after, through) + })?; + after = through; + } + Ok(total) } /// Embeds candidate rows in resumable, cancellable chunks and persists them to the vector plane. @@ -550,12 +582,16 @@ async fn run_embedding_backfill( let scan_target = vault.read(Db::Intelligence, move |s| scan_target_for(s, start_history_id))?; // Count visits still missing from this pair before the first request. Resume keeps its target. - let provider_id = provider.config.id.clone(); - let model = provider.config.default_model.clone(); - let build_lineage = lineage.to_owned(); - let embed_target = vault.read(Db::Intelligence, move |s| { - embed_target_for(s, &provider_id, &model, start_history_id, rebuild, &build_lineage) - })?; + let embed_target = embed_target_for( + vault, + &provider.config.id, + &provider.config.default_model, + start_history_id, + rebuild, + lineage, + scan_target, + run_control, + )?; // The cursor reflecting the last chunk whose vectors+map+Turso are ALL durably persisted (F2.1). // It NEVER advances past a chunk that has not been fully persisted, so persisting it on the failure // path resumes from REAL progress instead of the origin — and never SKIPS an un-persisted chunk diff --git a/src-tauri/crates/vault-core/src/ai/indexing/mod.rs b/src-tauri/crates/vault-core/src/ai/indexing/mod.rs index 3234f55b..8994d104 100644 --- a/src-tauri/crates/vault-core/src/ai/indexing/mod.rs +++ b/src-tauri/crates/vault-core/src/ai/indexing/mod.rs @@ -46,6 +46,8 @@ pub use super::generations::{ collect_in_background as collect_index_generations_in_background, collect_index_generations, }; +#[cfg(test)] +pub(super) use self::backfill::{COUNT_PAGE_IDS, COUNT_STOPPED}; #[cfg(test)] pub(super) use self::candidates::{collect_visit_chunk, select_embed_targets}; pub(crate) use self::content::enrichment_summary_for; diff --git a/src-tauri/crates/vault-core/src/ai/tests_native/indexing.rs b/src-tauri/crates/vault-core/src/ai/tests_native/indexing.rs index ba013aa4..3379a47c 100644 --- a/src-tauri/crates/vault-core/src/ai/tests_native/indexing.rs +++ b/src-tauri/crates/vault-core/src/ai/tests_native/indexing.rs @@ -208,6 +208,8 @@ mod rebuild; mod resume; +mod start; + /// Changing a service's model leaves the old model's index behind. Ways cleaning it up could go /// wrong: the index still in use deleted with it; the old rows deleted but its files kept (or the /// other way round); a ready ledger survives deleted files; cleanup repeats on every build. diff --git a/src-tauri/crates/vault-core/src/ai/tests_native/indexing/start.rs b/src-tauri/crates/vault-core/src/ai/tests_native/indexing/start.rs new file mode 100644 index 00000000..a132ce57 --- /dev/null +++ b/src-tauri/crates/vault-core/src/ai/tests_native/indexing/start.rs @@ -0,0 +1,171 @@ +//! Responsibilities: what a build reads before its first embedding request. +//! Not responsible for: the embed loop, resuming or rebuilding (their own groups). +//! Failure modes (2026-11-13: a build over an index of a few hundred thousand visits never +//! reached its first request. The statement that counts what is left to index walked the whole index once per +//! visit, and it was one statement, so it could not be stopped and held up every other read): +//! - a statement that reads visits against the index walks the index, or the visits, whole; +//! - the count is wrong: a visit taken back, or a row of another model, changes it; +//! - a stop asked for during the count is not seen until the count ends. +use super::*; +use crate::ai::indexing::{COUNT_PAGE_IDS, COUNT_STOPPED}; +use fixtures::{SeedVisit, seed_visits}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn pages(ids: impl IntoIterator) -> Vec { + ids.into_iter() + .map(|id| { + SeedVisit::chrome( + id, + "chrome:Default", + &format!("https://example.com/page/{id}"), + Some("Page"), + id, + ) + }) + .collect() +} + +#[test] +fn a_build_over_an_existing_index_reads_neither_it_nor_the_visits_whole() { + let runtime = Runtime::new().expect("runtime"); + let (_paths, config, connection) = prepared_archive(); + let vault = connection.vault.clone().with_config(config); + let provider = embedding_provider(); + seed_visits(&vault, pages(1..=40)); + runtime.block_on(build_ai_index(&vault, &provider, &AiIndexRequest::default())).expect("first"); + seed_visits(&vault, pages(41..=43)); + + vault.store().capture_query_plans(Db::Intelligence, true).unwrap(); + let report = runtime + .block_on(build_ai_index(&vault, &provider, &AiIndexRequest::default())) + .expect("second build"); + vault.store().capture_query_plans(Db::Intelligence, false).unwrap(); + assert_eq!(report.indexed_items, 3); + + let joins: Vec<_> = vault + .store() + .take_query_plans(Db::Intelligence) + .unwrap() + .into_iter() + .filter(|plan| plan.sql.contains("archive.visits") && plan.sql.contains("ai_embeddings")) + .collect(); + assert!( + joins.iter().any(|plan| plan.sql.contains("COUNT(*)")), + "the build no longer counts what is left to index here: {joins:#?}" + ); + for plan in &joins { + for step in &plan.steps { + // Every row of one index shares these three values, so a search held by them alone + // reads all of it. (Cleanup also bounds `id`, and is fine.) + assert!( + !step.ends_with("(provider_id=? AND model=? AND lineage=?)"), + "walks the whole index for each visit: {plan:#?}" + ); + assert!( + !step.starts_with("SCAN visits"), + "reads every visit in one statement: {plan:#?}" + ); + } + } +} + +#[test] +fn the_count_of_what_is_left_is_the_visits_shown_that_have_no_row_of_this_model() { + let runtime = Runtime::new().expect("runtime"); + let (_paths, config, connection) = prepared_archive(); + let vault = connection.vault.clone().with_config(config.clone()); + let archive = TestDatabase::new(&vault, Db::Archive); + let provider = embedding_provider(); + seed_visits(&vault, pages(1..=6)); + let (indexed, first) = + run_backfill_chunk(&runtime, &vault, &config, &provider, &AiIndexRequest::default(), 0); + assert_eq!((indexed.len(), first.embed_target), (6, 6)); + + // Left to index: 3 lost its row, 7 has a row of another model only, 8 is new. + // Not left: 9 was taken back. + seed_visits(&vault, pages(7..=9)); + connection.execute("DELETE FROM ai_embeddings WHERE history_id=3", ()).unwrap(); + let mut other = embedding_provider(); + other.config.default_model = "another-embedding-model".to_string(); + let lineage = source_paths(&vault, &provider) + .vectors_dir + .file_name() + .unwrap() + .to_str() + .unwrap() + .to_owned(); + let row = IndexedVisit { + history_id: 7, + profile_id: "chrome:Default".into(), + url: "https://example.com/page/7".into(), + title: Some("Page".into()), + domain: "example.com".into(), + visited_at: "2026-04-04T00:00:00Z".into(), + content: "content".into(), + content_hash: "other-model".into(), + content_key: 0, + needs_embedding: true, + }; + let other_model = other.clone(); + connection + .write(move |s| { + crate::ai::indexing::upsert_embedding( + s, + &other_model, + &row, + "2026-04-04T00:00:00Z", + &lineage, + ) + }) + .unwrap(); + archive + .execute( + "UPDATE visits SET reverted_at='2026-04-05T00:00:00Z', reverted_by_run_id=1 WHERE id=9", + (), + ) + .unwrap(); + + let (_, second) = + run_backfill_chunk(&runtime, &vault, &config, &provider, &AiIndexRequest::default(), 0); + assert_eq!(second.embed_target, 3); +} + +/// Lets the count read its first page, then asks the build to stop. +struct StopAfterTheFirstPage(AtomicUsize); +impl AiRunControl for StopAfterTheFirstPage { + fn checkpoint(&self, detail: &str) -> Result<()> { + if detail == COUNT_STOPPED && self.0.fetch_add(1, Ordering::SeqCst) == 1 { + return Err(AiRunCancelled::new(detail).into()); + } + Ok(()) + } +} + +#[test] +fn a_stop_asked_for_during_the_count_ends_the_build_before_the_count_does() { + let runtime = Runtime::new().expect("runtime"); + let (_paths, config, connection) = prepared_archive(); + let vault = connection.vault.clone().with_config(config); + let provider = embedding_provider(); + // Three visits whose ids are far enough apart for the count to take three reads. + seed_visits(&vault, pages([1, COUNT_PAGE_IDS + 1, 2 * COUNT_PAGE_IDS + 1])); + let control = Arc::new(StopAfterTheFirstPage(AtomicUsize::new(0))); + let stop: Arc = control.clone(); + let error = runtime + .block_on(build_ai_index_with_control( + &vault, + &provider, + &AiIndexRequest::default(), + Some(stop), + 0, + 0, + None, + )) + .expect_err("the build went on after it was asked to stop"); + assert!(error.downcast_ref::().is_some(), "{error:#}"); + assert_eq!(control.0.load(Ordering::SeqCst), 2, "the count read on after the stop"); + assert_eq!( + embedding_count(&connection, &provider.config.id, &provider.config.default_model).unwrap(), + 0 + ); +} diff --git a/src-tauri/crates/vault-core/src/search/indexer.rs b/src-tauri/crates/vault-core/src/search/indexer.rs index 2c2fe297..c349cc55 100644 --- a/src-tauri/crates/vault-core/src/search/indexer.rs +++ b/src-tauri/crates/vault-core/src/search/indexer.rs @@ -2,7 +2,8 @@ //! Not responsible for: archive writes, normalization policy or query sessions. //! Failure modes: acknowledging before commit loses pages; replay duplicates pages; //! failed rebuild replaces good readers; missing index silently looks empty; -//! close leaves the writer or encryption cache alive; unbounded queues retain the corpus. +//! close leaves the writer or encryption cache alive; unbounded queues retain the corpus; +//! an idle poll writes to the archive. //! Tests: search::tests, vault-search canonical/crash/recovery contracts. use super::{documents, generations::Generations}; @@ -101,6 +102,7 @@ impl Indexer { cancel: worker_cancel, generations, published: worker_index.clone(), + pruned: None, }; let mut result = if deferred { Ok(()) @@ -325,6 +327,9 @@ struct Worker { state: Arc>, stop: CancelToken, cancel: Arc>, + /// The sequence the outbox was last pruned through by this owner. `None` until the first + /// prune, which also removes what a crash between publishing and pruning left behind. + pruned: Option, } impl Worker { fn fail(&self, error: &anyhow::Error) { @@ -374,19 +379,24 @@ impl Worker { state.documents_processed += documents; state.documents_total = state.documents_total.max(state.documents_processed); } - // Includes a crash after publication but before pruning. - self.acknowledge(after)?; + // Includes a crash after publication but before pruning. Once pruned through `after` + // there is nothing left to remove, and the poll runs ten times a second: a write that + // deletes nothing still makes the archive writer checkpoint and keep readers out. + if self.pruned != Some(after) { + self.acknowledge(after)?; + } let mut state = self.state.lock().unwrap(); state.applied_seq = after; state.phase = if after >= target { IndexerPhase::Ready } else { IndexerPhase::Updating }; state.error = None; Ok(()) } - fn acknowledge(&self, seq: u64) -> Result<()> { + fn acknowledge(&mut self, seq: u64) -> Result<()> { self.store.write(Db::Archive, Priority::Batch, move |s| { s.execute("DELETE FROM search_outbox WHERE seq<=?1", [seq as i64])?; Ok(()) })?; + self.pruned = Some(seq); Ok(()) } fn rebuild( diff --git a/src-tauri/crates/vault-core/src/search/recovery_tests.rs b/src-tauri/crates/vault-core/src/search/recovery_tests.rs index 3f128a10..2708f353 100644 --- a/src-tauri/crates/vault-core/src/search/recovery_tests.rs +++ b/src-tauri/crates/vault-core/src/search/recovery_tests.rs @@ -1,7 +1,10 @@ //! Responsibilities: kill real owner applies and recover missing/corrupt derived indexes. //! Not responsible for: mocking storage publication or testing cryptographic primitives. //! Failure modes: commit/ack crash loses an event, old locks survive death, missing sidecar -//! looks complete, or corruption destroys canonical facts. Runs both storage modes. +//! looks complete, or corruption destroys canonical facts; an indexer with nothing to do writes +//! to the archive on every poll (2026-11-13: ten empty writes a second, each followed by a +//! checkpoint that kept readers out); rows a crash left in the outbox are never pruned. +//! Runs both storage modes. use super::{SearchRequest, SearchSession}; use crate::{SetNotesRequest, Vault}; use std::{ @@ -195,3 +198,59 @@ fn cancelling_a_rebuild_preserves_search_and_a_later_rebuild_can_finish() { crate::test_support::assert_search_handoff(&vault); } } + +#[test] +fn an_indexer_with_nothing_to_do_does_not_write_to_the_archive() { + let vault = Vault::open_temp().unwrap(); + super::tests::seed(&vault, 25); + vault.search().cycle().unwrap(); + // Let the writer finish the checkpoint that follows the last real write. + std::thread::sleep(Duration::from_millis(500)); + let before = vault.store().metrics(vault_store::Db::Archive); + // Ten polls of the indexer. + std::thread::sleep(Duration::from_secs(1)); + let after = vault.store().metrics(vault_store::Db::Archive); + assert_eq!( + (after.passive_checkpoints, after.truncate_checkpoints), + (before.passive_checkpoints, before.truncate_checkpoints), + "the idle indexer kept the archive writer checkpointing" + ); + crate::test_support::assert_search_handoff(&vault); +} + +#[test] +fn outbox_rows_a_crash_left_behind_are_pruned_at_the_next_start() { + let outbox = |vault: &Vault| { + vault + .store() + .read(vault_store::Db::Archive, |s| { + s.query_one("SELECT COUNT(*) FROM search_outbox", (), |r| Ok(r.get::(0)?)) + }) + .unwrap() + }; + for key in [None, Some([99; 32])] { + let vault = Vault::open_temp_with_key(key).unwrap(); + super::tests::seed(&vault, 25); + vault.search().cycle().unwrap(); + assert_eq!(outbox(&vault), 0); + // What a crash between publishing the index and pruning leaves: rows the index has + // already applied. + vault + .store() + .write(vault_store::Db::Archive, vault_store::Priority::Batch, |s| { + s.execute( + "INSERT INTO search_outbox(seq,page_id,change) VALUES(1,1,'upsert')", + (), + )?; + Ok(()) + }) + .unwrap(); + let paths = vault.paths().clone(); + let config = vault.config().clone(); + vault.close().unwrap(); + let reopened = Vault::open(paths, config, key).unwrap(); + reopened.search().cycle().unwrap(); + assert_eq!(outbox(&reopened), 0); + crate::test_support::assert_search_handoff(&reopened); + } +} diff --git a/src-tauri/crates/vault-store/src/checkpoint.rs b/src-tauri/crates/vault-store/src/checkpoint.rs index 2aa601d0..a26f7218 100644 --- a/src-tauri/crates/vault-store/src/checkpoint.rs +++ b/src-tauri/crates/vault-store/src/checkpoint.rs @@ -1,10 +1,14 @@ //! Responsibilities: coordinate reader admission with idle WAL truncation and record results. //! Not responsible for: automatic checkpoint tuning or interrupting statements. //! Failure modes: TRUNCATE races new readers; reader completion fails to wake an idle -//! writer; busy checkpoint is reported as success; WAL grows across short reads. -//! Tests: checkpoint tests and wal tests. +//! writer; busy checkpoint is reported as success; WAL grows across short reads; a read that +//! runs long keeps every other reader out for as long as it runs, or once more each time the +//! writer thinks of truncating. Tests: checkpoint tests, wal tests and admission tests. use crate::{Error, Result, engine::Engine}; -use std::sync::{Arc, Condvar, Mutex}; +use std::{ + sync::{Arc, Condvar, Mutex}, + time::{Duration, Instant}, +}; /// Operational measurements distinguish a completed commit from later maintenance. #[derive(Clone, Debug, Default)] @@ -13,6 +17,10 @@ pub struct Metrics { pub batch_pending: usize, pub passive_checkpoints: u64, pub truncate_checkpoints: u64, + /// Idle truncates the writer put off because a read was still running when it had waited + /// long enough. The reads inside at one wait cost one, however many writes come while + /// they run. + pub truncates_put_off: u64, pub checkpoint_busy: u64, pub last_checkpoint_frames: Option, pub last_checkpoint_backfilled: Option, @@ -23,15 +31,20 @@ pub struct Metrics { } #[derive(Default)] struct Admission { - active: usize, + /// The readers inside, by entry number. Numbers only grow, so a lower one entered earlier. + inside: Vec, + entered: u64, truncating: bool, + /// The newest reader there was when the writer last gave up waiting. Every reader that + /// was inside then has this number or a lower one. + given_up: u64, } pub(crate) struct Gate { state: Mutex, changed: Condvar, wake: Box, } -pub(crate) struct ReadGuard<'a>(&'a Gate); +pub(crate) struct ReadGuard<'a>(&'a Gate, u64); pub(crate) struct TruncateGuard<'a>(&'a Gate); impl Gate { @@ -47,19 +60,29 @@ impl Gate { while s.truncating { s = self.changed.wait(s).unwrap() } - s.active += 1; - ReadGuard(self) + s.entered += 1; + let entry = s.entered; + s.inside.push(entry); + ReadGuard(self, entry) } // Reserve admission only while the writer is idle. Existing short readers - // finish normally; new readers wait for this checkpoint, never for a batch. - pub fn reserve_truncate(&self) -> TruncateGuard<'_> { + // finish normally; new readers wait for this checkpoint, never for a batch, and + // never for a reader that is still running (`TruncateGuard::wait_for_readers`). + /// `None` while a reader the writer has already given up waiting for is still inside. + /// Keeping new readers out for it again would gain nothing, whatever made the writer + /// ask: a later write, or word that some other reader has left. + pub fn reserve_truncate(&self) -> Option> { let mut s = self.state.lock().unwrap(); + let given_up = s.given_up; + if s.inside.iter().any(|entry| *entry <= given_up) { + return None; + } s.truncating = true; - TruncateGuard(self) + Some(TruncateGuard(self)) } pub fn try_truncate(&self) -> Option> { let mut s = self.state.lock().unwrap(); - if s.active != 0 || s.truncating { + if !s.inside.is_empty() || s.truncating { return None; } s.truncating = true; @@ -67,18 +90,30 @@ impl Gate { } } impl TruncateGuard<'_> { - pub fn wait_for_readers(&self) { + /// Waits, for at most `limit`, until the readers already inside have left, and says + /// whether they have. If one is still running, the caller drops this guard, so readers are + /// let in again, and truncates later: [`Gate::reserve_truncate`] gives no other guard + /// until the readers given up on here are gone. Waiting without a limit made every new + /// read wait for the slowest one running (2026-11-13: for hours). + pub fn wait_for_readers(&self, limit: Duration) -> bool { + let deadline = Instant::now() + limit; let mut state = self.0.state.lock().unwrap(); - while state.active != 0 { - state = self.0.changed.wait(state).unwrap(); + while !state.inside.is_empty() { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + state.given_up = state.entered; + return false; + } + state = self.0.changed.wait_timeout(state, left).unwrap().0; } + true } } impl Drop for ReadGuard<'_> { fn drop(&mut self) { let mut s = self.0.state.lock().unwrap(); - s.active -= 1; - let last = s.active == 0; + s.inside.retain(|entry| *entry != self.1); + let last = s.inside.is_empty(); self.0.changed.notify_all(); drop(s); if last { @@ -154,6 +189,39 @@ mod tests { drop(truncate); assert!(gate.try_truncate().is_some()); } + + /// What the writer does when a reader outlasts its wait. No time passes: the limit is zero. + fn give_up(gate: &Gate) { + let guard = gate.reserve_truncate().expect("nothing kept the writer from waiting"); + assert!(!guard.wait_for_readers(Duration::ZERO)); + } + #[test] + fn readers_are_kept_out_once_for_a_reader_that_stays() { + let gate = Gate::new(|| {}); + let long = gate.enter(); + give_up(&gate); + // Asked again, whatever the reason: a later write, word of a reader that left before. + assert!(gate.reserve_truncate().is_none()); + let newer = gate.enter(); + assert!(gate.reserve_truncate().is_none()); + drop(long); + // `newer` came in after that wait, so the writer waits for it once too. + give_up(&gate); + assert!(gate.reserve_truncate().is_none()); + drop(newer); + assert!(gate.reserve_truncate().unwrap().wait_for_readers(Duration::ZERO)); + } + #[test] + fn every_reader_inside_at_the_wait_has_been_given_up_on() { + let gate = Gate::new(|| {}); + let first = gate.enter(); + let second = gate.enter(); + give_up(&gate); + drop(first); + assert!(gate.reserve_truncate().is_none(), "the second reader was waited for as well"); + drop(second); + assert!(gate.reserve_truncate().is_some()); + } } #[cfg(test)] diff --git a/src-tauri/crates/vault-store/src/config.rs b/src-tauri/crates/vault-store/src/config.rs index f117deab..0c0b6be1 100644 --- a/src-tauri/crates/vault-store/src/config.rs +++ b/src-tauri/crates/vault-store/src/config.rs @@ -7,6 +7,7 @@ use std::{ num::NonZeroUsize, path::{Path, PathBuf}, sync::Arc, + time::Duration, }; /// Stable database identities keep business callers independent of file layout. @@ -72,6 +73,8 @@ pub struct Config { pub readers_per_database: NonZeroUsize, pub page_cache_kib: NonZeroUsize, pub interactive_queue_capacity: NonZeroUsize, + /// How long one statement may run before the log names it (`running.rs`). + pub long_statement_after: Duration, pub migrations: MigrationRegistry, } impl Config { @@ -87,6 +90,7 @@ impl Config { readers_per_database: NonZeroUsize::new(2).unwrap(), page_cache_kib: NonZeroUsize::new(8192).unwrap(), interactive_queue_capacity: NonZeroUsize::new(64).unwrap(), + long_statement_after: Duration::from_secs(30), migrations: MigrationRegistry::default(), } } diff --git a/src-tauri/crates/vault-store/src/engine.rs b/src-tauri/crates/vault-store/src/engine.rs index e12a3bb7..6eb2fa0b 100644 --- a/src-tauri/crates/vault-store/src/engine.rs +++ b/src-tauri/crates/vault-store/src/engine.rs @@ -32,6 +32,8 @@ pub(crate) struct Settings { pub scratch_key: Option<[u8; 32]>, pub io: Option, pub cache_kib: usize, + /// Where the writer and each reader say what they are running (`running.rs`). + pub watched: Option<(Arc, Vec>)>, } impl Settings { pub fn new(config: &Config, db: Db) -> Self { @@ -48,6 +50,7 @@ impl Settings { scratch_key: config.keys[Db::Scratch as usize], io: config.io.clone(), cache_kib: config.page_cache_kib.get(), + watched: None, } } fn builder(&self, read_only: bool) -> turso::Builder { @@ -96,6 +99,7 @@ pub(crate) fn preflight(config: &Config) -> Result<()> { conn: &conn, prepared: None, read_only: true, + running: None, _thread: PhantomData, scratch: None, scratch_read: Default::default(), @@ -163,13 +167,15 @@ pub(crate) struct Engine { pub conn: turso::Connection, pub database: turso::Database, prepared: StatementCache, + pub running: Option>, } impl Engine { pub fn open(settings: &Settings, compiled: Arc) -> Result { let rt = runtime()?; let database = rt.block_on(settings.builder(false).build())?; let conn = database.connect()?; - let engine = Self { rt, conn, database, prepared: StatementCache::new(compiled) }; + let running = settings.watched.as_ref().map(|(writer, _)| writer.clone()); + let engine = Self { rt, conn, database, prepared: StatementCache::new(compiled), running }; engine.configure(settings, false)?; Ok(engine) } @@ -177,10 +183,13 @@ impl Engine { database: turso::Database, settings: &Settings, compiled: Arc, + index: usize, ) -> Result { let rt = runtime()?; let conn = database.connect()?; - let engine = Self { rt, conn, database, prepared: StatementCache::new(compiled) }; + let running = + settings.watched.as_ref().and_then(|(_, readers)| readers.get(index).cloned()); + let engine = Self { rt, conn, database, prepared: StatementCache::new(compiled), running }; engine.configure(settings, true)?; Ok(engine) } @@ -192,6 +201,7 @@ impl Engine { conn: &self.conn, prepared: Some(&self.prepared), read_only, + running: self.running.as_deref(), _thread: PhantomData, scratch: None, scratch_read: Default::default(), @@ -276,7 +286,7 @@ mod tests { let settings = Settings::new(&config, Db::Archive); let writer = Engine::open(&settings, Default::default()).unwrap(); let reader = - Engine::reader(writer.database.clone(), &settings, Default::default()).unwrap(); + Engine::reader(writer.database.clone(), &settings, Default::default(), 0).unwrap(); for engine in [&writer, &reader] { let main = pragma_number(engine, "PRAGMA main.cache_size"); let scratch = pragma_number(engine, "PRAGMA scratch.cache_size"); diff --git a/src-tauri/crates/vault-store/src/lib.rs b/src-tauri/crates/vault-store/src/lib.rs index 69ea5b66..286f7590 100644 --- a/src-tauri/crates/vault-store/src/lib.rs +++ b/src-tauri/crates/vault-store/src/lib.rs @@ -14,6 +14,7 @@ mod migration; mod owner_lock; mod query_plans; mod queue; +mod running; mod session; mod statement_cache; pub use query_plans::QueryPlan; @@ -46,6 +47,8 @@ pub struct Store { ownership: Mutex>>, closed: AtomicBool, paths: Paths, + /// After `workers`, whose connections it watches: it stops when the store is dropped. + watch: running::Watch, } impl Store { /// Keep the ownership inode reserved across a verified maintenance replacement. @@ -79,6 +82,7 @@ impl Store { ownership: Mutex::new(Some(lock)), closed: AtomicBool::new(false), paths: config.paths.clone(), + watch: running::Watch::start(config.long_statement_after)?, }; // Keep scratch's database handle alive before any connection attaches it. for db in [Db::Scratch, Db::Archive, Db::SourceEvidence, Db::Intelligence, Db::Agent] { @@ -94,9 +98,15 @@ impl Store { } else { None }; + let mut settings = engine::Settings::new(&config, db); + settings.watched = Some((store.watch.slot(format!("{db:?} writer")), { + (0..config.readers_per_database.get()) + .map(|index| store.watch.slot(format!("{db:?} reader {index}"))) + .collect() + })); let workers = worker::Workers::start( db, - engine::Settings::new(&config, db), + settings, config.migrations.get(db), config.readers_per_database.get(), config.interactive_queue_capacity.get(), diff --git a/src-tauri/crates/vault-store/src/running.rs b/src-tauri/crates/vault-store/src/running.rs new file mode 100644 index 00000000..a9229b5e --- /dev/null +++ b/src-tauri/crates/vault-store/src/running.rs @@ -0,0 +1,231 @@ +//! Responsibilities: name in the log a statement that has been running for a long time, again +//! each time that time doubles, and once more when it ends. +//! Not responsible for: stopping it (the SDK has no interrupt), timing statements that end +//! soon, work made of many short statements, or what the store runs for itself (BEGIN and +//! COMMIT, checkpoints, a migration's bookkeeping, a query plan, copying a database). +//! Failure modes: a statement runs for hours and the log says nothing (2026-11-13); the line +//! carries a value written into the statement; every statement pays for the watch; one long +//! statement fills the log; the watcher outlives the store. Tests: tests/long_statement.rs. +use std::{ + sync::{Arc, Condvar, Mutex}, + thread::{self, JoinHandle}, + time::{Duration, Instant}, +}; + +/// Bytes of a statement kept for the log line. Copied on every statement, so kept short. +const SHOWN: usize = 300; + +struct Statement { + since: Instant, + /// The age at which the watcher next names it. + next: Duration, + named: bool, +} +#[derive(Default)] +struct Now { + statement: Option, + /// The start of the statement's text, as written. Reused, so a statement allocates nothing. + sql: String, + /// Whether the text went on past what `sql` keeps. + cut: bool, +} + +/// What one connection is running now. +pub(crate) struct Slot { + label: String, + after: Duration, + now: Mutex, +} +/// Held while a statement runs. +pub(crate) struct Running<'a>(Option<&'a Slot>); + +impl Slot { + /// A statement begun while this connection is already inside one (a row callback that + /// queries again) belongs to the outer one and is not watched on its own. + pub fn begin(&self, sql: &str) -> Running<'_> { + let mut now = self.now.lock().unwrap(); + if now.statement.is_some() { + return Running(None); + } + let mut end = sql.len().min(SHOWN); + while !sql.is_char_boundary(end) { + end -= 1; + } + now.sql.clear(); + now.sql.push_str(&sql[..end]); + now.cut = end < sql.len(); + now.statement = Some(Statement { since: Instant::now(), next: self.after, named: false }); + Running(Some(self)) + } +} +impl Drop for Running<'_> { + fn drop(&mut self) { + let Some(slot) = self.0 else { return }; + let ended = slot.now.lock().unwrap().statement.take(); + if let Some(statement) = ended.filter(|statement| statement.named) { + log::warn!( + "{} finished the statement it had been running for {}", + slot.label, + seconds(statement.since.elapsed()) + ); + } + } +} + +struct Shared { + slots: Mutex>>, + stopped: Mutex, + wake: Condvar, + after: Duration, +} +impl Shared { + fn name_long_statements(&self) { + for slot in self.slots.lock().unwrap().iter() { + let mut now = slot.now.lock().unwrap(); + let Now { statement: Some(statement), sql, cut } = &mut *now else { continue }; + let age = statement.since.elapsed(); + if age < statement.next { + continue; + } + statement.next *= 2; + statement.named = true; + log::warn!( + "{} has been running one statement for {}: {}", + slot.label, + seconds(age), + without_values(sql, *cut) + ); + } + } +} + +/// Owns the thread that looks at every connection's statement a few times per `after`. +pub(crate) struct Watch { + shared: Arc, + thread: Option>, +} +impl Watch { + pub fn start(after: Duration) -> std::io::Result { + let shared = Arc::new(Shared { + slots: Mutex::default(), + stopped: Mutex::new(false), + wake: Condvar::new(), + after, + }); + let watched = shared.clone(); + // Often enough that the first line is not much later than `after`, and no more often + // than every few seconds in the app, where `after` is half a minute. + let every = (after / 6).clamp(Duration::from_millis(10), Duration::from_secs(5)); + let thread = thread::Builder::new().name("store-watch".into()).spawn(move || { + let mut stopped = watched.stopped.lock().unwrap(); + while !*stopped { + stopped = watched.wake.wait_timeout(stopped, every).unwrap().0; + if !*stopped { + watched.name_long_statements(); + } + } + })?; + Ok(Self { shared, thread: Some(thread) }) + } + /// A place for one more connection to say what it is running. + pub fn slot(&self, label: String) -> Arc { + let slot = Arc::new(Slot { label, after: self.shared.after, now: Mutex::default() }); + self.shared.slots.lock().unwrap().push(slot.clone()); + slot + } +} +impl Drop for Watch { + fn drop(&mut self) { + *self.shared.stopped.lock().unwrap() = true; + self.shared.wake.notify_all(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +fn seconds(age: Duration) -> String { + if age < Duration::from_secs(10) { + format!("{:.1} s", age.as_secs_f64()) + } else { + format!("{} s", age.as_secs()) + } +} + +/// The statement on one line, with what stands between quotes replaced by `?` and comments +/// left out: bound values are never in the text, but a statement put together with a value +/// in it must not put that value in the log. Quotes and comments are told apart the way +/// `sql::tokens` does it, since an apostrophe in a comment is not the start of a literal. +/// Whatever is still open where the text ends is dropped with it. +fn without_values(sql: &str, cut: bool) -> String { + let mut shown = String::with_capacity(sql.len()); + let mut space = false; + let mut rest = sql.chars().peekable(); + while let Some(c) = rest.next() { + let closer = match c { + '\'' | '"' | '`' => Some(c), + '[' => Some(']'), + _ => None, + }; + if let Some(closer) = closer { + let _ = rest.by_ref().find(|inside| *inside == closer); + if std::mem::take(&mut space) { + shown.push(' '); + } + shown.push('?'); + } else if c == '-' && rest.peek() == Some(&'-') { + let _ = rest.by_ref().find(|inside| *inside == '\n'); + space = !shown.is_empty(); + } else if c == '/' && rest.peek() == Some(&'*') { + rest.next(); + let mut star = false; + for inside in rest.by_ref() { + if star && inside == '/' { + break; + } + star = inside == '*'; + } + space = !shown.is_empty(); + } else if c.is_whitespace() { + space = !shown.is_empty(); + } else { + if std::mem::take(&mut space) { + shown.push(' '); + } + shown.push(c); + } + } + if cut { + shown.push('…'); + } + shown +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn text_between_quotes_never_reaches_the_line() { + let written = "SELECT id\n FROM visits WHERE url='https://a.example/it''s' AND \"col\">1"; + assert_eq!(without_values(written, false), "SELECT id FROM visits WHERE url=?? AND ?>1"); + // Cut inside a literal: the rest of the kept text is the value and stays out. + assert_eq!( + without_values("SELECT 1 WHERE note='half a secr", true), + "SELECT 1 WHERE note=?…" + ); + } + #[test] + fn a_quote_in_a_comment_does_not_turn_the_literals_after_it_inside_out() { + // The validator lets comments through (`sql::tokens`), and the app's statements have + // them. An apostrophe in one used to open a literal that the next real quote closed. + assert_eq!( + without_values( + "SELECT /* user's note */ 'private-value' FROM t -- it's\n WHERE a=[it's] AND b=`c's`", + false + ), + "SELECT ? FROM t WHERE a=? AND b=?" + ); + assert_eq!(without_values("SELECT 1 /* user's 'private", true), "SELECT 1…"); + assert_eq!(without_values("SELECT 2 -- user's 'private", true), "SELECT 2…"); + } +} diff --git a/src-tauri/crates/vault-store/src/session.rs b/src-tauri/crates/vault-store/src/session.rs index 526df024..64e90613 100644 --- a/src-tauri/crates/vault-store/src/session.rs +++ b/src-tauri/crates/vault-store/src/session.rs @@ -31,6 +31,7 @@ pub struct Session<'a> { pub(crate) conn: &'a turso::Connection, pub(crate) prepared: Option<&'a crate::statement_cache::StatementCache>, pub(crate) read_only: bool, + pub(crate) running: Option<&'a crate::running::Slot>, pub(crate) _thread: PhantomData>, pub(crate) scratch: Option<&'a crate::checkpoint::Gate>, pub(crate) archive: Option<&'a crate::checkpoint::Gate>, @@ -100,6 +101,7 @@ impl<'a> Session<'a> { /// Runs Turso's structural and row/index consistency checks on this snapshot. /// This fixed read-only pragma does not expose arbitrary connection settings. pub fn integrity_check(&self) -> Result> { + let _running = self.watch("PRAGMA integrity_check"); self.runtime.block_on(async { let mut rows = self.conn.query("PRAGMA integrity_check", ()).await?; let mut messages = Vec::new(); @@ -119,10 +121,17 @@ impl<'a> Session<'a> { ) -> Result { self.check_sql(sql)?; let mut statement = self.take_statement(sql)?; + let _running = self.watch(sql); let result = work(&mut statement); self.return_statement(sql, statement); result } + /// Says this connection is running `sql` until the guard is dropped. Every way a job can + /// run a statement goes through here, or a long one runs unnamed (`running`): the calls + /// below, `integrity_check`, and a prepared statement's `execute` and `query`. + pub(crate) fn watch(&self, sql: &str) -> Option> { + self.running.map(|slot| slot.begin(sql)) + } /// A compiled statement for `sql`: from this connection's cache, or newly compiled. pub(crate) fn take_statement(&self, sql: &str) -> Result { match self.prepared { diff --git a/src-tauri/crates/vault-store/src/statements.rs b/src-tauri/crates/vault-store/src/statements.rs index aba20ffe..282e5a62 100644 --- a/src-tauri/crates/vault-store/src/statements.rs +++ b/src-tauri/crates/vault-store/src/statements.rs @@ -1,7 +1,8 @@ //! Responsibilities: reuse native prepared statements and stream rows on the owning thread. //! Not responsible for: transactions, database selection or business SQL. //! Failure modes: rebinding overlaps a live cursor, a statement escapes its Session, -//! policy is bypassed, or optional reads suppress failures. Tests: statements.rs. +//! policy is bypassed, optional reads suppress failures, or a statement run from here is +//! not watched while it runs. Tests: statements.rs, long_statement.rs. use crate::{Error, Result, Row, Session}; @@ -43,6 +44,7 @@ impl Statement<'_, '_> { /// Executes with fresh parameter bindings in the current transaction. pub fn execute(&mut self, params: impl turso::IntoParams) -> Result { let runtime = self.session.runtime; + let _running = self.session.watch(&self.sql); Ok(runtime.block_on(self.native().execute(params))?) } @@ -51,8 +53,9 @@ impl Statement<'_, '_> { let params = params.into_params()?; self.session.record_plan(&self.sql, ¶ms)?; let runtime = self.session.runtime; + let running = self.session.watch(&self.sql); let native = runtime.block_on(self.native().query(params))?; - Ok(Rows { runtime: self.session.runtime, native, _owner: std::marker::PhantomData }) + Ok(Rows { runtime, native, running, _owner: std::marker::PhantomData }) } /// Requires one row without collecting the result set. @@ -85,13 +88,20 @@ impl Statement<'_, '_> { pub struct Rows<'a> { runtime: &'a tokio::runtime::Runtime, native: turso::Rows, + /// The statement counts as running until its last row is read, it fails, or this cursor + /// is dropped: not for as long as the `Statement` is kept, which may be a whole batch. + running: Option>, _owner: std::marker::PhantomData<&'a mut std::rc::Rc<()>>, } impl Rows<'_> { /// Advances without collecting the remaining result into memory. #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Result> { - Ok(self.runtime.block_on(self.native.next())?) + let row = self.runtime.block_on(self.native.next()); + if !matches!(row, Ok(Some(_))) { + self.running = None; + } + Ok(row?) } } diff --git a/src-tauri/crates/vault-store/src/worker.rs b/src-tauri/crates/vault-store/src/worker.rs index b110c924..7ee40a2b 100644 --- a/src-tauri/crates/vault-store/src/worker.rs +++ b/src-tauri/crates/vault-store/src/worker.rs @@ -1,7 +1,9 @@ //! Responsibilities: start, service and join connection-owning reader/writer threads. //! Not responsible for: application work or async APIs outside this crate. //! Failure modes: connections cross threads; panic kills an owner; startup failure -//! leaks threads; interactive jobs wait behind queued batches. Tests: concurrency, opening. +//! leaks threads; interactive jobs wait behind queued batches; a writer waiting to +//! checkpoint keeps readers and later writes waiting behind a read that is still running. +//! Tests: concurrency, opening, admission. use crate::{ Db, Error, Metrics, Migration, Priority, Result, Session, checkpoint::Gate, @@ -16,8 +18,15 @@ use std::{ mpsc, }, thread::{self, JoinHandle}, + time::Duration, }; +/// How long a writer that wants to truncate the WAL keeps new readers out while the readers +/// already inside finish. Reads are short (`Store::read`), so they normally leave within it. +/// One that does not must not hold up every other read: the writer lets readers in again and +/// truncates later. +const READER_DRAIN: Duration = Duration::from_millis(50); + type Reply = Box; type Job = Box, Option<&Gate>) -> Reply + Send>; thread_local! {static IN_OWNER:Cell=const{Cell::new(false)};} @@ -85,9 +94,12 @@ impl Workers { || { // No read pool or ready signal exists yet. Truncating between batches // also bounds retained WAL state as the migrated corpus grows. - let _admission = migration_gate.reserve_truncate(); - _admission.wait_for_readers(); - if !crate::checkpoint::run(&engine, true, &migration_metrics) { + let admission = migration_gate + .reserve_truncate() + .filter(|admission| admission.wait_for_readers(READER_DRAIN)); + if admission.is_none() + || !crate::checkpoint::run(&engine, true, &migration_metrics) + { let metrics = migration_metrics.lock().unwrap(); return Err(Error::Operation( std::io::Error::other(format!( @@ -125,6 +137,8 @@ impl Workers { } completion = Some(reply); } + // Some reader was the last to leave. That may have been a while ago, + // with others inside since: the gate knows, and is asked below. Next::Maintenance => {} Next::Closed => { if let Some(_guard) = gate.try_truncate() { @@ -133,15 +147,26 @@ impl Workers { break; } } - if dirty && writer.pending() == (0, 0) { - let guard = gate.reserve_truncate(); + // No guard while a read the writer already waited for is still running: + // once per long read is enough. + if dirty + && writer.pending() == (0, 0) + && let Some(guard) = gate.reserve_truncate() + { // Acknowledgement belongs to COMMIT, not to maintenance. // In particular, an active reader may depend on this reply. if let Some(reply) = completion.take() { reply(); } - guard.wait_for_readers(); - dirty = !crate::checkpoint::run(&engine, true, &metrics); + if guard.wait_for_readers(READER_DRAIN) { + dirty = !crate::checkpoint::run(&engine, true, &metrics); + } else { + // A read is running long. Its snapshot pins the WAL whatever this + // thread does, so waiting on gains nothing and would keep every + // other read, and the next write, waiting with it. Dropping the + // guard lets readers in again. + metrics.lock().unwrap().truncates_put_off += 1; + } } if let Some(reply) = completion { reply(); @@ -164,7 +189,7 @@ impl Workers { move || { IN_OWNER.with(|v| v.set(true)); let engine = match crate::session::catch_job(|| { - Engine::reader(database, &settings, compiled) + Engine::reader(database, &settings, compiled, index) }) { Ok(e) => e, Err(error) => { diff --git a/src-tauri/crates/vault-store/tests/admission.rs b/src-tauri/crates/vault-store/tests/admission.rs new file mode 100644 index 00000000..684f8bd4 --- /dev/null +++ b/src-tauri/crates/vault-store/tests/admission.rs @@ -0,0 +1,210 @@ +//! Responsibilities: a read that runs long delays the idle checkpoint, and nothing else. +//! Not responsible for: how long a read may run, or WAL size while one is still running. +//! Failure modes (2026-11-13: one statement ran for hours on an Intelligence reader and every +//! other read of Archive and Intelligence waited for it, because a writer that had just +//! committed kept new readers out until the readers already running had left): +//! - after a write, a new read waits for an unrelated read that is still running; +//! - the same across databases: an Intelligence read of `archive.*` holds up Archive reads; +//! - the writer stays parked behind that read, so later writes are never served; +//! - the checkpoint put off for a long read is forgotten once that read ends; +//! - the writer keeps readers out for the same long read again: at every later write, or when +//! it hears of some other reader that left before. +//! +//! None of these measures how long anything took. `PROMPT` and the deadlines only keep a +//! broken build from hanging the suite; what a writer did is read from `truncates_put_off`. +mod support; +use std::{ + sync::{Arc, mpsc}, + thread, + time::{Duration, Instant}, +}; +use vault_store::{Db, Priority, Store}; + +/// Long enough that a wait for the held reader cannot be mistaken for a slow machine. +const PROMPT: Duration = Duration::from_secs(5); + +/// A read of `sql` on `db` that stays open until the returned sender is used or dropped. +fn hold_reader( + store: &Arc, + db: Db, + sql: &'static str, +) -> (mpsc::Sender<()>, thread::JoinHandle<()>) { + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel::<()>(); + let worker = store.clone(); + let reader = thread::spawn(move || { + worker + .read(db, move |c| { + c.query_one(sql, (), |r| Ok(r.get::(0)?))?; + started_tx.send(()).unwrap(); + let _ = release_rx.recv(); + Ok(()) + }) + .unwrap() + }); + started_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + (release_tx, reader) +} + +/// Runs `work` on its own thread and returns its result if it finished within [`PROMPT`]. +fn promptly(work: impl FnOnce() -> T + Send + 'static) -> Option { + let (done_tx, done_rx) = mpsc::channel(); + thread::spawn(move || { + let _ = done_tx.send(work()); + }); + done_rx.recv_timeout(PROMPT).ok() +} + +fn open() -> (tempfile::TempDir, Arc) { + let (dir, store) = support::open(); + let store = Arc::new(store); + support::insert(&store, 1).unwrap(); + (dir, store) +} + +/// Returns once the Archive writer has put a truncate off `times` times. +fn wait_until_put_off(store: &Store, times: u64) { + let deadline = Instant::now() + Duration::from_secs(10); + while store.metrics(Db::Archive).truncates_put_off < times { + assert!(Instant::now() < deadline, "the writer never gave up on the reader"); + thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn a_read_after_a_write_does_not_wait_for_a_read_that_is_still_running() { + let (_dir, store) = open(); + let (release, held) = hold_reader(&store, Db::Archive, "SELECT count(*) FROM visits"); + support::insert(&store, 2).unwrap(); + let worker = store.clone(); + let seen = promptly(move || support::count(&worker)); + release.send(()).unwrap(); + held.join().unwrap(); + assert_eq!(seen, Some(2), "the read waited for the reader that was still running"); +} + +#[test] +fn an_archive_read_does_not_wait_for_an_intelligence_read_of_the_archive() { + let (_dir, store) = open(); + let (release, held) = + hold_reader(&store, Db::Intelligence, "SELECT count(*) FROM archive.visits"); + support::insert(&store, 2).unwrap(); + let worker = store.clone(); + let seen = promptly(move || support::count(&worker)); + release.send(()).unwrap(); + held.join().unwrap(); + assert_eq!(seen, Some(2), "the Archive read waited for the Intelligence reader"); +} + +#[test] +fn writes_are_served_while_a_read_is_still_running() { + let (_dir, store) = open(); + let (release, held) = hold_reader(&store, Db::Archive, "SELECT count(*) FROM visits"); + support::insert(&store, 2).unwrap(); + let worker = store.clone(); + let second = promptly(move || support::insert(&worker, 3).is_ok()); + release.send(()).unwrap(); + held.join().unwrap(); + assert_eq!(second, Some(true), "the second write waited for the reader that was still running"); + assert_eq!(support::count(&store), 3); +} + +#[test] +fn the_checkpoint_put_off_for_a_long_read_runs_once_that_read_ends() { + let (dir, store) = open(); + let wal = dir.path().join("archive/history-vault.db-wal"); + let (release, held) = hold_reader(&store, Db::Archive, "SELECT count(*) FROM visits"); + store + .write(Db::Archive, Priority::Batch, |tx| { + tx.execute( + "WITH RECURSIVE seq(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM seq WHERE x<200) INSERT INTO visits(id,url,title,visited_at) SELECT 1000+x,'https://example.test',hex(zeroblob(400)),x FROM seq", + (), + )?; + Ok(()) + }) + .unwrap(); + wait_until_put_off(&store, 1); + let before = store.metrics(Db::Archive).truncate_checkpoints; + assert!(std::fs::metadata(&wal).unwrap().len() > 32, "the write left nothing to checkpoint"); + release.send(()).unwrap(); + held.join().unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + while std::fs::metadata(&wal).unwrap().len() > 32 { + assert!(Instant::now() < deadline, "the WAL was not truncated after the long read ended"); + thread::sleep(Duration::from_millis(5)); + } + assert!(store.metrics(Db::Archive).truncate_checkpoints > before); + assert_eq!(support::count(&store), 201); +} + +#[test] +fn later_writes_do_not_keep_readers_out_again_for_the_same_long_read() { + let (_dir, store) = open(); + let (release, held) = hold_reader(&store, Db::Archive, "SELECT count(*) FROM visits"); + // A write is served only once the writer is done with the one before it, waiting for + // readers included. So by the last of these, every earlier one that waited has been counted. + for id in 2..23 { + support::insert(&store, id).unwrap(); + } + let put_off = store.metrics(Db::Archive).truncates_put_off; + release.send(()).unwrap(); + held.join().unwrap(); + assert_eq!(put_off, 1, "the writer waited for the same read more than once"); +} + +#[test] +fn word_of_a_reader_that_left_earlier_does_not_bring_a_second_wait() { + let (_dir, store) = open(); + // A write that stays open: until it ends, the writer hears nothing. + let (writing_tx, writing_rx) = mpsc::channel(); + let (finish_tx, finish_rx) = mpsc::channel::<()>(); + let worker = store.clone(); + let write = thread::spawn(move || { + worker + .write(Db::Archive, Priority::Batch, move |tx| { + tx.execute( + "INSERT INTO visits(id,url,title,visited_at) VALUES (2,'https://example.test','page',2)", + (), + )?; + writing_tx.send(()).unwrap(); + let _ = finish_rx.recv(); + Ok(()) + }) + .unwrap() + }); + writing_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + // A short read ends with nobody else inside, which the writer is told and hears later. + assert_eq!(support::count(&store), 1); + // By then this read is inside, and stays. + let (release, held) = hold_reader(&store, Db::Archive, "SELECT count(*) FROM visits"); + finish_tx.send(()).unwrap(); + write.join().unwrap(); + wait_until_put_off(&store, 1); + // With nothing queued the writer now hears of the short read. Each of these is served only + // after it is done with what came before, so whatever that news made it do has been counted. + for id in 3..6 { + support::insert(&store, id).unwrap(); + } + let put_off = store.metrics(Db::Archive).truncates_put_off; + release.send(()).unwrap(); + held.join().unwrap(); + assert_eq!(put_off, 1, "the writer waited again for the read it had given up on"); +} + +#[test] +fn a_second_long_read_inside_at_the_wait_does_not_bring_another_once_the_first_leaves() { + let (_dir, store) = open(); + let (release_first, first) = hold_reader(&store, Db::Archive, "SELECT count(*) FROM visits"); + let (release_second, second) = hold_reader(&store, Db::Archive, "SELECT count(*) FROM visits"); + support::insert(&store, 2).unwrap(); + wait_until_put_off(&store, 1); + release_first.send(()).unwrap(); + first.join().unwrap(); + for id in 3..6 { + support::insert(&store, id).unwrap(); + } + let put_off = store.metrics(Db::Archive).truncates_put_off; + release_second.send(()).unwrap(); + second.join().unwrap(); + assert_eq!(put_off, 1, "the writer waited again for a read that was inside the first time"); +} diff --git a/src-tauri/crates/vault-store/tests/long_statement.rs b/src-tauri/crates/vault-store/tests/long_statement.rs new file mode 100644 index 00000000..69c4d5b6 --- /dev/null +++ b/src-tauri/crates/vault-store/tests/long_statement.rs @@ -0,0 +1,170 @@ +//! Responsibilities: a statement that runs long is named in the log while it runs. +//! Not responsible for: stopping it, or how long a statement should take. +//! Its own binary, because the logger is process-wide. +//! Failure modes (2026-11-13: one statement ran for hours and the log said nothing; it was +//! found by sampling the process): +//! - a statement runs long and no line names it until it ends, or ever; +//! - only some ways of running a statement are watched: one prepared first, then run or read +//! row by row, goes unnamed; +//! - a cursor read to its end and kept still counts as running; +//! - the line carries a value written into the statement, which may be the user's data; +//! - statements that end soon fill the log; +//! - nothing says the long statement has ended. +mod support; +use std::{ + sync::{Arc, Mutex, mpsc}, + thread, + time::{Duration, Instant}, +}; +use vault_store::{Db, Priority, Store}; + +struct Lines(Mutex>); +impl log::Log for Lines { + fn enabled(&self, _: &log::Metadata<'_>) -> bool { + true + } + fn log(&self, record: &log::Record<'_>) { + self.0.lock().unwrap().push(format!("{} {}", record.level(), record.args())); + } + fn flush(&self) {} +} +static LOG: Lines = Lines(Mutex::new(Vec::new())); + +/// The first line from `from` on that has `text` in it. The deadline only keeps a broken build +/// from hanging the suite. +fn line_with(from: usize, text: &str) -> Option { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Some(line) = LOG.0.lock().unwrap().iter().skip(from).find(|l| l.contains(text)) { + return Some(line.clone()); + } + if Instant::now() > deadline { + return None; + } + thread::sleep(Duration::from_millis(5)); + } +} +fn lines() -> usize { + LOG.0.lock().unwrap().len() +} + +const WALK: &str = + "SELECT id FROM visits WHERE url <> 'https://private.example/a path' ORDER BY id"; +const PREPARED: &str = + "SELECT title FROM visits WHERE url <> 'https://private.example/b path' ORDER BY id"; +/// Counts to `?1` and inserts one row: as slow as the number is large. +const SLOW_INSERT: &str = "WITH RECURSIVE seq(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM seq WHERE x(); + let worker = store.clone(); + let reader = thread::spawn(move || { + worker + .read(Db::Archive, move |c| { + let mut waited = false; + c.for_each(WALK, (), |_| { + if !waited { + waited = true; + started_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + } + Ok(()) + }) + }) + .unwrap() + }); + started_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let running = line_with(0, "has been running one statement").expect("no line while it ran"); + assert!(running.starts_with("WARN Archive reader"), "{running}"); + assert!(running.contains("SELECT id FROM visits WHERE url <> ? ORDER BY id"), "{running}"); + assert!(!running.contains("private"), "{running}"); + release_tx.send(()).unwrap(); + reader.join().unwrap(); + let ended = line_with(0, "finished the statement").expect("no line when it ended"); + assert!(ended.starts_with("WARN Archive reader"), "{ended}"); + + // Forty short statements came before it: only the long one is in the log. + let so_far = LOG.0.lock().unwrap().clone(); + assert!( + so_far + .iter() + .all(|line| line.contains("SELECT id FROM visits") || line.contains("finished")), + "{so_far:#?}" + ); + + // The same for a statement prepared first and read row by row. It has ended once its last + // row is read, though the cursor is still there. + let from = lines(); + let (started_tx, started_rx) = mpsc::channel(); + let (read_on_tx, read_on_rx) = mpsc::channel::<()>(); + let (at_end_tx, at_end_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel::<()>(); + let worker = store.clone(); + let reader = thread::spawn(move || { + worker + .read(Db::Archive, move |c| { + let mut statement = c.prepare(PREPARED)?; + let mut rows = statement.query(())?; + rows.next()?; + started_tx.send(()).unwrap(); + read_on_rx.recv().unwrap(); + while rows.next()?.is_some() {} + at_end_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + Ok(()) + }) + .unwrap() + }); + started_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let running = line_with(from, "has been running one statement") + .expect("no line while a prepared statement's rows were being read"); + assert!(running.starts_with("WARN Archive reader"), "{running}"); + assert!(running.contains("SELECT title FROM visits WHERE url <> ? ORDER BY id"), "{running}"); + read_on_tx.send(()).unwrap(); + at_end_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let ended = LOG.0.lock().unwrap().iter().skip(from).any(|l| l.contains("finished")); + release_tx.send(()).unwrap(); + reader.join().unwrap(); + assert!(ended, "the cursor was read to its end and the statement still counted as running"); + + // And for a prepared statement run in one go. Nothing can hold one open, so it is given + // more to do until it has run long enough to be named, however fast the machine. + let from = lines(); + let mut count_to = 50_000_i64; + let running = loop { + let began = Instant::now(); + store + .write(Db::Archive, Priority::Batch, move |tx| { + tx.prepare(SLOW_INSERT)?.execute([count_to])?; + Ok(()) + }) + .unwrap(); + let took = began.elapsed(); + let named = LOG.0.lock().unwrap().iter().skip(from).find(|l| l.contains("seq(x)")).cloned(); + if let Some(line) = named { + break line; + } + assert!(took < Duration::from_secs(5), "ran for {took:?} and was never named"); + count_to *= 4; + }; + assert!(running.starts_with("WARN Archive writer"), "{running}"); + assert!(running.contains("SELECT 1000000+x,?,?,x FROM seq WHERE x=?1"), "{running}"); + assert!(!running.contains("private"), "{running}"); +} diff --git a/src-tauri/crates/vault-worker/tests/archive_scale_bench.rs b/src-tauri/crates/vault-worker/tests/archive_scale_bench.rs index 481bcf1f..e74f6702 100644 --- a/src-tauri/crates/vault-worker/tests/archive_scale_bench.rs +++ b/src-tauri/crates/vault-worker/tests/archive_scale_bench.rs @@ -96,6 +96,11 @@ static ALLOCATOR: CountingAllocator = CountingAllocator; /// Failure mode (f): use the real export and allocator, comparing two archive sizes in an /// otherwise idle integration-test process. This guards against collecting rows/strings again. +/// +/// The store's readers keep the pages they read, up to their cache size, and that is the store's +/// memory, not the export's: the export runs until it leaves nothing more behind before it is +/// measured. (Until 2026-11-13 the search indexer wrote to the archive ten times a second with +/// nothing to write, and each of those writes emptied the caches, so they never filled.) #[test] fn export_heap_stays_bounded_as_archive_grows() { // The allocator is process-wide; another test opening a Vault must not count as export memory. @@ -111,7 +116,7 @@ fn export_heap_stays_bounded_as_archive_grows() { let mut peaks = Vec::new(); for visits in [10_000, 100_000] { let vault = native_export_fixture(visits); - let heap = report_memory("bounded export heap", 1, || { + let export = || { let result = vault_core::export_history( &vault, vault_core::ExportRequest { @@ -124,7 +129,19 @@ fn export_heap_stays_bounded_as_archive_grows() { .unwrap(); assert_eq!(result.count as u64, visits); std::fs::remove_file(result.path).unwrap(); - }); + }; + let mut runs = 0; + loop { + let before = HEAP_CURRENT.load(Ordering::Relaxed); + export(); + let kept = HEAP_CURRENT.load(Ordering::Relaxed).saturating_sub(before); + if kept < 128 * 1024 { + break; + } + runs += 1; + assert!(runs < 16, "every export leaves more behind: {kept} bytes after {runs} runs"); + } + let heap = report_memory("bounded export heap", 1, export); assert!(heap < 2 * 1024 * 1024, "export allocated {heap} bytes above baseline"); peaks.push(heap); } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 05623f97..dbb3883e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -426,6 +426,10 @@ fn build_logging_plugin( // Every segment flush, merge and file delete is an INFO line: a search index build // filled rust.log with them and pushed the app's own lines out of the rotation. .level_for("tantivy", tauri_plugin_log::log::LevelFilter::Warn) + // The HTML parser warns "foster parenting not implemented" for many of the pages whose + // text is fetched, dozens of times a second: on 2026-11-13 those were the only lines + // left in rust.log, which keeps five files of 40 KB. + .level_for("html5ever", tauri_plugin_log::log::LevelFilter::Error) .rotation_strategy(RotationStrategy::KeepSome(5)) .timezone_strategy(TimezoneStrategy::UseLocal) .target(