Answer A: Anthropic Claude Sonnet 5
import threading
import time
from collections import OrderedDict
from typing import Callable, TypeVar, Generic, Hashable, Optional, Any
K = TypeVar("K", bound=Hashable)
V = TypeVar("V")
class _InFlight(Generic[V]):
slots = ("event", "value", "exc", "owner", "done", "detached")
def __init__(self, owner: int) -> None:
self.event = threading.Event()
self.value: Optional[V] = None
self.exc: Optional[BaseException] = None
self.owner = owner
self.done = False
self.detached = False
class _Entry(Generic[V]):
slots = ("value", "expire_at")
def...
Show Full Answer ▼
import threading
import time
from collections import OrderedDict
from typing import Callable, TypeVar, Generic, Hashable, Optional, Any
K = TypeVar("K", bound=Hashable)
V = TypeVar("V")
class _InFlight(Generic[V]):
slots = ("event", "value", "exc", "owner", "done", "detached")
def __init__(self, owner: int) -> None:
self.event = threading.Event()
self.value: Optional[V] = None
self.exc: Optional[BaseException] = None
self.owner = owner
self.done = False
self.detached = False
class _Entry(Generic[V]):
slots = ("value", "expire_at")
def __init__(self, value: V, expire_at: float) -> None:
self.value = value
self.expire_at = expire_at
class SingleFlightTTLCache(Generic[K, V]):
def init(
self,
capacity: int,
ttl: float,
clock: Callable[[], float] = time.monotonic,
) -> None:
if capacity < 0:
raise ValueError("capacity must be non-negative")
if ttl <= 0:
raise ValueError("ttl must be positive")
self._capacity = capacity
self._ttl = ttl
self._clock = clock
self._lock = threading.Lock()
self._store: "OrderedDict[K, _Entry[V]]" = OrderedDict()
self._inflight: dict[K, _InFlight[V]] = {}
# per-thread stack of keys currently being computed by this thread,
# used to detect same-thread recursion into an in-flight key.
self._thread_local = threading.local()
def _owned_keys(self) -> set:
stack = getattr(self._thread_local, "stack", None)
if stack is None:
stack = set()
self._thread_local.stack = stack
return stack
def _evict_if_needed(self) -> None:
while len(self._store) > self._capacity:
self._store.popitem(last=False)
def _purge_expired_locked(self) -> None:
now = self._clock()
expired_keys = [k for k, e in self._store.items() if now >= e.expire_at]
for k in expired_keys:
del self._store[k]
def get_or_compute(self, key: K, compute: Callable[[], V]) -> V:
owned = self._owned_keys()
while True:
with self._lock:
# Check completed, unexpired entry first.
entry = self._store.get(key)
if entry is not None:
if self._clock() >= entry.expire_at:
del self._store[key]
else:
self._store.move_to_end(key)
return entry.value
inflight = self._inflight.get(key)
if inflight is not None:
if inflight.owner == threading.get_ident() and key in owned:
raise RuntimeError(
"Detected same-thread recursive computation for key: "
f"{key!r}"
)
# Wait for existing computation outside the lock.
wait_target = inflight
else:
wait_target = None
my_flight = _InFlight(owner=threading.get_ident())
self._inflight[key] = my_flight
if wait_target is not None:
wait_target.event.wait()
if wait_target.exc is not None:
raise wait_target.exc
return wait_target.value # type: ignore[return-value]
# We own the computation for this key now.
owned.add(key)
try:
result = compute()
except BaseException as e:
with self._lock:
current = self._inflight.get(key)
if current is my_flight:
del self._inflight[key]
my_flight.exc = e
my_flight.done = True
my_flight.event.set()
raise
else:
with self._lock:
current = self._inflight.get(key)
still_current = current is my_flight
if still_current:
del self._inflight[key]
if still_current and not my_flight.detached:
expire_at = self._clock() + self._ttl
if self._capacity > 0:
self._store[key] = _Entry(result, expire_at)
self._store.move_to_end(key)
self._evict_if_needed()
# capacity == 0: never store
# If detached or superseded, do not store the result,
# but still release waiters below with the value.
my_flight.value = result
my_flight.done = True
my_flight.event.set()
return result
finally:
owned.discard(key)
def invalidate(self, key: K) -> None:
with self._lock:
if key in self._store:
del self._store[key]
inflight = self._inflight.get(key)
if inflight is not None:
inflight.detached = True
del self._inflight[key]
def clear(self) -> None:
with self._lock:
self._store.clear()
for inflight in self._inflight.values():
inflight.detached = True
self._inflight.clear()
def __len__(self) -> int:
with self._lock:
self._purge_expired_locked()
return len(self._store)
Result
Winning Votes
3 / 3
Average Score
Total Score
Overall Comments
Answer A is a mostly complete and executable implementation. It correctly uses a global lock only for shared state, runs computations and waits outside the lock, shares in-flight work, propagates BaseException failures, supports detaching on invalidate/clear, handles capacity zero, and implements LRU ordering for normal cache hits and insertions. Its main correctness weakness is that insertion eviction does not purge expired entries first, so expired non-LRU entries can cause unnecessary eviction of still-valid entries. There are also minor quality issues such as unused fields/imports and a somewhat informal recursion guard, but the design is generally sound.
View Score Details ▼
Correctness
Weight 35%Correct for most core behaviors: thread-safe single-flight, concurrent independent computations, exception propagation including BaseException, detachment on invalidate/clear, and capacity-zero sharing. The notable flaw is eviction without first removing expired entries, which can evict valid LRU entries unnecessarily when expired entries remain in the store.
Completeness
Weight 20%Implements all requested public methods and covers nearly all required cases, including failure recovery, lazy __len__ expiration, LRU updates, and detached flights. It misses a subtle but important interaction between expiration cleanup and capacity eviction.
Code Quality
Weight 20%The state model is simple and understandable, using OrderedDict, a lock, events, and per-thread ownership tracking. Some details are rough, such as unused fields/imports, untyped helper return values, and no expired purge before eviction, but the structure is maintainable.
Practical Value
Weight 15%Would be usable for many real workloads and handles difficult concurrency scenarios without polling or serializing independent computations. The expired-entry eviction bug could cause surprising loss of valid cache entries in long-running use.
Instruction Following
Weight 10%Follows the requested API, uses only the standard library, returns code only, includes type hints, rejects invalid constructor arguments, and targets Python 3.11-compatible syntax.
Total Score
Overall Comments
Answer A provides an exceptionally high-quality, robust, and correct implementation of the complex thread-safe cache. It demonstrates a deep understanding of concurrency primitives and race conditions. The code is well-structured, uses appropriate data structures (like OrderedDict for LRU), and correctly implements all specified features, including the subtle details of invalidation, recursion detection, and failure handling. The locking strategy is fine-grained and correct, avoiding holding the global lock during long-running computations or waits, which is critical for performance.
View Score Details ▼
Correctness
Weight 35%The implementation is highly correct and robust. It correctly handles complex concurrency scenarios, such as races between computation completion and invalidation, by checking if the flight is still current. The locking is fine-grained, releasing the lock before waiting or computing. Exception handling and recursion detection are also implemented correctly.
Completeness
Weight 20%The answer is fully complete, implementing every required feature from the prompt. This includes the main `get_or_compute` logic, `invalidate`, `clear`, `__len__`, constructor validation, LRU eviction, TTL expiration, single-flight, failure handling, and the more subtle requirements like same-thread recursion detection and correct behavior for zero capacity.
Code Quality
Weight 20%The code quality is excellent. It is well-structured with helper classes (`_InFlight`, `_Entry`) that clearly model the state. It uses appropriate and efficient data structures (`OrderedDict` for O(1) LRU operations). The code is clean, readable, and includes proper type hints.
Practical Value
Weight 15%This implementation is of high practical value. It is a robust, performant, and feature-complete cache that could be used directly in a production environment to solve the problem of thundering herds.
Instruction Following
Weight 10%The answer meticulously follows all instructions in the prompt. It uses only the standard library for Python 3.11, implements the exact API requested, and correctly adheres to all the detailed behavioral specifications regarding concurrency, locking, eviction, and invalidation.
Total Score
Overall Comments
Answer A is a carefully engineered, nearly complete solution. It uses a global lock only for short state transitions, an Event per in-flight computation so waiters block without holding the lock, a per-thread owned-key set for same-thread recursion detection, and a detached flag plus identity check (current is my_flight) so detached or superseded computations can never publish over newer values. Capacity-zero sharing, exception propagation for BaseException including KeyboardInterrupt/SystemExit, lazy expiry purge in len, OrderedDict-based LRU with correct eviction, and waiters receiving results even when the entry is immediately evicted are all handled. Minor nits: re-raising the same exception object in multiple waiter threads can share traceback state, waiters cannot re-observe a fresher cached value if one appears while they wait (acceptable per spec), and the owner check in recursion detection is slightly redundant. Overall it is robust, idiomatic, and matches the specification closely.
View Score Details ▼
Correctness
Weight 35%Expiration uses clock() >= expire_at as required, TTL is measured from compute completion, waiters are released via Event on both success and any BaseException, failures are not cached and retries work, detached flights cannot overwrite newer values thanks to the identity check against the current in-flight record, same-thread recursion raises RuntimeError, and no lock is held during compute or waiting. Only minor issues remain, such as re-raising the same exception instance across threads.
Completeness
Weight 20%All specified behaviors are implemented: constructor validation, LRU hits with move_to_end, single-flight per generation, capacity-zero sharing without retention, invalidate and clear with proper detachment semantics, lazy expiry in __len__, eviction excluding in-flight entries, and waiters receiving results even if immediately evicted. Nothing from the requirement list is missing.
Code Quality
Weight 20%Clean state modeling with __slots__ dataclass-like helpers, OrderedDict for LRU, per-thread local set for ownership, clear separation of the wait path and the owner path, consistent type hints, and explanatory comments. Slightly dense control flow in get_or_compute but well organized.
Practical Value
Weight 15%Directly usable in real concurrent code: no busy-waiting, independent keys compute in parallel, injectable clock enables deterministic testing, and failure recovery keeps internal state consistent even under KeyboardInterrupt or SystemExit.
Instruction Following
Weight 10%Returns code only, uses only the standard library, targets Python 3.11 compatible syntax, matches the exact constructor and method signatures, includes type hints, and avoids polling as instructed.