Orivel Orivel
Open menu

Implement a Thread-Safe Single-Flight TTL/LRU Cache

Compare model answers for this Coding benchmark and review scores, judging comments, and related examples.

Login or register to use likes and favorites. Register

X f L

Contents

Task Overview

Benchmark Genres

Coding

Task Creator Model

Answering Models

Judge Models

Task Prompt

Write a complete Python 3.11 implementation of a generic class named SingleFlightTTLCache using only the standard library. Return code only.

The constructor has the signature SingleFlightTTLCache(capacity: int, ttl: float, clock: Callable[[], float] = time.monotonic). Reject negative capacity and nonpositive TTL with ValueError. Keys are hashable. The cache stores successful results only.

Implement get_or_compute(key, compute). If an unexpired cached value exists, return it and mark that key as the most recently...

Show more

Write a complete Python 3.11 implementation of a generic class named SingleFlightTTLCache using only the standard library. Return code only.

The constructor has the signature SingleFlightTTLCache(capacity: int, ttl: float, clock: Callable[[], float] = time.monotonic). Reject negative capacity and nonpositive TTL with ValueError. Keys are hashable. The cache stores successful results only.

Implement get_or_compute(key, compute). If an unexpired cached value exists, return it and mark that key as the most recently used. A value is expired when clock() is greater than or equal to its expiration time. Expiration is measured from the time compute finishes successfully.

If the key is missing or expired, call the zero-argument compute callable. At most one computation may be active for a key in the current cache generation. Concurrent callers requesting that key must wait and receive the same result. Computations for different keys must be able to run concurrently. Do not hold the cache's global lock while running compute or while waiting for another computation.

If compute raises any BaseException, every caller already waiting on that computation must be released and observe that failure. The failure must not be cached, and a later call must be able to retry. Ensure internal state remains usable even for KeyboardInterrupt or SystemExit.

Completed values are managed by least-recently-used order. When insertion makes the number of completed entries exceed capacity, evict the least recently used entries. In-flight computations do not count toward capacity and must never be evicted. With capacity zero, callers still share an in-flight computation, but its result is not retained afterward. A caller waiting on a successful computation must still receive its result even if that result is immediately evicted.

Also implement invalidate(key) and clear(), both returning None. invalidate removes any completed entry for the key. If that key currently has an in-flight computation, detach that computation from the current generation: callers already attached to it still receive its outcome, but the outcome must not be cached, and a subsequent caller may begin a fresh computation for the same key. clear applies the same rule to all keys. An older detached computation must never overwrite a newer value.

Implement len so it returns the number of currently unexpired completed entries, excluding in-flight computations. It must lazily remove expired entries before counting.

Detect direct or indirect same-thread recursion back into an in-flight key owned by that thread, such as computing A, then B, then A. Raise RuntimeError instead of deadlocking. Calls for an in-flight key owned by another thread must wait normally.

Do not use polling or busy-waiting. The implementation must remain correct under concurrent cache hits, expiration, eviction, failed computation, invalidation, clearing, and completion of detached or superseded computations. Include type hints, but do not depend on third-party packages.

Judging Policy

A strong solution provides executable Python 3.11 code with the requested API and precise TTL and LRU behavior. It should synchronize shared state without serializing independent computations, wake all waiters on both success and every kind of failure, and avoid deadlocks during recursive use. Invalidation and clearing must safely detach existing flights so stale completions cannot publish over newer generations, while callers already attached to detached flights still receive their outcomes. Evaluation should also...

Show more

A strong solution provides executable Python 3.11 code with the requested API and precise TTL and LRU behavior. It should synchronize shared state without serializing independent computations, wake all waiters on both success and every kind of failure, and avoid deadlocks during recursive use. Invalidation and clearing must safely detach existing flights so stale completions cannot publish over newer generations, while callers already attached to detached flights still receive their outcomes. Evaluation should also cover capacity zero, expiration boundaries with a fake clock, exception recovery, lazy cleanup in len, concurrent eviction, and races among completion, invalidation, and new computation. Code quality, clear state modeling, appropriate condition signaling, and avoidance of polling or leaked transient state are important.

Answers

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

#1 | Winner

Winning Votes

3 / 3

Average Score

86
Judge Models OpenAI GPT-5.5

Total Score

81

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%
80

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%
85

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%
75

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%
80

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%
90

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

95

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%
95

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%
100

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%
90

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%
90

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%
100

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

81

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%
83

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%
80

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%
78

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%
80

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%
85

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.

import collections
import heapq
import threading
import time
from collections.abc import Callable
from typing import Any, Dict, Optional, Tuple, TypeVar

K = TypeVar("K")
V = TypeVar("V")

class SingleFlightTTLCache[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...
Show Full Answer

import collections
import heapq
import threading
import time
from collections.abc import Callable
from typing import Any, Dict, Optional, Tuple, TypeVar

K = TypeVar("K")
V = TypeVar("V")

class SingleFlightTTLCache[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._cache: Dict[K, Tuple[float, V]] = {}
    self._in_flight: Dict[K, _InFlight[V]] = {}
    self._lru: collections.deque[K] = collections.deque()
    self._lock = threading.Lock()
    self._thread_recursion_guard: Dict[int, K] = {}

def get_or_compute(self, key: K, compute: Callable[[], V]) -> V:
    with self._lock:
        if key in self._thread_recursion_guard:
            raise RuntimeError("Recursive call to in-flight key")

        now = self.clock()
        if key in self._cache:
            expiration_time, value = self._cache[key]
            if now < expiration_time:
                self._lru.remove(key)
                self._lru.append(key)
                return value
            else:
                del self._cache[key]
                self._lru.remove(key)

        if key in self._in_flight:
            in_flight = self._in_flight[key]
            in_flight.waiters.append(threading.current_thread())
            self._thread_recursion_guard[threading.get_ident()] = key
            try:
                return in_flight.result.result()
            finally:
                self._thread_recursion_guard.pop(threading.get_ident(), None)

        if self.capacity == 0:
            # No caching, just compute and return
            try:
                return compute()
            except BaseException as e:
                raise e

        in_flight = _InFlight[V]()
        self._in_flight[key] = in_flight
        in_flight.waiters.append(threading.current_thread())
        self._thread_recursion_guard[threading.get_ident()] = key

    try:
        result = compute()
        expiration_time = self.clock() + self.ttl
        self.put(key, expiration_time, result)
        in_flight.result.set(result)
        return result
    except BaseException as e:
        self.release_in_flight(key, e)
        raise e
    finally:
        self.release_in_flight_waiters(key)
        self._thread_recursion_guard.pop(threading.get_ident(), None)

def put(self, key: K, expiration_time: float, value: V) -> None:
    with self._lock:
        if key in self._in_flight:
            # If the key is still in-flight, it means it was detached
            # and we should not overwrite a newer value.
            # This can happen if invalidate was called while compute was running.
            return

        self._cache[key] = (expiration_time, value)
        self._lru.append(key)
        self.evict_if_needed()

def evict_if_needed(self) -> None:
    while len(self._cache) > self.capacity:
        lru_key = self._lru.popleft()
        if lru_key in self._cache:
            del self._cache[lru_key]

def invalidate(self, key: K) -> None:
    with self._lock:
        if key in self._cache:
            del self._cache[key]
            self._lru.remove(key)
        if key in self._in_flight:
            # Detach the in-flight computation from the cache.
            # Callers already waiting will still get the result,
            # but it won't be cached.
            self._in_flight[key].detached = True

def clear(self) -> None:
    with self._lock:
        self._cache.clear()
        self._lru.clear()
        for in_flight in self._in_flight.values():
            in_flight.detached = True

def __len__(self) -> int:
    self.remove_expired()
    return len(self._cache)

def remove_expired(self) -> None:
    with self._lock:
        now = self.clock()
        keys_to_remove = [
            key
            for key, (expiration_time, _) in self._cache.items()
            if now >= expiration_time
        ]
        for key in keys_to_remove:
            del self._cache[key]
            self._lru.remove(key)

def release_in_flight(self, key: K, exception: BaseException) -> None:
    with self._lock:
        if key not in self._in_flight:
            return
        in_flight = self._in_flight[key]
        if not in_flight.detached:
            in_flight.result.set_exception(exception)
        else:
            # If detached, the result should not be cached.
            # We still need to signal waiters.
            in_flight.result.set_exception(exception)
        del self._in_flight[key]

def release_in_flight_waiters(self, key: K) -> None:
    with self._lock:
        if key not in self._in_flight:
            return
        in_flight = self._in_flight[key]
        # Wake up all waiters
        for waiter in in_flight.waiters:
            waiter.unblock()
        in_flight.waiters.clear()

class _InFlight[V]:
def init(self) -> None:
self.result: threading.Future[V] = threading.Future()
self.waiters: list[threading.Thread] = []
self.detached: bool = False

Result

#2

Winning Votes

0 / 3

Average Score

14
Judge Models OpenAI GPT-5.5

Total Score

10

Overall Comments

Answer B is not a viable Python 3.11 implementation. It uses Python 3.12 generic class syntax, references nonexistent standard-library APIs such as threading.Future and Thread.unblock, waits while holding the global lock, fails to cache successful computations because put returns while the key is still in _in_flight, does not implement capacity-zero single-flight behavior, and does not properly detach in-flight computations on invalidate or clear. It attempts the requested API but is largely non-executable and incorrect.

View Score Details

Correctness

Weight 35%
5

Largely incorrect and not runnable as written. It uses nonexistent threading.Future and Thread.unblock, waits under the global lock, does not cache successes, mishandles capacity zero, and does not remove or supersede in-flight records correctly on invalidate/clear.

Completeness

Weight 20%
15

Defines the requested methods but many required behaviors are absent or broken: Python 3.11 compatibility, single-flight for capacity zero, safe waiter release, proper caching, fresh computation after invalidation, and stale completion protection.

Code Quality

Weight 20%
10

The code has severe API and design problems, including invalid Python 3.11 syntax, nonexistent APIs, unused imports, a broken recursion guard, duplicate-prone deque LRU management, and helper methods whose logic conflicts with the in-flight lifecycle.

Practical Value

Weight 15%
5

Has essentially no practical value because it will not run correctly and can deadlock or raise unrelated AttributeError exceptions in normal use.

Instruction Following

Weight 10%
20

Returns code only and attempts the named class and methods, but violates the Python 3.11 requirement with PEP 695 syntax and relies on nonexistent threading APIs, so it does not meet the implementation instruction.

Total Score

12

Overall Comments

Answer B is a deeply flawed and incorrect implementation. It contains several critical bugs that make it unusable. Most notably, it holds the global lock while waiting for a computation to finish, which would serialize all cache operations and lead to deadlocks. It also uses non-existent APIs (threading.Future, thread.unblock()), making the code unrunnable. Furthermore, it fails to correctly implement key requirements such as LRU eviction (using an inefficient O(N) deque.remove), same-thread recursion detection, single-flight for zero capacity, and the specified invalidation semantics. The code leaks memory by not cleaning up in-flight entries on success.

View Score Details

Correctness

Weight 35%
10

The implementation is fundamentally incorrect. It holds the global lock while waiting for a future to resolve (`in_flight.result.result()`), which would cause deadlocks and serialize all cache access. It uses non-existent APIs (`threading.Future`, `thread.unblock()`). The logic for invalidation, recursion detection, and capacity zero is also incorrect. The code leaks `_in_flight` entries on successful computations.

Completeness

Weight 20%
20

The answer is missing correct implementations for several key requirements. It fails to provide single-flight for `capacity=0`. The invalidation logic does not allow a new computation to start. The same-thread recursion detection is non-functional. While the method signatures are present, their implementations do not fulfill the prompt's requirements.

Code Quality

Weight 20%
15

The code quality is very poor. It is unrunnable due to the use of non-existent APIs. It uses an inefficient data structure for LRU (`collections.deque` with `remove()`, which is an O(N) operation). The logic is convoluted and difficult to follow, leading to the numerous bugs present in the implementation.

Practical Value

Weight 15%
0

The implementation has no practical value. It is non-functional, and if the API errors were fixed, it would introduce deadlocks and memory leaks into any application that used it.

Instruction Following

Weight 10%
10

The answer fails to follow numerous critical instructions. It violates the requirement to not hold the global lock while waiting. It fails to implement the specified behavior for invalidation, capacity zero, and recursion detection. The use of non-existent APIs from the `threading` module is a major failure to provide valid code from the standard library.

Total Score

20

Overall Comments

Answer B is fundamentally broken. It uses PEP 695 generic class syntax (class SingleFlightTTLCache[K, V]) which is a SyntaxError on the required Python 3.11. Even ignoring that, threading.Future does not exist (Future lives in concurrent.futures), Future has no set() method, and threading.Thread has no unblock() method, so the code would crash at runtime. Waiters call result.result() while holding the global cache lock, guaranteeing deadlock with the computing thread and directly violating the requirement not to hold the lock while waiting. The recursion guard checks keys against thread idents, so it never works correctly and falsely blocks unrelated calls. On success, the in-flight entry is never removed from _in_flight, so put() refuses to cache any result and the stale future serves values forever, breaking TTL. Capacity zero bypasses single-flight sharing entirely, contradicting the spec. Unused heapq import and O(n) deque removals further reduce quality.

View Score Details

Correctness

Weight 35%
12

Fails at multiple fatal levels: PEP 695 class syntax is invalid on Python 3.11; threading.Future, Future.set, and Thread.unblock do not exist; waiters hold the global lock while blocking on the future, guaranteeing deadlock; the recursion guard compares keys to thread idents so it is nonfunctional; successful results are never cached because the in-flight entry is never removed before put() checks it; TTL and eviction therefore never apply.

Completeness

Weight 20%
28

All required methods are present in name, and detachment via a flag is attempted, but capacity zero skips single-flight sharing entirely, the recursion requirement is effectively unimplemented, waiter release logic is vestigial, and the success path never cleans up in-flight state, so several mandated behaviors are absent or non-functional.

Code Quality

Weight 20%
23

Unused heapq import, redundant TypeVars alongside PEP 695 parameters, O(n) deque.remove calls for LRU maintenance, public helper methods (put, evict_if_needed, release_in_flight) leaking internal mechanics, duplicated dead branches in release_in_flight, and a waiters list of Thread objects that serves no working purpose.

Practical Value

Weight 15%
15

Cannot be run on the target Python version and would crash or deadlock on newer versions, so it delivers no practical utility without a substantial rewrite.

Instruction Following

Weight 10%
30

Returns code only and sticks to intended stdlib usage, but violates the explicit Python 3.11 requirement via PEP 695 syntax, references APIs that do not exist in the standard library as named, and breaks the rule against holding the global lock while waiting.

Comparison Summary

Final rank order is determined by judge-wise rank aggregation (average rank + Borda tie-break). Average score is shown for reference.

Judges: 3

Winning Votes

3 / 3

Average Score

86
View this answer

Winning Votes

0 / 3

Average Score

14
View this answer

Judging Results

Why This Side Won

Answer A wins decisively on the heavily weighted correctness and completeness criteria: it is executable on Python 3.11, implements single-flight semantics, detachment, recursion detection, TTL, LRU eviction, capacity-zero sharing, and exception recovery essentially as specified, with only cosmetic nits. Answer B fails to even parse on Python 3.11 due to PEP 695 syntax, references nonexistent APIs (threading.Future, Future.set, Thread.unblock), deadlocks by waiting on a future while holding the global lock, has a broken recursion guard, never caches successful results correctly, and skips single-flight for capacity zero. The weighted result overwhelmingly favors A on every criterion.

Why This Side Won

Answer A is the winner because it provides a complete, correct, and robust solution that meets all the complex requirements of the prompt. In contrast, Answer B is fundamentally broken, with critical concurrency bugs (incorrect locking), incorrect logic for several key features (invalidation, recursion detection), inefficient data structure choices, and the use of non-existent APIs that prevent it from running at all. Answer A's implementation is of a professional quality, while Answer B's is non-functional and demonstrates a misunderstanding of the core concepts required.

Judge Models OpenAI GPT-5.5

Why This Side Won

Answer A wins decisively because it is executable Python 3.11 code and satisfies most of the required concurrency, single-flight, TTL, LRU, invalidation, failure, and capacity-zero behavior. Answer B contains syntax and runtime errors and fails several central requirements, including safe waiting, successful caching, detachment semantics, and Python 3.11 compatibility.

X f L