Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:zap: Stream view fingerprints and refine search cancellation https://github.com/siyuan-note/siyuan/issues/20692

Daniel87e61d96aa11
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
index 66bacc4123..23bf3675d4 100644
--- a/docs/PERFORMANCE.md
+++ b/docs/PERFORMANCE.md
@@ -17,7 +17,7 @@ Records start with `siyuan-performance ` followed by JSON. `duration_us` and `st
| Operation | Stage boundary and counters |
|---|---|
| `transaction` | Begin, automations, apply, finalize, commit; operation count |
-| `document.load` | Transaction boundary, capture/load/parse tree, locate blocks, render response; block count; `source_snapshot = 1` identifies an ordinary cached source parsed outside the transaction lock |
+| `document.load` | `wait_transactions` waits for the serial boundary, `flush_transactions` executes the captured batch, `load_tree` captures or fully loads the source, and `parse_source` parses cached source bytes outside the lock, followed by lookup and response rendering; block count, `flushed_transactions` counts transactions actively executed by this read, and `source_snapshot = 1` identifies an ordinary cached source |
| `document.save` | Prepare/serialize, encrypt, compare, write, notify; prepared and written bytes |
| `index.flush` | Lock wait, take queue, begin/execute/commit, notify, persist queue completion; batch size and oldest enqueue age |
| `index.update` | Main-block and complete auxiliary projection, block comparison, auxiliary-index comparison, writes; `blocks_total` counts previously indexed blocks, `blocks_projected` counts generated main blocks, `changeset = 1` identifies a usable transaction hint; changed blocks and planned auxiliary deletions and insertions |
@@ -40,16 +40,20 @@ Ordinary table, list and gallery views can evaluate templates needed by filters,
Ordinary cached document opening waits for the serial execution lock, including any dequeued transaction still executing. With queued work, it completes the single batch captured after acquiring that lock and captures the document source before releasing it. Transactions arriving after that batch do not extend this path to a globally empty queue. Empty-queue captures can share the read lock. Writes, undo/replay and the existing global flush operation keep their completion rules; this is a global editing boundary, without document-specific transaction routing.
+`wait_transactions` includes lock waiting for writes already in progress. `flush_transactions` and `flushed_transactions` describe only the batch actively captured and executed by this read; earlier in-flight transactions are not included in that count. These records distinguish waiting, queued execution and source-processing costs. They do not establish that transactions for other documents can be skipped.
+
Ordinary cached documents copy their independently decoded source bytes and parent titles at that boundary, then parse and render after releasing the transaction lock. Later edits, moves, cache invalidation or parent renames cannot change that captured source; parsing cannot recreate a subsequently removed file. The snapshot is local to one read and introduces no retained cache. Encrypted documents, cache misses and parent chains requiring repair retain the original global queue wait and complete loader, including authentication, compatibility repair and index refresh. They release the transaction lock before that wait/load to preserve lifecycle lock ordering, and do not gain the finite-batch guarantee. Source copying and reading parent titles also have costs proportional to their input. SQL-derived reference counts, virtual references and other response metadata retain their existing asynchronous index behavior; this is not a combined filesystem/SQL/sync snapshot.
Main-block projection resolves heading parents once per physical sibling list within a projection. Transactions consisting entirely of tracked `update` operations can provide changed and removed subtree IDs and affected containers. Heading structure, inline HTML, untracked writes, missing or changed root metadata, and other transaction operations retain complete main-block projection. Queue coalescing unions hints only within the same notebook, document and path and preserves ordered delete, move, rename and other index-operation boundaries. Hints exist only in process memory; recovery loads the complete authenticated source and performs an idempotent full update. Complete auxiliary projection and the existing whole-document `.sy` save remain in place.
-View order reuse applies only to live ordinary sources with at least 512 detached rows, static fields and closed pure templates required before pagination. It covers table, list and galleries without covers; query, grouping, context filters, target positioning, calculations, date/time, relation, rollup, assets and external or dynamic dependencies retain their existing paths. Plain views and views whose templates are all display-only do not pay for an order fingerprint. The key includes the source version and cache generation, actual data and view definition, carrier, language and write scope; temporary data or sort changes produce different keys. Fingerprinting encodes values in bounded chunks. It still validates and hashes the complete input, and source parsing still scales with source size.
+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. Common block, plain text and template values use a streaming fingerprint with types, pointer-presence markers and length boundaries; other values retain complete chunked JSON. The buffer does not grow with an ordinary field's content. Regression checks require new persisted value fields to update fingerprint coverage. This representation is only an in-process cache key. It still validates and hashes the complete input, and source parsing still scales with source size; a saved source version alone cannot establish that temporary values are unchanged.
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).
+Search cancellation reaches individual-field highlighting and document keyword partitioning. Text up to 4 KiB keeps complete matching, followed by cancellation checks while generating markup. Larger cancelable literal highlighting scans 64 KiB windows with overlap sufficient for the longest keyword's UTF-8 representation, checks cancellation between individual matches, and avoids duplicate temporary match collections. Window crossings, case/Han variants and empty matches remain equivalent to complete matching. Cancellation does not return partial fields or result collections. Result formatting generates only the highlighting it consumes; other callers requesting similarity scores retain the existing scoring. Regex compilation, an individual arbitrary-regex match, whole-tree or database-definition parsing, and underlying file reads remain non-preemptible individual operations, so there is no universal cancellation-latency bound.
+
Export kernel and browser captures separately as UTF-8 files. From `app/`, summarize each run with:
```text
@@ -70,6 +74,9 @@ go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkUpsertTreeAuxiliaryIndexes$
go 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 ./model -run '^$' -bench '^BenchmarkAttributeViewOrderFingerprint$' -benchmem -benchtime=300ms -count=3
+go test ./search -run '^$' -bench '^BenchmarkMarkTextContext$' -benchmem -benchtime=200ms -count=3
+go test ./model -run '^$' -bench '^BenchmarkSearchProcessingContext$' -benchmem -benchtime=300ms -count=3
go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkFTSExactCountReuse$' -benchmem -benchtime=200ms -count=3
go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^Benchmark(DocumentReadBoundarySource|DocumentReadBoundaryEmpty|FlushTxQueueEmpty)$' -benchmem -benchtime=1s -count=3
go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^BenchmarkDocument(SearchCandidates|CandidateIndexWrite)$' -benchmem -benchtime=200ms -count=3
@@ -84,6 +91,9 @@ go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^BenchmarkDocument(Sear
| `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 |
+| `BenchmarkAttributeViewOrderFingerprint` | 1,000 / 10,000 / 50,000 rows, the same template dependency fixture, a fixed parsed ordinary source | Eligibility checks, dependency planning and complete fingerprinting; excludes source parsing and page rendering, and its independent medians cannot be subtracted exactly from whole-page medians |
+| `BenchmarkMarkTextContext` | 20 / 20,000 repetitions of `alpha & beta `, matching `alpha` | Complete highlighting with a non-cancelable or cancelable context; the cancelable context stays active to measure checking costs for successful requests |
+| `BenchmarkSearchProcessingContext` | One block whose content and first-child content contain 20 / 20,000 repetitions of `alpha & beta `, plus name, alias, memo, tag and path | Complete block-result formatting under an active cancelable request, including highlighting, truncation and escaping; excludes querying, counts and frontend work |
| `BenchmarkFTSExactCountReuse` | 1,000 / 10,000 / 100,000 / 1,000,000 blocks, 100 per document; all, 0.1% or no blocks match; first 50 blocks | Warm in-memory FTS row decoding and exact block/document counts; uncached separate reads versus a cold or reused snapshot count; cold mode includes cache clearing |
| `BenchmarkDocumentReadBoundarySource` | 1,000 / 5,000 / 20,000 flat paragraphs with 128 ASCII content bytes each | Source capture alone, or full loading using a global flush versus the read boundary; warm mode uses the content cache, cold mode removes it each iteration; both reuse the OS file cache and exclude queue backlog and response rendering |
| `BenchmarkDocumentSearchCandidates` | 10,000 / 100,000 / 1,000,000 blocks, 100 per document; every document, one document or no document matches | Complete document query/count/row decoding without candidates, with a block scan producing root IDs, or with a prebuilt document trigram index; `candidate_build_ms` and `candidate_bytes` separately report index construction and SQLite page growth |
@@ -91,6 +101,22 @@ go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^BenchmarkDocument(Sear
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.
+## Fingerprint and result-formatting comparison
+
+On 2026-10-19, the follow-up working tree based on `9539ed7d` was measured on Windows amd64, Intel i7-8750H, Go 1.27.2, with `fts5 sqlcipher`. Go source overlays restored the original fingerprint planner, or the original search result formatter and highlighting implementation; other code and fixtures were identical. View fixtures contain nine fields, including two template dependencies required by filter/sort and five display-only templates, with page size 50. View figures are medians of three samples with three timed operations per sample. Formatting uses `BenchmarkSearchProcessingContext`, at least 300 ms per sample, repeated three times.
+
+| Path | Original implementation | Follow-up implementation |
+|---|---|---|
+| 1,000 rows, order cache hit | 41.6 ms | 25.8 ms |
+| 10,000 rows, order cache hit | 281 ms | 177 ms |
+| 10,000 rows, order cache miss | 949 ms | 727 ms |
+| 10,000 rows, control without order reuse | 710 ms | 706 ms |
+| Complete result formatting, 260-byte content | 38.3 µs | 34.4 µs |
+| Complete result formatting, 260,000-byte content | 25.7 ms | 21.7 ms |
+| Result-formatting Go allocations, 260,000-byte content | 10.0 MB/op | 7.81 MB/op |
+
+The separate 10,000-row eligibility, dependency-plan and complete-fingerprint benchmark is approximately 42 ms and excludes source parsing. The empty-queue transaction boundary is approximately 29 ns/op with zero allocations. An order-cache miss varies a temporary view name; it is not a cold OS file cache. Three-sample measurements still show variance. These figures describe fixed paths, not P95, real-workspace interaction, peak process memory or processing proportional only to page size.
+
## Document candidate experiment
Candidate queries and the trigram index exist only in tests and benchmarks; production search and storage do not use them. The scan experiment admits one literal substring and retains the complete query for exact results, counts and ordering. Commas, LIKE wildcards and NUL require fallback for that candidate term. Its fixture comparisons include case sensitivity, path matching, filters, quotes, cross-block keywords, separators, NUL, all sort modes and pagination. They establish equivalence for those fixtures, rather than a proof for every query plan and aggregation order.
@@ -140,7 +166,10 @@ go test ./util -run Performance -count=1
go test -tags fts5 ./sql -run 'TestAuxiliary|TestUpsertTree|TestStaticTemplateKeyDependencies' -count=1
go test ./model -run 'TestAttributeViewTemplatePlan|TestRenderAttributeViewUsesTemplateDependencyPlan|TestShouldDeferAttributeViewTemplateValues|TestRenderAttributeViewDefersDisplayOnlyTemplatesUntilAfterPagination' -count=1
go 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 -tags 'fts5 sqlcipher' ./sql ./model -run 'TestTreeIndexChanges|TestIndexHeading|TestIndexProjection|TestTransactionIndexChanges|TestFTSCount|TestReusableTemplateKey|TestAttributeViewOrder' -count=1
+go test ./search -run 'TestMarkTextContext' -count=1
+go test -tags 'fts5 sqlcipher' ./model -run 'TestSearchProcessing' -count=1
+go test ./search -run '^$' -fuzz '^FuzzMarkTextContextMatchesComplete$' -fuzztime=20s -parallel=2
go test -race ./cache -run TestAVOrderedIDs -count=1
go test -tags 'fts5 sqlcipher' ./model ./filesys -run 'TestDocumentReadBoundary|TestCachedTreeSource|TestAssetRelinkLockCancels|TestDocumentSearchCandidate' -count=1
go test -race -tags 'fts5 sqlcipher' ./model ./filesys -run 'TestDocumentReadBoundary|TestCachedTreeSource|TestAssetRelinkLockCancels|TestQueuedTransactionWaitForCommit|TestFlushTxQueueWaitsForDequeuedTransaction|TestWaitForSubmittedTransactionBatch|TestTransactionCompletion' -count=1
diff --git a/docs/PERFORMANCE.zh-CN.md b/docs/PERFORMANCE.zh-CN.md
index 6c17f4c523..3383f23605 100644
--- a/docs/PERFORMANCE.zh-CN.md
+++ b/docs/PERFORMANCE.zh-CN.md
@@ -17,7 +17,7 @@
| 操作 | 阶段边界和计数 |
|---|---|
| `transaction` | 开始、自动化、应用操作、整理、提交;操作数 |
-| `document.load` | 事务边界、捕获/加载/解析树、定位块、渲染响应;块数;`source_snapshot = 1` 表示普通缓存来源在事务锁外解析 |
+| `document.load` | `wait_transactions` 等待串行边界、`flush_transactions` 执行捕获批次、`load_tree` 捕获或完整加载、`parse_source` 在锁外解析缓存来源,之后定位块及渲染响应;块数、`flushed_transactions` 为本次读取主动执行的事务数,`source_snapshot = 1` 表示使用普通缓存来源 |
| `document.save` | 准备/序列化、加密、比对、写入、通知;待保存字节数和实际写入字节数 |
| `index.flush` | 等锁、提取队列、开始/执行/提交、通知、持久化队列完成状态;批次大小和最老入队任务的等待时间 |
| `index.update` | 主块及完整附属投影、块比较、附属索引比较、写入;`blocks_total` 为已有索引块数,`blocks_projected` 为生成的主块数,`changeset = 1` 表示采用事务提示;变化块数、计划删除及插入的附属记录数 |
@@ -40,16 +40,20 @@
普通缓存文档的打开先等待串行执行锁,包括已从队列取出但仍在执行的事务。有排队任务时,完成取得该锁后捕获的单个批次,并在释放锁前取得文档来源;该批次之后新到达的事务不会把这条路径延长到全局队列清空。空队列捕获可以共享读锁。写入、撤销/重放及既有全局刷新操作保持原有完成规则;这是全局编辑边界,尚未按文档路由事务。
+`wait_transactions` 包含其他写入已经开始执行时的锁等待;`flush_transactions` 和 `flushed_transactions` 只归属本次读取主动提取并执行的批次,不能将此前的在途事务计入该计数。这些记录用于区分等待、执行排队工作和来源处理的成本,不表示已经证明可以跳过其他文档事务。
+
普通缓存文档在该边界复制独立解压的来源字节和父级标题,释放事务锁后再解析和渲染。后续编辑、移动、缓存失效或父文档改名不会改变已捕获来源,解析也不会重建之后被移除的文件。快照只用于本次读取,不新增常驻缓存。加密文档、缓存未命中及父链需要订正的情况继续使用原有全局队列等待和完整加载,包含认证、兼容订正和索引刷新;等待/加载前释放事务锁以保留生命周期锁顺序,这些回退路径没有有限批次保证。复制来源和读取父级标题也有随输入增长的成本。SQL 派生的引用计数、虚拟引用及其他响应元数据保持原有异步索引行为,这不是文件系统、SQL 和同步的联合快照。
主块投影在每次投影内按物理兄弟列表统一解析标题父级。全部由已跟踪 `update` 操作构成的事务,可提供变更及删除子树的块 ID 和受影响容器。标题结构、行级 HTML、未跟踪写入、缺失或变化的根元数据,以及其他事务操作继续完整主块投影。队列只在同一笔记本、文档和路径内合并提示,保留删除、移动、重命名及其他索引操作的有序边界。提示只存在于进程内存,恢复时从完整已认证源文件执行幂等的完整更新。完整附属投影和整篇 `.sy` 的保存方式保持不变。
-视图顺序复用只用于实时普通源、至少 512 个游离条目、静态字段,以及分页前必须计算的封闭纯模板。覆盖表格、列表和无封面的画廊;查询、分组、上下文筛选、目标定位、汇总、日期/时间、关联、汇总字段、资源及外部或动态依赖继续原路径。普通视图及模板全部仅用于显示的视图不计算顺序指纹。键包含源版本和缓存代次、实际数据和视图定义、载体、语言及写入范围,临时数据或排序变化产生不同键。指纹分块编码属性值,仍校验并哈希完整输入,源数据解析也仍随源大小增长。
+视图顺序复用只用于实时普通源、至少 512 个游离条目、静态字段,以及分页前必须计算的封闭纯模板。覆盖表格、列表和无封面的画廊;查询、分组、上下文筛选、目标定位、汇总、日期/时间、关联、汇总字段、资源及外部或动态依赖继续原路径。普通视图及模板全部仅用于显示的视图不计算顺序指纹。键包含源版本和缓存代次、实际数据和视图定义、载体、语言及写入范围,临时数据或排序变化产生不同键。常见块、纯文本和模板值使用包含类型、指针存在性和长度边界的流式指纹,其余值继续分块编码完整 JSON,缓冲区不随单个普通字段内容增长。回归检查要求新增持久化值字段同时更新指纹覆盖。该表示只用于进程内缓存键,仍校验并哈希完整输入,源数据解析也仍随源大小增长;不能只以已保存的源版本判断临时值未变。
顺序缓存只保留独立的不可变 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)。
+搜索取消传入单块字段高亮和文档关键词归属判断。至多 4 KiB 的文本保留整段匹配,之后在生成高亮时检查取消。更大的可取消字面高亮按 64 KiB 窗口扫描,保留最长关键字的 UTF-8 重叠区,在每个匹配之间检查取消,并避免重复收集临时匹配数组;跨窗口、大小写、繁简和空匹配与完整匹配保持一致。取消不会返回未完成的字段或结果集合。结果加工只生成实际使用的高亮,需要相似度分数的其他调用保持原评分。正则编译、任意正则的单次匹配、整树或数据库定义解析及底层文件读取等单次内部调用仍非可抢占操作,因此没有统一的取消延迟上限。
+
将内核与浏览器采样分别导出为 UTF-8 文件。在 `app/` 下汇总每次运行:
```text
@@ -70,6 +74,9 @@ go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkUpsertTreeAuxiliaryIndexes$
go 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 ./model -run '^$' -bench '^BenchmarkAttributeViewOrderFingerprint$' -benchmem -benchtime=300ms -count=3
+go test ./search -run '^$' -bench '^BenchmarkMarkTextContext$' -benchmem -benchtime=200ms -count=3
+go test ./model -run '^$' -bench '^BenchmarkSearchProcessingContext$' -benchmem -benchtime=300ms -count=3
go test -tags fts5 ./sql -run '^$' -bench '^BenchmarkFTSExactCountReuse$' -benchmem -benchtime=200ms -count=3
go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^Benchmark(DocumentReadBoundarySource|DocumentReadBoundaryEmpty|FlushTxQueueEmpty)$' -benchmem -benchtime=1s -count=3
go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^BenchmarkDocument(SearchCandidates|CandidateIndexWrite)$' -benchmem -benchtime=200ms -count=3
@@ -84,6 +91,9 @@ go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^BenchmarkDocument(Sear
| `BenchmarkDatabaseTemplateDependencies` | 1 千 / 1 万 / 5 万个游离条目,筛选/排序需要两个有依赖关系的模板,另有五个显示模板,每页 50 条 | 完整计算与按依赖计算对照,包含计划构建、字段渲染、筛选/排序和分页;每次迭代清除已渲染集合缓存 |
| `BenchmarkIndexProjection` | 1 千 / 5 千 / 2 万个段落,一处普通正文变化 | 独立标题父级查找、请求内统一解析,以及两个主块投影对照;均包含完整附属投影,不含 SQL 写入 |
| `BenchmarkDatabaseViewOrderReuse` | 100 / 1 千 / 1 万 / 5 万个游离条目,使用同一模板依赖夹具,每页 50 条 | 源解析及完整处理、顺序未命中或顺序复用;内容相同的对照快照共用原始/规范化缓存,但不参与跨请求复用;冷模式改变临时视图名称,包含指纹及准入成本 |
+| `BenchmarkAttributeViewOrderFingerprint` | 1 千 / 1 万 / 5 万条,同一模板依赖夹具,固定已解析的普通来源 | 资格检查、依赖规划及完整指纹;不含源解析或页面渲染,不能将其与独立整页基准的中位数精确相减 |
+| `BenchmarkMarkTextContext` | 20 / 2 万次重复 `alpha & beta `,匹配 `alpha` | 无取消来源与可取消来源的完整高亮;可取消来源在测量期间保持有效,用于评估正常请求的检查成本 |
+| `BenchmarkSearchProcessingContext` | 单个块的正文及首子块文本包含 20 / 2 万次重复 `alpha & beta `,并包含名称、别名、备注、标签和路径 | 有效可取消请求的完整块结果加工;包含高亮、截断及转义,不含查询、计数或前端 |
| `BenchmarkFTSExactCountReuse` | 1 千 / 1 万 / 10 万 / 100 万个块,每篇 100 块;全部、0.1% 或无块命中,取前 50 块 | 热内存 FTS 行解码及精确块/文档计数;无缓存的分开读取与冷/热快照计数对照,冷模式包含缓存清理 |
| `BenchmarkDocumentReadBoundarySource` | 1 千 / 5 千 / 2 万个扁平段落,每块 128 字节 ASCII 正文 | 单独捕获来源,或全局刷新与读取边界下的完整加载;热模式使用正文缓存,冷模式每次移除正文缓存;均复用操作系统文件缓存,不含排队积压和响应渲染 |
| `BenchmarkDocumentSearchCandidates` | 1 万 / 10 万 / 100 万个块,每篇 100 块;全部文档、一篇文档或无文档命中 | 无候选、扫描块以生成根 ID,以及预建文档 trigram 索引三条路径的完整文档查询、计数和行解码;`candidate_build_ms` 和 `candidate_bytes` 单独记录索引构建和 SQLite 页面增长 |
@@ -91,6 +101,22 @@ go test -tags 'fts5 sqlcipher' ./model -run '^$' -bench '^BenchmarkDocument(Sear
可通过子基准筛选缩小规模,例如 `-bench '^BenchmarkDocumentSearch$/^10000$'`。数据库建立和夹具生成不在计时循环内。显示/模板基准在迭代间复用属性视图,顺序复用基准每次解析新视图;原始/规范化源缓存均已预热,不代表冷启动打开。`-benchmem` 测量 Go 分配,不是 SQLite 原生分配或总 RSS。基准结果是对应路径的基线,不是应用延迟或整体提速结论。FTS 必须包括低命中及无命中查询,因为版本/快照校验可能比它们的少量计数更贵。
+## 指纹与结果加工对照
+
+2026-10-19,在基于 `9539ed7d` 的后续工作树上,使用 Windows amd64、Intel i7-8750H、Go 1.27.2 及 `fts5 sqlcipher` 测量。对照通过 Go 源码覆盖恢复原指纹规划器,或恢复原搜索结果加工及高亮实现,其余代码和夹具一致。视图夹具为九个字段,其中两个模板依赖用于筛选/排序、五个模板仅用于显示,每页 50 条;每项为三组、每组执行三次后的中位数。结果加工使用 `BenchmarkSearchProcessingContext`,每组运行至少 300 ms,重复三组。
+
+| 路径 | 原实现 | 后续实现 |
+|---|---|---|
+| 1 千行,顺序缓存命中 | 41.6 ms | 25.8 ms |
+| 1 万行,顺序缓存命中 | 281 ms | 177 ms |
+| 1 万行,顺序缓存未命中 | 949 ms | 727 ms |
+| 1 万行,不复用顺序的对照路径 | 710 ms | 706 ms |
+| 260 字节正文的完整结果加工 | 38.3 µs | 34.4 µs |
+| 26 万字节正文的完整结果加工 | 25.7 ms | 21.7 ms |
+| 26 万字节正文,结果加工 Go 分配量 | 10.0 MB/op | 7.81 MB/op |
+
+单独的万行资格检查、依赖规划及完整指纹基准约为 42 ms,来源解析不包含在内。空队列事务边界约为 29 ns/op、零分配。顺序缓存未命中指临时视图名称改变,不是操作系统冷文件缓存。三组样本仍有波动,以上只说明固定路径的成本变化,不代表 P95、真实工作区交互、进程峰值内存或只与页大小相关的处理。
+
## 文档候选实验
候选查询及 trigram 索引只存在于测试和基准,实际搜索和存储不使用它们。扫描实验用一个字面子串产生候选根 ID,继续通过完整查询确定结果、计数和顺序;包含逗号、LIKE 通配符和 NUL 的候选词回退。夹具对照包含大小写、路径匹配、过滤、引号、跨块关键词、分隔符、NUL、全部排序方式和分页,只证明这些夹具等价,不代表已经证明任意查询计划和聚合顺序等价。
@@ -140,7 +166,10 @@ go test ./util -run Performance -count=1
go test -tags fts5 ./sql -run 'TestAuxiliary|TestUpsertTree|TestStaticTemplateKeyDependencies' -count=1
go test ./model -run 'TestAttributeViewTemplatePlan|TestRenderAttributeViewUsesTemplateDependencyPlan|TestShouldDeferAttributeViewTemplateValues|TestRenderAttributeViewDefersDisplayOnlyTemplatesUntilAfterPagination' -count=1
go 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 -tags 'fts5 sqlcipher' ./sql ./model -run 'TestTreeIndexChanges|TestIndexHeading|TestIndexProjection|TestTransactionIndexChanges|TestFTSCount|TestReusableTemplateKey|TestAttributeViewOrder' -count=1
+go test ./search -run 'TestMarkTextContext' -count=1
+go test -tags 'fts5 sqlcipher' ./model -run 'TestSearchProcessing' -count=1
+go test ./search -run '^$' -fuzz '^FuzzMarkTextContextMatchesComplete$' -fuzztime=20s -parallel=2
go test -race ./cache -run TestAVOrderedIDs -count=1
go test -tags 'fts5 sqlcipher' ./model ./filesys -run 'TestDocumentReadBoundary|TestCachedTreeSource|TestAssetRelinkLockCancels|TestDocumentSearchCandidate' -count=1
go test -race -tags 'fts5 sqlcipher' ./model ./filesys -run 'TestDocumentReadBoundary|TestCachedTreeSource|TestAssetRelinkLockCancels|TestQueuedTransactionWaitForCommit|TestFlushTxQueueWaitsForDequeuedTransaction|TestWaitForSubmittedTransactionBatch|TestTransactionCompletion' -count=1
diff --git a/kernel/model/attribute_view_order_fingerprint.go b/kernel/model/attribute_view_order_fingerprint.go
new file mode 100644
index 0000000000..c6065534e4
--- /dev/null
+++ b/kernel/model/attribute_view_order_fingerprint.go
@@ -0,0 +1,122 @@
+package model
+
+import (
+ "encoding/binary"
+ "encoding/json"
+ "hash"
+
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+// attributeViewOrderFingerprint 对普通值保留全部 JSON 字段的输入,缓冲区不随字段内容增长。
+type attributeViewOrderFingerprint struct {
+ digest hash.Hash
+ buffer [4096]byte
+ used int
+}
+
+func (fingerprint *attributeViewOrderFingerprint) flush() {
+ _, _ = fingerprint.digest.Write(fingerprint.buffer[:fingerprint.used])
+ fingerprint.used = 0
+}
+
+func (fingerprint *attributeViewOrderFingerprint) flag(value bool) {
+ if fingerprint.used == len(fingerprint.buffer) {
+ fingerprint.flush()
+ }
+ if value {
+ fingerprint.buffer[fingerprint.used] = 1
+ } else {
+ fingerprint.buffer[fingerprint.used] = 0
+ }
+ fingerprint.used++
+}
+
+func (fingerprint *attributeViewOrderFingerprint) integer(value int64) {
+ if len(fingerprint.buffer)-fingerprint.used < binary.MaxVarintLen64 {
+ fingerprint.flush()
+ }
+ fingerprint.used += binary.PutVarint(fingerprint.buffer[fingerprint.used:], value)
+}
+
+func (fingerprint *attributeViewOrderFingerprint) text(value string) {
+ if len(fingerprint.buffer)-fingerprint.used < binary.MaxVarintLen64 {
+ fingerprint.flush()
+ }
+ fingerprint.used += binary.PutUvarint(fingerprint.buffer[fingerprint.used:], uint64(len(value)))
+ for len(value) > 0 {
+ if fingerprint.used == len(fingerprint.buffer) {
+ fingerprint.flush()
+ }
+ copied := copy(fingerprint.buffer[fingerprint.used:], value)
+ fingerprint.used += copied
+ value = value[copied:]
+ }
+}
+
+func plainAttributeViewOrderValue(value *av.Value) bool {
+ return value == nil || (value.Number == nil && value.Date == nil && value.MSelect == nil &&
+ value.URL == nil && value.Email == nil && value.Phone == nil && value.Location == nil &&
+ value.MAsset == nil && value.Created == nil && value.Updated == nil && value.Checkbox == nil &&
+ value.Relation == nil && value.Rollup == nil && (value.Text == nil || value.Text.Rich == nil))
+}
+
+func (fingerprint *attributeViewOrderFingerprint) value(value *av.Value) {
+ fingerprint.flag(value != nil)
+ if value == nil {
+ return
+ }
+ fingerprint.text(value.ID)
+ fingerprint.text(value.KeyID)
+ fingerprint.text(value.BlockID)
+ fingerprint.text(string(value.Type))
+ fingerprint.flag(value.IsDetached)
+ fingerprint.integer(value.CreatedAt)
+ fingerprint.integer(value.UpdatedAt)
+ fingerprint.text(value.RenderedContent)
+ fingerprint.flag(value.HasRenderTemplate)
+ fingerprint.flag(value.Block != nil)
+ if block := value.Block; block != nil {
+ fingerprint.text(block.CollectionRuleID)
+ fingerprint.text(block.ID)
+ fingerprint.text(block.Icon)
+ fingerprint.text(block.Content)
+ fingerprint.text(string(block.RefSubtype))
+ fingerprint.integer(block.Created)
+ fingerprint.integer(block.Updated)
+ }
+ fingerprint.flag(value.Text != nil)
+ if value.Text != nil {
+ fingerprint.text(value.Text.Content)
+ }
+ fingerprint.flag(value.Template != nil)
+ if value.Template != nil {
+ fingerprint.text(value.Template.Content)
+ }
+}
+
+func (fingerprint *attributeViewOrderFingerprint) writeValues(encoder *json.Encoder, values []*av.Value) error {
+ for start := 0; start < len(values); start += 128 {
+ chunk := values[start:min(start+128, len(values))]
+ plain := true
+ for _, value := range chunk {
+ if !plainAttributeViewOrderValue(value) {
+ plain = false
+ break
+ }
+ }
+ fingerprint.flag(plain)
+ if plain {
+ for _, value := range chunk {
+ fingerprint.value(value)
+ }
+ } else {
+ fingerprint.flush()
+ if err := encoder.Encode(chunk); err != nil {
+ return err
+ }
+ }
+ }
+ fingerprint.flush()
+ return nil
+}
diff --git a/kernel/model/attribute_view_order_fingerprint_test.go b/kernel/model/attribute_view_order_fingerprint_test.go
new file mode 100644
index 0000000000..9db696679d
--- /dev/null
+++ b/kernel/model/attribute_view_order_fingerprint_test.go
@@ -0,0 +1,148 @@
+package model
+
+import (
+ "crypto/sha256"
+ "encoding/json"
+ "math"
+ "reflect"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+func orderValueFingerprint(values []*av.Value) ([32]byte, error) {
+ digest := sha256.New()
+ encoder := json.NewEncoder(digest)
+ if err := encoder.Encode(len(values)); err != nil {
+ return [32]byte{}, err
+ }
+ fingerprint := attributeViewOrderFingerprint{digest: digest}
+ if err := fingerprint.writeValues(encoder, values); err != nil {
+ return [32]byte{}, err
+ }
+ var result [32]byte
+ digest.Sum(result[:0])
+ return result, nil
+}
+
+func TestAttributeViewOrderFingerprintCoversPersistedValueFields(t *testing.T) {
+ // 增加字段时同时决定流式表示或完整 JSON 回退,避免新字段静默漏出失效边界。
+ for _, test := range []struct {
+ typ reflect.Type
+ fields []string
+ }{
+ {reflect.TypeFor[av.Value](), []string{"ID", "KeyID", "BlockID", "Type", "IsDetached", "CreatedAt", "UpdatedAt",
+ "Block", "Text", "Number", "Date", "MSelect", "URL", "Email", "Phone", "Location", "MAsset", "Template",
+ "Created", "Updated", "Checkbox", "Relation", "Rollup", "RenderedContent", "HasRenderTemplate"}},
+ {reflect.TypeFor[av.ValueBlock](), []string{"CollectionRuleID", "ID", "Icon", "Content", "RefSubtype", "Created", "Updated"}},
+ {reflect.TypeFor[av.ValueText](), []string{"Content", "Rich"}},
+ {reflect.TypeFor[av.ValueTemplate](), []string{"Content"}},
+ } {
+ var actual []string
+ for _, field := range reflect.VisibleFields(test.typ) {
+ if field.IsExported() && field.Tag.Get("json") != "-" {
+ actual = append(actual, field.Name)
+ }
+ }
+ slices.Sort(actual)
+ slices.Sort(test.fields)
+ if !slices.Equal(actual, test.fields) {
+ t.Fatalf("%s fingerprint field coverage changed: got %v, want %v", test.typ, actual, test.fields)
+ }
+ }
+
+ for _, field := range reflect.VisibleFields(reflect.TypeFor[av.Value]()) {
+ if field.Tag.Get("json") == "-" {
+ continue
+ }
+ t.Run(field.Name, func(t *testing.T) {
+ value := &av.Value{}
+ before, err := orderValueFingerprint([]*av.Value{value})
+ if err != nil {
+ t.Fatal(err)
+ }
+ changed := reflect.ValueOf(value).Elem().FieldByName(field.Name)
+ switch changed.Kind() {
+ case reflect.String:
+ changed.SetString("changed")
+ case reflect.Bool:
+ changed.SetBool(true)
+ case reflect.Int64:
+ changed.SetInt(-1)
+ case reflect.Pointer:
+ changed.Set(reflect.New(changed.Type().Elem()))
+ case reflect.Slice:
+ changed.Set(reflect.MakeSlice(changed.Type(), 1, 1))
+ default:
+ t.Fatalf("unhandled value field %s", field.Name)
+ }
+ after, err := orderValueFingerprint([]*av.Value{value})
+ if err != nil || before == after {
+ t.Fatalf("field did not invalidate fingerprint: %v", err)
+ }
+ })
+ }
+}
+
+func TestAttributeViewOrderFingerprintRetainsPayloadFieldsAndBoundaries(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ first, other []*av.Value
+ }{
+ {"string boundaries", []*av.Value{{ID: "ab", KeyID: "c"}}, []*av.Value{{ID: "a", KeyID: "bc"}}},
+ {"nil and empty value", []*av.Value{nil}, []*av.Value{{}}},
+ {"nil and empty text", []*av.Value{{}}, []*av.Value{{Text: &av.ValueText{}}}},
+ {"empty slice", nil, []*av.Value{{}}},
+ {"long text tail", []*av.Value{{Text: &av.ValueText{Content: strings.Repeat("🙂", 4096)}}},
+ []*av.Value{{Text: &av.ValueText{Content: strings.Repeat("🙂", 4096) + "\x00"}}}},
+ {"fallback payload", []*av.Value{{Number: &av.ValueNumber{Content: 1}}},
+ []*av.Value{{Number: &av.ValueNumber{Content: 2}}}},
+ {"multiple payloads", []*av.Value{{Text: &av.ValueText{Content: "plain"}, Number: &av.ValueNumber{Content: 1}}},
+ []*av.Value{{Text: &av.ValueText{Content: "changed"}, Number: &av.ValueNumber{Content: 1}}}},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ first, err := orderValueFingerprint(test.first)
+ if err != nil {
+ t.Fatal(err)
+ }
+ other, err := orderValueFingerprint(test.other)
+ if err != nil || first == other {
+ t.Fatalf("different inputs share fingerprint: %v", err)
+ }
+ repeated, err := orderValueFingerprint(test.first)
+ if err != nil || repeated != first {
+ t.Fatalf("fingerprint is not deterministic: %v", err)
+ }
+ })
+ }
+ for _, field := range reflect.VisibleFields(reflect.TypeFor[av.ValueBlock]()) {
+ t.Run("block/"+field.Name, func(t *testing.T) {
+ value := &av.Value{Block: &av.ValueBlock{}}
+ before, _ := orderValueFingerprint([]*av.Value{value})
+ changed := reflect.ValueOf(value.Block).Elem().FieldByName(field.Name)
+ if changed.Kind() == reflect.String {
+ changed.SetString("changed")
+ } else {
+ changed.SetInt(math.MinInt64)
+ }
+ after, err := orderValueFingerprint([]*av.Value{value})
+ if err != nil || before == after {
+ t.Fatalf("block field did not invalidate fingerprint: %v", err)
+ }
+ })
+ }
+ values := make([]*av.Value, 257)
+ values[128] = &av.Value{Template: &av.ValueTemplate{Content: "before"}}
+ before, _ := orderValueFingerprint(values)
+ values[128].Template.Content = "after"
+ after, err := orderValueFingerprint(values)
+ if err != nil || before == after {
+ t.Fatalf("later chunk did not invalidate fingerprint: %v", err)
+ }
+ values[0] = &av.Value{Number: &av.ValueNumber{Content: math.NaN()}}
+ if _, err = orderValueFingerprint(values); err == nil {
+ t.Fatal("invalid JSON fallback admitted a fingerprint")
+ }
+}
diff --git a/kernel/model/attribute_view_order_reuse.go b/kernel/model/attribute_view_order_reuse.go
index 73b65ff280..d6e7031a27 100644
--- a/kernel/model/attribute_view_order_reuse.go
+++ b/kernel/model/attribute_view_order_reuse.go
@@ -29,22 +29,24 @@ func planAttributeViewOrderReuse(attrView *av.AttributeView, view *av.View, node
return nil
}
// 实际内存值也参与指纹,避免预览或临时编辑沿用持久化源版本下的旧顺序。
- // 分块编码保留完整输入覆盖,避免为大型视图生成另一份完整 JSON 临时副本。
+ // 常见值以带长度边界的字节流编码,其他值分块使用完整 JSON。
digest := sha256.New()
encoder := json.NewEncoder(digest)
definition := *attrView
definition.KeyValues = nil
err := encoder.Encode(struct {
+ Format string
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)})
+ }{"stream1", &definition, view, nodeID, util.Lang, writable, version, generation, len(attrView.KeyValues)})
if err != nil {
return nil
}
+ valuesDigest := attributeViewOrderFingerprint{digest: digest}
for _, values := range attrView.KeyValues {
if err = encoder.Encode(struct {
Key *av.Key
@@ -53,10 +55,8 @@ func planAttributeViewOrderReuse(attrView *av.AttributeView, view *av.View, node
}{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
- }
+ if err = valuesDigest.writeValues(encoder, values.Values); err != nil {
+ return nil
}
}
var fingerprint [32]byte
diff --git a/kernel/model/attribute_view_order_reuse_benchmark_test.go b/kernel/model/attribute_view_order_reuse_benchmark_test.go
index 15c7ea148d..b19302a72e 100644
--- a/kernel/model/attribute_view_order_reuse_benchmark_test.go
+++ b/kernel/model/attribute_view_order_reuse_benchmark_test.go
@@ -66,3 +66,22 @@ func BenchmarkDatabaseViewOrderReuse(b *testing.B) {
}
}
}
+
+func BenchmarkAttributeViewOrderFingerprint(b *testing.B) {
+ for _, size := range []int{1000, 10000, 50000} {
+ b.Run(fmt.Sprint(size), func(b *testing.B) {
+ load := setupAttributeViewOrderReuseFixture(b, av.LayoutTypeTable, size, 5)
+ database := load()
+ view := database.Views[0]
+ checkAttrView(database, view)
+ upgradeAttributeViewSpec(database)
+ b.ReportAllocs()
+ for b.Loop() {
+ if planAttributeViewOrderReuse(database, view, "", false) == nil {
+ b.Fatal("eligible source did not produce a fingerprint")
+ }
+ }
+ b.ReportMetric(float64(size), "rows/op")
+ })
+ }
+}
diff --git a/kernel/model/document_read_boundary.go b/kernel/model/document_read_boundary.go
index 20e8e130e6..bfed668440 100644
--- a/kernel/model/document_read_boundary.go
+++ b/kernel/model/document_read_boundary.go
@@ -15,6 +15,7 @@ func loadDocumentAtTransactionBoundary(id, boxID string, timing *util.Performanc
}
if source != nil {
timing.Count("source_snapshot", 1)
+ timing.Stage("parse_source")
return source.Parse(util.NewLute())
}
// 完整加载可能涉及生命周期等待、格式订正与补建父文档,沿用全局完成等待及原有锁顺序。
@@ -36,14 +37,16 @@ func captureDocumentSourceAtTransactionBoundary(id, boxID string, timing *util.P
return
}
source, err = filesys.CaptureCachedTreeSource(bt.BoxID, bt.Path)
- })
+ }, timing)
return
}
-func readAtTransactionBoundary(read func()) {
+func readAtTransactionBoundary(read func(), timing *util.Performance) {
+ timing.Stage("wait_transactions")
flushLock.RLock()
if txQueueSize() == 0 {
defer flushLock.RUnlock()
+ timing.Count("flushed_transactions", 0)
read()
return
}
@@ -54,7 +57,10 @@ func readAtTransactionBoundary(read func()) {
isFlushing.Store(false)
flushLock.Unlock()
}()
- for _, transaction := range takeQueuedTransactions() {
+ timing.Stage("flush_transactions")
+ transactions := takeQueuedTransactions()
+ timing.Count("flushed_transactions", int64(len(transactions)))
+ for _, transaction := range transactions {
flushTx(transaction)
}
read()
diff --git a/kernel/model/document_read_boundary_fts5_test.go b/kernel/model/document_read_boundary_fts5_test.go
index 0612f99b85..9ccebccb3a 100644
--- a/kernel/model/document_read_boundary_fts5_test.go
+++ b/kernel/model/document_read_boundary_fts5_test.go
@@ -208,7 +208,7 @@ func TestDocumentReadBoundaryReturnsBeforeLaterWriteAndKeepsUndoCompletion(t *te
queued := []*Transaction{later}
PerformTransactions(&queued)
snapshot, err = loadTreeByBlockIDInBox0(fixture.childID, "", false)
- })
+ }, nil)
if err != nil || treenode.GetNodeInTree(snapshot, fixture.childID).Text() != "captured source" {
t.Fatalf("read did not retain the source at its boundary: %v", err)
}
diff --git a/kernel/model/document_read_boundary_test.go b/kernel/model/document_read_boundary_test.go
index 8137c75d04..33c7763859 100644
--- a/kernel/model/document_read_boundary_test.go
+++ b/kernel/model/document_read_boundary_test.go
@@ -15,7 +15,7 @@ func TestDocumentReadBoundarySharesReadsAndExcludesWrites(t *testing.T) {
var readers sync.WaitGroup
for range 2 {
readers.Go(func() {
- readAtTransactionBoundary(func() { entered <- struct{}{}; <-resume })
+ readAtTransactionBoundary(func() { entered <- struct{}{}; <-resume }, nil)
})
}
for range 2 {
@@ -58,7 +58,7 @@ func TestDocumentReadBoundaryFinishesCapturedBatchAndLeavesLaterTransactions(t *
next := []*Transaction{later}
PerformTransactions(&next)
observed <- finished(first) && finished(second) && !finished(later)
- })
+ }, nil)
close(readDone)
}()
flushLock.Unlock()
@@ -77,7 +77,7 @@ func TestDocumentReadBoundaryReleasesLockAfterReadPanic(t *testing.T) {
t.Error("read panic was unexpectedly swallowed")
}
}()
- readAtTransactionBoundary(func() { panic("injected snapshot read failure") })
+ readAtTransactionBoundary(func() { panic("injected snapshot read failure") }, nil)
}()
if !flushLock.TryLock() {
t.Fatal("failed source capture retained the transaction lock")
@@ -89,6 +89,6 @@ func BenchmarkDocumentReadBoundaryEmpty(b *testing.B) {
FlushTxQueue()
b.ReportAllocs()
for b.Loop() {
- readAtTransactionBoundary(func() {})
+ readAtTransactionBoundary(func() {}, nil)
}
}
diff --git a/kernel/model/search.go b/kernel/model/search.go
index f595d0f7d0..2a5e99a9d9 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -2669,16 +2669,24 @@ func loadFTSAndHPathMatchBlocks(ctx context.Context, matches []ftsAndHPathMatch,
if nil == sqlBlock {
continue
}
- ret = append(ret, fromFTSAndHPathMatchSQLBlock(sqlBlock, match.source, rawQuery, beforeLen))
+ block := fromFTSAndHPathMatchSQLBlockContext(ctx, sqlBlock, match.source, rawQuery, beforeLen)
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
+ ret = append(ret, block)
}
return
}
func fromFTSAndHPathMatchSQLBlock(sqlBlock *sql.Block, source int, rawQuery string, beforeLen int) *Block {
+ return fromFTSAndHPathMatchSQLBlockContext(context.Background(), sqlBlock, source, rawQuery, beforeLen)
+}
+
+func fromFTSAndHPathMatchSQLBlockContext(ctx context.Context, sqlBlock *sql.Block, source int, rawQuery string, beforeLen int) *Block {
if 0 == source {
- return fromSQLBlockWithHPathTerms(sqlBlock, "", "", beforeLen)
+ return fromSQLBlockWithHPathTermsContext(ctx, sqlBlock, "", "", beforeLen)
}
- return fromHPathSearchSQLBlock(sqlBlock, rawQuery, beforeLen)
+ return fromSQLBlockWithHPathTermsContext(ctx, sqlBlock, "", rawQuery, beforeLen)
}
func queryFTSSnippetBlocksByRowID(ctx context.Context, query string, rowIDs []int64, boxID string) (ret map[int64]*sql.Block, err error) {
@@ -2897,12 +2905,15 @@ func fullTextSearchByLikeWithRootInBox(ctx context.Context, query, boxFilter, pa
}
if 1 == result[i]["matchSource"].(int64) {
docContent, _ := result[i]["docContent"].(string)
- contentTerms, hPathTerms := partitionSearchTerms(docContent, terms)
- ret = append(ret, fromHPathSearchSQLBlockWithContentTerms(resultBlock, hPathTerms, contentTerms, beforeLen))
+ contentTerms, hPathTerms := partitionSearchTermsContext(ctx, docContent, terms)
+ ret = append(ret, fromSQLBlockWithHPathTermsContext(ctx, resultBlock, contentTerms, hPathTerms, beforeLen))
} else {
- ret = append(ret, fromSQLBlockWithHPathTerms(resultBlock, terms, "", beforeLen))
+ ret = append(ret, fromSQLBlockWithHPathTermsContext(ctx, resultBlock, terms, "", beforeLen))
}
}
+ if ctx.Err() != nil {
+ return nil, 0, 0
+ }
if 1 > len(ret) {
ret = []*Block{}
}
@@ -3128,6 +3139,13 @@ func highlightByRegexpInBox(query, typeFilter, id, boxID string) (ret []string)
}
func markSearch(text string, keyword string, beforeLen int) (marked string, score float64) {
+ return markSearchContext(context.Background(), text, keyword, beforeLen, true)
+}
+
+func markSearchContext(ctx context.Context, text, keyword string, beforeLen int, scoreResult bool) (marked string, score float64) {
+ if ctx.Err() != nil {
+ return
+ }
confSearchSnapshot := Conf.LoadSearch()
if 0 == len(keyword) {
@@ -3143,13 +3161,19 @@ func markSearch(text string, keyword string, beforeLen int) (marked string, scor
keyword = strings.Join(keywords, search.TermSep)
marked = strings.ReplaceAll(text, search.SearchMarkLeft, "")
marked = strings.ReplaceAll(marked, search.SearchMarkRight, "")
- _, marked = search.MarkText(marked, keyword, beforeLen, confSearchSnapshot.CaseSensitive)
+ _, marked = search.MarkTextContext(ctx, marked, keyword, beforeLen, confSearchSnapshot.CaseSensitive)
+ if ctx.Err() != nil {
+ return "", 0
+ }
marked = util.EscapeHTML(marked)
return
}
- pos, marked := search.MarkText(text, keyword, beforeLen, confSearchSnapshot.CaseSensitive)
- if -1 < pos {
+ pos, marked := search.MarkTextContext(ctx, text, keyword, beforeLen, confSearchSnapshot.CaseSensitive)
+ if ctx.Err() != nil {
+ return "", 0
+ }
+ if scoreResult && -1 < pos {
if 0 == pos {
score = 1
}
@@ -3162,15 +3186,25 @@ func markSearch(text string, keyword string, beforeLen int) (marked string, scor
}
func partitionSearchTerms(text, terms string) (matched, unmatched string) {
+ return partitionSearchTermsContext(context.Background(), text, terms)
+}
+
+func partitionSearchTermsContext(ctx context.Context, text, terms string) (matched, unmatched string) {
var matchedTerms, unmatchedTerms []string
for _, term := range search.SplitKeyword(terms) {
- pos, _ := search.MarkText(text, term, -1, Conf.Search.Load().CaseSensitive)
+ if ctx.Err() != nil {
+ return "", ""
+ }
+ pos, _ := search.MarkTextContext(ctx, text, term, -1, Conf.Search.Load().CaseSensitive)
if -1 < pos {
matchedTerms = append(matchedTerms, term)
} else {
unmatchedTerms = append(unmatchedTerms, term)
}
}
+ if ctx.Err() != nil {
+ return "", ""
+ }
return strings.Join(matchedTerms, search.TermSep), strings.Join(unmatchedTerms, search.TermSep)
}
@@ -3183,7 +3217,11 @@ func fromSQLBlocksContext(ctx context.Context, sqlBlocks *[]*sql.Block, terms st
if ctx.Err() != nil {
return nil
}
- ret = append(ret, fromSQLBlock(sqlBlock, terms, beforeLen))
+ block := fromSQLBlockWithHPathTermsContext(ctx, sqlBlock, terms, terms, beforeLen)
+ if ctx.Err() != nil {
+ return nil
+ }
+ ret = append(ret, block)
}
return
}
@@ -3193,7 +3231,11 @@ func fromSQLBlock(sqlBlock *sql.Block, terms string, beforeLen int) (block *Bloc
}
func fromSQLBlockWithHPathTerms(sqlBlock *sql.Block, contentTerms, hPathTerms string, beforeLen int) (block *Block) {
- if nil == sqlBlock {
+ return fromSQLBlockWithHPathTermsContext(context.Background(), sqlBlock, contentTerms, hPathTerms, beforeLen)
+}
+
+func fromSQLBlockWithHPathTermsContext(ctx context.Context, sqlBlock *sql.Block, contentTerms, hPathTerms string, beforeLen int) (block *Block) {
+ if nil == sqlBlock || ctx.Err() != nil {
return
}
@@ -3211,9 +3253,15 @@ func fromSQLBlockWithHPathTerms(sqlBlock *sql.Block, contentTerms, hPathTerms st
}
}
- content, _ = markSearch(content, contentTerms, beforeLen)
+ content, _ = markSearchContext(ctx, content, contentTerms, beforeLen, false)
+ if ctx.Err() != nil {
+ return nil
+ }
content = maxContent(content, 5120)
- tag, _ := markSearch(sqlBlock.Tag, contentTerms, beforeLen)
+ tag, _ := markSearchContext(ctx, sqlBlock.Tag, contentTerms, beforeLen, false)
+ if ctx.Err() != nil {
+ return nil
+ }
markdown := maxContent(sqlBlock.Markdown, 5120)
fContent := util.EscapeHTML(sqlBlock.FContent) // fContent 会用于和 content 对比,在反链计算时用于判断是否是列表项下第一个子块,所以也需要转义 https://github.com/siyuan-note/siyuan/issues/11001
block = &Block{
@@ -3249,21 +3297,27 @@ func fromSQLBlockWithHPathTerms(sqlBlock *sql.Block, contentTerms, hPathTerms st
if "" != hPathTerms {
hPathBeforeLen = -1
}
- markBlockHPath(block, sqlBlock.HPath, hPathTerms, hPathBeforeLen)
- if "" != block.Name {
- block.Name, _ = markSearch(block.Name, contentTerms, 256)
- }
- if "" != block.Alias {
- block.Alias, _ = markSearch(block.Alias, contentTerms, 256)
+ markBlockHPathContext(ctx, block, sqlBlock.HPath, hPathTerms, hPathBeforeLen)
+ for _, field := range []*string{&block.Name, &block.Alias, &block.Memo} {
+ if ctx.Err() != nil {
+ return nil
+ }
+ if *field != "" {
+ *field, _ = markSearchContext(ctx, *field, contentTerms, 256, false)
+ }
}
- if "" != block.Memo {
- block.Memo, _ = markSearch(block.Memo, contentTerms, 256)
+ if ctx.Err() != nil {
+ return nil
}
return
}
func markBlockHPath(block *Block, hPath, terms string, beforeLen int) {
- hPath, _ = markSearch(hPath, terms, beforeLen)
+ markBlockHPathContext(context.Background(), block, hPath, terms, beforeLen)
+}
+
+func markBlockHPathContext(ctx context.Context, block *Block, hPath, terms string, beforeLen int) {
+ hPath, _ = markSearchContext(ctx, hPath, terms, beforeLen, false)
if !strings.HasPrefix(hPath, "/") {
hPath = "/" + hPath
}
diff --git a/kernel/model/search_attribute_view.go b/kernel/model/search_attribute_view.go
index 790c345332..a0ae887d7f 100644
--- a/kernel/model/search_attribute_view.go
+++ b/kernel/model/search_attribute_view.go
@@ -41,6 +41,9 @@ func compactAttributeViewSearchResultsContext(ctx context.Context, blocks []*Blo
continue
}
tree, err := LoadTreeByBlockIDInExactBox(block.ID, block.Box)
+ if ctx.Err() != nil {
+ return
+ }
if nil != err || nil == tree {
continue
}
@@ -53,6 +56,9 @@ func compactAttributeViewSearchResultsContext(ctx context.Context, blocks []*Blo
avBox = tree.Box
}
attrView, err := av.ParseAttributeViewForIndexInBox(node.AttributeViewID, avBox)
+ if ctx.Err() != nil {
+ return
+ }
if nil != err || nil == attrView {
continue
}
diff --git a/kernel/model/search_processing_context_benchmark_test.go b/kernel/model/search_processing_context_benchmark_test.go
new file mode 100644
index 0000000000..92b5ea2506
--- /dev/null
+++ b/kernel/model/search_processing_context_benchmark_test.go
@@ -0,0 +1,33 @@
+package model
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+)
+
+func BenchmarkSearchProcessingContext(b *testing.B) {
+ previous := Conf
+ Conf = NewAppConf()
+ Conf.Search.Store(conf.NewSearch())
+ b.Cleanup(func() { Conf = previous })
+ for _, repeat := range []int{20, 20000} {
+ b.Run(fmt.Sprint(repeat), func(b *testing.B) {
+ content := strings.Repeat("alpha & beta ", repeat)
+ blocks := []*sql.Block{{ID: "block", Type: "p", Content: content, FContent: content,
+ Name: "alpha", Alias: "beta", Memo: "alpha memo", Tag: "#alpha#", HPath: "/alpha/beta"}}
+ ctx, cancel := context.WithCancel(context.Background())
+ b.Cleanup(cancel)
+ b.ReportAllocs()
+ for b.Loop() {
+ if result := fromSQLBlocksContext(ctx, &blocks, "alpha", 36); len(result) != 1 {
+ b.Fatal("result formatting did not complete")
+ }
+ }
+ })
+ }
+}
diff --git a/kernel/model/search_processing_context_test.go b/kernel/model/search_processing_context_test.go
new file mode 100644
index 0000000000..8fb2bc25be
--- /dev/null
+++ b/kernel/model/search_processing_context_test.go
@@ -0,0 +1,71 @@
+package model
+
+import (
+ "context"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+)
+
+type searchProcessingCancelContext struct {
+ context.Context
+ cancel context.CancelFunc
+ checks atomic.Int32
+}
+
+func (ctx *searchProcessingCancelContext) Err() error {
+ if ctx.checks.Add(1) >= 10 {
+ ctx.cancel()
+ }
+ return ctx.Context.Err()
+}
+
+func TestSearchProcessingContextStopsWithinOneBlock(t *testing.T) {
+ previous := Conf
+ Conf = NewAppConf()
+ Conf.Search.Store(conf.NewSearch())
+ t.Cleanup(func() { Conf = previous })
+ for _, field := range []string{"content", "path", "alias"} {
+ t.Run(field, func(t *testing.T) {
+ block := &sql.Block{ID: "one-block", Type: "p"}
+ content := strings.Repeat("value & ", 200000)
+ switch field {
+ case "content":
+ block.Content = content
+ case "path":
+ block.HPath = content
+ case "alias":
+ block.Alias = content
+ }
+ base, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ ctx := &searchProcessingCancelContext{Context: base, cancel: cancel}
+ blocks := []*sql.Block{block}
+ if got := fromSQLBlocksContext(ctx, &blocks, "missing", 36); len(got) != 0 || base.Err() == nil {
+ t.Fatalf("canceled block formatting completed: count=%d err=%v", len(got), base.Err())
+ }
+ })
+ }
+}
+
+func TestSearchProcessingKeepsHighlightAndRequestedScores(t *testing.T) {
+ previous := Conf
+ Conf = NewAppConf()
+ Conf.Search.Store(conf.NewSearch())
+ t.Cleanup(func() { Conf = previous })
+ for _, text := range []string{"alpha & beta alpha", "A&B", "诗經", "plain", "__@mark__alpha__mark@__"} {
+ for _, keyword := range []string{"alpha", "&", "诗经", ""} {
+ want, score := markSearch(text, keyword, 36)
+ ctx, cancel := context.WithCancel(context.Background())
+ got, gotScore := markSearchContext(ctx, text, keyword, 36, true)
+ textOnly, _ := markSearchContext(ctx, text, keyword, 36, false)
+ cancel()
+ if got != want || gotScore != score || textOnly != want {
+ t.Fatalf("context or score omission changed presentation: text=%q keyword=%q", text, keyword)
+ }
+ }
+ }
+}
diff --git a/kernel/search/mark.go b/kernel/search/mark.go
index 3aaecbfb75..8013de577e 100644
--- a/kernel/search/mark.go
+++ b/kernel/search/mark.go
@@ -17,6 +17,7 @@
package search
import (
+ "context"
"fmt"
"regexp"
"strings"
@@ -37,6 +38,18 @@ func MarkText(text string, keyword string, beforeLen int, caseSensitive bool) (p
return
}
+// MarkTextContext 在匹配和生成高亮期间检查请求取消,不返回未完成的高亮片段。
+func MarkTextContext(ctx context.Context, text, keyword string, beforeLen int, caseSensitive bool) (pos int, marked string) {
+ if ctx.Err() != nil {
+ return -1, ""
+ }
+ if keyword == "" {
+ return -1, text
+ }
+ pos, marked, _ = encloseHighlightingRawContext(ctx, text, SplitKeyword(keyword), "<mark>", "</mark>", caseSensitive, false, beforeLen)
+ return
+}
+
const (
TermSep = "__term@sep__"
SearchMarkLeft = "__@mark__"
@@ -75,14 +88,32 @@ func EncloseHighlightingRaw(text string, keywords []string, openMark, closeMark
// encloseHighlightingRaw 在原始文本上完成上下文截取和高亮,beforeLen 小于零时保留全部前文。
func encloseHighlightingRaw(text string, keywords []string, openMark, closeMark string, caseSensitive, splitWords bool, beforeLen int) (pos int, ret string, matched bool) {
+ return encloseHighlightingRawContext(context.Background(), text, keywords, openMark, closeMark, caseSensitive, splitWords, beforeLen)
+}
+
+func encloseHighlightingRawContext(ctx context.Context, text string, keywords []string, openMark, closeMark string, caseSensitive, splitWords bool, beforeLen int) (pos int, ret string, matched bool) {
pos = -1
+ if ctx.Err() != nil {
+ return
+ }
reg, err := compileHighlightingRegexp(keywords, caseSensitive, splitWords)
+ if ctx.Err() != nil {
+ return
+ }
if err != nil {
ret = html.EscapeString(text)
return
}
- indexes := reg.FindAllStringIndex(text, -1)
+ var indexes [][]int
+ if len(text) <= 4096 || ctx.Done() == nil || splitWords {
+ indexes = reg.FindAllStringIndex(text, -1)
+ } else {
+ indexes = findHighlightingMatchesContext(ctx, reg, text, keywords)
+ }
+ if ctx.Err() != nil {
+ return
+ }
if 1 > len(indexes) {
ret = html.EscapeString(text)
return
@@ -94,6 +125,9 @@ func encloseHighlightingRaw(text string, keywords []string, openMark, closeMark
start = indexes[0][0]
var count int
for 0 < start { // 关键字前面太长的话缩短一些
+ if ctx.Err() != nil {
+ return -1, "", false
+ }
_, size := utf8.DecodeLastRuneInString(text[:start])
start -= size
count++
@@ -111,6 +145,9 @@ func encloseHighlightingRaw(text string, keywords []string, openMark, closeMark
}
last := start
for _, index := range indexes {
+ if ctx.Err() != nil {
+ return -1, "", false
+ }
buf.WriteString(html.EscapeString(text[last:index[0]]))
if !matched {
pos = buf.Len()
@@ -126,6 +163,9 @@ func encloseHighlightingRaw(text string, keywords []string, openMark, closeMark
// 避免反斜杠转义生成的高亮标签 https://github.com/siyuan-note/siyuan/issues/9790
ret = strings.ReplaceAll(ret, "\\<span", "\\\\<span")
+ if ctx.Err() != nil {
+ return -1, "", false
+ }
return
}
diff --git a/kernel/search/mark_context.go b/kernel/search/mark_context.go
new file mode 100644
index 0000000000..32f66e2b7b
--- /dev/null
+++ b/kernel/search/mark_context.go
@@ -0,0 +1,64 @@
+package search
+
+import (
+ "context"
+ "regexp"
+ "unicode/utf8"
+)
+
+const highlightingWindowBytes = 64 * 1024
+
+// findHighlightingMatchesContext 用于不带词边界的字面高亮表达式,繁简及大小写等价类仍各匹配一个字符。
+// 窗口保留完整关键字的重叠区,只接纳窗口内开始的匹配,避免截断跨窗口关键字。
+func findHighlightingMatchesContext(ctx context.Context, expression *regexp.Regexp, text string, keywords []string) (matches [][]int) {
+ lookahead := 0
+ for _, keyword := range keywords {
+ characters := utf8.RuneCountInString(keyword)
+ if characters >= len(text)/utf8.UTFMax {
+ lookahead = len(text)
+ break
+ }
+ lookahead = max(lookahead, characters*utf8.UTFMax)
+ }
+ previousEnd := -1
+ for offset := 0; offset <= len(text); {
+ if ctx.Err() != nil {
+ return nil
+ }
+ boundary := offset + min(highlightingWindowBytes, len(text)-offset)
+ for adjustment := 0; adjustment < utf8.UTFMax-1 && boundary < len(text) && !utf8.RuneStart(text[boundary]); adjustment++ {
+ boundary++
+ }
+ end := boundary + min(lookahead, len(text)-boundary)
+ for adjustment := 0; adjustment < utf8.UTFMax-1 && end < len(text) && !utf8.RuneStart(text[end]); adjustment++ {
+ end++
+ }
+ match := expression.FindStringIndex(text[offset:end])
+ if ctx.Err() != nil {
+ return nil
+ }
+ if match == nil || (offset+match[0] >= boundary && boundary < len(text)) {
+ if boundary == len(text) {
+ return matches
+ }
+ offset = boundary
+ continue
+ }
+ start, finish := offset+match[0], offset+match[1]
+ // 连续匹配的交界可能再次报告空匹配,沿用 regexp 对相邻空匹配的抑制规则。
+ if start != finish || finish != previousEnd {
+ match[0], match[1] = start, finish
+ matches = append(matches, match)
+ }
+ previousEnd = finish
+ offset = finish
+ if start == finish {
+ if offset == len(text) {
+ return matches
+ }
+ _, size := utf8.DecodeRuneInString(text[offset:])
+ offset += size
+ }
+ }
+ return
+}
diff --git a/kernel/search/mark_context_test.go b/kernel/search/mark_context_test.go
new file mode 100644
index 0000000000..0921452383
--- /dev/null
+++ b/kernel/search/mark_context_test.go
@@ -0,0 +1,136 @@
+package search
+
+import (
+ "context"
+ "fmt"
+ "math/rand"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type highlightingCancelContext struct {
+ context.Context
+ cancel context.CancelFunc
+ checks atomic.Int32
+ after int32
+}
+
+func (ctx *highlightingCancelContext) Err() error {
+ if ctx.checks.Add(1) >= ctx.after {
+ ctx.cancel()
+ }
+ return ctx.Context.Err()
+}
+
+func TestMarkTextContextMatchesCompleteHighlighting(t *testing.T) {
+ previous := util.SearchHanSensitive.Load()
+ t.Cleanup(func() { util.SearchHanSensitive.Store(previous) })
+ cases := []struct {
+ name, text, keyword string
+ }{
+ {"window boundary", strings.Repeat("x", highlightingWindowBytes-2) + "alpha end", "alpha"},
+ {"unicode boundary", strings.Repeat("x", highlightingWindowBytes-1) + "🙂诗經 & tail", "🙂诗经"},
+ {"many matches", strings.Repeat("ababc <&> Kk ", 20000), "ab" + TermSep + "abc" + TermSep + "k"},
+ {"empty matches", strings.Repeat("🙂x", 1500), " "},
+ {"no matches", strings.Repeat("&🙂", highlightingWindowBytes), "missing"},
+ {"invalid UTF8", strings.Repeat("x\xff", highlightingWindowBytes), "x"},
+ {"empty input", "", "a"},
+ {"empty keyword", "A&B", ""},
+ }
+ random := rand.New(rand.NewSource(20692))
+ words := []string{"ab", "abc", "诗經", "🙂", "K", "&", "\x00", "\xff"}
+ for i := range 16 {
+ var content strings.Builder
+ for content.Len() < highlightingWindowBytes+i {
+ content.WriteString(words[random.Intn(len(words))])
+ }
+ cases = append(cases, struct{ name, text, keyword string }{
+ fmt.Sprintf("mixed-%d", i), content.String(), words[i%len(words)] + TermSep + "ab",
+ })
+ }
+ for _, hanSensitive := range []bool{true, false} {
+ util.SearchHanSensitive.Store(hanSensitive)
+ for _, test := range cases {
+ for _, beforeLen := range []int{-1, 1, 36} {
+ t.Run(fmt.Sprintf("%t/%s/%d", hanSensitive, test.name, beforeLen), func(t *testing.T) {
+ for _, caseSensitive := range []bool{true, false} {
+ wantPos, want := MarkText(test.text, test.keyword, beforeLen, caseSensitive)
+ ctx, cancel := context.WithCancel(context.Background())
+ gotPos, got := MarkTextContext(ctx, test.text, test.keyword, beforeLen, caseSensitive)
+ cancel()
+ if gotPos != wantPos || got != want {
+ t.Fatalf("context changed highlight: position %d/%d, bytes %d/%d, case=%t",
+ gotPos, wantPos, len(got), len(want), caseSensitive)
+ }
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestMarkTextContextStopsInsideLargeValues(t *testing.T) {
+ for _, keyword := range []string{"hit", "missing"} {
+ t.Run(keyword, func(t *testing.T) {
+ base, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ ctx := &highlightingCancelContext{Context: base, cancel: cancel, after: 10}
+ pos, marked := MarkTextContext(ctx, strings.Repeat("hit & ", 200000), keyword, -1, true)
+ if base.Err() == nil || pos != -1 || marked != "" {
+ t.Fatalf("large value was completed after cancellation: err=%v pos=%d bytes=%d", base.Err(), pos, len(marked))
+ }
+ if ctx.checks.Load() > ctx.after+2 {
+ t.Fatalf("canceled highlighting continued checking: %d", ctx.checks.Load())
+ }
+ })
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if pos, marked := MarkTextContext(ctx, "plain", "", 0, true); pos != -1 || marked != "" {
+ t.Fatal("empty keyword ignored cancellation")
+ }
+}
+
+func FuzzMarkTextContextMatchesComplete(f *testing.F) {
+ f.Add("ababc ab & alpha", "ab"+TermSep+"abc", true)
+ f.Add(strings.Repeat("x", highlightingWindowBytes-2)+"🙂alpha", "🙂alpha", false)
+ f.Add(strings.Repeat("🙂", 2000), " ", false)
+ f.Add("Kk詩經 &\x00\xff", "k"+TermSep+"诗经", false)
+ f.Fuzz(func(t *testing.T, text, keyword string, caseSensitive bool) {
+ if len(text) > 256*1024 || len(keyword) > 64 {
+ t.Skip()
+ }
+ wantPos, want := MarkText(text, keyword, 36, caseSensitive)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ gotPos, got := MarkTextContext(ctx, text, keyword, 36, caseSensitive)
+ if gotPos != wantPos || got != want {
+ t.Fatalf("context changed highlight: position %d/%d, bytes %d/%d", gotPos, wantPos, len(got), len(want))
+ }
+ })
+}
+
+func BenchmarkMarkTextContext(b *testing.B) {
+ for _, repeat := range []int{20, 20000} {
+ text := strings.Repeat("alpha & beta ", repeat)
+ for _, cancellable := range []bool{false, true} {
+ b.Run(fmt.Sprintf("repeats_%d/cancellable_%t", repeat, cancellable), func(b *testing.B) {
+ var ctx context.Context = context.Background()
+ if cancellable {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithCancel(ctx)
+ b.Cleanup(cancel)
+ }
+ b.ReportAllocs()
+ for b.Loop() {
+ if pos, _ := MarkTextContext(ctx, text, "alpha", 36, true); pos < 0 {
+ b.Fatal("missing highlight")
+ }
+ }
+ })
+ }
+ }
+}