perf(library): memoize scan parses per save (#143)
CI / ci (push) Canceled after 0s

Every FSEvents change — each 1 s autosave echo — ran Post.scan over the
whole library: read + frontmatter parse + title per post.md, O(library
bytes) per save cycle while writing, and the posts array was replaced
unconditionally, so every observing pane regrouped and re-rendered even
when nothing changed.

Post.scan now takes an optional PostScanCache (path+mtime+size-keyed
parse memo, nil default — every other caller unchanged): the readdir
walk stays the truth, only changed files are read and re-parsed. The
stamp is captured BEFORE the read and keys the store, so a mid-scan
rewrite can never be pinned as fresh — a late overlapping store keys
its own pre-read stamp and the next scan misses (review-caught race,
pinned by a same-size-rewrite test). rescan skips the posts assignment
when the scan equals the current list; @Observable invalidates on
assignment regardless of equality, so panes stop re-rendering on the
app's own autosave echoes.

Deliberately skipped (measured cold): folder(of:) caching (stat-only
walk) and refreshCards throttling (O(open piece), card surfacing
depends on it).

Closes #143
This commit is contained in:
AlexKucera committed 2026-11-03 11:19:50 +01:00
1 parent cc317b65b9
commit a2f6dc1653
9 files changed
+287 -39

No files matched your search

+10 -2
View File
@@ -157,6 +157,9 @@ final class PostsModel {
/// Home the watcher is bound to; also the rescan target.
private var watchedHome: URL?
private var watcher = PostsWatcher()
/// #143 (OPT-F3): scan parse memo — a rescan re-parses only changed
/// post.md files, not the library (see PostScanCache).
private let scanCache = PostScanCache()
/// #93: per-file watcher on the open external file — the #67 conflict
/// check reused verbatim for foreign files.
private var externalWatcher = PostsWatcher()
@@ -195,13 +198,18 @@ final class PostsModel {
// move) must not receive the OLD session's stale disk text as a
// spurious #67 conflict.
let openSession = session
let scanMemo = scanCache // detached capture, not a property read
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
let posts = Post.scan(home: home)
let posts = Post.scan(home: home, cache: scanMemo)
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
return (posts, disk)
}.value
guard !Task.isCancelled else { return }
posts = scanned
// #143: @Observable invalidates on assignment regardless of equality —
// skip the no-op so panes don't regroup on our own autosave echoes.
if scanned != posts {
posts = scanned
}
if let id = selectedPostID, !posts.contains(where: { $0.id == id }),
// Stale-scan guard (#137 suite find): the snapshot can PREDATE the
// current selection — bind's initial rescan (detached scan over the