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: Optimize index projection and reuse view orders and FTS counts https://github.com/siyuan-note/siyuan/issues/20692
Daniel9436ff610061
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.mdindex ef56246e95..1706c899f8 100644--- a/docs/PERFORMANCE.md+++ b/docs/PERFORMANCE.md@@ -20,10 +20,11 @@ Records start with `siyuan-performance ` followed by JSON. `duration_us` and `st| `document.load` | Transaction barrier, load/parse tree, locate blocks, render response; block count || `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` | Full tree projection, block comparison, auxiliary-index comparison, writes; total and changed blocks, planned auxiliary deletions and insertions |+| `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 || `database.view`, `database.fields`, `database.rows` | Load and sync wait, field calculation, filter, sort, aggregation, pagination, conditional colors; row counts before filtering, after filtering and after pagination || `database.templates` | Template evaluation; evaluated values, including attempts that report template errors; `database.fields` also counts required and deferred template fields when a plan is used || `search`, `search.fts`, `search.path`, `search.regexp`, `search.document` | Query, result processing, exact count, grouping/references; method, returned results, matches and cancellation |+| `search.snapshot` | Ordinary FTS snapshot preparation, result rows and exact count; `count_cache_hit = 1` identifies a reused count || `editor.content` | Parse/normalize, DOM insertion, synchronous render dispatch, global state; render roots and loaded top-level blocks || `editor.databases` | Elapsed time until serial database initialization finishes; candidate root count |@@ -33,7 +34,17 @@ Nested operations overlap: do not add a parent duration to its children. `editorAuxiliary-index updates compare complete business-field snapshots in the existing transaction. Equal per-block multisets retain their stored IDs; changed blocks replace only their affected table records. Full projection remains necessary for reference and asset metadata that can change independently of a block hash. Counters describe planned row writes, including operations in transactions that subsequently fail; they are not committed-row totals.-Ordinary table, list and gallery views can evaluate templates needed by filters, sorting, calculations and conditional colors, plus their transitive dependencies, before pagination. Other templates run on the current page. Both passes share original raw-value snapshots and preserve required display output. Search, grouped layouts, unresolved/cyclic dependencies, opaque template expressions and dependencies that would change the original evaluation order retain full evaluation. Existing views eligible for deferring every template keep that behavior.+Ordinary table, list and gallery views can evaluate templates needed by filters, sorting, calculations and conditional colors, plus their transitive dependencies, before pagination. Other templates run on the current page. Both passes share original raw-value snapshots and preserve required display output. Search, grouped layouts, unresolved/cyclic dependencies, opaque template expressions and dependencies that would change the original evaluation order retain full evaluation. Existing views eligible for deferring every template keep that behavior. `database.fields` records `order_cache_hit = 1` when it regenerates a page from a reusable order. An ordinary FTS request using `search.snapshot` includes its count in the parent query stage; the parent's separate count stage then contains only dispatch overhead.++## Projection and reuse boundaries++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.++The order cache retains only independent immutable ID strings, with 16 slots and a 4 MiB logical byte budget including metadata. It regenerates the current page's values instead of sharing rendered objects. Existing source replacement/removal and global cache clearing invalidate orders and reject in-flight writes from older versions. Encrypted sources, historical paths and in-memory snapshots do not enter this cache. Cache hits reduce repeated field evaluation, filtering and sorting; they do not make the whole request proportional only to page size. Compare first-use overhead, subsequent pages and mutation-heavy workloads separately.++Exact-count reuse applies only to fixed ordinary FTS queries without custom ignore SQL. Count SQL and bound string arguments fingerprint the query and scope. Database and native connection identity plus SQLite `data_version`, `total_changes()` and `schema_version` identify the index state; versions are compared on the same connection. Own writes and other connections' commits invalidate reuse, and rollbacks may cause harmless misses. Result rows and counts use one read snapshot; version sampling before and after establishing that snapshot disables reuse across a changing boundary. There is no TTL correctness shortcut. The fixed 512-slot count cache occupies less than 128 KiB and retains no query body. Database close/rebuild and SQL cache clearing reject old admissions. Encrypted queries, custom SQL and dynamic ignore conditions keep their existing paths. Cancellation releases the snapshot and reserved connection. See SQLite's [version semantics](https://sqlite.org/pragma.html#pragma_data_version) and [snapshot isolation](https://sqlite.org/isolation.html).Export kernel and browser captures separately as UTF-8 files. From `app/`, summarize each run with:@@ -53,6 +64,9 @@ go test ./model -run '^$' -bench '^BenchmarkDatabaseDisplayPage$' -benchmem -bengo test ./model -run '^$' -bench '^BenchmarkDocumentSearch$' -benchmem -benchtime=200ms -count=3go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkUpsertTreeAuxiliaryIndexes$' -benchmem -benchtime=200ms -count=3go test ./model -run '^$' -bench '^BenchmarkDatabaseTemplateDependencies$' -benchmem -benchtime=200ms -count=3+go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkIndexProjection$' -benchmem -benchtime=200ms -count=3+go test ./model -run '^$' -bench '^BenchmarkDatabaseViewOrderReuse$' -benchmem -benchtime=200ms -count=3+go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkFTSExactCountReuse$' -benchmem -benchtime=200ms -count=3```| Benchmark | Fixed workload | Included work |@@ -60,10 +74,13 @@ go test ./model -run '^$' -bench '^BenchmarkDatabaseTemplateDependencies$' -benc| `BenchmarkDocumentJSON` | 1,000 / 5,000 / 20,000 paragraph blocks, 112 ASCII content bytes per block, no references/assets, flat structure | Document preparation/JSON serialization or JSON parsing/validation; preparation uses a temporary directory; no product binary or workspace is replaced || `BenchmarkDatabaseDisplayPage` | 1,000 / 10,000 / 50,000 detached rows, block/text/display-template fields, page size 50, no filter/group/sort | Render fields using the existing display-template deferral, paginate and evaluate the current page's template || `BenchmarkDocumentSearch` | 10,000 / 100,000 / 1,000,000 indexed blocks, 100 blocks per document, two keywords in separate paragraphs, every document matches, first 50 documents | Warm in-memory SQLite document query, exact count and result-row decoding; no FTS, disk I/O, full API formatting or frontend |-| `BenchmarkUpsertTreeAuxiliaryIndexes` | 1,000 / 5,000 / 20,000 paragraphs with a tag and custom attribute per block, one document tag; alternate one paragraph's ordinary text | Complete auxiliary replacement versus incremental comparison and writes, including identical full projections, block/FTS updates and transaction commit; SQLite `total_changes()` delta is reported as `sqlite_changes/op` and includes internal FTS writes |+| `BenchmarkUpsertTreeAuxiliaryIndexes` | 1,000 / 5,000 / 20,000 paragraphs with a tag and custom attribute per block, one document tag; alternate one paragraph's ordinary text | Complete auxiliary replacement, incremental writes with complete main projection, or a root/paragraph change set; all use batched heading-parent resolution, complete auxiliary projection, block/FTS updates and transaction commit; `sqlite_changes/op` includes internal FTS writes and compaction || `BenchmarkDatabaseTemplateDependencies` | 1,000 / 10,000 / 50,000 detached rows, two dependent templates required by filter/sort and five display templates, page size 50 | Complete versus dependency-based evaluation, including plan creation, field rendering, filter/sort and pagination; each iteration clears the rendered-collection cache |+| `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 |-Use sub-benchmark filters for smaller runs, for example `-bench '^BenchmarkDocumentSearch$/^10000$'`. Database setup and fixture generation are outside measured loops. The database benchmark reuses the attribute view across iterations; it is not 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.+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.## Product captures@@ -94,8 +111,12 @@ go test ./util -run Performance -count=1go test -tags fts5 ./sql -run 'TestAuxiliary|TestUpsertTree|TestStaticTemplateKeyDependencies' -count=1go test ./model -run 'TestAttributeViewTemplatePlan|TestRenderAttributeViewUsesTemplateDependencyPlan|TestShouldDeferAttributeViewTemplateValues|TestRenderAttributeViewDefersDisplayOnlyTemplatesUntilAfterPagination' -count=1go test -tags 'fts5 sqlcipher' ./sql -run '^TestAuxiliaryIndexEncryptedUpdateAndReopen$' -count=1+go test -tags 'fts5 sqlcipher' ./sql ./model -run 'TestTreeIndexChanges|TestIndexHeading|TestIndexProjection|TestTransactionIndexChanges|TestFTSCount|TestReusableTemplateKey|TestAttributeViewOrderReuse' -count=1+go test -race ./cache -run TestAVOrderedIDs -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.Auxiliary-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.diff --git a/docs/PERFORMANCE.zh-CN.md b/docs/PERFORMANCE.zh-CN.mdindex 265107f8dc..ceb8e6266e 100644--- a/docs/PERFORMANCE.zh-CN.md+++ b/docs/PERFORMANCE.zh-CN.md@@ -20,10 +20,11 @@| `document.load` | 事务屏障、加载/解析树、定位块、渲染响应;块数 || `document.save` | 准备/序列化、加密、比对、写入、通知;待保存字节数和实际写入字节数 || `index.flush` | 等锁、提取队列、开始/执行/提交、通知、持久化队列完成状态;批次大小和最老入队任务的等待时间 |-| `index.update` | 完整树投影、块比较、附属索引比较、写入;总块数和变化块数、计划删除及插入的附属记录数 |+| `index.update` | 主块及完整附属投影、块比较、附属索引比较、写入;`blocks_total` 为已有索引块数,`blocks_projected` 为生成的主块数,`changeset = 1` 表示采用事务提示;变化块数、计划删除及插入的附属记录数 || `database.view`、`database.fields`、`database.rows` | 加载和同步等待、字段计算、筛选、排序、汇总、分页、条件色;筛选前、筛选后及分页后的条目数 || `database.templates` | 模板求值;求值次数,包括产生模板错误的尝试;使用计算计划时,`database.fields` 还记录必需和延迟计算的模板字段数 || `search`、`search.fts`、`search.path`、`search.regexp`、`search.document` | 查询、结果加工、精确计数、分组/引用;方法、返回结果数、命中数和取消状态 |+| `search.snapshot` | 普通 FTS 快照准备、结果行和精确计数;`count_cache_hit = 1` 表示复用计数 || `editor.content` | 解析/规范化、DOM 插入、同步渲染调度、全局状态;渲染根节点数和已加载的顶层块数 || `editor.databases` | 串行数据库初始化完成前的经过时间;候选根节点数 |@@ -33,7 +34,17 @@附属索引更新在原有事务内比较完整业务字段快照。各块记录的多重集相等时保留原有记录 ID;有变化时只替换该块在对应表中的记录。引用和附件元数据可能独立于块哈希变化,因此仍保留完整投影。计数表示计划写入行数,包含之后失败的事务中的操作,不能视为已提交行数。-普通表格、列表和画廊视图可在分页前计算筛选、排序、汇总及条件着色所需的模板和传递依赖,其余模板只计算当前页。两次计算共享原始值快照,并保留必需字段已生成的显示结果。搜索、分组布局、无法解析或循环的依赖、不透明模板表达式,以及会改变原有求值顺序的依赖继续完整计算。原本可以延迟全部模板的视图保持已有行为。+普通表格、列表和画廊视图可在分页前计算筛选、排序、汇总及条件着色所需的模板和传递依赖,其余模板只计算当前页。两次计算共享原始值快照,并保留必需字段已生成的显示结果。搜索、分组布局、无法解析或循环的依赖、不透明模板表达式,以及会改变原有求值顺序的依赖继续完整计算。原本可以延迟全部模板的视图保持已有行为。通过复用顺序重新生成页面时,`database.fields` 记录 `order_cache_hit = 1`。普通 FTS 使用 `search.snapshot` 时,计数耗时包含在上层查询阶段,上层单独的计数阶段只剩调度开销。++## 投影与复用边界++主块投影在每次投影内按物理兄弟列表统一解析标题父级。全部由已跟踪 `update` 操作构成的事务,可提供变更及删除子树的块 ID 和受影响容器。标题结构、行级 HTML、未跟踪写入、缺失或变化的根元数据,以及其他事务操作继续完整主块投影。队列只在同一笔记本、文档和路径内合并提示,保留删除、移动、重命名及其他索引操作的有序边界。提示只存在于进程内存,恢复时从完整已认证源文件执行幂等的完整更新。完整附属投影和整篇 `.sy` 的保存方式保持不变。++视图顺序复用只用于实时普通源、至少 512 个游离条目、静态字段,以及分页前必须计算的封闭纯模板。覆盖表格、列表和无封面的画廊;查询、分组、上下文筛选、目标定位、汇总、日期/时间、关联、汇总字段、资源及外部或动态依赖继续原路径。普通视图及模板全部仅用于显示的视图不计算顺序指纹。键包含源版本和缓存代次、实际数据和视图定义、载体、语言及写入范围,临时数据或排序变化产生不同键。指纹分块编码属性值,仍校验并哈希完整输入,源数据解析也仍随源大小增长。++顺序缓存只保留独立的不可变 ID 字符串,最多 16 个条目,逻辑字节预算为 4 MiB,包含元数据。命中后重新生成当前页的值,不共享渲染对象。既有源替换/删除及全局清理使顺序失效,并拒绝旧版本在途请求写回。加密源、历史路径和内存快照不进入该缓存。命中可减少重复的字段求值、筛选和排序,但不能让整个请求只与页大小相关。应分别对照首次开销、后续翻页和高频修改工作负载。++精确计数复用只用于没有自定义忽略 SQL 的固定普通 FTS 查询。计数 SQL 和绑定字符串参数标识查询及范围;数据库、原生连接身份和 SQLite 的 `data_version`、`total_changes()`、`schema_version` 标识索引状态,版本只在同一连接上比较。自身写入及其他连接提交使复用失效,回滚可能造成无害的未命中。结果行和计数使用同一读取快照,建立快照前后的版本采样会在边界变化时停用复用,不按 TTL 推断正确性。计数缓存固定 512 个槽位,占用低于 128 KiB,不保留查询正文。关闭/重建数据库和 SQL 缓存清理拒绝旧请求准入。加密查询、自定义 SQL 和动态忽略条件保持原路径。取消释放快照及预留连接。参见 SQLite 的[版本语义](https://sqlite.org/pragma.html#pragma_data_version)和[快照隔离](https://sqlite.org/isolation.html)。将内核与浏览器采样分别导出为 UTF-8 文件。在 `app/` 下汇总每次运行:@@ -53,6 +64,9 @@ go test ./model -run '^$' -bench '^BenchmarkDatabaseDisplayPage$' -benchmem -bengo test ./model -run '^$' -bench '^BenchmarkDocumentSearch$' -benchmem -benchtime=200ms -count=3go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkUpsertTreeAuxiliaryIndexes$' -benchmem -benchtime=200ms -count=3go test ./model -run '^$' -bench '^BenchmarkDatabaseTemplateDependencies$' -benchmem -benchtime=200ms -count=3+go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkIndexProjection$' -benchmem -benchtime=200ms -count=3+go test ./model -run '^$' -bench '^BenchmarkDatabaseViewOrderReuse$' -benchmem -benchtime=200ms -count=3+go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkFTSExactCountReuse$' -benchmem -benchtime=200ms -count=3```| 基准 | 固定工作负载 | 包含的工作 |@@ -60,10 +74,13 @@ go test ./model -run '^$' -bench '^BenchmarkDatabaseTemplateDependencies$' -benc| `BenchmarkDocumentJSON` | 1 千 / 5 千 / 2 万个段落块,每块 112 字节 ASCII 正文,无引用/资源,扁平结构 | 文档准备/JSON 序列化,或 JSON 解析/校验;准备过程使用临时目录,不替换产品内核或工作区 || `BenchmarkDatabaseDisplayPage` | 1 千 / 1 万 / 5 万个游离条目,块/文本/显示模板字段,每页 50 条,无筛选/分组/排序 | 通过已有显示模板延迟计算生成字段、分页并求值当前页模板 || `BenchmarkDocumentSearch` | 1 万 / 10 万 / 100 万个索引块,每篇 100 块,两个词分别位于不同段落,每篇均命中,取前 50 篇 | 热内存 SQLite 文档查询、精确计数及结果行解码;不含 FTS、磁盘 I/O、完整 API 加工或前端 |-| `BenchmarkUpsertTreeAuxiliaryIndexes` | 1 千 / 5 千 / 2 万个段落,每块一个标签和自定义属性,文档另有一个标签;交替修改一个段落的普通正文 | 完整替换附属记录与增量比较、写入对照,两者均包含相同的完整投影、块/FTS 更新和事务提交;`sqlite_changes/op` 来自 SQLite `total_changes()` 差值,包含 FTS 内部写入 |+| `BenchmarkUpsertTreeAuxiliaryIndexes` | 1 千 / 5 千 / 2 万个段落,每块一个标签和自定义属性,文档另有一个标签;交替修改一个段落的普通正文 | 完整替换附属记录、完整主块投影加增量写入,以及根/段落变更集三条路径;均批量解析标题父级,包含完整附属投影、块/FTS 更新和事务提交;`sqlite_changes/op` 包含 FTS 内部写入及整理 || `BenchmarkDatabaseTemplateDependencies` | 1 千 / 1 万 / 5 万个游离条目,筛选/排序需要两个有依赖关系的模板,另有五个显示模板,每页 50 条 | 完整计算与按依赖计算对照,包含计划构建、字段渲染、筛选/排序和分页;每次迭代清除已渲染集合缓存 |+| `BenchmarkIndexProjection` | 1 千 / 5 千 / 2 万个段落,一处普通正文变化 | 独立标题父级查找、请求内统一解析,以及两个主块投影对照;均包含完整附属投影,不含 SQL 写入 |+| `BenchmarkDatabaseViewOrderReuse` | 100 / 1 千 / 1 万 / 5 万个游离条目,使用同一模板依赖夹具,每页 50 条 | 源解析及完整处理、顺序未命中或顺序复用;内容相同的对照快照共用原始/规范化缓存,但不参与跨请求复用;冷模式改变临时视图名称,包含指纹及准入成本 |+| `BenchmarkFTSExactCountReuse` | 1 千 / 1 万 / 10 万 / 100 万个块,每篇 100 块;全部、0.1% 或无块命中,取前 50 块 | 热内存 FTS 行解码及精确块/文档计数;无缓存的分开读取与冷/热快照计数对照,冷模式包含缓存清理 |-可通过子基准筛选缩小规模,例如 `-bench '^BenchmarkDocumentSearch$/^10000$'`。数据库建立和夹具生成不在计时循环内。数据库视图基准在迭代间复用属性视图,不代表冷启动打开。`-benchmem` 测量 Go 分配,不是 SQLite 原生分配或总 RSS。基准结果是对应路径的基线,不是应用延迟或整体提速结论。+可通过子基准筛选缩小规模,例如 `-bench '^BenchmarkDocumentSearch$/^10000$'`。数据库建立和夹具生成不在计时循环内。显示/模板基准在迭代间复用属性视图,顺序复用基准每次解析新视图;原始/规范化源缓存均已预热,不代表冷启动打开。`-benchmem` 测量 Go 分配,不是 SQLite 原生分配或总 RSS。基准结果是对应路径的基线,不是应用延迟或整体提速结论。FTS 必须包括低命中及无命中查询,因为版本/快照校验可能比它们的少量计数更贵。## 产品采样@@ -94,8 +111,12 @@ go test ./util -run Performance -count=1go test -tags fts5 ./sql -run 'TestAuxiliary|TestUpsertTree|TestStaticTemplateKeyDependencies' -count=1go test ./model -run 'TestAttributeViewTemplatePlan|TestRenderAttributeViewUsesTemplateDependencyPlan|TestShouldDeferAttributeViewTemplateValues|TestRenderAttributeViewDefersDisplayOnlyTemplatesUntilAfterPagination' -count=1go test -tags 'fts5 sqlcipher' ./sql -run '^TestAuxiliaryIndexEncryptedUpdateAndReopen$' -count=1+go test -tags 'fts5 sqlcipher' ./sql ./model -run 'TestTreeIndexChanges|TestIndexHeading|TestIndexProjection|TestTransactionIndexChanges|TestFTSCount|TestReusableTemplateKey|TestAttributeViewOrderReuse' -count=1+go test -race ./cache -run TestAVOrderedIDs -count=1```取消测试覆盖全局及笔记本路由数据库中运行的 SQLite 工作和连接复用。使用独立内存库的夹具验证路由,不验证 SQLCipher 格式兼容性。渲染测试使用真实浏览器 DOM,覆盖插入范围、全量替换、选区节点身份、前插滚动补偿以及过期/已移除节点;组件渲染器以调用记录器替代。组件行为及真机输入法/触摸交互还需各自的回归检查。语义搜索继续保持串行调度,其内核取消另行实施。附属索引测试将五类表与完整替换结果对照,覆盖重复记录、删除、元数据变化、重放、失败回滚、NULL 区分和分批删除。两万块回归在普通正文编辑时禁止任何附属表写入。SQLCipher 测试使用真实加密库,验证索引迁移/重开、错误密钥拒绝和全局库隔离。模板计划测试对表格、列表和画廊的分页值、顺序、总数、条件着色及汇总结果做完整计算对照,同时覆盖原始值和过期显示状态。这些内核改动由桌面端和移动端共用,不改变前端交互。++变更集测试对照完整 SQL/FTS 快照,覆盖合并事务、删除/替换子块、根元数据回退、有序边界、写入失败及不带提示的恢复。顺序复用测试对照表格/列表/画廊的完整响应,覆盖已保存和临时编辑、排序/写入范围、空结果、排除依赖、字节上限、ID 不可变性和并发失效。FTS 测试分别在建立快照前、版本确认前及读取行期间安排真实 WAL 提交,验证本次快照计数及后续失效,并覆盖回滚、SQL/参数隔离、取消及旧请求准入。还应按影响运行周边 SQL、AV、事务和 API 权限回归;这些定向测试不能替代真实工作区 RSS 或设备交互测量。diff --git a/kernel/av/av.go b/kernel/av/av.goindex 202c1d251d..8c503fd103 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -59,6 +59,17 @@ type AttributeView struct {RenderedViewables map[string]Viewable `json:"-"` // 已经渲染好的视图cardCoverPositionsChanged bool+ sourceVersion uint64+ sourceGeneration uint64+ liveOrdinarySource bool+}++// RenderSourceVersion 只标识当前工作区普通数据库的已认证源版本,临时副本不参与跨请求复用。+func (attrView *AttributeView) RenderSourceVersion() (version, generation uint64) {+ if attrView != nil && attrView.liveOrdinarySource {+ return attrView.sourceVersion, attrView.sourceGeneration+ }+ return 0, 0}// CustomColorRenderContext 为历史和仓库快照渲染解析关联数据库当时的调色板。@@ -835,6 +846,7 @@ func ReadAttributeViewCustomColorUsageByPath(avJSONPath string) (avID string, in}func parseAttributeViewByPathInBoxWithOptions(avJSONPath, boxID string, resolveColors bool) (ret *AttributeView, err error) {+ generation := cache.GetAVCacheGeneration()if !filelock.IsExist(avJSONPath) {err = ErrViewNotFoundreturn@@ -886,6 +898,8 @@ func parseAttributeViewByPathInBoxWithOptions(avJSONPath, boxID string, resolveC}}if nil == err {+ ret.sourceVersion, ret.sourceGeneration = dataVersion, generation+ ret.liveOrdinarySource = boxID == "" && filepath.Clean(avJSONPath) == filepath.Join(util.DataDir, "storage", "av", avID+".json")if resolveColors {ret.ResolveDirectColors()cache.SetAVSearchDataInBox(avID, boxID, dataVersion, newAttributeViewSearchInfo(ret))diff --git a/kernel/cache/av.go b/kernel/cache/av.goindex 8273c5ecc1..4a32cac069 100644--- a/kernel/cache/av.go+++ b/kernel/cache/av.go@@ -18,6 +18,7 @@ package cacheimport ("bytes"+ "strings""sync""sync/atomic"@@ -204,6 +205,7 @@ func ClearAVCache() {avSearchDataCacheLock.Lock()defer avSearchDataCacheLock.Unlock()avCacheGeneration.Add(1)+ clearAVOrderedIDs("")avCacheKeys = map[string]map[string]uint64{}avCache.Clear()avDataVersions = map[string]uint64{}@@ -246,5 +248,9 @@ func invalidateAVSearchDataByKeyLocked(key string) (version uint64) {version = avDataVersionavDataVersions[key] = versiondelete(avSearchDataCache, key)+ _, avID, found := strings.Cut(key, "\x00")+ if found {+ clearAVOrderedIDs(avID)+ }return}diff --git a/kernel/cache/av_order.go b/kernel/cache/av_order.gonew file mode 100644index 0000000000..5e25467513--- /dev/null+++ b/kernel/cache/av_order.go@@ -0,0 +1,116 @@+package cache++import (+ "strings"+ "sync"+)++const avOrderMaxBytes = 4 * 1024 * 1024+const avOrderSlots = 16+const avOrderMetadataBytes = avOrderSlots * 192++type avOrderEntry struct {+ key [32]byte+ avID string+ version uint64+ ids string+ count int+ used uint64+}++var avOrders = struct {+ sync.Mutex+ entries [avOrderSlots]avOrderEntry+ bytes int+ clock uint64+}{bytes: avOrderMetadataBytes}++// GetAVOrderedIDs 返回普通数据库同版本的独立 ID 切片,不共享可变渲染对象。+func GetAVOrderedIDs(avID string, version, generation uint64, key [32]byte) ([]string, bool) {+ avSearchDataCacheLock.RLock()+ defer avSearchDataCacheLock.RUnlock()+ if version == 0 || avDataVersions[avCacheKey(avID, "")] != version || avCacheGeneration.Load() != generation {+ return nil, false+ }+ avOrders.Lock()+ defer avOrders.Unlock()+ for i := range avOrders.entries {+ entry := &avOrders.entries[i]+ if entry.used != 0 && entry.key == key && entry.avID == avID && entry.version == version {+ avOrders.clock+++ entry.used = avOrders.clock+ if entry.count == 0 {+ return []string{}, true+ }+ return strings.Split(entry.ids, "\x00"), true+ }+ }+ return nil, false+}++// SetAVOrderedIDs 限制保留字节和条目数,并拒绝失效前已开始的旧请求写回。+func SetAVOrderedIDs(avID string, version, generation uint64, key [32]byte, ids []string) bool {+ cost := len(avID)+ for _, id := range ids {+ if id == "" || strings.ContainsRune(id, 0) {+ return false+ }+ cost += len(id) + 1+ if cost > avOrderMaxBytes-avOrderMetadataBytes {+ return false+ }+ }+ avSearchDataCacheLock.RLock()+ defer avSearchDataCacheLock.RUnlock()+ if version == 0 || avDataVersions[avCacheKey(avID, "")] != version || avCacheGeneration.Load() != generation {+ return false+ }+ avOrders.Lock()+ defer avOrders.Unlock()+ for i := range avOrders.entries {+ entry := &avOrders.entries[i]+ if entry.used != 0 && entry.key == key {+ avOrders.bytes -= len(entry.avID) + len(entry.ids)+ *entry = avOrderEntry{}+ }+ }+ for {+ slot, oldest := -1, -1+ for i, entry := range avOrders.entries {+ if entry.used == 0 {+ slot = i+ } else if oldest < 0 || entry.used < avOrders.entries[oldest].used {+ oldest = i+ }+ }+ if slot >= 0 && avOrders.bytes+cost <= avOrderMaxBytes {+ payload := strings.Join(ids, "\x00")+ if len(ids) == 1 {+ payload = strings.Clone(payload)+ }+ avOrders.clock+++ avOrders.entries[slot] = avOrderEntry{key: key, avID: strings.Clone(avID), version: version, ids: payload, count: len(ids), used: avOrders.clock}+ avOrders.bytes += len(avID) + len(payload)+ return true+ }+ if oldest < 0 {+ return false+ }+ entry := &avOrders.entries[oldest]+ avOrders.bytes -= len(entry.avID) + len(entry.ids)+ *entry = avOrderEntry{}+ }+}++// 调用方持有 avSearchDataCacheLock,失效与准入使用一致的锁顺序。+func clearAVOrderedIDs(avID string) {+ avOrders.Lock()+ defer avOrders.Unlock()+ for i := range avOrders.entries {+ entry := &avOrders.entries[i]+ if avID == "" || entry.avID == avID {+ avOrders.bytes -= len(entry.avID) + len(entry.ids)+ *entry = avOrderEntry{}+ }+ }+}diff --git a/kernel/cache/av_order_test.go b/kernel/cache/av_order_test.gonew file mode 100644index 0000000000..871b4fe297--- /dev/null+++ b/kernel/cache/av_order_test.go@@ -0,0 +1,112 @@+package cache++import (+ "crypto/sha256"+ "fmt"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+)++func TestAVOrderedIDsPreserveIsolationAndRejectStaleWrites(t *testing.T) {+ ClearAVCache()+ t.Cleanup(ClearAVCache)+ const id = "av-order-test"+ version := SetAVDataWithVersionInBox(id, "", []byte(`{}`))+ generation := GetAVCacheGeneration()+ key := sha256.Sum256([]byte("view definition and scope"))+ input := []string{"first", "second"}+ if !SetAVOrderedIDs(id, version, generation, key, input) {+ t.Fatal("valid source version was rejected")+ }+ input[0] = "changed input"+ got, ok := GetAVOrderedIDs(id, version, generation, key)+ if !ok || len(got) != 2 || got[0] != "first" {+ t.Fatal("input mutation changed the cached order")+ }+ got[0] = "changed result"+ again, _ := GetAVOrderedIDs(id, version, generation, key)+ if again[0] != "first" {+ t.Fatal("returned slices shared mutable state")+ }+ RemoveAVData(id)+ if _, ok = GetAVOrderedIDs(id, version, generation, key); ok || SetAVOrderedIDs(id, version, generation, key, input) {+ t.Fatal("invalidated source accepted an old read or write")+ }+ version = SetAVDataWithVersionInBox(id, "", []byte(`{"changed":true}`))+ if !SetAVOrderedIDs(id, version, generation, key, []string{}) {+ t.Fatal("empty result set was rejected")+ }+ if ids, hit := GetAVOrderedIDs(id, version, generation, key); !hit || len(ids) != 0 {+ t.Fatal("empty result set was confused with a cache miss")+ }+ ClearAVCache()+ if SetAVOrderedIDs(id, version, generation, key, input) || avOrders.bytes != avOrderMetadataBytes {+ t.Fatal("global invalidation retained payloads or admitted an old request")+ }+ scopedVersion := SetAVDataWithVersionInBox(id, "encrypted-box", []byte(`{}`))+ if SetAVOrderedIDs(id, scopedVersion, GetAVCacheGeneration(), key, input) {+ t.Fatal("scoped encrypted data entered the ordinary-source order cache")+ }+}++func TestAVOrderedIDsByteBudgetAndEviction(t *testing.T) {+ ClearAVCache()+ t.Cleanup(ClearAVCache)+ version := SetAVDataWithVersionInBox("av", "", []byte(`{}`))+ generation := GetAVCacheGeneration()+ for i := range 24 {+ key := sha256.Sum256([]byte(fmt.Sprint(i)))+ if !SetAVOrderedIDs("av", version, generation, key, []string{strings.Repeat("x", 512*1024)}) {+ t.Fatal("bounded entry was rejected")+ }+ if avOrders.bytes > avOrderMaxBytes {+ t.Fatalf("retained bytes exceeded budget: %d", avOrders.bytes)+ }+ }+ if _, ok := GetAVOrderedIDs("av", version, generation, sha256.Sum256([]byte("0"))); ok {+ t.Fatal("oldest entry was not evicted")+ }+ if _, ok := GetAVOrderedIDs("av", version, generation, sha256.Sum256([]byte("23"))); !ok {+ t.Fatal("newest entry was lost")+ }+ if SetAVOrderedIDs("av", version, generation, [32]byte{}, []string{strings.Repeat("x", avOrderMaxBytes)}) {+ t.Fatal("oversized entry exceeded the byte budget")+ }+}++func TestAVOrderedIDsConcurrentInvalidationAndAdmission(t *testing.T) {+ ClearAVCache()+ t.Cleanup(ClearAVCache)+ const id = "concurrent-order"+ generation := GetAVCacheGeneration()+ key := sha256.Sum256([]byte("concurrent view"))+ var workers sync.WaitGroup+ var invalid atomic.Bool+ for range 4 {+ workers.Go(func() {+ for range 100 {+ version := EnsureAVDataVersionInBox(id, "")+ SetAVOrderedIDs(id, version, generation, key, []string{"first", "second"})+ if ids, found := GetAVOrderedIDs(id, version, generation, key); found {+ if len(ids) != 2 || ids[0] != "first" || ids[1] != "second" {+ invalid.Store(true)+ }+ ids[0] = "local mutation"+ }+ }+ })+ }+ for range 100 {+ RemoveAVData(id)+ }+ workers.Wait()+ if invalid.Load() {+ t.Fatal("concurrent reads shared mutable IDs or admitted a partial payload")+ }+ ClearAVCache()+ if avOrders.bytes != avOrderMetadataBytes {+ t.Fatal("invalidation retained a concurrently admitted payload")+ }+}diff --git a/kernel/model/attribute_view_automation_fts5_test.go b/kernel/model/attribute_view_automation_fts5_test.goindex ffe20bf1f0..21010298b2 100644--- a/kernel/model/attribute_view_automation_fts5_test.go+++ b/kernel/model/attribute_view_automation_fts5_test.go@@ -214,7 +214,7 @@ func TestAutomationEncryptedUnavailableReferencePause(t *testing.T) {_, source, target, statusID, _ := setupAutomationTest(t)boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x72}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x72}, 32))t.Cleanup(func() {for _, view := range []*av.AttributeView{source, target} {av.SetAVBoxID(view.ID, "")@@ -407,7 +407,7 @@ func TestAutomationRelationKeywordsKeepCryptoBoundary(t *testing.T) {_, source, target, _, logsID := setupAutomationTest(t)boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x62}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x62}, 32))t.Cleanup(func() {av.SetAVBoxID(target.ID, "")forgetRuntimeEncryptedBox(boxID)@@ -731,7 +731,7 @@ func TestAutomationEncryptedExecutionAndFailures(t *testing.T) {boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)key := bytes.Repeat([]byte{0x71}, 32)- setDEKForTest(boxID, key)+ prepareUnlockedEncryptedBoxTest(t, boxID, key)t.Cleanup(func() {for _, view := range []*av.AttributeView{source, target} {av.SetAVBoxID(view.ID, "")diff --git a/kernel/model/attribute_view_binding_test.go b/kernel/model/attribute_view_binding_test.goindex a6ff8e79a0..e9f4f3668b 100644--- a/kernel/model/attribute_view_binding_test.go+++ b/kernel/model/attribute_view_binding_test.go@@ -137,7 +137,7 @@ func TestUpdateBoundBlockAvsAttributeDoesNotWriteOutsideBox(t *testing.T) {util.Langs["en"][382] = "Cannot export database [%s]. Check database bindings and notebook location"const encryptedBoxID = "20260909101000-encbox0"markRuntimeEncryptedBox(encryptedBoxID)- setDEKForTest(encryptedBoxID, bytes.Repeat([]byte{0x73}, 32))+ prepareUnlockedEncryptedBoxTest(t, encryptedBoxID, bytes.Repeat([]byte{0x73}, 32))av.SetAVBoxID(fixture.attrView.ID, encryptedBoxID)t.Cleanup(func() {av.SetAVBoxID(fixture.attrView.ID, "")diff --git a/kernel/model/attribute_view_block_history_fts5_test.go b/kernel/model/attribute_view_block_history_fts5_test.goindex 0a7a2427e5..ecde524572 100644--- a/kernel/model/attribute_view_block_history_fts5_test.go+++ b/kernel/model/attribute_view_block_history_fts5_test.go@@ -263,7 +263,7 @@ func TestAttributeViewBoundHistoryRestore(t *testing.T) {if encrypted {boxID = ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x67}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x67}, 32))av.SetAVBoxID(before.ID, boxID)tree.Box = boxIDt.Cleanup(func() {diff --git a/kernel/model/attribute_view_calendar_fts5_test.go b/kernel/model/attribute_view_calendar_fts5_test.goindex 20d10d62c8..cff32664f9 100644--- a/kernel/model/attribute_view_calendar_fts5_test.go+++ b/kernel/model/attribute_view_calendar_fts5_test.go@@ -36,7 +36,7 @@ func TestAttributeViewCalendarDateUndoAndEncryptedReplay(t *testing.T) {if encrypted {boxID = ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x63}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x63}, 32))av.SetAVBoxID(original.ID, boxID)t.Cleanup(func() {av.SetAVBoxID(original.ID, "")diff --git a/kernel/model/attribute_view_fields_fts5_test.go b/kernel/model/attribute_view_fields_fts5_test.goindex 6afc96b2ab..13dbe5012c 100644--- a/kernel/model/attribute_view_fields_fts5_test.go+++ b/kernel/model/attribute_view_fields_fts5_test.go@@ -298,7 +298,7 @@ func TestAttributeViewFieldsEncryptedReplay(t *testing.T) {_, before, tx := setupAttributeViewFieldsTest(t, av.KeyTypeText)boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x62}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x62}, 32))av.SetAVBoxID(before.ID, boxID)t.Cleanup(func() {av.SetAVBoxID(before.ID, "")diff --git a/kernel/model/attribute_view_group_undo_fts5_test.go b/kernel/model/attribute_view_group_undo_fts5_test.goindex 7e8e79d7b6..d666498d43 100644--- a/kernel/model/attribute_view_group_undo_fts5_test.go+++ b/kernel/model/attribute_view_group_undo_fts5_test.go@@ -108,7 +108,7 @@ func TestAttributeViewGroupMoveEncrypted(t *testing.T) {_, before, tx := setupAttributeViewGroupMoveTest(t, av.LayoutTypeKanban, "C")boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x65}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x65}, 32))av.SetAVBoxID(before.ID, boxID)t.Cleanup(func() {av.SetAVBoxID(before.ID, "")diff --git a/kernel/model/attribute_view_option_undo_fts5_test.go b/kernel/model/attribute_view_option_undo_fts5_test.goindex 04d11c29e0..4bb0846096 100644--- a/kernel/model/attribute_view_option_undo_fts5_test.go+++ b/kernel/model/attribute_view_option_undo_fts5_test.go@@ -213,7 +213,7 @@ func TestAttributeViewOptionEncryptedReplay(t *testing.T) {boxID := ast.NewNodeID()dek := bytes.Repeat([]byte{0x64}, 32)markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, dek)+ prepareUnlockedEncryptedBoxTest(t, boxID, dek)t.Cleanup(func() {for _, view := range []*av.AttributeView{source, peer} {av.SetAVBoxID(view.ID, "")diff --git a/kernel/model/attribute_view_order_reuse.go b/kernel/model/attribute_view_order_reuse.gonew file mode 100644index 0000000000..73b65ff280--- /dev/null+++ b/kernel/model/attribute_view_order_reuse.go@@ -0,0 +1,218 @@+package model++import (+ "crypto/sha256"+ "encoding/json"+ "strings"++ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type attributeViewOrderReuse struct {+ key [32]byte+ avID string+ version, generation uint64+ orderedIDs []string+}++func planAttributeViewOrderReuse(attrView *av.AttributeView, view *av.View, nodeID string, writable bool) *attributeViewOrderReuse {+ version, generation := attrView.RenderSourceVersion()+ if version == 0 || generation != cache.GetAVCacheGeneration() || av.GetAVBoxID(attrView.ID) != "" ||+ version != cache.EnsureAVDataVersionInBox(attrView.ID, "") || !staticAttributeViewOrder(attrView, view) {+ return nil+ }+ templates := planAttributeViewTemplates(attrView, view, "", false)+ if templates == nil || len(templates.required) == 0 {+ return nil+ }+ // 实际内存值也参与指纹,避免预览或临时编辑沿用持久化源版本下的旧顺序。+ // 分块编码保留完整输入覆盖,避免为大型视图生成另一份完整 JSON 临时副本。+ digest := sha256.New()+ encoder := json.NewEncoder(digest)+ definition := *attrView+ definition.KeyValues = nil+ err := encoder.Encode(struct {+ Data *av.AttributeView+ View *av.View+ Carrier, Language string+ Writable bool+ Version, Generation uint64+ KeyValues int+ }{&definition, view, nodeID, util.Lang, writable, version, generation, len(attrView.KeyValues)})+ if err != nil {+ return nil+ }+ for _, values := range attrView.KeyValues {+ if err = encoder.Encode(struct {+ Key *av.Key+ Count int+ Nil bool+ }{values.Key, len(values.Values), values.Values == nil}); err != nil {+ return nil+ }+ for start := 0; start < len(values.Values); start += 128 {+ if err = encoder.Encode(values.Values[start:min(start+128, len(values.Values))]); err != nil {+ return nil+ }+ }+ }+ var fingerprint [32]byte+ digest.Sum(fingerprint[:0])+ return &attributeViewOrderReuse{key: fingerprint, avID: attrView.ID, version: version, generation: generation}+}++func staticAttributeViewOrder(attrView *av.AttributeView, view *av.View) bool {+ if attrView == nil || view == nil {+ return false+ }+ if view.IsGroupView() || len(view.Groups) > 0 || view.GroupItemIDs != nil || view.GroupCalc != nil {+ return false+ }+ fields := []*av.BaseField{}+ switch view.LayoutType {+ case av.LayoutTypeTable, av.LayoutTypeList:+ if view.GetTableLayout() == nil {+ return false+ }+ for _, field := range view.GetTableLayout().Columns {+ if field == nil || field.BaseField == nil {+ return false+ }+ if field.Calc != nil && field.Calc.Operator != av.CalcOperatorNone {+ return false+ }+ fields = append(fields, field.BaseField)+ }+ case av.LayoutTypeGallery:+ if view.Gallery == nil || view.Gallery.CoverFrom != av.CoverFromNone {+ return false+ }+ for _, field := range view.Gallery.CardFields {+ if field == nil || field.BaseField == nil {+ return false+ }+ fields = append(fields, field.BaseField)+ }+ default:+ return false+ }+ for _, field := range fields {+ if field != nil && field.Calc != nil && field.Calc.Operator != av.CalcOperatorNone {+ return false+ }+ }+ primary := attrView.GetBlockKeyValues()+ if primary == nil || len(primary.Values) < 512 {+ return false+ }+ for _, value := range primary.Values {+ if value == nil || !value.IsDetached || value.Block == nil || value.Block.ID != "" {+ return false+ }+ }+ if _, resolved := sql.GetTemplateKeysByResolutionOrder(attrView); !resolved {+ return false+ }+ for _, values := range attrView.KeyValues {+ if values == nil || values.Key == nil || !staticAttributeViewOrderType(values.Key.Type) {+ return false+ }+ if values.Key.Type == av.KeyTypeTemplate || strings.TrimSpace(values.Key.RenderTemplate) != "" {+ if !sql.IsReusableTemplateKey(attrView, values.Key) {+ return false+ }+ }+ for _, value := range values.Values {+ if value != nil && value.Text != nil && (value.Text.IsRich() || strings.Contains(value.Text.Content, "<") || strings.Contains(value.Text.Content, "((") || strings.Contains(value.Text.Content, "siyuan://")) {+ return false+ }+ }+ }+ var staticFilters func([]*av.ViewFilter) bool+ staticFilters = func(filters []*av.ViewFilter) bool {+ for _, filter := range filters {+ if filter == nil {+ continue+ }+ if filter.RelativeDate != nil || filter.RelativeDate2 != nil || !staticFilters(filter.Filters) ||+ (filter.Value != nil && !staticAttributeViewOrderType(filter.Value.Type)) {+ return false+ }+ }+ return true+ }+ if !staticFilters(view.Filters) {+ return false+ }+ for _, rule := range view.EffectiveConditionalColors() {+ if rule != nil && !staticFilters([]*av.ViewFilter{rule.Filter}) {+ return false+ }+ }+ return true+}++func staticAttributeViewOrderType(typ av.KeyType) bool {+ switch typ {+ case av.KeyTypeBlock, av.KeyTypeText, av.KeyTypeNumber, av.KeyTypeCheckbox, av.KeyTypeSelect, av.KeyTypeMSelect,+ av.KeyTypeURL, av.KeyTypeEmail, av.KeyTypePhone, av.KeyTypeTemplate:+ return true+ }+ return false+}++func (reuse *attributeViewOrderReuse) capture(items []av.Item) {+ if reuse == nil {+ return+ }+ reuse.orderedIDs = make([]string, len(items))+ for i, item := range items {+ reuse.orderedIDs[i] = item.GetID()+ }+}++func (reuse *attributeViewOrderReuse) store(renderContext *sql.AttributeViewRenderContext) {+ if reuse != nil && reuse.orderedIDs != nil && !renderContext.HasTemplateErrors() {+ cache.SetAVOrderedIDs(reuse.avID, reuse.version, reuse.generation, reuse.key, reuse.orderedIDs)+ }+}++func (reuse *attributeViewOrderReuse) renderPage(attrView *av.AttributeView, view *av.View, page, pageSize int,+ renderContext *sql.AttributeViewRenderContext) (av.Viewable, bool) {+ if reuse == nil {+ return nil, false+ }+ ids, found := cache.GetAVOrderedIDs(reuse.avID, reuse.version, reuse.generation, reuse.key)+ if !found {+ return nil, false+ }+ start, end := getAttributeViewRenderRange(page, pageSize, -1, view.PageSize, len(ids))+ pageView := *view+ pageView.GroupItemIDs = ids[start:end]+ rendered := sql.RenderViewWithContext(attrView, &pageView, "", false, renderContext)+ collection := rendered.(av.Collection)+ byID := map[string]av.Item{}+ for _, item := range collection.GetItems() {+ byID[item.GetID()] = item+ }+ items := make([]av.Item, 0, end-start)+ for _, id := range ids[start:end] {+ item := byID[id]+ if item == nil {+ delete(attrView.RenderedViewables, view.ID)+ return nil, false+ }+ items = append(items, item)+ }+ collection.SetItems(items)+ if gallery, ok := rendered.(*av.Gallery); ok {+ gallery.CardCount = len(ids)+ } else {+ av.TableFromViewable(rendered).RowCount = len(ids)+ }+ av.RenderConditionalColors(rendered, view, attrView, nil, map[string]*av.AttributeView{})+ return rendered, true+}diff --git a/kernel/model/attribute_view_order_reuse_benchmark_test.go b/kernel/model/attribute_view_order_reuse_benchmark_test.gonew file mode 100644index 0000000000..15c7ea148d--- /dev/null+++ b/kernel/model/attribute_view_order_reuse_benchmark_test.go@@ -0,0 +1,68 @@+package model++import (+ "fmt"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func BenchmarkDatabaseViewOrderReuse(b *testing.B) {+ for _, size := range []int{100, 1000, 10000, 50000} {+ for _, mode := range []string{"complete", "cold", "reused"} {+ b.Run(fmt.Sprintf("rows_%d/%s", size, mode), func(b *testing.B) {+ load := setupAttributeViewOrderReuseFixture(b, av.LayoutTypeTable, size, 5)+ initial := load()+ viewID := initial.Views[0].ID+ // 相同内容的非实时路径只关闭跨请求顺序复用,共用同一原始及规范化数据缓存。+ comparisonPath := filepath.Join(b.TempDir(), initial.ID+".json")+ data, err := os.ReadFile(filepath.Join(util.DataDir, "storage", "av", initial.ID+".json"))+ if err != nil {+ b.Fatal(err)+ }+ if err = os.WriteFile(comparisonPath, data, 0600); err != nil {+ b.Fatal(err)+ }+ if _, err = renderAttributeView(initial, "", viewID, "", "", 1, 50, nil, false, false, nil, ""); err != nil {+ b.Fatal(err)+ }+ if size >= 512 {+ probe := load()+ if _, err = renderAttributeView(probe, "", viewID, "", "", 2, 50, nil, false, false, nil, ""); err != nil {+ b.Fatal(err)+ }+ values, _ := probe.GetKeyValues("required")+ if values.Values[0].Template.Content != values.Key.Template {+ b.Fatal("benchmark order cache was not primed")+ }+ }+ b.ReportAllocs()+ b.ResetTimer()+ for i := range b.N {+ var database *av.AttributeView+ if mode == "complete" {+ database, err = av.ParseAttributeViewByPath(comparisonPath)+ } else {+ database = load()+ }+ if err != nil {+ b.Fatal(err)+ }+ if mode == "cold" {+ // 不同临时名称产生未命中的定义指纹,包含指纹计算与准入开销。+ database.Views[0].Name = fmt.Sprintf("cold-%d", i)+ }+ rendered, renderErr := renderAttributeView(database, "", viewID, "", "", 2, 50, nil, false, false, nil, "")+ if renderErr != nil || rendered.(av.Collection).CountItems() != 50 {+ b.Fatalf("unexpected page: %v", renderErr)+ }+ }+ b.StopTimer()+ b.ReportMetric(float64(size), "rows/op")+ })+ }+ }+}diff --git a/kernel/model/attribute_view_order_reuse_test.go b/kernel/model/attribute_view_order_reuse_test.gonew file mode 100644index 0000000000..9f6ac8284a--- /dev/null+++ b/kernel/model/attribute_view_order_reuse_test.go@@ -0,0 +1,229 @@+package model++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func setupAttributeViewOrderReuseTest(t *testing.T, layout av.LayoutType) func() *av.AttributeView {+ return setupAttributeViewOrderReuseFixture(t, layout, 600, 2)+}++func setupAttributeViewOrderReuseFixture(t testing.TB, layout av.LayoutType, size, displays int) func() *av.AttributeView {+ t.Helper()+ previousDir, previousLang, previousLangs := util.DataDir, util.Lang, util.AttrViewLangs+ util.DataDir, util.Lang = t.TempDir(), "en"+ util.AttrViewLangs = map[string]map[string]any{"en": {"key": "Key", "table": "Table", "list": "List", "gallery": "Gallery", "select": "Select"}}+ cache.ClearAVCache()+ t.Cleanup(func() {+ util.DataDir, util.Lang, util.AttrViewLangs = previousDir, previousLang, previousLangs+ cache.ClearAVCache()+ })+ database, view := newTemplatePlanTestView(size, displays, layout)+ database.ID, view.ID = "20261019130000-av00001", "20261019130000-view001"+ database.Spec = 6+ data, err := json.Marshal(database)+ if err != nil {+ t.Fatal(err)+ }+ directory := filepath.Join(util.DataDir, "storage", "av")+ if err = os.MkdirAll(directory, 0700); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(directory, database.ID+".json"), data, 0600); err != nil {+ t.Fatal(err)+ }+ return func() *av.AttributeView {+ t.Helper()+ result, parseErr := av.ParseAttributeView(database.ID)+ if parseErr != nil {+ t.Fatal(parseErr)+ }+ return result+ }+}++func TestAttributeViewOrderReuseMatchesCompletePageRendering(t *testing.T) {+ for _, layout := range []av.LayoutType{av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeGallery} {+ t.Run(string(layout), func(t *testing.T) {+ load := setupAttributeViewOrderReuseTest(t, layout)+ cold := load()+ cold.Views[0].ConditionalColors = []*av.ConditionalColorRule{{ID: "page-color", Target: "item", Color: &av.ValueSelect{Color: "3"},+ Filter: &av.ViewFilter{Column: "required", Operator: av.FilterOperatorContains,+ Value: &av.Value{Type: av.KeyTypeTemplate, Template: &av.ValueTemplate{Content: "eligible"}}}}}+ if err := av.SaveAttributeView(cold); err != nil {+ t.Fatal(err)+ }+ cold = load()+ viewID := cold.Views[0].ID+ if _, err := renderAttributeView(cold, "", viewID, "", "", 1, 50, nil, false, false, nil, ""); err != nil {+ t.Fatal(err)+ }+ hot := load()+ actual, err := renderAttributeView(hot, "", viewID, "", "", 2, 50, nil, false, false, nil, "")+ if err != nil {+ t.Fatal(err)+ }+ values, _ := hot.GetKeyValues("required")+ if values.Values[0].Template.Content != values.Key.Template {+ t.Fatal("cached order still evaluated off-page required templates")+ }+ data, _ := json.Marshal(load())+ complete, err := av.ParseAttributeViewData(hot.ID, data)+ if err != nil {+ t.Fatal(err)+ }+ expected, err := renderAttributeView(complete, "", viewID, "", "", 2, 50, nil, false, false, nil, "")+ if err != nil {+ t.Fatal(err)+ }+ if got, want := templatePlanSnapshot(t, actual), templatePlanSnapshot(t, expected); got != want {+ t.Fatalf("reused page differs: got=%s want=%s", got, want)+ }+ gotJSON, _ := json.Marshal(actual)+ wantJSON, _ := json.Marshal(expected)+ if string(gotJSON) != string(wantJSON) {+ t.Fatal("reused page changed response metadata or value identity")+ }+ changed := load()+ text, _ := changed.GetKeyValues("text")+ text.Values[0].Text.Content = "zzz temporary edit"+ rendered, err := renderAttributeView(changed, "", viewID, "", "", 1, 1, nil, false, false, nil, "")+ if err != nil || rendered.(av.Collection).GetItems()[0].GetID() != text.Values[0].BlockID {+ t.Fatalf("temporary data mutation reused stale order: %v", err)+ }+ })+ }+}++func TestAttributeViewOrderReuseRequiresCurrentLiveSourceAndRequiredTemplates(t *testing.T) {+ load := setupAttributeViewOrderReuseTest(t, av.LayoutTypeTable)+ database := load()+ view := database.Views[0]+ checkAttrView(database, view)+ upgradeAttributeViewSpec(database)+ read := planAttributeViewOrderReuse(database, view, "", false)+ write := planAttributeViewOrderReuse(database, view, "", true)+ if read == nil || write == nil || read.key == write.key {+ t.Fatal("eligible source did not separate read and write scopes")+ }+ data, err := json.Marshal(database)+ if err != nil {+ t.Fatal(err)+ }+ snapshot, err := av.ParseAttributeViewData(database.ID, data)+ if err != nil || planAttributeViewOrderReuse(snapshot, snapshot.Views[0], "", false) != nil {+ t.Fatalf("in-memory snapshot entered live reuse: %v", err)+ }+ path := filepath.Join(t.TempDir(), database.ID+".json")+ if err = os.WriteFile(path, data, 0600); err != nil {+ t.Fatal(err)+ }+ snapshot, err = av.ParseAttributeViewByPath(path)+ if err != nil || planAttributeViewOrderReuse(snapshot, snapshot.Views[0], "", false) != nil {+ t.Fatalf("historical path entered live reuse: %v", err)+ }+ view.Filters, view.Sorts = nil, nil+ if planAttributeViewOrderReuse(database, view, "", false) != nil {+ t.Fatal("display-only templates paid for cross-request order reuse")+ }+ current := load()+ cache.RemoveAVData(database.ID)+ if planAttributeViewOrderReuse(current, current.Views[0], "", false) != nil {+ t.Fatal("invalidated source entered a new cache version")+ }+}++func TestAttributeViewOrderReuseExcludesExternalAndDynamicDependencies(t *testing.T) {+ for _, scenario := range []string{"bound", "rich", "time", "raw", "pointer format", "relation", "relative date", "calculation", "group"} {+ t.Run(scenario, func(t *testing.T) {+ database, view := newTemplatePlanTestView(600, 2, av.LayoutTypeTable)+ switch scenario {+ case "bound":+ database.GetBlockKeyValues().Values[0].IsDetached = false+ case "rich":+ database.KeyValues[1].Values[0].Text.Rich = &av.ValueTextRich{Content: "((block))"}+ case "time":+ database.KeyValues[2].Key.Template = `.action{now}`+ case "raw":+ database.KeyValues[2].Key.Template = `.action{.Text_raw.Text.Content}`+ case "pointer format":+ database.KeyValues[2].Key.Template = `.action{printf "%p" .Text}`+ case "relation":+ database.KeyValues[1].Key.Type = av.KeyTypeRelation+ case "relative date":+ view.Filters[0].RelativeDate = &av.RelativeDate{}+ case "calculation":+ view.Table.Columns[0].Calc = &av.FieldCalc{Operator: av.CalcOperatorCountAll}+ case "group":+ view.Group = &av.ViewGroup{Field: "text"}+ }+ if staticAttributeViewOrder(database, view) {+ t.Fatal("untracked dependency was admitted to cross-request reuse")+ }+ })+ }+}++func TestAttributeViewOrderReuseTracksSavedSourceSortAndEmptyResults(t *testing.T) {+ for _, scenario := range []string{"saved source", "temporary sort", "empty filter", "writable", "later value chunk"} {+ t.Run(scenario, func(t *testing.T) {+ load := setupAttributeViewOrderReuseTest(t, av.LayoutTypeTable)+ initial := load()+ viewID := initial.Views[0].ID+ if _, err := renderAttributeView(initial, "", viewID, "", "", 1, 50, nil, false, false, nil, ""); err != nil {+ t.Fatal(err)+ }+ current := load()+ writable := false+ switch scenario {+ case "saved source":+ text, _ := current.GetKeyValues("text")+ text.Values[0].Text.Content = "zzz saved change"+ if err := av.SaveAttributeView(current); err != nil {+ t.Fatal(err)+ }+ current = load()+ case "temporary sort":+ current.Views[0].Sorts[0].Order = av.SortOrderAsc+ case "empty filter":+ current.Views[0].Filters[0].Value.Template.Content = "no rows satisfy this filter"+ case "writable":+ writable = true+ case "later value chunk":+ text, _ := current.GetKeyValues("text")+ text.Values[513].Text.Content = "zzz later chunk change"+ }+ data, err := json.Marshal(current)+ if err != nil {+ t.Fatal(err)+ }+ complete, err := av.ParseAttributeViewData(current.ID, data)+ if err != nil {+ t.Fatal(err)+ }+ actual, err := renderAttributeView(current, "", viewID, "", "", 1, 50, nil, false, writable, nil, "")+ if err != nil {+ t.Fatal(err)+ }+ expected, err := renderAttributeView(complete, "", viewID, "", "", 1, 50, nil, false, writable, nil, "")+ if err != nil {+ t.Fatal(err)+ }+ got, _ := json.Marshal(actual)+ want, _ := json.Marshal(expected)+ if string(got) != string(want) {+ t.Fatalf("%s reused an incompatible order", scenario)+ }+ if scenario == "empty filter" && actual.(av.Collection).CountItems() != 0 {+ t.Fatal("empty filtered order retained previous rows")+ }+ })+ }+}diff --git a/kernel/model/attribute_view_recovery_fts5_test.go b/kernel/model/attribute_view_recovery_fts5_test.goindex 5cb0a3aa57..a60d38dbb7 100644--- a/kernel/model/attribute_view_recovery_fts5_test.go+++ b/kernel/model/attribute_view_recovery_fts5_test.go@@ -94,7 +94,7 @@ func TestAttributeViewMissingDatabaseHistoryRecovery(t *testing.T) {if encrypted {boxID = ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x73}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x73}, 32))av.SetAVBoxID(before.ID, boxID)t.Cleanup(func() {av.SetAVBoxID(before.ID, "")@@ -433,7 +433,7 @@ func TestAttributeViewBoundHistoryOneWayEncrypted(t *testing.T) {dest, keyID, itemID := addDeletedBlockOneWayTestRelation(t, source)boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x79}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x79}, 32))t.Cleanup(func() {for _, view := range []*av.AttributeView{source, dest} {av.SetAVBoxID(view.ID, "")diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.goindex 233c1f3f0d..a012a586ae 100644--- a/kernel/model/attribute_view_render.go+++ b/kernel/model/attribute_view_render.go@@ -559,6 +559,14 @@ func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierViewrenderContext := sql.NewAttributeViewRenderContext()renderContext.ReadOnly = !writabledefer renderContext.PushTemplateErrors()+ var orderReuse *attributeViewOrderReuse+ if !ignoreRows && strings.TrimSpace(query) == "" && filterContext == nil && target == nil && targetGroupID == "" {+ orderReuse = planAttributeViewOrderReuse(attrView, view, nodeID, writable)+ if reused, found := orderReuse.renderPage(attrView, view, page, pageSize, renderContext); found {+ timing.Count("order_cache_hit", 1)+ return reused, nil+ }+ }templatePlan := planAttributeViewTemplates(attrView, view, query, ignoreRows)deferTemplateValues := templatePlan != niltiming.Stage("fields")@@ -584,14 +592,15 @@ func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierViewrenderTargetItemID = ""}var targetIndex, targetOffset int- targetIndex, targetOffset, err = renderViewableInstance(viewable, view, attrView, page, pageSize, ignoreRows,- renderTargetItemID, renderContext, filterContext)+ targetIndex, targetOffset, err = renderViewableInstanceWithOrder(viewable, view, attrView, page, pageSize, ignoreRows,+ renderTargetItemID, renderContext, orderReuse.capture, filterContext)if nil != err {return}if deferTemplateValues {sql.FillAttributeViewTemplateValuesForKeysWithContext(attrView, view, viewable.(av.Collection), templatePlan.deferred, renderContext)}+ orderReuse.store(renderContext)if nil != target && targetIndex >= 0 && !view.IsGroupView() && view.LayoutType != av.LayoutTypeKanban {setAttributeViewRenderTarget(target, "", targetIndex, targetOffset, view.PageSize)}@@ -1081,6 +1090,12 @@ func attrViewFiltersUseRenderedValues(filters []*av.ViewFilter, renderTemplateKefunc renderViewableInstance(viewable av.Viewable, view *av.View, attrView *av.AttributeView, page, pageSize int,ignoreRows bool, targetItemID string,renderContext *sql.AttributeViewRenderContext, filterContexts ...*av.FilterContext) (targetIndex, targetOffset int, err error) {+ return renderViewableInstanceWithOrder(viewable, view, attrView, page, pageSize, ignoreRows, targetItemID, renderContext, nil, filterContexts...)+}++func renderViewableInstanceWithOrder(viewable av.Viewable, view *av.View, attrView *av.AttributeView, page, pageSize int,+ ignoreRows bool, targetItemID string, renderContext *sql.AttributeViewRenderContext, captureOrder func([]av.Item),+ filterContexts ...*av.FilterContext) (targetIndex, targetOffset int, err error) {timing := util.BeginPerformance("database.rows")defer timing.Finish()timing.Count("page_size", int64(pageSize))@@ -1118,6 +1133,9 @@ func renderViewableInstance(viewable av.Viewable, view *av.View, attrView *av.Atav.Sort(viewable, attrView)timing.Stage("calculate")av.Calc(viewable, attrView)+ if captureOrder != nil {+ captureOrder(viewable.(av.Collection).GetItems())+ }timing.Stage("paginate")// 日历按可见范围读取,不使用普通条目分页。diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.goindex d8bd28f2fb..9a11b0f293 100644--- a/kernel/model/crypto_test.go+++ b/kernel/model/crypto_test.go@@ -38,6 +38,63 @@ func setDEKForTest(boxID string, dek []byte) {cachedDEKs[boxID] = dek}+// prepareUnlockedEncryptedBoxTest 为数据读写测试设置加密身份、密钥和已完成初始化的生命周期。+func prepareUnlockedEncryptedBoxTest(t *testing.T, boxID string, dek []byte) {+ t.Helper()+ dataDir := filepath.Clean(util.DataDir)+ key := bytes.Clone(dek)+ markRuntimeEncryptedBox(boxID)+ setDEKForTest(boxID, key)+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)+ t.Cleanup(func() {+ cachedDEKsLock.Lock()+ zeroAndClear(cachedDEKs[boxID])+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ zeroAndClear(key)+ removeEncryptedBoxLifecycle(boxID)+ runtimeEncryptedBoxes.CompareAndDelete(boxID, dataDir)+ runtimeNormalBoxes.CompareAndDelete(boxID, dataDir)+ })+}++func TestUnlockedEncryptedBoxFixtureLifecycle(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = oldDataDir })+ const boxID = "20261019000000-fixture"+ key := bytes.Repeat([]byte{0x69}, 32)+ t.Run("unlocked", func(t *testing.T) {+ prepareUnlockedEncryptedBoxTest(t, boxID, key)+ if !IsEncryptedBox(boxID) || !isBoxUnlockedForAccess(boxID) {+ t.Fatal("fixture did not initialize an accessible encrypted notebook")+ }+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ t.Fatal(err)+ }+ ReleaseEncryptedBoxOperation(boxID)+ setEncryptedBoxStateWithAdmission(boxID, EncryptedBoxStateUnlocked, false)+ if err := AcquireEncryptedBoxOperation(boxID); err == nil {+ ReleaseEncryptedBoxOperation(boxID)+ t.Fatal("fixture bypassed operation admission")+ }+ setEncryptedBoxState(boxID, EncryptedBoxStateError)+ setDEKForTest(boxID, bytes.Clone(key))+ if _, err := GetDEKIfUnlocked(boxID); err == nil {+ t.Fatal("fixture bypassed an unavailable notebook state")+ }+ })+ if IsBoxUnlocked(boxID) || isRuntimeEncryptedBox(boxID) {+ t.Fatal("fixture retained its key or notebook identity")+ }+ if _, exists := encryptedBoxLifecycles.Load(boxID); exists {+ t.Fatal("fixture retained its lifecycle")+ }+ if !bytes.Equal(key, bytes.Repeat([]byte{0x69}, 32)) {+ t.Fatal("fixture changed its caller's key")+ }+}+func TestEncryptedBoxIdentityRejectsInvalidIDs(t *testing.T) {oldDataDir := util.DataDirutil.DataDir = t.TempDir()diff --git a/kernel/model/export_attribute_view_test.go b/kernel/model/export_attribute_view_test.goindex cc2f741da6..28a81ba8ea 100644--- a/kernel/model/export_attribute_view_test.go+++ b/kernel/model/export_attribute_view_test.go@@ -202,7 +202,7 @@ func TestAttributeViewExportDoesNotCrossEncryptedBoundary(t *testing.T) {"en": {"key": "Key", "select": "Select", "table": "Table", "gallery": "Gallery"},}markRuntimeEncryptedBox(encryptedBoxID)- setDEKForTest(encryptedBoxID, bytes.Repeat([]byte{0x42}, 32))+ prepareUnlockedEncryptedBoxTest(t, encryptedBoxID, bytes.Repeat([]byte{0x42}, 32))t.Cleanup(func() {util.Lang, util.AttrViewLangs = oldLang, oldAttrViewLangsav.SetAVBoxID(encryptedAvID, "")diff --git a/kernel/model/file.go b/kernel/model/file.goindex d0e86a2e1a..23c35d4613 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -1223,12 +1223,16 @@ func loadNodesByMode(node *ast.Node, inputIndex, mode, size int, isDoc, isHeadin}func writeTreeUpsertQueue(tree *parse.Tree) (err error) {+ return writeTreeUpsertQueueWithChanges(tree, nil)+}++func writeTreeUpsertQueueWithChanges(tree *parse.Tree, changes *sql.TreeIndexChanges) (err error) {isNew := !filelock.IsExist(filepath.Join(util.DataDir, tree.Box, tree.Path))size, err := filesys.WriteTree(tree)if err != nil {return}- sql.UpsertTreeQueue(tree)+ sql.UpsertTreeQueueWithChanges(tree, changes)refreshDocInfoWithSize(tree, size)if isNew {refreshBoxDocInfo(tree)diff --git a/kernel/model/search.go b/kernel/model/search.goindex 99f02e34b8..f595d0f7d0 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -2554,7 +2554,14 @@ func fullTextSearchByFTSInBox(ctx context.Context, query, boxFilter, pathFilterargs = append(args, boxArgs...)args = append(args, pathArgs...)timing.Stage("query")- blocks, _ := sql.SelectBlocksRawStmtArgsInBoxContext(ctx, stmt, args, pageSize, boxID)+ var blocks []*sql.Block+ counted := boxID == "" && ignoreFilter == ""+ if counted {+ countStatement := "SELECT COUNT(id), COUNT(DISTINCT root_id) FROM " + table + " WHERE (" + table + " MATCH ?) AND " + typeFilter + boxFilter + pathFilter+ blocks, matchedBlockCount, matchedRootCount, _ = sql.SelectFTSBlocksWithCountContext(ctx, stmt, countStatement, args)+ } else {+ blocks, _ = sql.SelectBlocksRawStmtArgsInBoxContext(ctx, stmt, args, pageSize, boxID)+ }timing.Stage("format")ret = fromSQLBlocksContext(ctx, &blocks, "", beforeLen)if 1 > len(ret) {@@ -2562,7 +2569,9 @@ func fullTextSearchByFTSInBox(ctx context.Context, query, boxFilter, pathFilter}timing.Stage("count")- matchedBlockCount, matchedRootCount = fullTextSearchCountByFTSInBox(ctx, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, boxID)+ if !counted {+ matchedBlockCount, matchedRootCount = fullTextSearchCountByFTSInBox(ctx, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, boxID)+ }return}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex e026cae077..c2f5c0a57d 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -2129,6 +2129,7 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {tx.markListItemFoldCandidate(oldNode, tree)}+ tx.captureIndexReplacement(tree, oldNode, updatedNode)if oldNode.IsContainerBlock() {// 更新容器块的话需要考虑其子块中可能存在的折叠标题,需要把这些折叠标题的下方块移动到新节点下面treenode.MoveFoldHeading(updatedNode, oldNode)@@ -2198,8 +2199,9 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {}treenode.CreatedUpdated(updatedNode)+ tx.captureIndexReplacement(tree, updatedNode, updatedNode)tx.nodes[updatedNode.ID] = updatedNode- tx.writeTree(tree)+ tx.writeTreeWithIndexChanges(tree)upsertAvBlockRel(updatedNode)@@ -2754,8 +2756,9 @@ type Transaction struct {nodes map[string]*ast.Node // 事务中变更的节点relatedAvIDs []string // 事务中变更的属性视图 IDchangedRootIDs []string // 变更的树 ID 列表(包含了变更定义块后影响的动态锚文本所在的树)- mutatedRootIDs []string // 提交后保留实际修改的文档 ID,避免为查询结果持有文档树- boxIcons map[string]string // 事务提交后需要同步的笔记本图标+ indexChanges map[string]*transactionIndexChanges+ mutatedRootIDs []string // 提交后保留实际修改的文档 ID,避免为查询结果持有文档树+ boxIcons map[string]string // 事务提交后需要同步的笔记本图标isGlobalAssetsInit bool // 是否初始化过全局资源判断isGlobalAssets bool // 是否属于全局资源@@ -2854,6 +2857,7 @@ func (tx *Transaction) begin() (err error) {tx.templateDocTreeRootSnapshot = niltx.trees = map[string]*parse.Tree{}tx.nodes = map[string]*ast.Node{}+ tx.indexChanges = niltx.mindmapSummarySiblings = niltx.mutatedRootIDs = niltx.changedRootIDs = nil@@ -3008,7 +3012,9 @@ func (tx *Transaction) commit() (err error) {}writeTransactionTree := tx.writeTransactionTreeif nil == writeTransactionTree {- writeTransactionTree = writeTreeUpsertQueue+ writeTransactionTree = func(source *parse.Tree) error {+ return writeTreeUpsertQueueWithChanges(source, tx.treeIndexChanges(source))+ }}if err = writeTransactionTree(tree); err != nil {return@@ -3091,6 +3097,7 @@ func (tx *Transaction) commit() (err error) {// releaseCommittedResources 释放执行期间的文档树;操作中的撤销快照及广播所需的文档 ID 继续保留。func (tx *Transaction) releaseCommittedResources() {tx.trees, tx.nodes, tx.boxIcons = nil, nil, nil+ tx.indexChanges = niltx.mindmapSummarySiblings = niltx.relatedAvIDs = niltx.removedCreatedDocs, tx.removedTemplateCreatedDocs = nil, nil@@ -3112,6 +3119,7 @@ func (tx *Transaction) releaseCommittedResources() {}func (tx *Transaction) rollback() {+ tx.indexChanges = niltx.mindmapSummarySiblings = niltx.rollbackCollectionCreatedTrees()tx.finishAttributeViewMutation(true)@@ -3274,6 +3282,14 @@ func (tx *Transaction) loadTree(id string) (ret *parse.Tree, err error) {}func (tx *Transaction) writeTree(tree *parse.Tree) {+ if tx.indexChanges == nil {+ tx.indexChanges = map[string]*transactionIndexChanges{}+ }+ tx.indexChanges[tree.ID] = &transactionIndexChanges{full: true}+ tx.writeTreeWithIndexChanges(tree)+}++func (tx *Transaction) writeTreeWithIndexChanges(tree *parse.Tree) {tx.trees[tree.ID] = treeif err := tx.captureCollectionTree(tree); err != nil {tx.collectionState().err = errdiff --git a/kernel/model/transaction_index_changes.go b/kernel/model/transaction_index_changes.gonew file mode 100644index 0000000000..62ccfc3e63--- /dev/null+++ b/kernel/model/transaction_index_changes.go@@ -0,0 +1,71 @@+package model++import (+ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++type transactionIndexChanges struct {+ blockIDs map[string]bool+ full bool+}++// captureIndexReplacement 记录替换前后的子树和容器,标题结构及未知写入保留完整投影。+func (tx *Transaction) captureIndexReplacement(tree *parse.Tree, before, after *ast.Node) {+ if tx.indexChanges == nil {+ tx.indexChanges = map[string]*transactionIndexChanges{}+ }+ change := tx.indexChanges[tree.ID]+ if change == nil {+ change = &transactionIndexChanges{blockIDs: map[string]bool{}}+ tx.indexChanges[tree.ID] = change+ }+ if change.full {+ return+ }+ record := func(root *ast.Node) {+ ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering {+ if node.Type == ast.NodeHeading || node.Type == ast.NodeInlineHTML {+ change.full = true+ }+ if node.IsBlock() && node.ID != "" {+ change.blockIDs[node.ID] = true+ }+ }+ return ast.WalkContinue+ })+ }+ record(before)+ record(after)+ for parent := before.Parent; parent != nil && parent.Type != ast.NodeDocument; parent = parent.Parent {+ record(parent)+ }+ // 段落编辑也会刷新语义标题父级的时间戳,这些标题只需重新生成自身主块。+ for _, parent := range treenode.ParentNodesWithHeadings(before) {+ if parent.IsBlock() && parent.ID != "" {+ change.blockIDs[parent.ID] = true+ }+ }+ change.blockIDs[tree.ID] = true+}++func (tx *Transaction) treeIndexChanges(tree *parse.Tree) *sql.TreeIndexChanges {+ change := tx.indexChanges[tree.ID]+ if change == nil || change.full {+ return nil+ }+ // 事务整理可能补入属性或结构操作,未收集其完整影响时不能沿用局部提示。+ for _, operation := range tx.DoOperations {+ if operation == nil || operation.Action != "update" {+ return nil+ }+ }+ ids := make([]string, 0, len(change.blockIDs))+ for id := range change.blockIDs {+ ids = append(ids, id)+ }+ return sql.NewTreeIndexChanges(ids)+}diff --git a/kernel/model/transaction_index_changes_fts5_test.go b/kernel/model/transaction_index_changes_fts5_test.gonew file mode 100644index 0000000000..ee3b504f86--- /dev/null+++ b/kernel/model/transaction_index_changes_fts5_test.go@@ -0,0 +1,124 @@+//go:build fts5++package model++import (+ "encoding/json"+ "errors"+ "fmt"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestTransactionIndexChangesCoverReplacementAndContainers(t *testing.T) {+ const removedID, addedID = "20261019120000-removed", "20261019120000-added01"+ tree := treenode.NewTree("20261019000000-box0001", "/20261019000000-root001.sy", "/Document", "Document")+ before := &ast.Node{ID: "quote", Type: ast.NodeBlockquote}+ before.AppendChild(treenode.NewParagraph(removedID))+ tree.Root.AppendChild(before)+ after := &ast.Node{ID: "quote", Type: ast.NodeBlockquote}+ after.AppendChild(treenode.NewParagraph(addedID))+ tx := &Transaction{DoOperations: []*Operation{{Action: "update"}}}+ tx.captureIndexReplacement(tree, before, after)+ change := tx.indexChanges[tree.ID]+ if tx.treeIndexChanges(tree) == nil || !change.blockIDs[tree.ID] || !change.blockIDs["quote"] ||+ !change.blockIDs[removedID] || !change.blockIDs[addedID] {+ t.Fatalf("replacement lost deleted blocks or container projections: %+v", change)+ }+ tx.DoOperations = append(tx.DoOperations, &Operation{Action: "setAttrs"})+ if tx.treeIndexChanges(tree) != nil {+ t.Fatal("untracked transaction finalization retained a partial hint")+ }+ tx.DoOperations = tx.DoOperations[:1]+ after.AppendChild(&ast.Node{ID: "heading", Type: ast.NodeHeading, HeadingLevel: 1})+ tx.captureIndexReplacement(tree, before, after)+ if tx.treeIndexChanges(tree) != nil {+ t.Fatal("heading structure changes must retain complete projection")+ }+}++func TestTransactionIndexChangesPersistCoalescedUpdatesAndReleaseHints(t *testing.T) {+ for _, withHeading := range []bool{false, true} {+ t.Run(fmt.Sprintf("heading_parent_%t", withHeading), func(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ tree, err := LoadTreeByBlockID(fixture.childID)+ if err != nil {+ t.Fatal(err)+ }+ heading := &ast.Node{Type: ast.NodeHeading, ID: "20260801000000-heading", HeadingLevel: 1}+ if withHeading {+ heading.SetIALAttr("id", heading.ID)+ heading.SetIALAttr("updated", "20260801000000")+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Parent heading")})+ tree.Root.PrependChild(heading)+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ }+ sql.UpsertTreeQueue(tree)+ sql.FlushQueue()+ for step := range 3 {+ transaction := &Transaction{DoOperations: []*Operation{{Action: "update", ID: fixture.childID,+ Data: fmt.Sprintf(`<div data-node-id="%s" data-type="NodeParagraph"><div contenteditable="true">incremental edit %d</div></div>`, fixture.childID, step)}}}+ observed := false+ transaction.writeTransactionTree = func(source *parse.Tree) error {+ change := transaction.indexChanges[source.ID]+ if change == nil || change.full || !change.blockIDs[fixture.childID] || !change.blockIDs[source.ID] || transaction.treeIndexChanges(source) == nil {+ t.Fatalf("ordinary transaction did not collect its complete affected set: %+v", change)+ }+ if withHeading && !change.blockIDs[heading.ID] {+ t.Fatal("heading ancestor timestamp was omitted from the affected set")+ }+ observed = true+ return writeTreeUpsertQueueWithChanges(source, transaction.treeIndexChanges(source))+ }+ if err = PerformTxSync(transaction); err != nil {+ t.Fatal(err)+ }+ if !observed || transaction.indexChanges != nil {+ t.Fatal("transaction did not release its completed hint")+ }+ }+ sql.FlushQueue()+ query := "SELECT id,parent_id,root_id,hash,box,path,hpath,content,markdown,ial FROM blocks ORDER BY id"+ snapshot := func() string {+ t.Helper()+ rows, err := sql.QueryNoLimit(query)+ if err != nil {+ t.Fatal(err)+ }+ data, err := json.Marshal(rows)+ if err != nil {+ t.Fatal(err)+ }+ return string(data)+ }+ before := snapshot()+ tree, err = LoadTreeByBlockID(fixture.childID)+ if err != nil || treenode.GetNodeInTree(tree, fixture.childID).Text() != "incremental edit 2" {+ t.Fatalf("coalesced transaction did not persist the final text: %v", err)+ }+ sql.UpsertTreeQueue(tree)+ sql.FlushQueue()+ if before != snapshot() {+ t.Fatal("transaction-scoped index differs from a complete update")+ }+ failing := &Transaction{DoOperations: []*Operation{{Action: "update", ID: fixture.childID,+ Data: fmt.Sprintf(`<div data-node-id="%s" data-type="NodeParagraph"><div contenteditable="true">failed edit</div></div>`, fixture.childID)}},+ writeTransactionTree: func(*parse.Tree) error { return errors.New("injected source write failure") }}+ if err = PerformTxSync(failing); err == nil || failing.indexChanges != nil {+ t.Fatal("failed transaction retained its partial hint")+ }+ if snapshot() != before {+ t.Fatal("failed source write changed the committed index")+ }+ })+ }+}diff --git a/kernel/model/transaction_memory_fts5_test.go b/kernel/model/transaction_memory_fts5_test.goindex 0740ec9b50..aec44fc341 100644--- a/kernel/model/transaction_memory_fts5_test.go+++ b/kernel/model/transaction_memory_fts5_test.go@@ -67,6 +67,9 @@ func TestCompletedTransactionBatchReleasesDocumentTrees(t *testing.T) {time.Sleep(10 * time.Millisecond)}for _, tx := range transactions {+ if tx.indexChanges != nil {+ t.Fatal("completed transaction retained its index change set")+ }if tx.state.Load() != 2 || !slices.Equal(tx.GetChangedRootIDs(), []string{fixture.sourceID}) ||!slices.Equal(tx.GetMutatedRootIDs(), []string{fixture.sourceID}) {t.Fatal("releasing document trees changed committed transaction metadata")diff --git a/kernel/sql/auxiliary_index_sqlcipher_test.go b/kernel/sql/auxiliary_index_sqlcipher_test.goindex 07d86bdfb6..bffbcfddaf 100644--- a/kernel/sql/auxiliary_index_sqlcipher_test.go+++ b/kernel/sql/auxiliary_index_sqlcipher_test.go@@ -37,6 +37,7 @@ func TestAuxiliaryIndexEncryptedUpdateAndReopen(t *testing.T) {if err := database.QueryRow("PRAGMA cipher_version").Scan(&version); err != nil || version == "" {t.Fatalf("SQLCipher required: %q, %v", version, err)}+ useChanges := falsewrite := func(full bool) {t.Helper()tx, err := beginTxForBox(tree.Box)@@ -47,6 +48,8 @@ func TestAuxiliaryIndexEncryptedUpdateAndReopen(t *testing.T) {defer tx.Rollback()if full {err = indexTree(tx, tree, nil)+ } else if useChanges {+ err = upsertTreeWithChanges(tx, tree, nil, NewTreeIndexChanges([]string{tree.Root.FirstChild.ID}))} else {err = upsertTree(tx, tree, nil)}@@ -67,6 +70,15 @@ func TestAuxiliaryIndexEncryptedUpdateAndReopen(t *testing.T) {t.Fatalf("unchanged encrypted %s records were rewritten", table.name)}}+ useChanges = true+ tree.Root.FirstChild.FirstChild.Tokens = []byte("private change-set update ")+ write(false)+ got = upsertTableSnapshots(t, database, true)+ for _, table := range upsertTestTables[:5] {+ if !reflect.DeepEqual(got[table.name], want[table.name]) {+ t.Fatalf("scoped encrypted update rewrote %s", table.name)+ }+ }// 重开旧版加密库时补建索引并保留已有数据。for _, table := range []auxiliaryIndexTable{spanIndex, assetIndex, attributeIndex} {execDeletePathTestSQL(t, database, "DROP INDEX idx_"+table.name+"_root_id")diff --git a/kernel/sql/av.go b/kernel/sql/av.goindex 6c164beef8..0d1db8a44c 100644--- a/kernel/sql/av.go+++ b/kernel/sql/av.go@@ -70,6 +70,11 @@ func NewAttributeViewRenderContext() *AttributeViewRenderContext {return &AttributeViewRenderContext{templateErrors: map[string]*attributeViewTemplateRenderError{}}}+// HasTemplateErrors 判断本次求值是否产生模板错误,错误结果不参与跨请求复用。+func (context *AttributeViewRenderContext) HasTemplateErrors() bool {+ return context != nil && len(context.templateErrors) != 0+}+func (context *AttributeViewRenderContext) addTemplateError(attrView *av.AttributeView, templateKey *av.Key,item av.Item, renderErr error) {if nil == context || nil == attrView || nil == templateKey || nil == item || nil == renderErr {@@ -514,8 +519,18 @@ func executeTemplateField(tpl *template.Template, ial map[string]string, keyValufunc generateAttrViewItems(attrView *av.AttributeView, view *av.View) (ret map[string][]*av.KeyValues) {ret = map[string][]*av.KeyValues{}+ var included map[string]bool+ if view.GroupItemIDs != nil {+ included = make(map[string]bool, len(view.GroupItemIDs))+ for _, id := range view.GroupItemIDs {+ included[id] = true+ }+ }for _, keyValues := range attrView.KeyValues {for _, val := range keyValues.Values {+ if included != nil && !included[val.BlockID] {+ continue+ }values := ret[val.BlockID]if nil == values {values = []*av.KeyValues{{Key: keyValues.Key, Values: []*av.Value{val}}}diff --git a/kernel/sql/av_template_plan.go b/kernel/sql/av_template_plan.goindex 03fd2a53e6..7806512270 100644--- a/kernel/sql/av_template_plan.go+++ b/kernel/sql/av_template_plan.go@@ -1,11 +1,98 @@package sqlimport (+ "regexp"+ "strings""text/template/parse""github.com/siyuan-note/siyuan/kernel/av")+var reusableTemplateFormat = regexp.MustCompile(`%(?:%|[-+# 0]*[0-9]*(?:\.[0-9]+)?[svdf])`)++// IsReusableTemplateKey 仅接纳封闭的字段访问和字符串格式化,不依赖时间、SQL 或外部状态。+func IsReusableTemplateKey(attrView *av.AttributeView, key *av.Key) bool {+ if _, known := StaticTemplateKeyDependencies(attrView, key); !known {+ return false+ }+ content := key.Template+ if key.Type != av.KeyTypeTemplate {+ content = key.RenderTemplate+ }+ tpl, err := compileTemplateField(content)+ if err != nil || !reusableTemplateNode(tpl.Tree.Root) {+ return false+ }+ variables, err := getTemplateVars(content)+ if err != nil {+ return false+ }+ for _, variable := range variables {+ if strings.HasSuffix(variable, "_raw") || strings.HasSuffix(variable, "_created") || strings.HasSuffix(variable, "_end") {+ return false+ }+ known := false+ for _, values := range attrView.KeyValues {+ if values != nil && values.Key != nil && (variable == values.Key.ID || variable == values.Key.Name) {+ known = true+ }+ }+ if !known {+ return false+ }+ }+ return true+}++func reusableTemplateNode(node parse.Node) bool {+ if node == nil {+ return true+ }+ switch current := node.(type) {+ case *parse.ListNode:+ for _, child := range current.Nodes {+ if !reusableTemplateNode(child) {+ return false+ }+ }+ case *parse.ActionNode:+ return reusableTemplateNode(current.Pipe)+ case *parse.PipeNode:+ for _, command := range current.Cmds {+ if !reusableTemplateNode(command) {+ return false+ }+ }+ case *parse.CommandNode:+ if len(current.Args) > 0 && current.Args[0].Type() == parse.NodeIdentifier {+ name := current.Args[0].String()+ if name == "printf" {+ if len(current.Args) < 2 || current.Args[1].Type() != parse.NodeString || strings.Contains(reusableTemplateFormat.ReplaceAllString(current.Args[1].(*parse.StringNode).Text, ""), "%") {+ return false+ }+ } else if name == "index" {+ if len(current.Args) != 3 || current.Args[2].Type() != parse.NodeString ||+ (current.Args[1].Type() != parse.NodeDot && !isTemplateIDModField(current.Args[1])) {+ return false+ }+ } else if name != "print" && name != "println" {+ return false+ }+ }+ for _, argument := range current.Args {+ if !reusableTemplateNode(argument) {+ return false+ }+ }+ case *parse.FieldNode:+ if isTemplateIDModField(current) {+ return current.Ident[0] == "id_mod" && len(current.Ident) <= 2+ }+ return len(current.Ident) == 1+ }+ return true+}+// StaticTemplateKeyDependencies 复用字段依赖解析,仅为可静态识别的表达式返回完整依赖。// 分支、命名模板、变量别名或动态访问保留完整求值路径,避免将遗漏依赖当成显示字段。func StaticTemplateKeyDependencies(attrView *av.AttributeView, key *av.Key) ([]*av.Key, bool) {diff --git a/kernel/sql/av_template_plan_test.go b/kernel/sql/av_template_plan_test.goindex 9cea89be65..c35230cb2c 100644--- a/kernel/sql/av_template_plan_test.go+++ b/kernel/sql/av_template_plan_test.go@@ -50,3 +50,32 @@ func TestStaticTemplateKeyDependencies(t *testing.T) {t.Fatal("nil template was treated as known")}}++func TestReusableTemplateKeyRequiresClosedPureExpressions(t *testing.T) {+ text := av.NewKey("text", "Text", "", av.KeyTypeText)+ key := av.NewKey("template", "Template", "", av.KeyTypeTemplate)+ database := &av.AttributeView{KeyValues: []*av.KeyValues{{Key: text}, {Key: key}}}+ for _, test := range []struct {+ content string+ reuse bool+ }{+ {`.action{.Text}`, true}, {`.action{index . "Text"}`, true},+ {`.action{.id_mod.text}`, true}, {`.action{index .id_mod "text"}`, true},+ {`.action{printf "%s %%" .Text}`, true}, {`.action{.Text | printf "%10s"}`, true},+ {`.action{print .Text " suffix"}`, true}, {`.action{println .Text}`, true},+ {`.action{printf "%p" .Text}`, false}, {`.action{printf "%[1]p" .Text}`, false},+ {`.action{printf .Text "value"}`, false}, {`.action{printf "%T" .Text}`, false},+ {`.action{now}`, false}, {`.action{queryBlocks "SELECT * FROM blocks"}`, false},+ {`.action{.Text_raw.Text.Content}`, false}, {`.action{.Text_created}`, false},+ {`.action{index .id_mod_raw "text"}`, false}, {`.action{.Unknown}`, false},+ {`.action{index . "Unknown"}`, false}, {`.action{.id_mod.text.Unknown}`, false},+ {`.action{if .Text}.action{.Text}.action{end}`, false}, {`.action{`, false},+ } {+ t.Run(test.content, func(t *testing.T) {+ key.Template = test.content+ if reusable := IsReusableTemplateKey(database, key); reusable != test.reuse {+ t.Fatalf("reusable=%t, want %t", reusable, test.reuse)+ }+ })+ }+}diff --git a/kernel/sql/cache.go b/kernel/sql/cache.goindex 94ff6b9d36..98e3e16109 100644--- a/kernel/sql/cache.go+++ b/kernel/sql/cache.go@@ -89,6 +89,7 @@ func blockCacheKey(id, boxID string) string {}func ClearCache() {+ clearFTSCountCache()blockCache.Clear()blockCacheKeysMu.Lock()blockCacheKeys = map[string]map[string]*blockCacheEntry{}diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex e59fbe9a73..eeeff25b98 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -688,6 +688,10 @@ func getEmbedRef(embedNode *ast.Node) (queryBlockID string) {}func fromTree(node *ast.Node, tree *parse.Tree) (blocks []*Block, spans []*Span, assets []*Asset, attributes []*Attribute) {+ return fromTreeWithChanges(node, tree, nil)+}++func projectTree(node *ast.Node, tree *parse.Tree, buildBlock indexBlockBuilder) (blocks []*Block, spans []*Span, assets []*Asset, attributes []*Attribute) {rootID := tree.Root.IDboxID := tree.Boxp := tree.Path@@ -697,7 +701,7 @@ func fromTree(node *ast.Node, tree *parse.Tree) (blocks []*Block, spans []*Span,}// 构造行级元素- spanBlocks, spanSpans, spanAssets, spanAttrs, walkStatus := buildSpanFromNode(n, tree, rootID, boxID, p)+ spanBlocks, spanSpans, spanAssets, spanAttrs, walkStatus := buildSpanFromNode(n, tree, rootID, boxID, p, buildBlock)if 0 < len(spanBlocks) {blocks = append(blocks, spanBlocks...)}@@ -725,8 +729,10 @@ func fromTree(node *ast.Node, tree *parse.Tree) (blocks []*Block, spans []*Span,return ast.WalkContinue}- b, attrs := buildBlockFromNode(n, tree)- blocks = append(blocks, b)+ b, attrs := buildBlock(n, tree)+ if b != nil {+ blocks = append(blocks, b)+ }if 0 < len(attrs) {attributes = append(attributes, attrs...)}@@ -787,7 +793,7 @@ func isAttr(name string) bool {return strings.HasPrefix(name, "custom-") || "name" == name || "alias" == name || "memo" == name || "bookmark" == name || "fold" == name || "heading-fold" == name || "style" == name}-func buildSpanFromNode(n *ast.Node, tree *parse.Tree, rootID, boxID, p string) (blocks []*Block, spans []*Span, assets []*Asset, attributes []*Attribute, walkStatus ast.WalkStatus) {+func buildSpanFromNode(n *ast.Node, tree *parse.Tree, rootID, boxID, p string, buildBlock indexBlockBuilder) (blocks []*Block, spans []*Span, assets []*Asset, attributes []*Attribute, walkStatus ast.WalkStatus) {boxLocalPath := filepath.Join(util.DataDir, boxID)docDirLocalPath := filepath.Join(boxLocalPath, p)switch n.Type {@@ -909,8 +915,10 @@ func buildSpanFromNode(n *ast.Node, tree *parse.Tree, rootID, boxID, p string) (}if ast.NodeHTMLBlock == n.Type || ast.NodeIFrame == n.Type || ast.NodeWidget == n.Type || ast.NodeAudio == n.Type || ast.NodeVideo == n.Type {- b, attrs := buildBlockFromNode(n, tree)- blocks = append(blocks, b)+ b, attrs := buildBlock(n, tree)+ if b != nil {+ blocks = append(blocks, b)+ }attributes = append(attributes, attrs...)}@@ -982,6 +990,10 @@ func BuildBlockFromNode(n *ast.Node, tree *parse.Tree) (block *Block) {}func buildBlockFromNode(n *ast.Node, tree *parse.Tree) (block *Block, attributes []*Attribute) {+ return buildBlockFromNodeWithHeadingParent(n, tree, treenode.HeadingParent(n))+}++func buildBlockFromNodeWithHeadingParent(n *ast.Node, tree *parse.Tree, headingParent *ast.Node) (block *Block, attributes []*Attribute) {boxID := tree.Boxp := tree.PathrootID := tree.Root.ID@@ -993,7 +1005,7 @@ func buildBlockFromNode(n *ast.Node, tree *parse.Tree) (block *Block, attributesvar content, fcontent, markdown, parentID stringialContent := treenode.IALStr(n)- hash := treenode.NodeHash(n, tree, luteEngine)+ hash := treenode.NodeHashWithHeadingParent(n, tree, luteEngine, headingParent)var length intif ast.NodeDocument == n.Type {content = n.IALAttr("title")@@ -1013,8 +1025,8 @@ func buildBlockFromNode(n *ast.Node, tree *parse.Tree) (block *Block, attributesfcontent = nodeStaticContent(fc, nil, true, false, true, true)parentID = n.Parent.ID- if h := treenode.HeadingParent(n); nil != h { // 如果在标题块下方,则将标题块作为父节点- parentID = h.ID+ if headingParent != nil { // 如果在标题块下方,则将标题块作为父节点+ parentID = headingParent.ID}length = utf8.RuneCountInString(fcontent)} else {@@ -1025,8 +1037,8 @@ func buildBlockFromNode(n *ast.Node, tree *parse.Tree) (block *Block, attributescontent = nodeStaticContent(n, nil, true, indexAssetPath.Load(), true, true)parentID = n.Parent.ID- if h := treenode.HeadingParent(n); nil != h {- parentID = h.ID+ if headingParent != nil {+ parentID = headingParent.ID}length = utf8.RuneCountInString(content)}@@ -1065,6 +1077,10 @@ func buildBlockFromNode(n *ast.Node, tree *parse.Tree) (block *Block, attributesUpdated: n.IALAttr("updated"),}+ return block, buildNodeAttributes(n, tree)+}++func buildNodeAttributes(n *ast.Node, tree *parse.Tree) (attributes []*Attribute) {attrs := parse.IAL2Map(n.KramdownIAL)for attrName, attrVal := range attrs {if !isAttr(attrName) {@@ -1077,9 +1093,9 @@ func buildBlockFromNode(n *ast.Node, tree *parse.Tree) (block *Block, attributesValue: attrVal,Type: "b",BlockID: n.ID,- RootID: rootID,- Box: boxID,- Path: p,+ RootID: tree.Root.ID,+ Box: tree.Box,+ Path: tree.Path,}attributes = append(attributes, attr)}@@ -1511,6 +1527,7 @@ func cleanupInvalidRefs(database *sql.DB) (err error) {}func CloseDatabase() {+ clearFTSCountCache()diagnostic := util.WatchOperation("close databases", "close index queue")defer diagnostic.Finish()closeIndexQueue()diff --git a/kernel/sql/index_changes.go b/kernel/sql/index_changes.gonew file mode 100644index 0000000000..97355ae155--- /dev/null+++ b/kernel/sql/index_changes.go@@ -0,0 +1,85 @@+package sql++import (+ "database/sql"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++// TreeIndexChanges 是完整事务影响集合的进程内提示;nil 表示必须重新生成全部主块投影。+// 集合须包含变更、删除和替换子树的块以及受影响容器,入队时复制且不写入恢复队列。+type TreeIndexChanges struct {+ blockIDs map[string]bool+}++func NewTreeIndexChanges(blockIDs []string) *TreeIndexChanges {+ result := &TreeIndexChanges{blockIDs: map[string]bool{}}+ for _, id := range blockIDs {+ if id != "" {+ result.blockIDs[id] = true+ }+ }+ if len(result.blockIDs) == 0 {+ return nil+ }+ return result+}++func mergeTreeIndexChanges(first, second *TreeIndexChanges) *TreeIndexChanges {+ if first == nil || second == nil {+ return nil+ }+ result := &TreeIndexChanges{blockIDs: make(map[string]bool, len(first.blockIDs)+len(second.blockIDs))}+ for id := range first.blockIDs {+ result.blockIDs[id] = true+ }+ for id := range second.blockIDs {+ result.blockIDs[id] = true+ }+ return result+}++func usableTreeIndexChanges(tx *sql.Tx, tree *parse.Tree, changes *TreeIndexChanges) (*TreeIndexChanges, error) {+ if changes == nil {+ return nil, nil+ }+ var box, path, hpath, hash, updated sql.NullString+ err := tx.QueryRow("SELECT box, path, hpath, hash, updated FROM blocks WHERE id = ? AND root_id = ? AND type = 'd'", tree.ID, tree.ID).Scan(&box, &path, &hpath, &hash, &updated)+ if err == sql.ErrNoRows {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }+ if !box.Valid || !path.Valid || !hpath.Valid || !hash.Valid || !updated.Valid ||+ box.String != tree.Box || path.String != tree.Path || hpath.String != tree.HPath {+ return nil, nil+ }+ root := *tree.Root+ root.KramdownIAL = make([][]string, len(tree.Root.KramdownIAL))+ for i, attribute := range tree.Root.KramdownIAL {+ root.KramdownIAL[i] = append([]string(nil), attribute...)+ }+ if root.IALAttr("updated") != updated.String {+ root.SetIALAttr("updated", updated.String)+ }+ if treenode.NodeHash(&root, tree, luteEngine) != hash.String {+ return nil, nil+ }+ stable := true+ treenode.WalkWithInlineTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && node.Type == ast.NodeInlineHTML {+ stable = false+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if !stable {+ return nil, nil+ }+ result := mergeTreeIndexChanges(changes, changes)+ result.blockIDs[tree.ID] = true+ return result, nil+}diff --git a/kernel/sql/index_changes_fts5_test.go b/kernel/sql/index_changes_fts5_test.gonew file mode 100644index 0000000000..08be0d4d61--- /dev/null+++ b/kernel/sql/index_changes_fts5_test.go@@ -0,0 +1,194 @@+//go:build fts5++package sql++import (+ "database/sql"+ "fmt"+ "os"+ "path/filepath"+ "reflect"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestTreeIndexChangesMatchCompleteUpdates(t *testing.T) {+ for _, scoped := range []bool{false, true} {+ t.Run(fmt.Sprint(scoped), func(t *testing.T) {+ previousDB, previousDisabled, previousDir := db, cacheDisabled, util.DataDir+ previousCached, previousIgnore := IndexIgnoreCached, indexIgnore+ db, cacheDisabled, util.DataDir = newDeletePathTestDB(t, scoped), true, t.TempDir()+ IndexIgnoreCached, indexIgnore = true, nil+ t.Cleanup(func() {+ db, cacheDisabled, util.DataDir = previousDB, previousDisabled, previousDir+ IndexIgnoreCached, indexIgnore = previousCached, previousIgnore+ ClearCache()+ })+ database := db+ oracle := newDeletePathTestDB(t, scoped)+ tree := newUpsertTestTree(12)+ write := func(target *sql.DB, changes *TreeIndexChanges) error {+ tx, err := target.Begin()+ if err != nil {+ return err+ }+ defer tx.Rollback()+ defer closeTxPreparedStmts(tx)+ if err = upsertTreeWithChanges(tx, tree, nil, changes); err != nil {+ return err+ }+ return commitTx(tx)+ }+ compare := func(changes *TreeIndexChanges) {+ t.Helper()+ if err := write(database, changes); err != nil {+ t.Fatal(err)+ }+ if err := write(oracle, nil); err != nil {+ t.Fatal(err)+ }+ if got, want := upsertTableSnapshots(t, database, false), upsertTableSnapshots(t, oracle, false); !reflect.DeepEqual(got, want) {+ for table := range got {+ if !reflect.DeepEqual(got[table], want[table]) {+ t.Errorf("%s differs: got=%v want=%v", table, got[table], want[table])+ }+ }+ t.FailNow()+ }+ execDeletePathTestSQL(t, database, "INSERT INTO blocks_fts(blocks_fts, rank) VALUES('integrity-check', 1)")+ }+ // 缺少根记录时忽略局部提示,重建全部记录。+ compare(NewTreeIndexChanges([]string{tree.Root.FirstChild.ID}))+ target := tree.Root.FirstChild.Next+ target.FirstChild.Tokens = []byte("changed target text ")+ target.SetIALAttr("updated", "20261019100001")+ tree.Root.SetIALAttr("updated", "20261019100001")+ changes := NewTreeIndexChanges([]string{target.ID})+ tx, _ := database.Begin()+ usable, err := usableTreeIndexChanges(tx, tree, changes)+ tx.Rollback()+ if err != nil || usable == nil {+ t.Fatalf("ordinary edit did not use its change set: %v", err)+ }+ blocks, _, _, _ := fromTreeWithChanges(tree.Root, tree, usable)+ if len(blocks) != 2 {+ t.Fatalf("ordinary edit projected %d blocks, want 2", len(blocks))+ }+ compare(changes)+ // 旧数据库缺失根元数据时保留完整回退,不能使局部提示漏掉其他块。+ execDeletePathTestSQL(t, database, "UPDATE blocks SET hash = NULL WHERE id = ?", tree.ID)+ tx, _ = database.Begin()+ usable, err = usableTreeIndexChanges(tx, tree, changes)+ tx.Rollback()+ if err != nil || usable != nil {+ t.Fatalf("NULL root metadata did not fall back: %v", err)+ }+ compare(changes)+ removed := tree.Root.FirstChild+ removed.Unlink()+ added := treenode.NewParagraph("20261019110000-added01")+ added.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("new child")})+ quote := &ast.Node{Type: ast.NodeBlockquote, ID: "20261019110000-quote01"}+ quote.SetIALAttr("id", quote.ID)+ quote.AppendChild(added)+ tree.Root.AppendChild(quote)+ compare(NewTreeIndexChanges([]string{removed.ID, quote.ID, added.ID}))+ before := upsertTableSnapshots(t, database, true)+ compare(NewTreeIndexChanges([]string{quote.ID, added.ID}))+ if !reflect.DeepEqual(before, upsertTableSnapshots(t, database, true)) {+ t.Fatal("identical change-set replay rewrote stored records")+ }+ // 路径元数据变化时不能沿用局部主块集合。+ tree.Path, tree.HPath = "/changed.sy", "/Changed"+ compare(NewTreeIndexChanges([]string{target.ID}))+ before = upsertTableSnapshots(t, database, true)+ target.SetIALAttr("custom-note", "fail")+ target.FirstChild.Tokens = []byte("text before rollback")+ execDeletePathTestSQL(t, database, "CREATE TRIGGER failure BEFORE INSERT ON attributes WHEN new.value = 'fail' BEGIN SELECT RAISE(ABORT, 'injected index failure'); END")+ if err := write(database, NewTreeIndexChanges([]string{target.ID})); err == nil {+ t.Fatal("injected failure did not roll back")+ }+ if !reflect.DeepEqual(before, upsertTableSnapshots(t, database, true)) {+ t.Fatal("failed scoped write modified the committed snapshot")+ }+ })+ }+}++func TestTreeIndexChangesQueueMergesAndPreservesBoundaries(t *testing.T) {+ prepareIndexQueueTest(t)+ previousQueue, previousData := operationQueue, util.DataDir+ operationQueue, util.DataDir = nil, t.TempDir()+ t.Cleanup(func() { operationQueue, util.DataDir = previousQueue, previousData; clearIndexQueueEntries() })+ tree := newUpsertTestTree(2)+ firstID, secondID := tree.Root.FirstChild.ID, tree.Root.LastChild.ID+ first := NewTreeIndexChanges([]string{firstID})+ UpsertTreeQueueWithChanges(tree, first)+ delete(first.blockIDs, firstID)+ UpsertTreeQueueWithChanges(tree, NewTreeIndexChanges([]string{secondID}))+ if len(operationQueue) != 1 || !operationQueue[0].indexChanges.blockIDs[firstID] || !operationQueue[0].indexChanges.blockIDs[secondID] {+ t.Fatal("coalesced snapshot lost an earlier affected block or retained the caller's mutable set")+ }+ UpsertTreeQueue(tree)+ UpsertTreeQueueWithChanges(tree, NewTreeIndexChanges([]string{firstID}))+ if len(operationQueue) != 1 || operationQueue[0].indexChanges != nil {+ t.Fatal("unknown full update was narrowed by a subsequent hint")+ }+ for _, action := range []string{"delete_id", "move", "rename_doc", "delete_ids", "update_refs"} {+ operationQueue = nil+ UpsertTreeQueueWithChanges(tree, NewTreeIndexChanges([]string{firstID}))+ operationQueue = append(operationQueue, &dbQueueOperation{action: action, removeTreeID: tree.ID, removeTreeBox: tree.Box, indexTree: tree, upsertTree: tree})+ UpsertTreeQueueWithChanges(tree, NewTreeIndexChanges([]string{secondID}))+ if len(operationQueue) != 3 {+ t.Fatalf("%s boundary was removed", action)+ }+ }+ operationQueue = nil+ other := *tree+ other.Box = "other-box"+ UpsertTreeQueueWithChanges(tree, NewTreeIndexChanges([]string{firstID}))+ UpsertTreeQueueWithChanges(&other, NewTreeIndexChanges([]string{secondID}))+ if len(operationQueue) != 2 {+ t.Fatal("documents in different notebooks shared an affected set")+ }+ // 以最终快照执行合并提示,覆盖先删后建和多次编辑。+ operationQueue = nil+ final := *tree+ final.Path = "/new.sy"+ UpsertTreeQueueWithChanges(tree, NewTreeIndexChanges([]string{firstID}))+ UpsertTreeQueueWithChanges(&final, NewTreeIndexChanges([]string{secondID}))+ if len(operationQueue) != 2 {+ t.Fatal("path transition was coalesced")+ }+}++func TestTreeIndexChangesNilAndEmptyRequireCompleteProjection(t *testing.T) {+ if NewTreeIndexChanges(nil) != nil || NewTreeIndexChanges([]string{""}) != nil ||+ mergeTreeIndexChanges(NewTreeIndexChanges([]string{"id"}), nil) != nil {+ t.Fatal("missing information was treated as an empty change")+ }+}++func TestTreeIndexChangesAreNotRecoveredAsPartialHints(t *testing.T) {+ prepareIndexQueueTest(t)+ previousDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = previousDir })+ tree := newUpsertTestTree(3)+ if err := os.MkdirAll(filepath.Join(util.DataDir, tree.Box), 0700); err != nil {+ t.Fatal(err)+ }+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ op := &dbQueueOperation{action: "upsert", upsertTree: tree, indexChanges: NewTreeIndexChanges([]string{tree.Root.FirstChild.ID})}+ entry := dbOpToIndexEntry(op)+ recovered, err := indexEntryToOp(*entry, util.NewLute(), "change set recovery test")+ if err != nil || recovered == nil || recovered.indexChanges != nil || recovered.upsertTree.Root.LastChild == nil {+ t.Fatalf("recovery must load a complete source without a partial hint: %+v, %v", recovered, err)+ }+}diff --git a/kernel/sql/index_projection.go b/kernel/sql/index_projection.gonew file mode 100644index 0000000000..ffc667e54f--- /dev/null+++ b/kernel/sql/index_projection.go@@ -0,0 +1,63 @@+package sql++import (+ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+)++// indexHeadingParents 仅用于本次投影,不跨请求保留可变文档或父级信息。+type indexHeadingParents struct {+ parents map[*ast.Node]*ast.Node+ indexed map[*ast.Node]bool+}++func (index *indexHeadingParents) get(node *ast.Node) *ast.Node {+ parent := node.Parent+ if parent == nil {+ return nil+ }+ if index.parents == nil {+ index.parents = map[*ast.Node]*ast.Node{}+ index.indexed = map[*ast.Node]bool{}+ }+ if !index.indexed[parent] {+ var headings []*ast.Node+ for current := parent.FirstChild; current != nil; current = current.Next {+ level := 16+ if current.Type == ast.NodeHeading {+ level = current.HeadingLevel+ for len(headings) > 0 && headings[len(headings)-1].HeadingLevel >= level {+ headings = headings[:len(headings)-1]+ }+ }+ semanticParent := parent+ for i := len(headings) - 1; i >= 0; i-- {+ if headings[i].HeadingLevel < level {+ semanticParent = headings[i]+ break+ }+ }+ index.parents[current] = semanticParent+ if current.Type == ast.NodeHeading {+ headings = append(headings, current)+ }+ }+ index.indexed[parent] = true+ }+ if semanticParent, found := index.parents[node]; found {+ return semanticParent+ }+ return parent+}++type indexBlockBuilder func(*ast.Node, *parse.Tree) (*Block, []*Attribute)++func fromTreeWithChanges(node *ast.Node, tree *parse.Tree, changes *TreeIndexChanges) ([]*Block, []*Span, []*Asset, []*Attribute) {+ parents := &indexHeadingParents{}+ return projectTree(node, tree, func(current *ast.Node, source *parse.Tree) (*Block, []*Attribute) {+ if changes != nil && !changes.blockIDs[current.ID] {+ return nil, buildNodeAttributes(current, source)+ }+ return buildBlockFromNodeWithHeadingParent(current, source, parents.get(current))+ })+}diff --git a/kernel/sql/index_projection_benchmark_fts5_test.go b/kernel/sql/index_projection_benchmark_fts5_test.gonew file mode 100644index 0000000000..3285f13544--- /dev/null+++ b/kernel/sql/index_projection_benchmark_fts5_test.go@@ -0,0 +1,56 @@+//go:build fts5++package sql++import (+ "fmt"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func BenchmarkIndexProjection(b *testing.B) {+ previousDir := util.DataDir+ util.DataDir = b.TempDir()+ b.Cleanup(func() { util.DataDir = previousDir })+ for _, size := range []int{1000, 5000, 20000} {+ for _, mode := range []string{"independent", "batch_parents", "changeset"} {+ b.Run(fmt.Sprintf("%d/%s", size, mode), func(b *testing.B) {+ tree := newUpsertTestTree(size)+ tree.Root.FirstChild.FirstChild.Tokens = []byte("changed ordinary paragraph content ")+ changes := NewTreeIndexChanges([]string{tree.ID, tree.Root.FirstChild.ID})+ b.ReportAllocs()+ b.ResetTimer()+ for range b.N {+ var blocks []*Block+ switch mode {+ case "independent":+ // 独立查找两次父级,对照哈希及主块字段各自解析父级的成本。+ blocks, _, _, _ = projectTree(tree.Root, tree, func(node *ast.Node, source *parse.Tree) (*Block, []*Attribute) {+ parent := treenode.HeadingParent(node)+ block, attributes := buildBlockFromNode(node, source)+ if node.Type != ast.NodeDocument && parent != nil && parent.ID != block.ParentID {+ b.Fatal("independent parent changed during projection")+ }+ return block, attributes+ })+ case "batch_parents":+ blocks, _, _, _ = fromTree(tree.Root, tree)+ case "changeset":+ blocks, _, _, _ = fromTreeWithChanges(tree.Root, tree, changes)+ }+ want := size + 1+ if mode == "changeset" {+ want = 2+ }+ if len(blocks) != want {+ b.Fatalf("projected %d blocks, want %d", len(blocks), want)+ }+ }+ })+ }+ }+}diff --git a/kernel/sql/index_projection_fts5_test.go b/kernel/sql/index_projection_fts5_test.gonew file mode 100644index 0000000000..28921047c2--- /dev/null+++ b/kernel/sql/index_projection_fts5_test.go@@ -0,0 +1,107 @@+//go:build fts5++package sql++import (+ "encoding/json"+ "fmt"+ "math/rand"+ "reflect"+ "slices"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func projectionSnapshot[T any](values []*T) []string {+ var result []string+ for _, value := range values {+ data, _ := json.Marshal(value)+ var fields map[string]any+ json.Unmarshal(data, &fields)+ delete(fields, "ID")+ delete(fields, "id")+ data, _ = json.Marshal(fields)+ result = append(result, string(data))+ }+ slices.Sort(result)+ return result+}++func TestIndexHeadingParentsMatchIndependentLookups(t *testing.T) {+ random := rand.New(rand.NewSource(20692))+ for _, nested := range []bool{false, true} {+ root := &ast.Node{Type: ast.NodeDocument, ID: "root"}+ parents := []*ast.Node{root}+ for i := range 1000 {+ node := &ast.Node{Type: ast.NodeParagraph, ID: fmt.Sprint(i)}+ if random.Intn(4) == 0 {+ node.Type, node.HeadingLevel = ast.NodeHeading, random.Intn(21)-2+ }+ parent := parents[random.Intn(len(parents))]+ parent.AppendChild(node)+ if nested && i%20 == 0 {+ node.Type = ast.NodeBlockquote+ parents = append(parents, node)+ }+ }+ for range 2 {+ index := &indexHeadingParents{}+ ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering {+ if got, want := index.get(node), treenode.HeadingParent(node); got != want {+ t.Fatalf("parent differs for %s: got=%v want=%v", node.ID, got, want)+ }+ }+ return ast.WalkContinue+ })+ root.FirstChild.Type, root.FirstChild.HeadingLevel = ast.NodeHeading, 1+ }+ }+}++func TestIndexProjectionMatchesIndependentLookups(t *testing.T) {+ previousDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = previousDir })+ tree := newUpsertTestTree(30)+ for i, node := 0, tree.Root.FirstChild; node != nil; i, node = i+1, node.Next {+ if i%4 == 0 {+ node.Type, node.HeadingLevel = ast.NodeHeading, i%6+1+ }+ }+ quote := &ast.Node{Type: ast.NodeBlockquote, ID: "20261019020000-quote01"}+ quote.SetIALAttr("id", quote.ID)+ paragraph := treenode.NewParagraph("20261019020000-child01")+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("nested text")})+ quote.AppendChild(paragraph)+ tree.Root.AppendChild(quote)+ wantBlocks, wantSpans, wantAssets, wantAttrs := projectTree(tree.Root, tree, buildBlockFromNode)+ gotBlocks, gotSpans, gotAssets, gotAttrs := fromTree(tree.Root, tree)+ if !reflect.DeepEqual(wantBlocks, gotBlocks) ||+ !reflect.DeepEqual(projectionSnapshot(wantSpans), projectionSnapshot(gotSpans)) ||+ !reflect.DeepEqual(projectionSnapshot(wantAssets), projectionSnapshot(gotAssets)) ||+ !reflect.DeepEqual(projectionSnapshot(wantAttrs), projectionSnapshot(gotAttrs)) {+ t.Fatal("batch parent resolution changed the complete business projection")+ }+ changes := NewTreeIndexChanges([]string{tree.ID, quote.ID, paragraph.ID})+ blocks, spans, assets, attrs := fromTreeWithChanges(tree.Root, tree, changes)+ if len(blocks) != 3 || !reflect.DeepEqual(projectionSnapshot(spans), projectionSnapshot(gotSpans)) ||+ !reflect.DeepEqual(projectionSnapshot(assets), projectionSnapshot(gotAssets)) ||+ !reflect.DeepEqual(projectionSnapshot(attrs), projectionSnapshot(gotAttrs)) {+ t.Fatal("scoped projection omitted complete auxiliary metadata")+ }+ for _, block := range blocks {+ found := false+ for _, complete := range wantBlocks {+ if complete.ID == block.ID {+ found = reflect.DeepEqual(block, complete)+ }+ }+ if !found {+ t.Fatalf("scoped block differs from complete projection: %+v", block)+ }+ }+}diff --git a/kernel/sql/live_photo_test.go b/kernel/sql/live_photo_test.goindex 4ca9533b2c..1527060a14 100644--- a/kernel/sql/live_photo_test.go+++ b/kernel/sql/live_photo_test.go@@ -21,7 +21,7 @@ func TestLivePhotoIndexesBothAssetsInOneImageSpan(t *testing.T) {image.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte("photo")})image.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("assets/photo.heic")})p.AppendChild(image)- _, spans, assets, _, _ := buildSpanFromNode(image, tree, tree.ID, tree.Box, tree.Path)+ _, spans, assets, _, _ := buildSpanFromNode(image, tree, tree.ID, tree.Box, tree.Path, buildBlockFromNode)if len(spans) != 1 || len(assets) != 2 {t.Fatalf("spans=%d, assets=%+v", len(spans), assets)}diff --git a/kernel/sql/queue.go b/kernel/sql/queue.goindex fe3a175fe8..9239389f15 100644--- a/kernel/sql/queue.go+++ b/kernel/sql/queue.go@@ -50,13 +50,14 @@ type dbQueueOperation struct {action string // upsert/delete/delete_id/rename/move/delete_box/delete_box_refs/index/delete_ids/update_block_content/delete_assets/index_nodeindexTree *parse.Tree // index/rename/moveupsertTree *parse.Tree // upsert/update_refs/delete_refs- removeTreeBox, removeTreePath string // delete- removeTreeID string // delete_id- removeTreeIDs []string // delete_ids- box string // delete_box/delete_box_refs/index/index_node- block *Block // update_block_content- id string // index_node- removeAssetHashes []string // delete_assets+ indexChanges *TreeIndexChanges+ removeTreeBox, removeTreePath string // delete+ removeTreeID string // delete_id+ removeTreeIDs []string // delete_ids+ box string // delete_box/delete_box_refs/index/index_node+ block *Block // update_block_content+ id string // index_node+ removeAssetHashes []string // delete_assetsbeginTxRetries uint8recoveryEntry *indexEntryrecoveredIndex bool@@ -436,7 +437,7 @@ func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]any) (err error}err = indexTree(tx, op.indexTree, context)case "upsert":- err = upsertTree(tx, op.upsertTree, context)+ err = upsertTreeWithChanges(tx, op.upsertTree, context, op.indexChanges)case "delete":err = batchDeleteByPathPrefix(tx, op.removeTreeBox, op.removeTreePath)if nil == err {@@ -619,15 +620,28 @@ func IndexTreeQueue(tree *parse.Tree) {}func UpsertTreeQueue(tree *parse.Tree) {+ UpsertTreeQueueWithChanges(tree, nil)+}++// UpsertTreeQueueWithChanges 合并同一文档的影响集合;未知影响范围或有序操作边界保留完整更新。+func UpsertTreeQueueWithChanges(tree *parse.Tree, changes *TreeIndexChanges) {dbQueueLock.Lock()defer dbQueueLock.Unlock()- newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "upsert"}- for i, op := range operationQueue {- if "upsert" == op.action && op.upsertTree != nil && op.upsertTree.ID == tree.ID { // 相同树则覆盖+ newOp := &dbQueueOperation{upsertTree: tree, indexChanges: mergeTreeIndexChanges(changes, changes), inQueueTime: time.Now(), action: "upsert"}+ for i := len(operationQueue) - 1; i >= 0; i-- {+ op := operationQueue[i]+ if "upsert" == op.action && op.upsertTree != nil && op.upsertTree.Box == tree.Box && op.upsertTree.ID == tree.ID && op.upsertTree.Path == tree.Path {+ newOp.indexChanges = mergeTreeIndexChanges(op.indexChanges, newOp.indexChanges)+ newOp.inQueueTime = op.inQueueTimeoperationQueue[i] = newOpreturn}+ // 删除、移动、重命名及其他索引操作不参与快照覆盖,保留原始执行顺序。+ if op.action != "upsert" && (op.boxID() == tree.Box || op.boxID() == "" || op.action == "delete_ids") ||+ op.action == "upsert" && op.upsertTree != nil && op.upsertTree.Box == tree.Box && op.upsertTree.ID == tree.ID {+ break+ }}appendOperation(newOp)}diff --git a/kernel/sql/search_count_cache.go b/kernel/sql/search_count_cache.gonew file mode 100644index 0000000000..6526b8aa44--- /dev/null+++ b/kernel/sql/search_count_cache.go@@ -0,0 +1,199 @@+package sql++import (+ "context"+ "crypto/sha256"+ "database/sql"+ "encoding/json"+ "errors"+ "sync"++ "github.com/mattn/go-sqlite3"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type ftsCountKey struct {+ database *sql.DB+ connection *sqlite3.SQLiteConn+ version [3]int64+ query [32]byte+}++type ftsCountEntry struct {+ key ftsCountKey+ matches, docs int+ used uint64+}++// 固定槽位不保留查询正文,包含连接身份、原生版本和参数指纹,总保留空间低于 128 KiB。+var ftsCounts = struct {+ sync.Mutex+ entries [128][4]ftsCountEntry+ clock uint64+ generation uint64+}{}++func clearFTSCountCache() {+ ftsCounts.Lock()+ defer ftsCounts.Unlock()+ ftsCounts.entries = [128][4]ftsCountEntry{}+ ftsCounts.generation+++}++func ftsCountGeneration() uint64 {+ ftsCounts.Lock()+ defer ftsCounts.Unlock()+ return ftsCounts.generation+}++func getFTSCount(key ftsCountKey, generation uint64) (matches, docs int, found bool) {+ ftsCounts.Lock()+ defer ftsCounts.Unlock()+ if generation != ftsCounts.generation {+ return+ }+ bucket := &ftsCounts.entries[int(key.query[0])%len(ftsCounts.entries)]+ for i := range bucket {+ entry := &bucket[i]+ if entry.used != 0 && entry.key == key {+ ftsCounts.clock+++ entry.used = ftsCounts.clock+ return entry.matches, entry.docs, true+ }+ }+ return+}++func setFTSCount(key ftsCountKey, generation uint64, matches, docs int) {+ ftsCounts.Lock()+ defer ftsCounts.Unlock()+ if generation != ftsCounts.generation {+ return+ }+ bucket := &ftsCounts.entries[int(key.query[0])%len(ftsCounts.entries)]+ slot := 0+ for i, entry := range bucket {+ if entry.used == 0 || entry.key == key {+ slot = i+ break+ }+ if entry.used < bucket[slot].used {+ slot = i+ }+ }+ ftsCounts.clock+++ bucket[slot] = ftsCountEntry{key: key, matches: matches, docs: docs, used: ftsCounts.clock}+}++// SelectFTSBlocksWithCountContext 在同一普通库读取快照内取得分页行及精确计数。+// 仅供固定 FTS 查询使用;加密库、自定义 SQL 和动态忽略条件使用各自的既有路径。+func SelectFTSBlocksWithCountContext(ctx context.Context, statement, countStatement string, args []any) (blocks []*Block, matches, docs int, err error) {+ if err = ctx.Err(); err != nil {+ return+ }+ if !checkRawBlockQueryStmt(statement, "") || !checkRawBlockQueryStmt(countStatement, "") {+ return nil, 0, 0, errors.New("unsupported FTS read statement")+ }+ database := db+ if database == nil {+ return nil, 0, 0, errors.New("database is nil")+ }+ connection, err := database.Conn(ctx)+ if err != nil {+ return+ }+ defer connection.Close()+ key := ftsCountKey{database: database}+ cacheable := true+ if err = connection.Raw(func(raw any) error {+ var supported bool+ key.connection, supported = raw.(*sqlite3.SQLiteConn)+ cacheable = supported+ return nil+ }); err != nil {+ return+ }+ stringArgs := make([]string, len(args))+ for i, argument := range args {+ value, ok := argument.(string)+ if !ok {+ cacheable = false+ }+ stringArgs[i] = value+ }+ encoded, marshalErr := json.Marshal(struct {+ Query string+ Args []string+ }{countStatement, stringArgs})+ if marshalErr != nil {+ cacheable = false+ }+ key.query = sha256.Sum256(encoded)+ generation := ftsCountGeneration()+ timing := util.BeginPerformance("search.snapshot")+ defer timing.Finish()+ key.version, err = ftsReadVersion(ctx, connection)+ if err != nil {+ return+ }+ transaction, err := connection.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})+ if err != nil {+ return+ }+ defer transaction.Rollback()+ // 先建立实际 B-tree 读取快照,再在同一连接上采集版本,避免将新计数标记成旧版本。+ var schemaObjects int+ if err = transaction.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_schema").Scan(&schemaObjects); err != nil {+ return+ }+ confirmedVersion, err := ftsReadVersion(ctx, transaction)+ if err != nil {+ return+ }+ cacheable = cacheable && key.version == confirmedVersion+ timing.Stage("rows")+ rows, err := transaction.QueryContext(ctx, statement, args...)+ if err != nil {+ return+ }+ for rows.Next() {+ if err = ctx.Err(); err != nil {+ rows.Close()+ return nil, 0, 0, err+ }+ block := scanBlockRows(rows)+ if block == nil {+ rows.Close()+ return nil, 0, 0, errors.New("invalid FTS block row")+ }+ blocks = append(blocks, block)+ }+ err = rows.Err()+ rows.Close()+ if err != nil {+ return+ }+ timing.Stage("count")+ if cacheable {+ if cachedMatches, cachedDocs, found := getFTSCount(key, generation); found {+ timing.Count("count_cache_hit", 1)+ return blocks, cachedMatches, cachedDocs, ctx.Err()+ }+ }+ if err = transaction.QueryRowContext(ctx, countStatement, args...).Scan(&matches, &docs); err != nil {+ return+ }+ if err = ctx.Err(); err == nil && cacheable {+ setFTSCount(key, generation, matches, docs)+ }+ return+}++type ftsVersionReader interface {+ QueryRowContext(context.Context, string, ...any) *sql.Row+}++func ftsReadVersion(ctx context.Context, reader ftsVersionReader) (version [3]int64, err error) {+ err = reader.QueryRowContext(ctx, "SELECT data_version, total_changes(), schema_version FROM pragma_data_version, pragma_schema_version").Scan(&version[0], &version[1], &version[2])+ return+}diff --git a/kernel/sql/search_count_cache_benchmark_fts5_test.go b/kernel/sql/search_count_cache_benchmark_fts5_test.gonew file mode 100644index 0000000000..da72fd2a08--- /dev/null+++ b/kernel/sql/search_count_cache_benchmark_fts5_test.go@@ -0,0 +1,68 @@+//go:build fts5++package sql++import (+ "context"+ "fmt"+ "testing"+)++func BenchmarkFTSExactCountReuse(b *testing.B) {+ previousDB := db+ b.Cleanup(func() { db = previousDB; clearFTSCountCache() })+ for _, size := range []int{1000, 10000, 100000, 1000000} {+ b.Run(fmt.Sprint(size), func(b *testing.B) {+ db = newDeletePathTestDB(b, false)+ statement := `WITH RECURSIVE n(x) AS (VALUES(0) UNION ALL SELECT x+1 FROM n WHERE x+1<?)+INSERT INTO blocks (` + ftsCountTestFields + `)+SELECT printf('%023d',x),'',printf('%023d',x/100),'','box','/doc.sy','/doc','','','','',+CASE WHEN x%1000=0 THEN 'common rare' ELSE 'common' END,'','',6,'p','','',0,'20261019000000','20261019000000' FROM n`+ if _, err := db.Exec(statement, size); err != nil {+ b.Fatal(err)+ }+ if _, err := db.Exec("INSERT INTO blocks_fts(blocks_fts) VALUES('rebuild')"); err != nil {+ b.Fatal(err)+ }+ for _, term := range []string{"common", "rare", "absent"} {+ for _, mode := range []string{"uncached", "cold", "reused"} {+ b.Run(term+"/"+mode, func(b *testing.B) {+ ctx := context.Background()+ query := "SELECT " + ftsCountTestFields + " FROM blocks_fts WHERE blocks_fts MATCH ? LIMIT 50"+ count := "SELECT COUNT(id) AS matches,COUNT(DISTINCT root_id) AS docs FROM blocks_fts WHERE blocks_fts MATCH ?"+ args := []any{"content:(" + term + ")"}+ want := size+ if term == "rare" {+ want = (size + 999) / 1000+ } else if term == "absent" {+ want = 0+ }+ clearFTSCountCache()+ if _, matches, _, err := SelectFTSBlocksWithCountContext(ctx, query, count, args); err != nil || matches != want {+ b.Fatalf("invalid fixture: matches=%d, %v", matches, err)+ }+ b.ReportAllocs()+ b.ResetTimer()+ for range b.N {+ if mode == "uncached" {+ blocks, err := SelectBlocksRawStmtArgsInBoxContext(ctx, query, args, 50, "")+ counts, countErr := QueryNoLimitArgsInBoxContext(ctx, count, "", args...)+ if err != nil || countErr != nil || len(blocks) != min(want, 50) || len(counts) != 1 || counts[0]["matches"] != int64(want) {+ b.Fatalf("unexpected uncached result: %v, %v", err, countErr)+ }+ } else {+ if mode == "cold" {+ clearFTSCountCache()+ }+ blocks, matches, _, err := SelectFTSBlocksWithCountContext(ctx, query, count, args)+ if err != nil || matches != want || len(blocks) != min(want, 50) {+ b.Fatalf("unexpected snapshot result: matches=%d, %v", matches, err)+ }+ }+ }+ })+ }+ }+ })+ }+}diff --git a/kernel/sql/search_count_cache_fts5_test.go b/kernel/sql/search_count_cache_fts5_test.gonew file mode 100644index 0000000000..48c42e6f51--- /dev/null+++ b/kernel/sql/search_count_cache_fts5_test.go@@ -0,0 +1,268 @@+//go:build fts5++package sql++import (+ "context"+ "crypto/sha256"+ "database/sql"+ "errors"+ "fmt"+ "path/filepath"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+ "unsafe"++ "github.com/88250/lute/parse"+ "github.com/mattn/go-sqlite3"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const ftsCountTestFields = "id,parent_id,root_id,hash,box,path,hpath,name,alias,memo,tag,content,fcontent,markdown,length,type,subtype,ial,sort,created,updated"+const ftsCountTestStatement = "SELECT " + ftsCountTestFields + " FROM blocks_fts WHERE blocks_fts MATCH ? ORDER BY id LIMIT 1"+const ftsCountTestCount = "SELECT COUNT(id) + observe_fts_count(), COUNT(DISTINCT root_id) FROM blocks_fts WHERE blocks_fts MATCH ?"++func prepareFTSCountCacheTest(t *testing.T, disk bool) (*sql.DB, *parse.Tree, *atomic.Int64, string) {+ t.Helper()+ previousDB, previousDisabled, previousDir := db, cacheDisabled, util.DataDir+ previousCached, previousIgnore := IndexIgnoreCached, indexIgnore+ cacheDisabled, util.DataDir, IndexIgnoreCached, indexIgnore = true, t.TempDir(), true, nil+ path := ""+ if disk {+ path = filepath.Join(t.TempDir(), "search.db")+ var err error+ db, err = sql.Open("sqlite3_extended", path+"?_journal_mode=WAL&_busy_timeout=1000")+ if err != nil {+ t.Fatal(err)+ }+ db.SetMaxOpenConns(1)+ initDBTables()+ opened := db+ t.Cleanup(func() { opened.Close() })+ } else {+ db = newDeletePathTestDB(t, false)+ }+ t.Cleanup(func() {+ db, cacheDisabled, util.DataDir = previousDB, previousDisabled, previousDir+ IndexIgnoreCached, indexIgnore = previousCached, previousIgnore+ ClearCache()+ })+ database := db+ tree := newUpsertTestTree(6)+ tx, err := database.Begin()+ if err != nil {+ t.Fatal(err)+ }+ if err = indexTree(tx, tree, nil); err == nil {+ err = commitTx(tx)+ }+ if err != nil {+ t.Fatal(err)+ }+ calls := &atomic.Int64{}+ connection, err := database.Conn(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ err = connection.Raw(func(raw any) error {+ return raw.(*sqlite3.SQLiteConn).RegisterFunc("observe_fts_count", func() int64 { calls.Add(1); return 0 }, false)+ })+ connection.Close()+ if err != nil {+ t.Fatal(err)+ }+ clearFTSCountCache()+ return database, tree, calls, path+}++func TestFTSCountCacheTracksOwnCommitsRollbackAndArguments(t *testing.T) {+ database, tree, calls, _ := prepareFTSCountCacheTest(t, false)+ query := func(statement, term string, want int) {+ t.Helper()+ _, matches, docs, err := SelectFTSBlocksWithCountContext(context.Background(), statement, ftsCountTestCount, []any{"content:(" + term + ")"})+ if err != nil || matches != want || docs != min(want, 1) {+ t.Fatalf("incorrect exact count: %d/%d, want %d, err=%v", matches, docs, want, err)+ }+ }+ query(ftsCountTestStatement, "original", 6)+ query(ftsCountTestStatement+" OFFSET 1", "original", 6)+ if calls.Load() != 1 {+ t.Fatal("pagination did not reuse the exact count")+ }+ write := func(commit bool) {+ t.Helper()+ tx, err := database.Begin()+ if err != nil {+ t.Fatal(err)+ }+ if err = insertBlocks(tx, []*Block{{ID: fmt.Sprint(calls.Load()), RootID: tree.ID, Content: "original new row", Type: "p"}}, nil); err != nil {+ t.Fatal(err)+ }+ if commit {+ err = commitTx(tx)+ } else {+ err = tx.Rollback()+ closeTxPreparedStmts(tx)+ }+ if err != nil {+ t.Fatal(err)+ }+ }+ write(true)+ query(ftsCountTestStatement, "original", 7)+ write(false)+ query(ftsCountTestStatement, "original", 7)+ query(ftsCountTestStatement, "missing", 0)+ query(ftsCountTestStatement+" OFFSET 2", "missing", 0)+ if calls.Load() != 4 {+ t.Fatalf("wrong version/argument reuse: %d count queries", calls.Load())+ }+ ClearCache()+ query(ftsCountTestStatement, "original", 7)+ if calls.Load() != 5 {+ t.Fatal("explicit invalidation reused an old count")+ }+}++func TestFTSCountSnapshotSurvivesConcurrentCommit(t *testing.T) {+ for _, boundary := range []string{"before snapshot", "before version confirmation", "during row read"} {+ t.Run(boundary, func(t *testing.T) {+ database, tree, _, path := prepareFTSCountCacheTest(t, true)+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ args := []any{"content:(original)"}+ if _, matches, _, err := SelectFTSBlocksWithCountContext(ctx, ftsCountTestStatement, ftsCountTestCount, args); err != nil || matches != 6 {+ t.Fatalf("warm snapshot: %d, %v", matches, err)+ }+ ready, resume := make(chan struct{}), make(chan struct{})+ var release sync.Once+ defer release.Do(func() { close(resume) })+ connection, err := database.Conn(ctx)+ if err != nil {+ t.Fatal(err)+ }+ statement := ftsCountTestStatement+ err = connection.Raw(func(raw any) error {+ native := raw.(*sqlite3.SQLiteConn)+ if boundary == "before version confirmation" || boundary == "before snapshot" {+ var invocations int+ native.RegisterAuthorizer(func(operation int, name, _, _ string) int {+ if boundary == "before snapshot" && operation == sqlite3.SQLITE_TRANSACTION && name == "BEGIN" ||+ boundary == "before version confirmation" && operation == sqlite3.SQLITE_PRAGMA && name == "data_version" {+ invocations+++ if boundary == "before snapshot" && invocations == 1 || boundary == "before version confirmation" && invocations == 2 {+ close(ready)+ <-resume+ }+ }+ return 0+ })+ return nil+ }+ statement = strings.Replace(statement, "content,fcontent", "content || hold_fts_snapshot(),fcontent", 1)+ return native.RegisterFunc("hold_fts_snapshot", func() string { close(ready); <-resume; return "" }, false)+ })+ connection.Close()+ if err != nil {+ t.Fatal(err)+ }+ result := make(chan error, 1)+ go func() {+ _, matches, docs, err := SelectFTSBlocksWithCountContext(ctx, statement, ftsCountTestCount, args)+ want := 6+ if boundary == "before snapshot" {+ want = 7+ }+ if err == nil && (matches != want || docs != 1) {+ err = fmt.Errorf("snapshot mixed old rows with new count: %d/%d", matches, docs)+ }+ result <- err+ }()+ select {+ case <-ready:+ case <-ctx.Done():+ t.Fatal("reader did not reach the commit boundary")+ }+ writer, err := sql.Open("sqlite3_extended", path+"?_journal_mode=WAL&_busy_timeout=1000")+ if err != nil {+ t.Fatal(err)+ }+ tx, err := writer.Begin()+ if err == nil {+ err = insertBlocks(tx, []*Block{{ID: "external", RootID: tree.ID, Type: "p", Content: "original external row"}}, nil)+ }+ if err == nil {+ err = commitTx(tx)+ }+ writer.Close()+ release.Do(func() { close(resume) })+ if err != nil {+ t.Fatal(err)+ }+ if err = <-result; err != nil {+ t.Fatal(err)+ }+ if _, matches, _, err := SelectFTSBlocksWithCountContext(ctx, ftsCountTestStatement, ftsCountTestCount, args); err != nil || matches != 7 {+ t.Fatalf("new snapshot reused a stale exact count: %d, %v", matches, err)+ }+ })+ }+}++func TestFTSCountCacheIsolatesCountSQLAndSkipsNonStringArguments(t *testing.T) {+ _, _, calls, _ := prepareFTSCountCacheTest(t, false)+ ctx := context.Background()+ args := []any{"content:(original)"}+ if _, matches, _, err := SelectFTSBlocksWithCountContext(ctx, ftsCountTestStatement, ftsCountTestCount, args); err != nil || matches != 6 {+ t.Fatalf("initial count: %d, %v", matches, err)+ }+ if _, matches, _, err := SelectFTSBlocksWithCountContext(ctx, ftsCountTestStatement,+ ftsCountTestCount+" AND type='d'", args); err != nil || matches != 0 {+ t.Fatalf("different count SQL reused a previous scope: %d, %v", matches, err)+ }+ query := strings.Replace(ftsCountTestStatement, " ORDER BY", " AND ?=1 ORDER BY", 1)+ for range 2 {+ if _, matches, _, err := SelectFTSBlocksWithCountContext(ctx, query, ftsCountTestCount+" AND ?=1", append(args, 1)); err != nil || matches != 6 {+ t.Fatalf("uncacheable argument changed exact results: %d, %v", matches, err)+ }+ }+ if calls.Load() != 4 {+ t.Fatalf("count SQL or argument type was ignored: %d calls", calls.Load())+ }+}++func TestFTSCountCacheCancellationBudgetAndStaleAdmission(t *testing.T) {+ database, _, _, _ := prepareFTSCountCacheTest(t, false)+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ if _, _, _, err := SelectFTSBlocksWithCountContext(ctx, ftsCountTestStatement, ftsCountTestCount, []any{"original"}); !errors.Is(err, context.Canceled) {+ t.Fatalf("canceled read: %v", err)+ }+ if err := database.Ping(); err != nil {+ t.Fatal("canceled search did not release its connection")+ }+ deadline, stop := context.WithTimeout(context.Background(), 10*time.Millisecond)+ defer stop()+ heavyCount := "WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<100000000) SELECT COUNT(*),1 FROM n WHERE ? IS NOT NULL"+ if _, _, _, err := SelectFTSBlocksWithCountContext(deadline, ftsCountTestStatement, heavyCount, []any{"original"}); !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("running count was not interrupted: %v", err)+ }+ reuse, release := context.WithTimeout(context.Background(), time.Second)+ defer release()+ if err := database.PingContext(reuse); err != nil {+ t.Fatalf("interrupted count left its connection occupied: %v", err)+ }+ if unsafe.Sizeof(ftsCounts) > 128*1024 {+ t.Fatal("fixed cache storage exceeded the byte budget")+ }+ generation := ftsCountGeneration()+ key := ftsCountKey{database: database, query: sha256.Sum256([]byte("scope"))}+ clearFTSCountCache()+ setFTSCount(key, generation, 10, 1)+ if _, _, found := getFTSCount(key, ftsCountGeneration()); found {+ t.Fatal("old request repopulated a new cache generation")+ }+}diff --git a/kernel/sql/upsert.go b/kernel/sql/upsert.goindex 58a193e7e5..f0d933ad0a 100644--- a/kernel/sql/upsert.go+++ b/kernel/sql/upsert.go@@ -447,15 +447,27 @@ func indexTree(tx *sql.Tx, tree *parse.Tree, context map[string]any) (err error)}func upsertTree(tx *sql.Tx, tree *parse.Tree, context map[string]any) (err error) {+ return upsertTreeWithChanges(tx, tree, context, nil)+}++func upsertTreeWithChanges(tx *sql.Tx, tree *parse.Tree, context map[string]any, changes *TreeIndexChanges) (err error) {if isIndexIgnored(tree) {return}timing := util.BeginPerformance("index.update")defer timing.Finish()timing.Stage("project")+ changes, err = usableTreeIndexChanges(tx, tree, changes)+ if err != nil {+ return+ }oldBlockHashes := queryBlockHashes(tx, tree.ID)- blocks, spans, assets, attributes := fromTree(tree.Root, tree)- timing.Count("blocks_total", int64(len(blocks)))+ blocks, spans, assets, attributes := fromTreeWithChanges(tree.Root, tree, changes)+ timing.Count("blocks_total", int64(len(oldBlockHashes)))+ timing.Count("blocks_projected", int64(len(blocks)))+ if changes != nil {+ timing.Count("changeset", 1)+ }timing.Stage("compare_blocks")newBlockHashes := map[string]string{}for _, block := range blocks {@@ -464,6 +476,9 @@ func upsertTree(tx *sql.Tx, tree *parse.Tree, context map[string]any) (err errorunChanges := hashset.New()var toRemoves []stringfor id, hash := range oldBlockHashes {+ if changes != nil && !changes.blockIDs[id] {+ continue+ }if newHash, ok := newBlockHashes[id]; ok {if newHash == hash {unChanges.Add(id)diff --git a/kernel/sql/upsert_benchmark_fts5_test.go b/kernel/sql/upsert_benchmark_fts5_test.goindex 8ae23fa38f..40dd667f18 100644--- a/kernel/sql/upsert_benchmark_fts5_test.go+++ b/kernel/sql/upsert_benchmark_fts5_test.go@@ -69,7 +69,9 @@ func BenchmarkUpsertTreeAuxiliaryIndexes(b *testing.B) {for _, mode := range []struct {name stringupdate func(*sql.Tx, *parse.Tree, map[string]any) error- }{{"complete", upsertTreeWithFullAuxiliaryReplacement}, {"incremental", upsertTree}} {+ }{{"complete", upsertTreeWithFullAuxiliaryReplacement}, {"incremental", upsertTree}, {"changeset", func(tx *sql.Tx, tree *parse.Tree, context map[string]any) error {+ return upsertTreeWithChanges(tx, tree, context, NewTreeIndexChanges([]string{tree.ID, tree.Root.FirstChild.ID}))+ }}} {b.Run(mode.name, func(b *testing.B) {database := newDeletePathTestDB(b, false)db = databasediff --git a/kernel/treenode/tree.go b/kernel/treenode/tree.goindex 59c8443de5..e277d0e0d7 100644--- a/kernel/treenode/tree.go+++ b/kernel/treenode/tree.go@@ -36,6 +36,11 @@ import ()func NodeHash(node *ast.Node, tree *parse.Tree, luteEngine *lute.Lute) string {+ return NodeHashWithHeadingParent(node, tree, luteEngine, HeadingParent(node))+}++// NodeHashWithHeadingParent 复用本次投影已解析的语义父级,避免重复查找前面的标题。+func NodeHashWithHeadingParent(node *ast.Node, tree *parse.Tree, luteEngine *lute.Lute, headingParent *ast.Node) string {var ialArray [][]stringif 0 < len(node.KramdownIAL) {ialArray = make([][]string, len(node.KramdownIAL))@@ -55,8 +60,8 @@ func NodeHash(node *ast.Node, tree *parse.Tree, luteEngine *lute.Lute) string {if nil != node.Parent {parentID = node.Parent.ID}- if h := HeadingParent(node); nil != h {- parentID = h.ID+ if headingParent != nil {+ parentID = headingParent.ID}data += parentIDreturn fmt.Sprintf("%x", sha256.Sum256(gulu.Str.ToBytes(data)))[:7]