Repository navigation
Fix/eviction race - #13
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
The change cannot be approved because a newly added source-adjacent file (src/main/scala/org/mbari/beholder/api/CaptureEndpoints.scala.orig) contains unresolved merge-conflict markers, indicating an accidental artifact that should be removed or relocated to avoid shipping conflicted content.
1 open issue
What changed in this PR
Fixes a production cache-eviction race where deferred deletion could remove a freshly recaptured frame file while the in-memory cache index still referenced it, leading to repeated FileNotFoundException/500s.
Changes:
- Switch eviction behavior to LRU-style via cache-hit
touch, reducing eviction of actively requested frames. - Make deletion recapture-safe and move file unlinks to a background deleter to avoid tying up capture workers.
- Treat “cache hit but missing file on disk” as a miss by dropping the stale entry and recapturing, with regression tests added.
- Bump
logback-classicand update repository documentation to reflect the new cache/eviction behavior.
| File | Description |
|---|---|
| src/test/scala/org/mbari/beholder/ImageCaptureSuite.scala | Adds tests validating that missing-on-disk cached entries are dropped and recaptured and that cache hits refresh entry recency. |
| src/test/scala/org/mbari/beholder/ImageCacheImplSuite.scala | Adds regression tests reproducing the eviction/recapture race and verifying deferred deletion, LRU touch behavior, and safe conditional removal semantics. |
| src/main/scala/org/mbari/beholder/ImageCapture.scala | Introduces a cache lookup path that checks for file existence, drops stale entries safely, and touches cache hits to drive LRU eviction. |
| src/main/scala/org/mbari/beholder/ImageCacheImpl.scala | Implements LRU touch, recapture-safe deferred deletion via an injected deleter, and conditional remove/replace safeguards to prevent index/file inconsistencies. |
| src/main/scala/org/mbari/beholder/ImageCache.scala | Extends the cache API to support touch and removeIfCurrent for LRU ordering and safe stale-entry cleanup. |
| src/main/scala/org/mbari/beholder/api/CaptureEndpoints.scala.orig | Adds a .orig copy of CaptureEndpoints containing merge-conflict markers that is not part of the compiled sources. |
| project/Dependencies.scala | Updates the build dependency for logback-classic from 1.6.7 to 1.6.8. |
| CLAUDE.md | Updates architecture/documentation notes to describe the new eviction, deletion, and cache self-healing behavior. |
Review effort: Balanced
Copilot was unable to complete this review at the selected tier due to model policy or plan restrictions.
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.

The Problem
The logs show beholder trying to serve a cached image that has already been deleted from disk:
Full stack trace
It's an eviction race: eviction deletes a frame that was just recaptured. Eviction first removes old entries from the index, then deletes their files by path. A cache path comes from the request
(
<root>/<host>/<url-path>/<hh_mm_ss.sss>.jpg), so a recaptured frame is written to the same path that is waiting to be deleted.Here's the time order:
deleteFromDisk(X)deletes the new fileFileNotFoundExceptionAfter t3 nothing ever looks at the entry again, so the 500s keep coming until a restart rebuilds the index from disk.
Our production settings make this much more likely:
BEHOLDER_CACHE_SIZE=50000×BEHOLDER_CACHE_FREEPCT=0.33frees about 16.5 GB per pass. That's up to tens of thousands ofFiles.deletecalls in a row, which can take seconds to minutes, so the t1 windowis wide.
put, so one of our 3 capture threads was out of service for the whole pass.A new regression test reproduces this sequence. With the old delete-by-path code it fails with the same symptom as production: the frame is in the index but the file is gone.
Solutions
Least-recently-used eviction. Each
CachedImagehas acreatedtimestamp, and eviction drops the oldest first. Cache hits now update that timestamp to the current time (ImageCache.touch), so eviction removes frames nobody hasasked for lately instead of the earliest captures. This makes the race rarer, but doesn't close it, because a least-recently-used frame can still be requested during a pass. Fixes 2 and 4 handle correctness. Two conditions keep
this safe alongside eviction:
touchonly refreshes an entry that is still the one in the index (replace(key, old, new)), so it can never bring back an entry eviction has already removed.remove(key, j)). An entry that a refresh or recapture has replaced is skipped, rather than removing the fresh entry from the indexwhile leaving it in the queue.
The refreshed timestamp is kept only in memory. After a restart, eviction order comes from file creation times.
Eviction no longer deletes a frame that has been recaptured (
ImageCacheImpl.deleteFromDisk). Before deleting a file, eviction checks whether its frame is back in the index, and skips it if so. The check and the delete happeninside
ConcurrentHashMap.computeon the frame's key. That holds the same lockputneeds for that key, so noputcan land between the check and the delete. This is the fix that closes the race in the table above.File deletes run on a background thread (
ImageCacheImpl.defaultDeleter). Index removal is still immediate, so an evicted frame stops being served right away. Only the file deletes move to a single daemon thread, which gives thecapture worker back. The deleter is a constructor parameter so tests can control exactly when deletes run.
A cache hit whose file is missing counts as a miss (
ImageCapture.findInCache). Both the endpoint's fast path andcapture()checkFiles.existson a hit. If the file is gone, the entry is dropped and the frame is recaptured.This covers two cases fix 2 can't see: ffmpeg has written the file but
puthasn't run yet, and files deleted by something outside beholder. Entries are dropped with the newImageCache.removeIfCurrent, which removes an entry only ifit is still the one that was looked up, so a concurrent fresh capture isn't thrown away. Each drop is logged at WARN, so it shows up at our production log level.
Tests
ImageCacheImplSuiteput.touchandremoveIfCurrentleave a newer entry alone, andtouchnever brings back a removed entry.ImageCaptureSuitefindInCachedrops a stale entry rather than just skipping it.All 18 suites pass (
sbt "Test/testOnly org.mbari.beholder.*").After deploying
Cached file … was missing from disk; dropped it from the cachewarnings are expected. They mean the remaining small race was caught and handled./var/cache/beholder.