Skip to content

Fix/eviction race - #13

Merged
hohonuuli merged 3 commits into
mainfrom
fix/eviction-race
Nov 24, 2026
Merged

hohonuuli merged 3 commits into
mainfrom
fix/eviction-race

Conversation

@hohonuuli

Copy link
Copy Markdown
Member

The Problem

The logs show beholder trying to serve a cached image that has already been deleted from disk:

2026-11-23T22:45:09,188Z [vert.x-eventloop-thread-0       ] WARN  org.mbari.beholder.Main$                           | Route failure: status=500
java.io.FileNotFoundException: /opt/beholder/cache/m3.shore.mbari.org/videos/M3/Projects/Piscivore/2023/Pontus_PC2_20230927_1/Piscivore_20230928T144422Z_Pontus_PC2_1.mp4/00_17_41.983.jpg (No such file or directory)
        at java.base/java.io.RandomAccessFile.open0(Native Method)
        ...
        at io.vertx.core.http.impl.http1.Http1ServerResponse.sendFile(Http1ServerResponse.java:449)
Full stack trace
2026-11-23T22:45:09,188Z [vert.x-eventloop-thread-0       ] WARN  org.mbari.beholder.Main$                           | Route failure: status=500
java.io.FileNotFoundException: /opt/beholder/cache/m3.shore.mbari.org/videos/M3/Projects/Piscivore/2023/Pontus_PC2_20230927_1/Piscivore_20230928T144422Z_Pontus_PC2_1.mp4/00_17_41.983.jpg (No such file or directory)
        at java.base/java.io.RandomAccessFile.open0(Native Method)
        at java.base/java.io.RandomAccessFile.open(RandomAccessFile.java:338)
        at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:257)
        at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:211)
        at io.vertx.core.http.impl.http1.Http1ServerResponse.sendFile(Http1ServerResponse.java:449)
        at io.vertx.core.http.HttpServerResponse.sendFile(HttpServerResponse.java:381)
        at io.vertx.core.http.HttpServerResponse.sendFile(HttpServerResponse.java:365)
        at sttp.tapir.server.vertx.encoders.VertxToResponseBody.fromRawValue$$anonfun$1$$anonfun$6(VertxToResponseBody.scala:42)
        at scala.Option.getOrElse(Option.scala:232)
        at sttp.tapir.server.vertx.encoders.VertxToResponseBody.fromRawValue$$anonfun$1(VertxToResponseBody.scala:42)
        at sttp.tapir.server.vertx.VertxBodyListener.onComplete$$anonfun$1(VertxBodyListener.scala:23)
        at sttp.tapir.server.vertx.encoders.VertxOutputEncoders$.apply$$anonfun$1(VertxOutputEncoders.scala:17)
        at sttp.tapir.server.vertx.VertxFutureServerInterpreter.endpointHandler$$anonfun$1$$anonfun$1$$anonfun$1(VertxFutureServerInterpreter.scala:76)
        at sttp.tapir.server.vertx.VertxFutureServerInterpreter$VertxFutureToScalaFuture.asScala(VertxFutureServerInterpreter.scala:100)
        at sttp.tapir.server.vertx.VertxFutureServerInterpreter$FutureFromVFuture$.apply(VertxFutureServerInterpreter.scala:90)
        at sttp.tapir.server.vertx.VertxFutureServerInterpreter.endpointHandler$$anonfun$1$$anonfun$1(VertxFutureServerInterpreter.scala:76)
        at scala.concurrent.impl.Promise$Transformation.run(Promise.scala:532)
        at sttp.tapir.server.vertx.VertxExecutionContext.execute(VertxFutureServerOptions.scala:74)
        at scala.concurrent.impl.Promise$Transformation.submitWithValue(Promise.scala:491)
        at scala.concurrent.impl.Promise$DefaultPromise.submitWithValue(Promise.scala:394)
        at scala.concurrent.impl.Promise$DefaultPromise.dispatchOrAddCallbacks(Promise.scala:345)
        at scala.concurrent.impl.Promise$DefaultPromise.flatMap(Promise.scala:189)
        at sttp.tapir.server.vertx.VertxFutureServerInterpreter.endpointHandler$$anonfun$1(VertxFutureServerInterpreter.scala:77)
        at io.vertx.ext.web.impl.BlockingHandlerDecorator.lambda$handle$0(BlockingHandlerDecorator.java:48)
        at io.vertx.core.impl.ExecuteBlocking$1.execute(ExecuteBlocking.java:36)
        at io.vertx.core.impl.WorkerTask.run(WorkerTask.java:57)
        at io.vertx.core.impl.TaskQueue.run(TaskQueue.java:87)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1090)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:614)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.base/java.lang.Thread.run(Thread.java:1474)

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:

time Eviction thread Request thread
t0 Removes frame X from the index and queues it for deletion
t1 Still deleting thousands of other files… Request for X misses the cache, runs ffmpeg, writes X, puts it as a fresh entry
t2 deleteFromDisk(X) deletes the new file
t3 Every request for X hits the cache and gets FileNotFoundException

After 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:

  • Each eviction is HUGE. BEHOLDER_CACHE_SIZE=50000 × BEHOLDER_CACHE_FREEPCT=0.33 frees about 16.5 GB per pass. That's up to tens of thousands of Files.delete calls in a row, which can take seconds to minutes, so the t1 window
    is wide.
  • Eviction ignored usage. It went strictly by capture time. A frame people were still asking for was evicted as soon as it was among the oldest, then requested again during the eviction pass, which is exactly when the race is open.
  • Eviction tied up a capture slot. The delete loop ran on the capture worker that called 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

  1. Least-recently-used eviction. Each CachedImage has a created timestamp, and eviction drops the oldest first. Cache hits now update that timestamp to the current time (ImageCache.touch), so eviction removes frames nobody has
    asked 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:

    • touch only 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.
    • Eviction removes an entry from the index only if it is still the exact entry that was queued (remove(key, j)). An entry that a refresh or recapture has replaced is skipped, rather than removing the fresh entry from the index
      while leaving it in the queue.

    The refreshed timestamp is kept only in memory. After a restart, eviction order comes from file creation times.

  2. 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 happen
    inside ConcurrentHashMap.compute on the frame's key. That holds the same lock put needs for that key, so no put can land between the check and the delete. This is the fix that closes the race in the table above.

  3. 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 the
    capture worker back. The deleter is a constructor parameter so tests can control exactly when deletes run.

  4. A cache hit whose file is missing counts as a miss (ImageCapture.findInCache). Both the endpoint's fast path and capture() check Files.exists on 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 put hasn't run yet, and files deleted by something outside beholder. Entries are dropped with the new ImageCache.removeIfCurrent, which removes an entry only if
    it 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

  • ImageCacheImplSuite
    • Reproduces the t0–t3 sequence with a test-controlled executor. Verified to fail with the old delete-by-path behavior.
    • Eviction deletes files off the thread that called put.
    • A touched frame outlives frames captured after it that nobody requested, and the size accounting stays correct.
    • touch and removeIfCurrent leave a newer entry alone, and touch never brings back a removed entry.
  • ImageCaptureSuite
    • A cached frame whose file was deleted is recaptured, not served.
    • findInCache drops a stale entry rather than just skipping it.
    • A cache hit refreshes the entry and doesn't trigger a recapture.

All 18 suites pass (sbt "Test/testOnly org.mbari.beholder.*").

After deploying

  • Some occasional Cached file … was missing from disk; dropped it from the cache warnings are expected. They mean the remaining small race was caught and handled.
  • A steady stream of them means something outside beholder is deleting files under /var/cache/beholder.
  • The restart that deploys this also rebuilds the index from disk, which clears any broken entries left in production.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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-classic and 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.

@hohonuuli
hohonuuli merged commit c4d4557 into main Nov 24, 2026
1 check passed
@hohonuuli
hohonuuli deleted the fix/eviction-race branch November 24, 2026 00:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants