An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Bound cached document reads and evaluate search candidates https://github.com/siyuan-note/siyuan/issues/20692
Daniel9539ed7d2066
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.mdindex 1706c899f8..66bacc4123 100644--- a/docs/PERFORMANCE.md+++ b/docs/PERFORMANCE.md@@ -17,7 +17,7 @@ Records start with `siyuan-performance ` followed by JSON. `duration_us` and `st| Operation | Stage boundary and counters ||---|---|| `transaction` | Begin, automations, apply, finalize, commit; operation count |-| `document.load` | Transaction barrier, load/parse tree, locate blocks, render response; block count |+| `document.load` | Transaction boundary, capture/load/parse tree, locate blocks, render response; block count; `source_snapshot = 1` identifies an ordinary cached source parsed outside the transaction lock || `document.save` | Prepare/serialize, encrypt, compare, write, notify; prepared and written bytes || `index.flush` | Lock wait, take queue, begin/execute/commit, notify, persist queue completion; batch size and oldest enqueue age || `index.update` | Main-block and complete auxiliary projection, block comparison, auxiliary-index comparison, writes; `blocks_total` counts previously indexed blocks, `blocks_projected` counts generated main blocks, `changeset = 1` identifies a usable transaction hint; changed blocks and planned auxiliary deletions and insertions |@@ -38,6 +38,10 @@ Ordinary table, list and gallery views can evaluate templates needed by filters,## Projection and reuse boundaries+Ordinary cached document opening waits for the serial execution lock, including any dequeued transaction still executing. With queued work, it completes the single batch captured after acquiring that lock and captures the document source before releasing it. Transactions arriving after that batch do not extend this path to a globally empty queue. Empty-queue captures can share the read lock. Writes, undo/replay and the existing global flush operation keep their completion rules; this is a global editing boundary, without document-specific transaction routing.++Ordinary cached documents copy their independently decoded source bytes and parent titles at that boundary, then parse and render after releasing the transaction lock. Later edits, moves, cache invalidation or parent renames cannot change that captured source; parsing cannot recreate a subsequently removed file. The snapshot is local to one read and introduces no retained cache. Encrypted documents, cache misses and parent chains requiring repair retain the original global queue wait and complete loader, including authentication, compatibility repair and index refresh. They release the transaction lock before that wait/load to preserve lifecycle lock ordering, and do not gain the finite-batch guarantee. Source copying and reading parent titles also have costs proportional to their input. SQL-derived reference counts, virtual references and other response metadata retain their existing asynchronous index behavior; this is not a combined filesystem/SQL/sync snapshot.+Main-block projection resolves heading parents once per physical sibling list within a projection. Transactions consisting entirely of tracked `update` operations can provide changed and removed subtree IDs and affected containers. Heading structure, inline HTML, untracked writes, missing or changed root metadata, and other transaction operations retain complete main-block projection. Queue coalescing unions hints only within the same notebook, document and path and preserves ordered delete, move, rename and other index-operation boundaries. Hints exist only in process memory; recovery loads the complete authenticated source and performs an idempotent full update. Complete auxiliary projection and the existing whole-document `.sy` save remain in place.View order reuse applies only to live ordinary sources with at least 512 detached rows, static fields and closed pure templates required before pagination. It covers table, list and galleries without covers; query, grouping, context filters, target positioning, calculations, date/time, relation, rollup, assets and external or dynamic dependencies retain their existing paths. Plain views and views whose templates are all display-only do not pay for an order fingerprint. The key includes the source version and cache generation, actual data and view definition, carrier, language and write scope; temporary data or sort changes produce different keys. Fingerprinting encodes values in bounded chunks. It still validates and hashes the complete input, and source parsing still scales with source size.@@ -67,6 +71,8 @@ go test ./model -run '^$' -bench '^BenchmarkDatabaseTemplateDependencies$' -bencgo test -tags fts5 ./sql -run '^$' -bench '^BenchmarkIndexProjection$' -benchmem -benchtime=200ms -count=3go test ./model -run '^$' -bench '^BenchmarkDatabaseViewOrderReuse$' -benchmem -benchtime=200ms -count=3go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkFTSExactCountReuse$' -benchmem -benchtime=200ms -count=3+go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^Benchmark(DocumentReadBoundarySource|DocumentReadBoundaryEmpty|FlushTxQueueEmpty)$' -benchmem -benchtime=1s -count=3+go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^BenchmarkDocument(SearchCandidates|CandidateIndexWrite)$' -benchmem -benchtime=200ms -count=3```| Benchmark | Fixed workload | Included work |@@ -79,9 +85,32 @@ go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkFTSExactCountReuse$' -bench| `BenchmarkIndexProjection` | 1,000 / 5,000 / 20,000 paragraphs, one ordinary text change | Independent heading-parent lookup versus request-local sibling resolution versus a two-block main projection; all include complete auxiliary projection, without SQL writes || `BenchmarkDatabaseViewOrderReuse` | 100 / 1,000 / 10,000 / 50,000 detached rows, the same template dependency fixture, page size 50 | Source parsing plus complete, uncached-order or reused-order rendering; the identical comparison snapshot shares the raw/normalized cache but is ineligible for cross-request reuse; cold mode varies a temporary view name to include fingerprint/admission costs || `BenchmarkFTSExactCountReuse` | 1,000 / 10,000 / 100,000 / 1,000,000 blocks, 100 per document; all, 0.1% or no blocks match; first 50 blocks | Warm in-memory FTS row decoding and exact block/document counts; uncached separate reads versus a cold or reused snapshot count; cold mode includes cache clearing |+| `BenchmarkDocumentReadBoundarySource` | 1,000 / 5,000 / 20,000 flat paragraphs with 128 ASCII content bytes each | Source capture alone, or full loading using a global flush versus the read boundary; warm mode uses the content cache, cold mode removes it each iteration; both reuse the OS file cache and exclude queue backlog and response rendering |+| `BenchmarkDocumentSearchCandidates` | 10,000 / 100,000 / 1,000,000 blocks, 100 per document; every document, one document or no document matches | Complete document query/count/row decoding without candidates, with a block scan producing root IDs, or with a prebuilt document trigram index; `candidate_build_ms` and `candidate_bytes` separately report index construction and SQLite page growth |+| `BenchmarkDocumentCandidateIndexWrite` | One document containing 100 / 1,000 / 20,000 blocks; alternate one block's SQL content | One block-table update/commit versus that update plus full-document aggregation and trigram replacement; excludes document serialization, file writes and the product's existing block FTS work; SQLite changes include internal index writes |Use sub-benchmark filters for smaller runs, for example `-bench '^BenchmarkDocumentSearch$/^10000$'`. Database setup and fixture generation are outside measured loops. Display/template benchmarks reuse the attribute view across iterations; order-reuse benchmarks parse a fresh view each time. Their raw/normalized source caches are warm, so none is a cold-open measurement. `-benchmem` measures Go allocations, not SQLite native allocations or total RSS. Benchmark results are baselines for those paths, not application latency or a general speedup claim. Include low-hit and no-hit FTS queries because version/snapshot validation can cost more than their small counts.+## Document candidate experiment++Candidate queries and the trigram index exist only in tests and benchmarks; production search and storage do not use them. The scan experiment admits one literal substring and retains the complete query for exact results, counts and ordering. Commas, LIKE wildcards and NUL require fallback for that candidate term. Its fixture comparisons include case sensitivity, path matching, filters, quotes, cross-block keywords, separators, NUL, all sort modes and pagination. They establish equivalence for those fixtures, rather than a proof for every query plan and aggregation order.++The index experiment uses a fixed field concatenation. A regular word tokenizer misses a query such as `alpha` inside `malpha`. A trigram index of all fields can also miss `alpha` formed by enabled `content + alias` when a disabled `name` would intervene in the indexed concatenation. The negative regression preserves both counterexamples. Adopting an index would first require complete recall across field settings, type/scope filtering and aggregation boundaries, plus authenticated rebuild/recovery and an acceptable write/storage budget. No new persisted index or migration is enabled by this change.++On 2026-10-19, Windows amd64, Intel i7-8750H, Go 1.27.2, `fts5 sqlcipher`, measurements on the batch-four working tree based on `9436ff6100` were as follows. Query/load/write times are three-sample medians; index construction and page growth were sampled once for the shared fixture:++| Workload | Comparison | Measurement |+|---|---|---|+| 20,000-block warm source | Original loader / captured-source loader / capture held under the transaction lock | 138 / 123 / 3.46 ms |+| 20,000-block content-cache miss | Original loader / capture miss followed by global fallback | 261 / 256 ms |+| 1,000,000 blocks, all documents match | Original / scan candidates / fixed-field trigram candidates | 660 / 1,012 / 991 ms |+| 1,000,000 blocks, one document matches | Original / scan candidates / fixed-field trigram candidates | 867 / 1,224 / 2.12 ms |+| 1,000,000 blocks, no document matches | Original / scan candidates / fixed-field trigram candidates | 810 / 553 / 0.337 ms |+| Candidate index at 1,000,000 blocks | Construction / SQLite page growth | 2.25 s / 96.3 MB |+| One SQL block update in a 20,000-block document | Block update only / update plus document trigram replacement | 0.015 / 63.3 ms; 1 / 789 SQLite changes |++The read change confines transaction exclusion to source capture on the warm path; whole-tree parsing remains expensive. Total source-load measurements showed substantial variance, especially on smaller fixtures, and do not establish faster product opens. The selective candidate index has substantial potential, but misses valid field combinations and increases high-hit query and write costs in this experiment, so it is not adopted. Large query samples sometimes contain only one operation and also show substantial variance; these are directional microbenchmarks, without latency percentiles, real-device interaction, recovery measurements or process RSS.+## Product capturesFor each comparison, record commit, toolchain and Electron versions, OS, hardware, build mode, actual data sizes, query hit rate, sample count, cache state and concurrent background work. Keep fixed content length, nesting, reference/asset count, database field definitions and templates. Capture cold open, warm reopen, subsequent pages, continuous typing and interaction during sync/indexing separately. Include small workspaces, low-hit queries, encrypted notebooks and desktop/browser/mobile paths.@@ -113,6 +142,8 @@ go test ./model -run 'TestAttributeViewTemplatePlan|TestRenderAttributeViewUsesTgo test -tags 'fts5 sqlcipher' ./sql -run '^TestAuxiliaryIndexEncryptedUpdateAndReopen$' -count=1go test -tags 'fts5 sqlcipher' ./sql ./model -run 'TestTreeIndexChanges|TestIndexHeading|TestIndexProjection|TestTransactionIndexChanges|TestFTSCount|TestReusableTemplateKey|TestAttributeViewOrderReuse' -count=1go test -race ./cache -run TestAVOrderedIDs -count=1+go test -tags 'fts5 sqlcipher' ./model ./filesys -run 'TestDocumentReadBoundary|TestCachedTreeSource|TestAssetRelinkLockCancels|TestDocumentSearchCandidate' -count=1+go test -race -tags 'fts5 sqlcipher' ./model ./filesys -run 'TestDocumentReadBoundary|TestCachedTreeSource|TestAssetRelinkLockCancels|TestQueuedTransactionWaitForCommit|TestFlushTxQueueWaitsForDequeuedTransaction|TestWaitForSubmittedTransactionBatch|TestTransactionCompletion' -count=1```Cancellation tests cover running SQLite work and connection reuse in global and notebook-routed databases. The scoped in-memory database fixture tests routing, not SQLCipher format compatibility. Rendering tests use real browser DOM for insertion roots, whole replacement, selection identity, prepend scroll compensation and stale/removed roots, with component renderers replaced by spies. Component behavior and real device IME/touch interactions require their own regression checks. Semantic search retains serial scheduling because its backend cancellation is a separate change.@@ -120,3 +151,5 @@ Cancellation tests cover running SQLite work and connection reuse in global andAuxiliary-index tests compare all five tables against complete replacement, including duplicates, removals, changed metadata, replay, failure rollback, NULL handling and batched deletion. A 20,000-block regression forbids any auxiliary-table write during an ordinary text edit. The SQLCipher test uses an actual encrypted database and verifies index migration/reopen, wrong-key rejection and isolation from the global database. Template-plan tests compare page values, order, counts, conditional colors and calculations against complete evaluation for table/list/gallery layouts, including original raw values and stale display state. These kernel changes are shared by desktop and mobile and do not change their frontend interactions.Change-set tests compare complete SQL/FTS snapshots, coalesced transactions, removed/replaced children, root metadata fallback, ordered boundaries, failed writes and recovery without hints. Order-reuse tests compare complete responses for table/list/gallery and exercise saved and temporary edits, sort/write scope, empty results, excluded dependencies, byte limits, immutable IDs and concurrent invalidation. FTS tests place real WAL commits before snapshot establishment, before version confirmation and during row reads, then verify both snapshot counts and subsequent invalidation. They also cover rollback, SQL/argument isolation, cancellation and stale admissions. Run the surrounding SQL, AV, transaction and API permission regressions as appropriate; these focused tests do not replace real-workspace RSS or device interaction measurements.++Read-boundary tests cover shared reads and writer exclusion, already executing commits, captured batch completion and later arrivals, cross-document moves, failed writes, undo replay, panic/error cleanup, cached bytes parsed after a later edit and complete GetDoc projection comparisons across focus/paging modes and highlights. Source tests compare complete trees and metadata after parent renames and file removal, including cache misses, repair fallback, stale paths and authorization. The SQLCipher case uses an encrypted block tree and content database and verifies authentication failure, preserved ciphertext, unrelated transaction progress during lifecycle waiting, response-lease waiting and rejection after locking. The shared kernel path serves desktop and mobile without changing their interaction code.diff --git a/docs/PERFORMANCE.zh-CN.md b/docs/PERFORMANCE.zh-CN.mdindex ceb8e6266e..6c17f4c523 100644--- a/docs/PERFORMANCE.zh-CN.md+++ b/docs/PERFORMANCE.zh-CN.md@@ -17,7 +17,7 @@| 操作 | 阶段边界和计数 ||---|---|| `transaction` | 开始、自动化、应用操作、整理、提交;操作数 |-| `document.load` | 事务屏障、加载/解析树、定位块、渲染响应;块数 |+| `document.load` | 事务边界、捕获/加载/解析树、定位块、渲染响应;块数;`source_snapshot = 1` 表示普通缓存来源在事务锁外解析 || `document.save` | 准备/序列化、加密、比对、写入、通知;待保存字节数和实际写入字节数 || `index.flush` | 等锁、提取队列、开始/执行/提交、通知、持久化队列完成状态;批次大小和最老入队任务的等待时间 || `index.update` | 主块及完整附属投影、块比较、附属索引比较、写入;`blocks_total` 为已有索引块数,`blocks_projected` 为生成的主块数,`changeset = 1` 表示采用事务提示;变化块数、计划删除及插入的附属记录数 |@@ -38,6 +38,10 @@## 投影与复用边界+普通缓存文档的打开先等待串行执行锁,包括已从队列取出但仍在执行的事务。有排队任务时,完成取得该锁后捕获的单个批次,并在释放锁前取得文档来源;该批次之后新到达的事务不会把这条路径延长到全局队列清空。空队列捕获可以共享读锁。写入、撤销/重放及既有全局刷新操作保持原有完成规则;这是全局编辑边界,尚未按文档路由事务。++普通缓存文档在该边界复制独立解压的来源字节和父级标题,释放事务锁后再解析和渲染。后续编辑、移动、缓存失效或父文档改名不会改变已捕获来源,解析也不会重建之后被移除的文件。快照只用于本次读取,不新增常驻缓存。加密文档、缓存未命中及父链需要订正的情况继续使用原有全局队列等待和完整加载,包含认证、兼容订正和索引刷新;等待/加载前释放事务锁以保留生命周期锁顺序,这些回退路径没有有限批次保证。复制来源和读取父级标题也有随输入增长的成本。SQL 派生的引用计数、虚拟引用及其他响应元数据保持原有异步索引行为,这不是文件系统、SQL 和同步的联合快照。+主块投影在每次投影内按物理兄弟列表统一解析标题父级。全部由已跟踪 `update` 操作构成的事务,可提供变更及删除子树的块 ID 和受影响容器。标题结构、行级 HTML、未跟踪写入、缺失或变化的根元数据,以及其他事务操作继续完整主块投影。队列只在同一笔记本、文档和路径内合并提示,保留删除、移动、重命名及其他索引操作的有序边界。提示只存在于进程内存,恢复时从完整已认证源文件执行幂等的完整更新。完整附属投影和整篇 `.sy` 的保存方式保持不变。视图顺序复用只用于实时普通源、至少 512 个游离条目、静态字段,以及分页前必须计算的封闭纯模板。覆盖表格、列表和无封面的画廊;查询、分组、上下文筛选、目标定位、汇总、日期/时间、关联、汇总字段、资源及外部或动态依赖继续原路径。普通视图及模板全部仅用于显示的视图不计算顺序指纹。键包含源版本和缓存代次、实际数据和视图定义、载体、语言及写入范围,临时数据或排序变化产生不同键。指纹分块编码属性值,仍校验并哈希完整输入,源数据解析也仍随源大小增长。@@ -67,6 +71,8 @@ go test ./model -run '^$' -bench '^BenchmarkDatabaseTemplateDependencies$' -bencgo test -tags fts5 ./sql -run '^$' -bench '^BenchmarkIndexProjection$' -benchmem -benchtime=200ms -count=3go test ./model -run '^$' -bench '^BenchmarkDatabaseViewOrderReuse$' -benchmem -benchtime=200ms -count=3go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkFTSExactCountReuse$' -benchmem -benchtime=200ms -count=3+go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^Benchmark(DocumentReadBoundarySource|DocumentReadBoundaryEmpty|FlushTxQueueEmpty)$' -benchmem -benchtime=1s -count=3+go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^BenchmarkDocument(SearchCandidates|CandidateIndexWrite)$' -benchmem -benchtime=200ms -count=3```| 基准 | 固定工作负载 | 包含的工作 |@@ -79,9 +85,32 @@ go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkFTSExactCountReuse$' -bench| `BenchmarkIndexProjection` | 1 千 / 5 千 / 2 万个段落,一处普通正文变化 | 独立标题父级查找、请求内统一解析,以及两个主块投影对照;均包含完整附属投影,不含 SQL 写入 || `BenchmarkDatabaseViewOrderReuse` | 100 / 1 千 / 1 万 / 5 万个游离条目,使用同一模板依赖夹具,每页 50 条 | 源解析及完整处理、顺序未命中或顺序复用;内容相同的对照快照共用原始/规范化缓存,但不参与跨请求复用;冷模式改变临时视图名称,包含指纹及准入成本 || `BenchmarkFTSExactCountReuse` | 1 千 / 1 万 / 10 万 / 100 万个块,每篇 100 块;全部、0.1% 或无块命中,取前 50 块 | 热内存 FTS 行解码及精确块/文档计数;无缓存的分开读取与冷/热快照计数对照,冷模式包含缓存清理 |+| `BenchmarkDocumentReadBoundarySource` | 1 千 / 5 千 / 2 万个扁平段落,每块 128 字节 ASCII 正文 | 单独捕获来源,或全局刷新与读取边界下的完整加载;热模式使用正文缓存,冷模式每次移除正文缓存;均复用操作系统文件缓存,不含排队积压和响应渲染 |+| `BenchmarkDocumentSearchCandidates` | 1 万 / 10 万 / 100 万个块,每篇 100 块;全部文档、一篇文档或无文档命中 | 无候选、扫描块以生成根 ID,以及预建文档 trigram 索引三条路径的完整文档查询、计数和行解码;`candidate_build_ms` 和 `candidate_bytes` 单独记录索引构建和 SQLite 页面增长 |+| `BenchmarkDocumentCandidateIndexWrite` | 一篇文档包含 100 / 1 千 / 2 万个块;交替修改一个块的 SQL 正文 | 单块表更新/提交,与该更新加全文档聚合及 trigram 替换对照;不含文档序列化、文件写入和产品已有块 FTS 更新;SQLite 改动包含索引内部写入 |可通过子基准筛选缩小规模,例如 `-bench '^BenchmarkDocumentSearch$/^10000$'`。数据库建立和夹具生成不在计时循环内。显示/模板基准在迭代间复用属性视图,顺序复用基准每次解析新视图;原始/规范化源缓存均已预热,不代表冷启动打开。`-benchmem` 测量 Go 分配,不是 SQLite 原生分配或总 RSS。基准结果是对应路径的基线,不是应用延迟或整体提速结论。FTS 必须包括低命中及无命中查询,因为版本/快照校验可能比它们的少量计数更贵。+## 文档候选实验++候选查询及 trigram 索引只存在于测试和基准,实际搜索和存储不使用它们。扫描实验用一个字面子串产生候选根 ID,继续通过完整查询确定结果、计数和顺序;包含逗号、LIKE 通配符和 NUL 的候选词回退。夹具对照包含大小写、路径匹配、过滤、引号、跨块关键词、分隔符、NUL、全部排序方式和分页,只证明这些夹具等价,不代表已经证明任意查询计划和聚合顺序等价。++索引实验使用固定字段拼接。普通分词器会漏掉 `malpha` 中的 `alpha`;全部字段的 trigram 索引也可能漏掉已启用的 `content + alias` 拼出的 `alpha`,因为未启用的 `name` 在索引拼接中插入了其他内容。负向回归保留这两个反例。启用索引前,需要先保证字段设置、类型/范围过滤和聚合边界下的完整召回,再完成认证重建/恢复验证并满足写入及存储预算。本次不启用新的持久化索引或迁移。++2026-10-19,在 Windows amd64、Intel i7-8750H、Go 1.27.2、`fts5 sqlcipher` 下,基于 `9436ff6100` 的第四批工作区测量如下。查询/加载/写入时间为三次采样中位数,索引构建和页面增长只对共用夹具测量一次:++| 工作负载 | 对照 | 测量结果 |+|---|---|---|+| 2 万块热来源 | 原加载 / 快照加载 / 事务锁内捕获 | 138 / 123 / 3.46 毫秒 |+| 2 万块正文缓存未命中 | 原加载 / 捕获未命中后的全局回退 | 261 / 256 毫秒 |+| 100 万块,全部文档命中 | 原查询 / 扫描候选 / 固定字段 trigram 候选 | 660 / 1,012 / 991 毫秒 |+| 100 万块,一篇文档命中 | 原查询 / 扫描候选 / 固定字段 trigram 候选 | 867 / 1,224 / 2.12 毫秒 |+| 100 万块,无文档命中 | 原查询 / 扫描候选 / 固定字段 trigram 候选 | 810 / 553 / 0.337 毫秒 |+| 100 万块候选索引 | 构建 / SQLite 页面增长 | 2.25 秒 / 96.3 MB |+| 2 万块文档中的单块 SQL 更新 | 只更新块 / 更新并替换文档 trigram | 0.015 / 63.3 毫秒;1 / 789 次 SQLite 改动 |++读取改动把热路径中的事务排斥限制在来源捕获阶段,整树解析仍然昂贵。来源总加载时间存在较大波动,小规模夹具尤其明显,不能据此证明产品打开更快。低命中候选索引有明显潜力,但实验会漏掉合法字段组合,并增加高命中查询和写入成本,因此不采用。大查询的部分采样只有一次操作,波动也较大;这些只是微基准方向性结果,不包含延迟分位数、真机交互、恢复测量或进程 RSS。+## 产品采样每组对照记录提交、工具链与 Electron 版本、操作系统、硬件、构建方式、实际数据规模、查询命中率、样本数、缓存状态和并发后台工作。固定正文长度、嵌套、引用/资源数量、数据库字段和模板。冷打开、热重开、后续翻页、连续输入及同步/索引期间交互分别采样,同时覆盖小工作区、低命中率查询、加密笔记本和桌面/浏览器/移动端路径。@@ -113,6 +142,8 @@ go test ./model -run 'TestAttributeViewTemplatePlan|TestRenderAttributeViewUsesTgo test -tags 'fts5 sqlcipher' ./sql -run '^TestAuxiliaryIndexEncryptedUpdateAndReopen$' -count=1go test -tags 'fts5 sqlcipher' ./sql ./model -run 'TestTreeIndexChanges|TestIndexHeading|TestIndexProjection|TestTransactionIndexChanges|TestFTSCount|TestReusableTemplateKey|TestAttributeViewOrderReuse' -count=1go test -race ./cache -run TestAVOrderedIDs -count=1+go test -tags 'fts5 sqlcipher' ./model ./filesys -run 'TestDocumentReadBoundary|TestCachedTreeSource|TestAssetRelinkLockCancels|TestDocumentSearchCandidate' -count=1+go test -race -tags 'fts5 sqlcipher' ./model ./filesys -run 'TestDocumentReadBoundary|TestCachedTreeSource|TestAssetRelinkLockCancels|TestQueuedTransactionWaitForCommit|TestFlushTxQueueWaitsForDequeuedTransaction|TestWaitForSubmittedTransactionBatch|TestTransactionCompletion' -count=1```取消测试覆盖全局及笔记本路由数据库中运行的 SQLite 工作和连接复用。使用独立内存库的夹具验证路由,不验证 SQLCipher 格式兼容性。渲染测试使用真实浏览器 DOM,覆盖插入范围、全量替换、选区节点身份、前插滚动补偿以及过期/已移除节点;组件渲染器以调用记录器替代。组件行为及真机输入法/触摸交互还需各自的回归检查。语义搜索继续保持串行调度,其内核取消另行实施。@@ -120,3 +151,5 @@ go test -race ./cache -run TestAVOrderedIDs -count=1附属索引测试将五类表与完整替换结果对照,覆盖重复记录、删除、元数据变化、重放、失败回滚、NULL 区分和分批删除。两万块回归在普通正文编辑时禁止任何附属表写入。SQLCipher 测试使用真实加密库,验证索引迁移/重开、错误密钥拒绝和全局库隔离。模板计划测试对表格、列表和画廊的分页值、顺序、总数、条件着色及汇总结果做完整计算对照,同时覆盖原始值和过期显示状态。这些内核改动由桌面端和移动端共用,不改变前端交互。变更集测试对照完整 SQL/FTS 快照,覆盖合并事务、删除/替换子块、根元数据回退、有序边界、写入失败及不带提示的恢复。顺序复用测试对照表格/列表/画廊的完整响应,覆盖已保存和临时编辑、排序/写入范围、空结果、排除依赖、字节上限、ID 不可变性和并发失效。FTS 测试分别在建立快照前、版本确认前及读取行期间安排真实 WAL 提交,验证本次快照计数及后续失效,并覆盖回滚、SQL/参数隔离、取消及旧请求准入。还应按影响运行周边 SQL、AV、事务和 API 权限回归;这些定向测试不能替代真实工作区 RSS 或设备交互测量。++读取边界测试覆盖共享读取和写入排斥、执行中的提交、捕获批次完成及后续入队、跨文档移动、写入失败、撤销重放、异常/错误清理、后续编辑完成后再解析缓存字节,以及聚焦/分页模式和高亮下的完整 GetDoc 返回值对照。来源测试在父文档改名和源文件移除后比较完整树及元数据,并覆盖缓存未命中、订正回退、过期路径和授权检查。SQLCipher 用例使用真实加密块树和内容库,验证认证失败、密文保留、生命周期等待期间其他事务继续完成、响应租约等待及锁定后的拒绝访问。桌面端和移动端共用该内核路径,无需改动交互代码。diff --git a/kernel/filesys/tree_cached_source.go b/kernel/filesys/tree_cached_source.gonew file mode 100644index 0000000000..6dc4a77022--- /dev/null+++ b/kernel/filesys/tree_cached_source.go@@ -0,0 +1,71 @@+package filesys++import (+ "path/filepath"+ "strings"++ "github.com/88250/lute"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// CachedTreeSource 保存普通文档缓存及父级标题的独立副本,解析不再访问文件或发布缓存。+type CachedTreeSource struct {+ data []byte+ boxID, path string+ parentHPathPrefix string+}++// CaptureCachedTreeSource 在调用方的读取边界内复制已缓存来源。+// 缓存缺失、加密来源和需要订正的父链返回 nil,由调用方完成完整加载。+func CaptureCachedTreeSource(boxID, p string) (*CachedTreeSource, error) {+ if err := validateTreePath(boxID, p); err != nil {+ return nil, err+ }+ _, encrypted, release, err := acquireCryptoLease(boxID)+ if err != nil {+ return nil, err+ }+ defer release()+ if encrypted {+ return nil, nil+ }+ data, ok := cache.GetTreeDataInBox(util.GetTreeID(p), boxID)+ if !ok {+ return nil, nil+ }+ if err = checkTreeFile(filepath.Join(util.DataDir, boxID, p)); err != nil {+ return nil, err+ }+ parts := strings.Split(strings.TrimPrefix(filepath.ToSlash(p), "/"), "/")+ var prefix strings.Builder+ prefix.WriteString("/")+ for i := 0; i < len(parts)-1; i++ {+ parentPath := filepath.Join(util.DataDir, boxID, strings.Join(parts[:i+1], "/")+".sy")+ properties, parentErr := readParentDocIAL(parentPath)+ if parentErr != nil {+ return nil, nil+ }+ title := properties["title"]+ if title == "" {+ title = "Untitled"+ }+ prefix.WriteString(title)+ prefix.WriteString("/")+ }+ return &CachedTreeSource{data: data, boxID: boxID, path: p, parentHPathPrefix: prefix.String()}, nil+}++// Parse 在调用方释放事务锁后构造独立树,保留捕获时的路径与父级标题。+func (source *CachedTreeSource) Parse(luteEngine *lute.Lute) (*parse.Tree, error) {+ tree, err := parseJSON2Tree(source.boxID, source.path, source.data, luteEngine)+ if err != nil {+ return nil, err+ }+ tree.Root.Path = source.path+ tree.HPath = source.parentHPathPrefix + tree.Root.IALAttr("title")+ tree.Hash = treenode.NodeHash(tree.Root, tree, luteEngine)+ return tree, nil+}diff --git a/kernel/filesys/tree_cached_source_test.go b/kernel/filesys/tree_cached_source_test.gonew file mode 100644index 0000000000..d06abecb32--- /dev/null+++ b/kernel/filesys/tree_cached_source_test.go@@ -0,0 +1,111 @@+package filesys++import (+ "bytes"+ "errors"+ "os"+ "testing"+ "time"++ "github.com/88250/lute/render"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func waitForCachedSource(t testing.TB, boxID, id string) {+ t.Helper()+ deadline := time.Now().Add(time.Second)+ for {+ if _, ok := cache.GetTreeDataInBox(id, boxID); ok {+ return+ }+ if time.Now().After(deadline) {+ t.Fatal("source cache was not published")+ }+ time.Sleep(time.Millisecond)+ }+}++func TestCachedTreeSourcePreservesCompleteTreeAndCapturedParent(t *testing.T) {+ for _, title := range []string{"Parent", ""} {+ t.Run("parent="+title, func(t *testing.T) {+ boxID, parentID, p, data := setupStalePathTest(t)+ childPath := writeStalePathFixture(t, boxID, p, data)+ parent := treenode.NewTree(boxID, "/"+parentID+".sy", "/"+title, title)+ if _, err := WriteTree(parent); err != nil {+ t.Fatal(err)+ }+ luteEngine := util.NewLute()+ want, err := LoadTree(boxID, p, luteEngine)+ if err != nil {+ t.Fatal(err)+ }+ waitForCachedSource(t, boxID, want.ID)+ source, err := CaptureCachedTreeSource(boxID, p)+ if err != nil || source == nil {+ t.Fatalf("could not capture warm source: %v", err)+ }+ parent.Root.SetIALAttr("title", "Renamed")+ if _, err = WriteTree(parent); err != nil {+ t.Fatal(err)+ }+ if err = os.Remove(childPath); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeDataInBox(want.ID, boxID)+ got, err := source.Parse(luteEngine)+ if err != nil {+ t.Fatal(err)+ }+ if got.Box != want.Box || got.Path != want.Path || got.HPath != want.HPath || got.Hash != want.Hash ||+ !bytes.Equal(render.NewJSONRenderer(got, luteEngine.RenderOptions, luteEngine.ParseOptions).Render(),+ render.NewJSONRenderer(want, luteEngine.RenderOptions, luteEngine.ParseOptions).Render()) {+ t.Fatal("snapshot parsing changed source projection or used later parent metadata")+ }+ got.Root.SetIALAttr("title", "Mutated local tree")+ again, err := source.Parse(luteEngine)+ if err != nil || again.Root.IALAttr("title") != want.Root.IALAttr("title") {+ t.Fatalf("snapshot parsing shared mutable tree state: %v", err)+ }+ if _, err = os.Stat(childPath); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("snapshot parsing recreated a removed source")+ }+ })+ }+}++func TestCachedTreeSourceRetainsFallbackAndAuthorization(t *testing.T) {+ boxID, _, p, data := setupStalePathTest(t)+ filePath := writeStalePathFixture(t, boxID, p, data)+ id := util.GetTreeID(p)+ if source, err := CaptureCachedTreeSource(boxID, p); err != nil || source != nil {+ t.Fatalf("cache miss should retain complete loading: %v", err)+ }+ cache.SetTreeDataInBox(id, boxID, data)+ waitForCachedSource(t, boxID, id)+ if source, err := CaptureCachedTreeSource(boxID, p); err != nil || source != nil {+ t.Fatalf("missing parent should retain complete repair: %v", err)+ }+ if err := os.Remove(filePath); err != nil {+ t.Fatal(err)+ }+ if _, err := CaptureCachedTreeSource(boxID, p); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("stale cached path was accepted: %v", err)+ }+ if _, err := CaptureCachedTreeSource(boxID, "/../conf.json"); err == nil {+ t.Fatal("invalid source path was accepted")+ }+ oldProvider, oldAcquire, oldRelease := DEKProvider, DEKLockAcquire, DEKLockRelease+ DEKLockAcquire, DEKLockRelease = nil, nil+ t.Cleanup(func() { DEKProvider, DEKLockAcquire, DEKLockRelease = oldProvider, oldAcquire, oldRelease })+ DEKProvider = func(string) ([]byte, error) { return bytes.Repeat([]byte{19}, 32), nil }+ if source, err := CaptureCachedTreeSource(boxID, p); err != nil || source != nil {+ t.Fatalf("encrypted source entered the ordinary snapshot path: %v", err)+ }+ locked := errors.New("notebook locked")+ DEKProvider = func(string) ([]byte, error) { return nil, locked }+ if _, err := CaptureCachedTreeSource(boxID, p); !errors.Is(err, locked) {+ t.Fatalf("cache capture bypassed authorization: %v", err)+ }+}diff --git a/kernel/model/asset_relink_batch.go b/kernel/model/asset_relink_batch.goindex a346b326c1..475f22bcb2 100644--- a/kernel/model/asset_relink_batch.go+++ b/kernel/model/asset_relink_batch.go@@ -12,7 +12,6 @@ import ("os""path/filepath""strings"- "sync""time""github.com/88250/gulu"@@ -127,7 +126,7 @@ func runAssetRelinks(ctx context.Context, mappings []apicontract.AssetRelinkMappreturn p.response(err)}-func lockAssetRelink(ctx context.Context, lock *sync.Mutex) error {+func lockAssetRelink(ctx context.Context, lock interface{ TryLock() bool }) error {ticker := time.NewTicker(10 * time.Millisecond)defer ticker.Stop()for {diff --git a/kernel/model/asset_relink_batch_test.go b/kernel/model/asset_relink_batch_test.goindex 5d25fc4857..e6a823ba8d 100644--- a/kernel/model/asset_relink_batch_test.go+++ b/kernel/model/asset_relink_batch_test.go@@ -6,6 +6,7 @@ import ("errors""os""path/filepath"+ "sync""testing""time"@@ -16,6 +17,52 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+type assetRelinkTryLockFunc func() bool++func (try assetRelinkTryLockFunc) TryLock() bool { return try() }++func TestAssetRelinkLockCancelsWhileDocumentReadIsActive(t *testing.T) {+ var lock sync.RWMutex+ lock.RLock()+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ attempted := make(chan struct{}, 1)+ go func() {+ done <- lockAssetRelink(ctx, assetRelinkTryLockFunc(func() bool {+ acquired := lock.TryLock()+ if !acquired {+ select {+ case attempted <- struct{}{}:+ default:+ }+ }+ return acquired+ }))+ }()+ select {+ case <-attempted:+ case <-time.After(5 * time.Second):+ t.Fatal("write lock was not attempted while the document read was active")+ }+ cancel()+ select {+ case err := <-done:+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("read-blocked write ignored cancellation: %v", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("read-blocked write did not cancel")+ }+ lock.RUnlock()+ ctx, cancel = context.WithTimeout(context.Background(), time.Second)+ defer cancel()+ if err := lockAssetRelink(ctx, &lock); err != nil {+ t.Fatalf("write lock was not available after the document read: %v", err)+ }+ lock.Unlock()+}+func TestAssetRelinkBatchPreflight(t *testing.T) {setupAssetRelinkTest(t)assetRelinkTestTree(t)diff --git a/kernel/model/document_read_boundary.go b/kernel/model/document_read_boundary.gonew file mode 100644index 0000000000..20e8e130e6--- /dev/null+++ b/kernel/model/document_read_boundary.go@@ -0,0 +1,61 @@+package model++import (+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// loadDocumentAtTransactionBoundary 在串行执行边界取得独立来源,普通缓存的解析和渲染在锁外完成。+// 普通缓存读取在空队列时共享读锁;有排队写入时,只完成取得写锁后捕获的一批。+func loadDocumentAtTransactionBoundary(id, boxID string, timing *util.Performance) (*parse.Tree, error) {+ source, err := captureDocumentSourceAtTransactionBoundary(id, boxID, timing)+ if err != nil {+ return nil, err+ }+ if source != nil {+ timing.Count("source_snapshot", 1)+ return source.Parse(util.NewLute())+ }+ // 完整加载可能涉及生命周期等待、格式订正与补建父文档,沿用全局完成等待及原有锁顺序。+ timing.Stage("wait_transactions")+ FlushTxQueue()+ timing.Stage("load_tree")+ return loadTreeByBlockIDInBox0(id, boxID, false)+}++func captureDocumentSourceAtTransactionBoundary(id, boxID string, timing *util.Performance) (source *filesys.CachedTreeSource, err error) {+ readAtTransactionBoundary(func() {+ timing.Stage("load_tree")+ bt, lookupErr := lookupBlockTreeInBox(id, boxID, false)+ if lookupErr != nil {+ err = lookupErr+ return+ }+ if IsEncryptedBox(bt.BoxID) {+ return+ }+ source, err = filesys.CaptureCachedTreeSource(bt.BoxID, bt.Path)+ })+ return+}++func readAtTransactionBoundary(read func()) {+ flushLock.RLock()+ if txQueueSize() == 0 {+ defer flushLock.RUnlock()+ read()+ return+ }+ flushLock.RUnlock()+ flushLock.Lock()+ isFlushing.Store(true)+ defer func() {+ isFlushing.Store(false)+ flushLock.Unlock()+ }()+ for _, transaction := range takeQueuedTransactions() {+ flushTx(transaction)+ }+ read()+}diff --git a/kernel/model/document_read_boundary_benchmark_test.go b/kernel/model/document_read_boundary_benchmark_test.gonew file mode 100644index 0000000000..ae16b11822--- /dev/null+++ b/kernel/model/document_read_boundary_benchmark_test.go@@ -0,0 +1,77 @@+package model++import (+ "fmt"+ "strings"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++// BenchmarkDocumentReadBoundarySource 测量完整来源树的加载,包含缓存解压、解析及读取锁成本。+func BenchmarkDocumentReadBoundarySource(b *testing.B) {+ for _, size := range []int{1000, 5000, 20000} {+ b.Run(fmt.Sprint(size), func(b *testing.B) {+ fixture := setupFileOperationTest(b)+ tree := treenode.NewTree(fixture.box.ID, fixture.sourcePath, "/Source", "Source")+ tree.Root.FirstChild.Unlink()+ for i := range size {+ node := treenode.NewParagraph(fmt.Sprintf("20261019000001-%07d", i))+ node.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(strings.Repeat("content ", 16))})+ tree.Root.AppendChild(node)+ }+ if _, err := filesys.WriteTree(tree); err != nil {+ b.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ deadline := time.Now().Add(time.Second)+ for {+ if _, ok := cache.GetTreeDataInBox(tree.ID, tree.Box); ok {+ break+ }+ if time.Now().After(deadline) {+ b.Fatal("source cache was not published")+ }+ time.Sleep(time.Millisecond)+ }+ b.Run("capture", func(b *testing.B) {+ b.ReportAllocs()+ for b.Loop() {+ if source, err := captureDocumentSourceAtTransactionBoundary(tree.ID, "", nil); err != nil || source == nil {+ b.Fatalf("source capture did not use the warm cache: %v", err)+ }+ }+ })+ for _, cold := range []bool{false, true} {+ for _, boundary := range []bool{false, true} {+ b.Run(fmt.Sprintf("cold=%t/boundary=%t", cold, boundary), func(b *testing.B) {+ if _, err := loadDocumentAtTransactionBoundary(tree.ID, "", nil); err != nil {+ b.Fatal(err)+ }+ b.ReportAllocs()+ for b.Loop() {+ if cold {+ cache.RemoveTreeDataInBox(tree.ID, tree.Box)+ }+ var err error+ if boundary {+ _, err = loadDocumentAtTransactionBoundary(tree.ID, "", nil)+ } else {+ FlushTxQueue()+ _, err = loadTreeByBlockIDInBox0(tree.ID, "", false)+ }+ if err != nil {+ b.Fatal(err)+ }+ }+ b.ReportMetric(float64(size), "blocks/op")+ })+ }+ }+ })+ }+}diff --git a/kernel/model/document_read_boundary_fts5_test.go b/kernel/model/document_read_boundary_fts5_test.gonew file mode 100644index 0000000000..0612f99b85--- /dev/null+++ b/kernel/model/document_read_boundary_fts5_test.go@@ -0,0 +1,237 @@+//go:build fts5++package model++import (+ "errors"+ "fmt"+ "reflect"+ "sync"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func documentBoundaryUpdate(id, content string) *Transaction {+ return &Transaction{DoOperations: []*Operation{{Action: "update", ID: id,+ Data: fmt.Sprintf(`<div data-node-id="%s" data-type="NodeParagraph"><div contenteditable="true">%s</div></div>`, id, content)}}}+}++func TestDocumentReadBoundaryWaitsForInFlightCommitAndOwnsItsSource(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ entered, resume := make(chan struct{}), make(chan struct{})+ var release sync.Once+ defer release.Do(func() { close(resume) })+ transaction := documentBoundaryUpdate(fixture.childID, "committed source")+ transaction.writeTransactionTree = func(tree *parse.Tree) error {+ close(entered)+ <-resume+ return writeTreeUpsertQueue(tree)+ }+ writeDone := make(chan error, 1)+ go func() { writeDone <- PerformTxSync(transaction) }()+ requireTransactionFinished(t, entered)+ readDone := make(chan struct{})+ var snapshot *parse.Tree+ var readErr error+ go func() {+ snapshot, readErr = loadDocumentAtTransactionBoundary(fixture.childID, "", nil)+ close(readDone)+ }()+ requireTransactionWaiting(t, readDone)+ release.Do(func() { close(resume) })+ requireTransactionFinished(t, readDone)+ if err := <-writeDone; err != nil {+ t.Fatal(err)+ }+ if readErr != nil || treenode.GetNodeInTree(snapshot, fixture.childID).Text() != "committed source" {+ t.Fatalf("read exposed block-tree metadata before source commit: %v", readErr)+ }+ if err := PerformTxSync(documentBoundaryUpdate(fixture.childID, "later source")); err != nil {+ t.Fatal(err)+ }+ if treenode.GetNodeInTree(snapshot, fixture.childID).Text() != "committed source" {+ t.Fatal("later edits mutated the previously captured document tree")+ }+}++func TestDocumentReadBoundaryParsesCachedSourceAfterReleasingWriteLock(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ if err := PerformTxSync(documentBoundaryUpdate(fixture.childID, "captured source")); err != nil {+ t.Fatal(err)+ }+ deadline := time.Now().Add(time.Second)+ for {+ if _, ok := cache.GetTreeDataInBox(fixture.sourceID, fixture.box.ID); ok {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("committed source was not cached")+ }+ time.Sleep(time.Millisecond)+ }+ source, err := captureDocumentSourceAtTransactionBoundary(fixture.childID, "", nil)+ if err != nil || source == nil {+ t.Fatalf("warm ordinary source did not use independent capture: %v", err)+ }+ done := make(chan struct{})+ var writeErr error+ go func() { writeErr = PerformTxSync(documentBoundaryUpdate(fixture.childID, "later source")); close(done) }()+ requireTransactionFinished(t, done)+ if writeErr != nil {+ t.Fatal(writeErr)+ }+ snapshot, err := source.Parse(util.NewLute())+ if err != nil || treenode.GetNodeInTree(snapshot, fixture.childID).Text() != "captured source" {+ t.Fatalf("later edit changed the captured bytes before parsing: %v", err)+ }+}++func TestDocumentReadBoundaryPreservesGetDocProjection(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Search.Store(conf.NewSearch())+ Conf.Editor.Load().DynamicLoadBlocks = 2+ Conf.Editor.Load().HeadingNumber = true+ tree, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ tree.Root.FirstChild.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("source first")})+ heading := &ast.Node{Type: ast.NodeHeading, ID: "20261019000000-heading", HeadingLevel: 1}+ heading.SetIALAttr("id", heading.ID)+ heading.SetIALAttr("fold", "1")+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Source heading")})+ tree.Root.AppendChild(heading)+ for i := range 3 {+ paragraph := treenode.NewParagraph(fmt.Sprintf("20261019000000-%07d", i))+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(fmt.Sprintf("source paragraph %d", i))})+ tree.Root.AppendChild(paragraph)+ }+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ sql.FlushQueue()+ for _, id := range []string{tree.ID, heading.ID, fixture.childID} {+ for mode := 0; mode <= 4; mode++ {+ for _, query := range []string{"", "source"} {+ load := func() []any {+ blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, box, path, backlink, keywords, numbers, info, loadErr := GetDoc(+ fixture.childID, heading.ID, id, 0, query, nil, nil, 0, mode, 2, false, map[string]string{}, true, true)+ if loadErr != nil {+ t.Fatal(loadErr)+ }+ return []any{blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, box, path, backlink, keywords, numbers, info}+ }+ cache.RemoveTreeDataInBox(tree.ID, tree.Box)+ want := load()+ deadline := time.Now().Add(time.Second)+ for {+ if _, ok := cache.GetTreeDataInBox(tree.ID, tree.Box); ok {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("document source was not cached")+ }+ time.Sleep(time.Millisecond)+ }+ if got := load(); !reflect.DeepEqual(got, want) {+ t.Fatalf("source snapshot changed document projection: id=%s mode=%d query=%q; got=%#v want=%#v", id, mode, query, got, want)+ }+ }+ }+ }+}++func TestDocumentReadBoundaryPreservesMoveFailureAndReadErrors(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ move := &Transaction{fromAPI: true, DoOperations: []*Operation{{Action: "move", ID: fixture.childID, ParentID: fixture.targetID}}}+ queued := []*Transaction{move}+ PerformTransactions(&queued)+ tree, err := loadDocumentAtTransactionBoundary(fixture.childID, "", nil)+ if err != nil || tree.ID != fixture.targetID || tree.Path != fixture.targetPath || treenode.GetNodeInTree(tree, fixture.childID) == nil {+ t.Fatalf("cross-document move produced a mixed source snapshot: %v", err)+ }+ requireTransactionFinished(t, waitForTransactionInTest(move))+ failure := documentBoundaryUpdate(fixture.childID, "failed source")+ failure.writeTransactionTree = func(*parse.Tree) error { return errors.New("injected source failure") }+ if err = PerformTxSync(failure); err == nil {+ t.Fatal("injected source failure was accepted")+ }+ tree, err = loadDocumentAtTransactionBoundary(fixture.childID, "", nil)+ if err != nil || treenode.GetNodeInTree(tree, fixture.childID).Text() == "failed source" {+ t.Fatalf("failed commit changed the captured source: %v", err)+ }+ if _, err = loadDocumentAtTransactionBoundary("invalid", "", nil); !errors.Is(err, ErrTreeNotFound) {+ t.Fatalf("invalid block ID changed its read error: %v", err)+ }+ done := make(chan struct{})+ go func() { _ = PerformTxSync(&Transaction{}); close(done) }()+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ t.Fatal("read error retained the transaction boundary")+ }+}++func TestDocumentReadBoundaryReturnsBeforeLaterWriteAndKeepsUndoCompletion(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ if err := PerformTxSync(documentBoundaryUpdate(fixture.childID, "captured source")); err != nil {+ t.Fatal(err)+ }+ entered, resume := make(chan struct{}), make(chan struct{})+ var release sync.Once+ defer release.Do(func() { close(resume) })+ later := documentBoundaryUpdate(fixture.childID, "subsequent source")+ later.writeTransactionTree = func(tree *parse.Tree) error {+ close(entered)+ <-resume+ return writeTreeUpsertQueue(tree)+ }+ var snapshot *parse.Tree+ var err error+ readAtTransactionBoundary(func() {+ queued := []*Transaction{later}+ PerformTransactions(&queued)+ snapshot, err = loadTreeByBlockIDInBox0(fixture.childID, "", false)+ })+ if err != nil || treenode.GetNodeInTree(snapshot, fixture.childID).Text() != "captured source" {+ t.Fatalf("read did not retain the source at its boundary: %v", err)+ }+ requireTransactionFinished(t, entered)+ completion := waitForTransactionInTest(later)+ globalFlush := make(chan struct{})+ go func() { FlushTxQueue(); close(globalFlush) }()+ requireTransactionWaiting(t, completion)+ requireTransactionWaiting(t, globalFlush)+ release.Do(func() { close(resume) })+ requireTransactionFinished(t, completion)+ requireTransactionFinished(t, globalFlush)+ if treenode.GetNodeInTree(snapshot, fixture.childID).Text() != "captured source" {+ t.Fatal("completion of a subsequent write changed the captured source")+ }+ undo := documentBoundaryUpdate(fixture.childID, "captured source")+ undo.isReplay = true+ if err = PerformTxSync(undo); err != nil {+ t.Fatal(err)+ }+ requireTransactionFinished(t, waitForTransactionInTest(undo))+ tree, err := loadDocumentAtTransactionBoundary(fixture.childID, "", nil)+ if err != nil || treenode.GetNodeInTree(tree, fixture.childID).Text() != "captured source" {+ t.Fatalf("undo replay was not fully committed at the next read boundary: %v", err)+ }+}diff --git a/kernel/model/document_read_boundary_sqlcipher_test.go b/kernel/model/document_read_boundary_sqlcipher_test.gonew file mode 100644index 0000000000..b27154f1f9--- /dev/null+++ b/kernel/model/document_read_boundary_sqlcipher_test.go@@ -0,0 +1,119 @@+//go:build fts5 && (sqlcipher || libsqlcipher)++package model++import (+ "bytes"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDocumentReadBoundaryEncryptedSourceAuthenticationAndLock(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())+ tree, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ boxID := fixture.box.ID+ key := bytes.Repeat([]byte{0x69}, 32)+ prepareUnlockedEncryptedBoxTest(t, boxID, key)+ oldTempDir := util.TempDir+ util.TempDir = t.TempDir()+ t.Cleanup(func() {+ FlushTxQueue()+ backgroundRefreshWaitGroup.Wait()+ sql.ClearQueue()+ sql.CloseEncryptedDB(boxID)+ treenode.CloseEncryptedBlockTreeDB(boxID)+ cache.RemoveTreeDataInBox(tree.ID, boxID)+ util.TempDir = oldTempDir+ })+ if err = treenode.OpenEncryptedBlockTreeDB(boxID, key); err != nil {+ t.Fatal(err)+ }+ if err = sql.OpenEncryptedDB(boxID, key); err != nil {+ t.Fatal(err)+ }+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ transaction := documentBoundaryUpdate(fixture.childID, "authenticated source")+ queued := []*Transaction{transaction}+ PerformTransactions(&queued)+ _, content, _, _, rootID, _, _, _, gotBox, _, _, _, _, _, err := GetDocInBox(+ "", "", fixture.childID, 0, "", nil, nil, 0, 0, 102400, false, map[string]string{}, true, false, boxID)+ if err != nil || !strings.Contains(content, "authenticated source") || rootID != tree.ID || gotBox != boxID {+ t.Fatalf("encrypted document did not capture its committed source: %v", err)+ }+ requireTransactionFinished(t, waitForTransactionInTest(transaction))+ // 生命周期等待沿用完整加载路径,不得占住全局事务锁而阻塞其他文档写入。+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocking)+ readDone := make(chan struct{})+ var waitingReadErr error+ go func() {+ _, waitingReadErr = loadDocumentAtTransactionBoundary(fixture.childID, boxID, nil)+ close(readDone)+ }()+ func() {+ defer setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)+ requireTransactionWaiting(t, readDone)+ writeDone := make(chan struct{})+ go func() { _ = PerformTxSync(&Transaction{}); close(writeDone) }()+ requireTransactionFinished(t, writeDone)+ }()+ requireTransactionFinished(t, readDone)+ if waitingReadErr != nil {+ t.Fatalf("encrypted read did not resume after its lifecycle transition: %v", waitingReadErr)+ }+ path := filepath.Join(util.DataDir, boxID, tree.Path)+ original, err := os.ReadFile(path)+ if err != nil || !util.IsCiphertext(original) {+ t.Fatalf("read boundary did not preserve encrypted source storage: %v", err)+ }+ tampered := bytes.Clone(original)+ tampered[len(tampered)-1] ^= 1+ if err = os.WriteFile(path, tampered, 0600); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeDataInBox(tree.ID, boxID)+ if _, err = loadDocumentAtTransactionBoundary(fixture.childID, boxID, nil); err == nil {+ t.Fatal("read boundary accepted unauthenticated ciphertext")+ }+ if unchanged, readErr := os.ReadFile(path); readErr != nil || !bytes.Equal(unchanged, tampered) {+ t.Fatalf("authentication failure changed source ciphertext: %v", readErr)+ }+ if err = os.WriteFile(path, original, 0600); err != nil {+ t.Fatal(err)+ }+ if err = AcquireEncryptedBoxOperation(boxID); err != nil {+ t.Fatal(err)+ }+ if _, err = loadDocumentAtTransactionBoundary(fixture.childID, boxID, nil); err != nil {+ ReleaseEncryptedBoxOperation(boxID)+ t.Fatal(err)+ }+ locked := make(chan struct{})+ go func() { LockBox(boxID); close(locked) }()+ requireTransactionWaiting(t, locked)+ ReleaseEncryptedBoxOperation(boxID)+ requireTransactionFinished(t, locked)+ if _, err = loadDocumentAtTransactionBoundary(fixture.childID, boxID, nil); err == nil {+ t.Fatal("locked notebook exposed its captured source through a cache")+ }+ if unchanged, readErr := os.ReadFile(path); readErr != nil || !bytes.Equal(unchanged, original) {+ t.Fatalf("locking changed the persisted encrypted document: %v", readErr)+ }+}diff --git a/kernel/model/document_read_boundary_test.go b/kernel/model/document_read_boundary_test.gonew file mode 100644index 0000000000..8137c75d04--- /dev/null+++ b/kernel/model/document_read_boundary_test.go@@ -0,0 +1,94 @@+package model++import (+ "sync"+ "testing"+ "time"+)++func TestDocumentReadBoundarySharesReadsAndExcludesWrites(t *testing.T) {+ FlushTxQueue()+ entered := make(chan struct{}, 2)+ resume := make(chan struct{})+ var release sync.Once+ defer release.Do(func() { close(resume) })+ var readers sync.WaitGroup+ for range 2 {+ readers.Go(func() {+ readAtTransactionBoundary(func() { entered <- struct{}{}; <-resume })+ })+ }+ for range 2 {+ select {+ case <-entered:+ case <-time.After(5 * time.Second):+ t.Fatal("empty-queue document reads did not share the read boundary")+ }+ }+ writer := make(chan struct{})+ go func() { flushLock.Lock(); flushLock.Unlock(); close(writer) }()+ select {+ case <-writer:+ t.Fatal("writer entered while a source snapshot was still being loaded")+ case <-time.After(20 * time.Millisecond):+ }+ release.Do(func() { close(resume) })+ readers.Wait()+ requireTransactionFinished(t, writer)+}++func TestDocumentReadBoundaryFinishesCapturedBatchAndLeavesLaterTransactions(t *testing.T) {+ FlushTxQueue()+ first, second, later := &Transaction{Timestamp: 1}, &Transaction{Timestamp: 2}, &Transaction{Timestamp: 3}+ flushLock.Lock()+ initial := []*Transaction{second, first}+ PerformTransactions(&initial)+ readDone := make(chan struct{})+ observed := make(chan bool, 1)+ go func() {+ readAtTransactionBoundary(func() {+ finished := func(tx *Transaction) bool {+ select {+ case <-tx.completion.Load().done:+ return true+ default:+ return false+ }+ }+ next := []*Transaction{later}+ PerformTransactions(&next)+ observed <- finished(first) && finished(second) && !finished(later)+ })+ close(readDone)+ }()+ flushLock.Unlock()+ requireTransactionFinished(t, readDone)+ if !<-observed {+ t.Fatal("source capture missed its completed batch or executed a later arrival")+ }+ FlushTxQueue()+}++func TestDocumentReadBoundaryReleasesLockAfterReadPanic(t *testing.T) {+ FlushTxQueue()+ func() {+ defer func() {+ if recover() == nil {+ t.Error("read panic was unexpectedly swallowed")+ }+ }()+ readAtTransactionBoundary(func() { panic("injected snapshot read failure") })+ }()+ if !flushLock.TryLock() {+ t.Fatal("failed source capture retained the transaction lock")+ }+ flushLock.Unlock()+}++func BenchmarkDocumentReadBoundaryEmpty(b *testing.B) {+ FlushTxQueue()+ b.ReportAllocs()+ for b.Loop() {+ readAtTransactionBoundary(func() {})+ }+}diff --git a/kernel/model/file.go b/kernel/model/file.goindex 23c35d4613..6a293d23f1 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -663,11 +663,9 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,//defer pprof.StopCPUProfile()timing.Stage("wait_transactions")- FlushTxQueue() // 写入数据时阻塞,避免获取到的数据不一致- timing.Stage("load_tree")inputIndex := index- tree, err := loadTreeByBlockIDInBox0(id, boxID, false)+ tree, err := loadDocumentAtTransactionBoundary(id, boxID, timing)if err != nil {if errors.Is(err, ErrBlockNotFound) {if 0 == mode {diff --git a/kernel/model/file_test.go b/kernel/model/file_test.goindex 95756f3d8b..d4f32cf8f0 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -44,7 +44,7 @@ type fileOperationTestFixture struct {childID string}-func setupFileOperationTest(t *testing.T) *fileOperationTestFixture {+func setupFileOperationTest(t testing.TB) *fileOperationTestFixture {originalConf := ConforiginalDataDir := util.DataDiroriginalBlockTreeDBPath := util.BlockTreeDBPathdiff --git a/kernel/model/search_document_candidate_experiment_fts5_test.go b/kernel/model/search_document_candidate_experiment_fts5_test.gonew file mode 100644index 0000000000..07db18774b--- /dev/null+++ b/kernel/model/search_document_candidate_experiment_fts5_test.go@@ -0,0 +1,278 @@+//go:build fts5++package model++import (+ gosql "database/sql"+ "fmt"+ "reflect"+ "strings"+ "testing"+ "time"+)++// documentCandidateExperiment 仅用于对照实验,不参与实际搜索。+// 单个字面子串产生候选根 ID,完整查询仍负责过滤、聚合、计数及排序。+func documentCandidateExperiment(statement, needle, strategy string, hpath bool) string {+ if needle == "" || strings.ContainsAny(needle, ",%_\x00") {+ return statement+ }+ predicate := buildSearchDocumentLikeFilter(columnConcat(), []string{needle})+ if hpath {+ predicate = buildSearchDocumentLikeFilterWithHPath(columnConcat(), normalizedHPathSearchField("hpath"), []string{needle})+ }+ candidates := "SELECT root_id FROM blocks WHERE " + predicate+ if strategy == "trigram" {+ if hpath || len([]rune(needle)) < 3 {+ return statement+ }+ candidates = `SELECT root_id FROM document_candidates WHERE content MATCH '"` + strings.ReplaceAll(needle, `"`, `""`) + `"'`+ }+ return strings.Replace(statement, " FROM blocks WHERE ", " FROM blocks WHERE root_id IN ("+candidates+") AND ", 1)+}++func TestDocumentSearchCandidateScanExperimentPreservesResults(t *testing.T) {+ for _, sensitive := range []bool{false, true} {+ t.Run(fmt.Sprint(sensitive), func(t *testing.T) {+ setSearchCaseSensitive(t, sensitive)+ database := newSearchHPathTestDB(t)+ setting := "OFF"+ if sensitive {+ setting = "ON"+ }+ for _, ddl := range []string{"CREATE INDEX idx_blocks_root_id ON blocks(root_id)", "PRAGMA case_sensitive_like=" + setting} {+ if _, err := database.Exec(ddl); err != nil {+ t.Fatal(err)+ }+ }+ for _, block := range [][5]string{+ {"substring", "substring", "/Other", "malpha", "d"},+ {"body", "substring", "/Other", "beta", "p"},+ {"upper", "upper", "/Other", "ALPHA beta", "d"},+ {"path", "path", "/Projects/alpha/beta", "plain", "d"},+ {"comma", "comma", "/Other", "boundary", "d"},+ {"marker", "comma", "/Other", "marker beta", "p"},+ {"nul", "nul", "/Other", "beta\x00stop", "d"},+ {"after", "nul", "/Other", "alpha", "p"},+ {"quote", "quote", "/Other", "author's beta", "d"},+ } {+ insertSearchHPathTestBlock(t, database, block[0], block[1], block[2], block[3], block[4])+ }+ for _, hpath := range []bool{false, true} {+ for _, query := range []string{"alpha beta", "boundary,marker beta", "author's beta", "alpha %", "_ beta", "missing beta"} {+ keywords := strings.Split(strings.ReplaceAll(query, "'", "''"), " ")+ for _, typ := range []string{"(type IN ('d','p'))", "(type = 'd')"} {+ for order := 0; order < 8; order++ {+ for page := 1; page < 4; page++ {+ for _, scope := range []struct {+ filter string+ args []any+ }{+ {},+ {" AND box = ? AND path LIKE ?", []any{"20260729120000-box000", "/substring%"}},+ {" AND id != 'body'", nil},+ } {+ statement := buildDocumentSearchStatement(query, keywords, typ, scope.filter, "", "", order, page, 2, hpath)+ args := append(append([]any{}, scope.args...), scope.args...)+ want := documentSearchRows(t, database, statement, args)+ for _, keyword := range keywords {+ candidate := documentCandidateExperiment(statement, keyword, "scan", hpath)+ if got := documentSearchRows(t, database, candidate, args); !reflect.DeepEqual(got, want) {+ t.Fatalf("candidate scan changed complete rows/count/order: query=%q hpath=%t type=%s page=%d order=%d; got=%v want=%v", query, hpath, typ, page, order, got, want)+ }+ }+ }+ }+ }+ }+ }+ }+ })+ }+}++func TestDocumentSearchCandidateIndexExperimentRejectsIncompleteRecall(t *testing.T) {+ setSearchCaseSensitive(t, false)+ database := newSearchHPathTestDB(t)+ insertSearchHPathTestBlock(t, database, "substring", "substring", "/Other", "malpha beta", "d")+ insertSearchHPathTestBlock(t, database, "fields", "fields", "/Other", "al", "d")+ if _, err := database.Exec("UPDATE blocks SET name = 'interruption', alias = 'pha beta' WHERE id = 'fields'"); err != nil {+ t.Fatal(err)+ }+ Conf.Search.Load().Name, Conf.Search.Load().Alias = false, true+ for _, ddl := range []string{+ "CREATE VIRTUAL TABLE block_candidates USING fts5(root_id UNINDEXED, content)",+ "INSERT INTO block_candidates SELECT root_id, content FROM blocks",+ "CREATE VIRTUAL TABLE document_candidates USING fts5(root_id UNINDEXED, content, tokenize='trigram')",+ "INSERT INTO document_candidates SELECT root_id, GROUP_CONCAT(content || name || alias || memo || ial || tag) FROM blocks GROUP BY root_id",+ } {+ if _, err := database.Exec(ddl); err != nil {+ t.Fatal(err)+ }+ }+ statement := buildDocumentSearchStatement("alpha beta", []string{"alpha", "beta"}, "(type = 'd')", "", "", "", 0, 1, 50, false)+ want := documentSearchRows(t, database, statement, nil)+ if len(want) != 2 {+ t.Fatalf("baseline must match substrings and enabled-field concatenation: %v", want)+ }+ words := documentSearchRows(t, database, "SELECT root_id FROM block_candidates WHERE content MATCH 'alpha'", nil)+ if len(words) != 0 {+ t.Fatalf("fixture did not demonstrate the substring recall boundary: %v", words)+ }+ got := documentSearchRows(t, database, documentCandidateExperiment(statement, "alpha", "trigram", false), nil)+ if len(got) != 1 || got[0][0] != "substring" {+ t.Fatalf("all-field trigram index must demonstrate the missing enabled-field join: %v", got)+ }+}++func newDocumentCandidateExperimentDB(b *testing.B, size int) *gosql.DB {+ b.Helper()+ database := newSearchHPathTestDB(b)+ if _, err := database.Exec("CREATE INDEX idx_blocks_root_id ON blocks(root_id)"); err != nil {+ b.Fatal(err)+ }+ tx, err := database.Begin()+ if err != nil {+ b.Fatal(err)+ }+ defer tx.Rollback()+ insert, err := tx.Prepare("INSERT INTO blocks VALUES (?, '', ?, '', '20261019000000-box0001', ?, '', '', '', '', '', ?, '', '', 32, ?, '', '', 0, '20261019000000', '20261019000000')")+ if err != nil {+ b.Fatal(err)+ }+ defer insert.Close()+ for i := range size {+ rootID := fmt.Sprintf("20261019000000-%07d", (i/100)*100)+ content, typ := "common text repeated for candidate experiment", "p"+ switch i % 100 {+ case 0:+ typ = "d"+ case 1:+ content = "alpha content across blocks"+ if i < 100 {+ content += " selective"+ }+ case 2:+ content = "beta content across blocks"+ }+ if _, err = insert.Exec(fmt.Sprintf("20261019000000-%07d", i), rootID, "/"+rootID+".sy", content, typ); err != nil {+ b.Fatal(err)+ }+ }+ if err = tx.Commit(); err != nil {+ b.Fatal(err)+ }+ return database+}++func documentCandidateExperimentBytes(b *testing.B, database *gosql.DB) int64 {+ b.Helper()+ var pages, pageSize int64+ if err := database.QueryRow("PRAGMA page_count").Scan(&pages); err != nil {+ b.Fatal(err)+ }+ if err := database.QueryRow("PRAGMA page_size").Scan(&pageSize); err != nil {+ b.Fatal(err)+ }+ return pages * pageSize+}++// BenchmarkDocumentSearchCandidates 对照无候选、扫描候选及固定字段聚合的 trigram 候选。+// 索引预先建成;其构建时间、页空间和更新成本需要与查询收益分别评估。+func BenchmarkDocumentSearchCandidates(b *testing.B) {+ setSearchCaseSensitive(b, false)+ for _, size := range []int{10000, 100000, 1000000} {+ b.Run(fmt.Sprint(size), func(b *testing.B) {+ database := newDocumentCandidateExperimentDB(b, size)+ before := documentCandidateExperimentBytes(b, database)+ start := time.Now()+ for _, ddl := range []string{+ "CREATE VIRTUAL TABLE document_candidates USING fts5(root_id UNINDEXED, content, tokenize='trigram')",+ "INSERT INTO document_candidates SELECT root_id, GROUP_CONCAT(" + columnConcat() + ") FROM blocks GROUP BY root_id",+ } {+ if _, err := database.Exec(ddl); err != nil {+ b.Fatal(err)+ }+ }+ buildMS := float64(time.Since(start).Microseconds()) / 1000+ bytes := documentCandidateExperimentBytes(b, database) - before+ for _, query := range []string{"alpha beta", "selective beta", "missing beta"} {+ keywords := strings.Split(query, " ")+ baseline := buildDocumentSearchStatement(query, keywords, "(type IN ('d','p'))", "", "", "", 0, 1, 50, false)+ want := documentSearchRows(b, database, baseline, nil)+ for _, strategy := range []string{"baseline", "scan", "trigram"} {+ statement := baseline+ if strategy != "baseline" {+ statement = documentCandidateExperiment(baseline, keywords[0], strategy, false)+ }+ if got := documentSearchRows(b, database, statement, nil); !reflect.DeepEqual(got, want) {+ b.Fatalf("%s candidate changed results for %q", strategy, query)+ }+ b.Run(strings.ReplaceAll(query, " ", "_")+"/"+strategy, func(b *testing.B) {+ b.ReportAllocs()+ for b.Loop() {+ documentSearchRows(b, database, statement, nil)+ }+ if strategy == "trigram" {+ b.ReportMetric(buildMS, "candidate_build_ms")+ b.ReportMetric(float64(bytes), "candidate_bytes")+ }+ })+ }+ }+ })+ }+}++// BenchmarkDocumentCandidateIndexWrite 测量单块 SQL 写入与附加全文档 trigram 重建的成本。+// 文档序列化、文件落盘及现有产品 FTS 写入不在此对照范围内。+func BenchmarkDocumentCandidateIndexWrite(b *testing.B) {+ setSearchCaseSensitive(b, false)+ for _, size := range []int{100, 1000, 20000} {+ b.Run(fmt.Sprint(size), func(b *testing.B) {+ database := newDocumentCandidateExperimentDB(b, size)+ for _, ddl := range []string{+ "UPDATE blocks SET root_id = 'document', type = CASE WHEN rowid = 1 THEN 'd' ELSE 'p' END",+ "CREATE VIRTUAL TABLE document_candidates USING fts5(root_id UNINDEXED, content, tokenize='trigram')",+ "INSERT INTO document_candidates SELECT root_id, GROUP_CONCAT(" + columnConcat() + ") FROM blocks GROUP BY root_id",+ } {+ if _, err := database.Exec(ddl); err != nil {+ b.Fatal(err)+ }+ }+ for _, indexed := range []bool{false, true} {+ b.Run(fmt.Sprintf("candidate=%t", indexed), func(b *testing.B) {+ var before, after int64+ if err := database.QueryRow("SELECT total_changes()").Scan(&before); err != nil {+ b.Fatal(err)+ }+ iteration := 0+ b.ReportAllocs()+ for b.Loop() {+ tx, err := database.Begin()+ if err != nil {+ b.Fatal(err)+ }+ if _, err = tx.Exec("UPDATE blocks SET content = ? WHERE rowid = 2", fmt.Sprintf("alpha changed text %d", iteration%2)); err == nil && indexed {+ if _, err = tx.Exec("DELETE FROM document_candidates WHERE root_id = 'document'"); err == nil {+ _, err = tx.Exec("INSERT INTO document_candidates SELECT root_id, GROUP_CONCAT(" + columnConcat() + ") FROM blocks WHERE root_id = 'document' GROUP BY root_id")+ }+ }+ if err != nil {+ tx.Rollback()+ b.Fatal(err)+ }+ if err = tx.Commit(); err != nil {+ b.Fatal(err)+ }+ iteration+++ }+ if err := database.QueryRow("SELECT total_changes()").Scan(&after); err != nil {+ b.Fatal(err)+ }+ b.ReportMetric(float64(after-before)/float64(b.N), "sqlite_changes/op")+ })+ }+ })+ }+}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex c2f5c0a57d..9dabed991a 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -110,7 +110,7 @@ func performTxSyncLocked(tx *Transaction) (err error) {var (txQueue []*TransactiontxQueueLock sync.Mutex- flushLock sync.Mutex+ flushLock sync.RWMutexisFlushing atomic.Bool)diff --git a/kernel/model/tree.go b/kernel/model/tree.goindex 72136b4152..7ae7b2318b 100644--- a/kernel/model/tree.go+++ b/kernel/model/tree.go@@ -279,6 +279,14 @@ func loadTreeByBlockIDInBox(id, boxID string) (ret *parse.Tree, err error) {}func loadTreeByBlockIDInBox0(id, boxID string, logNotFound bool) (ret *parse.Tree, err error) {+ bt, err := lookupBlockTreeInBox(id, boxID, logNotFound)+ if err != nil {+ return nil, err+ }+ return loadTreeByBlockTree(bt)+}++func lookupBlockTreeInBox(id, boxID string, logNotFound bool) (ret *treenode.BlockTree, err error) {if !ast.IsNodeIDPattern(id) {stack := logging.ShortStack()logging.LogErrorf("block id is invalid [id=%s], stack: [%s]", id, stack)@@ -310,8 +318,7 @@ func loadTreeByBlockIDInBox0(id, boxID string, logNotFound bool) (ret *parse.Trereturn nil, ErrTreeNotFound}- ret, err = loadTreeByBlockTree(bt)- return+ return bt, nil}var searchTreeLimiter = rate.NewLimiter(rate.Every(3*time.Second), 1)