perf(fs_watcher): fix _identify_actor lsof cache (~12-121x speedup) - #44
Merged
Conversation
The prior cache was functionally a no-op for every realistic workload. Two bugs: 1. Negative results were not cached — only `if result.stdout.strip()` stored entries. fs events mostly land on files with no holder (just-created tmp / write-then-close), so cache_size stayed 0 after every burst and every call paid the macOS lsof cost (~290ms/call measured). 2. Single global TTL — `_lsof_cache_time` was bumped on every successful invocation and checked against that one timestamp for all paths, entangling cache freshness across unrelated entries. Fix: per-entry (pid, name, timestamp) tuple in an OrderedDict, LRU bound at 512, both positive and negative results cached under the same TTL. TTL bumped from 2s to 30s — lsof on macOS is so slow that even a 10-path rotation cannot complete a round in 2s (10 * 290ms ≈ 3s), making any tighter TTL useless. 30s is well within the "best-effort actor attribution" tolerance. Measured speedup (scripts/profile_lsof.py): - repeat (1 path × 100): 33.9s → 0.28s (121x) - mixed (10 paths × 10): 36.0s → 2.9s (12.5x) - unique (100 unique): 33.6s → 29.6s (1.13x) `unique` is bound by lsof per-file cost; directory-batch is a Phase 2 follow-up that needs an ADR (changes the per-event contract). Public API unchanged. 14 new unit tests cover positive/negative caching, per-path TTL independence, LRU eviction, parse correctness. mypy clean, ruff clean, 890 → 904 pytest pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
v0.9 Track 1 deferred 항목 (
_identify_bulk_actorlsof subprocess) 본격 조사. 측정 결과는 가설보다 훨씬 더 나쁨.repeat(1 path × 100)mixed(10 paths × 10)unique(100 unique)(v0.9 노트의 "1.4s/100 events"는 patch가 걸린 측정. 실제 lsof 부담은 macOS 환경에서 per-call 290~340ms.)
발견한 캐시 버그 2건
기존
_lsof_cache는 사실상 no-op였다.if result.stdout.strip():가드 안에서만 캐시에 저장. 그런데 fs_events 대부분이 "이 파일 잡고 있는 프로세스 없음" 케이스라 빈 stdout → 저장 안 됨.cache_size=0상태로 100-call burst 끝남._lsof_cache_time하나로 모든 경로의 freshness 판정. 한 path의 subprocess 호출이 다른 path의 캐시 freshness까지 갱신하는 entanglement.Fix
OrderedDict[str, tuple[int, str, float]]로 교체:_lsof_cache_max = 512Public API 변경 없음. Behavior 변경 없음 (캐시 hit 여부만 빨라짐).
Files
sentinel_mac/collectors/fs_watcher.py—_identify_actor재작성, 캐시 자료구조 변경 (~25줄 변경)scripts/profile_lsof.py(신규) — 재현 가능한 측정 하네스. 기존profile_workload.py는 lsof를 patch out 했었음tests/test_lsof_cache.py(신규, 14 tests) — 구조 invariants / positive 캐싱 / negative 캐싱 / per-path TTL 독립성 / LRU 동작 / parse correctnessdocs/perf/v0.11-lsof-2026-05-05.md(신규) — 베이스라인 / 분석 / 결과 / 향후 follow-upCHANGELOG.md[Unreleased]Performance 항목향후 작업 (별도 PR)
lsof +D <parent> -F pcn한 번으로 디렉토리 내 모든 파일 커버.unique시나리오 N×290ms → 290ms로. per-event actor identification 흐름을 미루는 변경이라 ADR 필요.process_iter(['open_files']). macOS의 per-process syscall 비용 때문에 빨라질지는 측정 필요.Verification
python3 scripts/profile_lsof.py본 환경 재현 결과는 위 표와 동일Test plan
🤖 Generated with Claude Code