You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Rendered by tasks/render_tasks.py from bench/coding_benchmark_v4.py (which chains v3 and v2). Each task is worth 100 points: the functional criteria are awarded from the hidden test program's <group>: ok lines (all of them when it prints ALL_TESTS_PASSED), and code_quality is a text heuristic (see score_result in bench/coding_benchmark_v2.py). The model only ever sees the prompt.
Implement an LRU (Least Recently Used) cache in Python with O(1) get and put operations.
Requirements:
- `LRUCache(capacity: int)` — initialize with positive capacity
- `get(key: int) -> int` — return value if key exists, otherwise -1
- `put(key: int, value: int) -> None` — update or insert. Evict LRU when at capacity.
Output only the Python code, no explanation.
Hidden test program
# Basic testscache=LRUCache(2)
cache.put(1, 1)
cache.put(2, 2)
assertcache.get(1) ==1, f"Expected 1, got {cache.get(1)}"cache.put(3, 3) # evicts key 2assertcache.get(2) ==-1, f"Expected -1, got {cache.get(2)}"cache.put(4, 4) # evicts key 1assertcache.get(1) ==-1, f"Expected -1 for evicted key 1"assertcache.get(3) ==3assertcache.get(4) ==4# Edge: capacity 1c2=LRUCache(1)
c2.put(1, 10)
assertc2.get(1) ==10c2.put(2, 20)
assertc2.get(1) ==-1assertc2.get(2) ==20# Edge: update existing keyc3=LRUCache(2)
c3.put(1, 1)
c3.put(2, 2)
c3.get(1) # makes 1 recently usedc3.put(3, 3) # should evict 2, not 1assertc3.get(2) ==-1, "Should have evicted 2"assertc3.get(1) ==1, "1 should still be present"# Edge: overwrite valuec4=LRUCache(2)
c4.put(1, 1)
c4.put(1, 10)
assertc4.get(1) ==10, f"Expected updated value 10, got {c4.get(1)}"# Performance: should not degrade with many operationsimporttimec5=LRUCache(1000)
start=time.time()
foriinrange(10000):
c5.put(i, i)
foriinrange(10000):
c5.get(i)
elapsed=time.time() -startassertelapsed<1.0, f"Too slow: {elapsed:.2f}s for 20k ops"print("ALL_TESTS_PASSED")
2. Async Rate Limiter
Criterion
Points
basic_try_acquire
25
token_refill
20
async_acquire
20
multi_token
10
code_quality
25
total
100
Prompt
Implement a token bucket rate limiter in Python using asyncio.
Requirements:
- The class must be named exactly `RateLimiter`
- `RateLimiter(rate: float, burst: int)` — rate is tokens per second, burst is max tokens
- `async acquire(tokens: int = 1) -> None` — async; wait until tokens are available, then consume them
- `try_acquire(tokens: int = 1) -> bool` — **synchronous** (non-async); return True if acquired, False otherwise. Do NOT declare this as `async def` — callers invoke it without `await`.
- Must handle concurrent callers correctly
Output only the Python code, no explanation.
Hidden test program
importasyncioasyncdeftest_basic():
rl=RateLimiter(rate=10, burst=5)
# Should succeed immediately (burst allows 5)assertrl.try_acquire(1) ==Trueassertrl.try_acquire(1) ==Trueassertrl.try_acquire(1) ==Trueassertrl.try_acquire(1) ==Trueassertrl.try_acquire(1) ==True# Should fail (burst exhausted)assertrl.try_acquire(1) ==Falseprint("basic: ok")
asyncdeftest_refill():
rl=RateLimiter(rate=100, burst=5)
# Exhaust burstfor_inrange(5):
rl.try_acquire(1)
assertrl.try_acquire(1) ==False# Wait for refillawaitasyncio.sleep(0.06) # should refill ~6 tokens at 100/sassertrl.try_acquire(1) ==Trueprint("refill: ok")
asyncdeftest_acquire_waits():
rl=RateLimiter(rate=100, burst=1)
rl.try_acquire(1) # exhauststart=asyncio.get_event_loop().time()
awaitrl.acquire(1) # should wait ~0.01selapsed=asyncio.get_event_loop().time() -startassertelapsed>=0.005, f"Should have waited, only {elapsed:.3f}s"assertelapsed<0.5, f"Waited too long: {elapsed:.3f}s"print("acquire_waits: ok")
asyncdeftest_multi_token():
rl=RateLimiter(rate=10, burst=10)
assertrl.try_acquire(5) ==Trueassertrl.try_acquire(5) ==Trueassertrl.try_acquire(1) ==Falseprint("multi_token: ok")
asyncdefmain():
awaittest_basic()
awaittest_refill()
awaittest_acquire_waits()
awaittest_multi_token()
print("ALL_TESTS_PASSED")
asyncio.run(main())
3. Recursive Descent Parser
Criterion
Points
basic_arithmetic
15
operator_precedence
20
parentheses
15
unary_minus
15
floating_point
10
error_handling
10
code_quality
15
total
100
Prompt
Write a Python function that parses and evaluates simple mathematical expressions.
Support: +, -, *, /, parentheses, unary minus, floating point numbers.
Respect operator precedence (* and / before + and -).
Raise ValueError on invalid expressions.
`def evaluate(expr: str) -> float`
Output only the Python code, no explanation.
Implement a Trie (prefix tree) in Python with autocomplete functionality.
Requirements:
- `insert(word: str) -> None` — insert a word
- `search(word: str) -> bool` — return True if exact word exists
- `starts_with(prefix: str) -> bool` — return True if any word starts with prefix
- `autocomplete(prefix: str, limit: int = 5) -> list[str]` — return up to `limit` words starting with prefix, sorted alphabetically
- `delete(word: str) -> bool` — remove a word, return True if it existed
Output only the Python code, no explanation.
Implement a typed event emitter in Python.
Requirements:
- The class must be named exactly `EventEmitter` (not `TypedEventEmitter` or anything else)
- `on(event: str, callback: Callable) -> Callable` — register listener, return unsubscribe function
- `once(event: str, callback: Callable) -> Callable` — register one-time listener
- `emit(event: str, *args, **kwargs) -> None` — call all listeners for event
- `off(event: str, callback: Callable) -> None` — remove specific listener
- `listeners(event: str) -> list[Callable]` — return list of listeners
- `remove_all_listeners(event: str = None) -> None` — remove all listeners for event, or all events if None
Output only the Python code, no explanation.
Implement a regular-expression engine in Python with POSIX leftmost-longest semantics. No imports of `re` or any regex/parsing library (pure stdlib data structures only).
API:
- `regex_match(pattern: str, text: str) -> tuple[int, int] | None`
Return `(start, end)` of the match, or `None` if no match anywhere in text.
Pattern syntax to support:
- literal characters; `.` (any single char)
- quantifiers on the previous atom: `*` (0+), `+` (1+), `?` (0/1)
- character classes: `[abc]`, ranges `[a-z0-9]`, negation `[^abc]`
- alternation `|` (lowest precedence), grouping `(...)` (affects precedence only, no capture semantics needed)
- anchors: `^` (only valid at pattern start) and `$` (only at pattern end)
SEMANTICS — this is the core of the task and it is NOT Perl/PCRE:
- LEFTMOST-LONGEST (POSIX): the match is the one starting at the smallest possible index; among matches at that start, the one with the greatest end. This applies through alternation and quantifiers: `regex_match("a|ab", "xab")` must return `(1, 3)` — the LONGER alternative wins, unlike PCRE.
- A pattern that can match the empty string matches at the leftmost position: `regex_match("x*", "abc")` returns `(0, 0)`.
PERFORMANCE — also graded: patterns like `(a|aa)*c` against long runs of `a` with no `c` must complete in well under a second. Exponential backtracking will fail the test suite's time budget. Build a proper NFA/DFA simulation, not a recursive backtracker.
Invalid patterns (unbalanced parens, dangling quantifier like `*a`, unterminated class) must raise `ValueError`. ^ or $ appearing anywhere other than the very start/end of the whole pattern may also raise ValueError.
Output only the Python code, no explanation.
Implement a convergent replicated text document (a CRDT) in Python, stdlib only.
API:
- `Replica(site_id: str)` — one collaborator's copy. `site_id` is unique per replica.
- `r.local_insert(pos: int, ch: str) -> dict` — insert single char at index `pos` in r's current visible text; apply locally and return the operation as a JSON-serializable dict to broadcast.
- `r.local_delete(pos: int) -> dict` — delete visible char at index `pos`; apply locally, return the op.
- `r.apply(op: dict) -> None` — apply an op received from another replica (or a duplicate of any op, including one's own).
- `r.text() -> str` — current visible text.
Required semantics (exactly these — they are what the tests check):
1. IDENTITY: every inserted character gets the id `(counter, site_id)` where `counter` is a Lamport clock: each replica's counter starts at 0, increments by 1 on each LOCAL insert, and on receiving any op updates to `max(local, op_counter)` before/so that later local ids stay unique and causally greater. Deletes do not create new ids; a delete op names the id of the deleted character.
2. STRUCTURE (RGA / insert-after): an insert op records the id of the character it was inserted AFTER (`origin`), or the sentinel origin `None` for position 0. Deleted characters become invisible TOMBSTONES but keep their place in the sequence (they still serve as origins).
3. CONCURRENT ORDER RULE: characters inserted after the SAME origin appear in DESCENDING order of `(counter, site_id)` — i.e. higher counter first; ties on counter broken by higher site_id first. (This makes a replica's own consecutive typing read left-to-right, and gives one deterministic answer for concurrent inserts.) When walking to place a new node after its origin, it must skip over any nodes (and their descendants) with greater `(counter, site_id)` per this rule — the standard RGA insertion scan.
4. DELIVERY: ops may arrive OUT OF ORDER and DUPLICATED. `apply` must be idempotent (same op twice = once). An insert whose origin hasn't arrived yet, or a delete whose target hasn't arrived yet, must be BUFFERED and applied automatically once its dependency arrives. No exceptions thrown for any of this.
5. CONVERGENCE: any set of replicas that has received the same set of ops (in any order, with any duplication) has identical `text()`.
Output only the Python code, no explanation.
Hidden test program
importsys, json, randomdefok(group):
print(f"{group}: ok"); sys.stdout.flush()
defdup(op):
returnjson.loads(json.dumps(op))
# basic single-replica editinga=Replica("A")
ops= []
fori, chinenumerate("hello"):
ops.append(a.local_insert(i, ch))
asserta.text() =="hello"ops.append(a.local_delete(0))
asserta.text() =="ello"ops.append(a.local_insert(0, "H"))
asserta.text() =="Hello"ok("basic")
# ops are JSON-serializable dictsforopinops:
assertisinstance(op, dict)
json.dumps(op)
ok("serializable")
# two-way convergence with the EXACT concurrent-order rulea=Replica("A"); b=Replica("B")
oa=a.local_insert(0, "x") # A: (1,"A")b.apply(dup(oa))
assertb.text() =="x"o1=a.local_insert(1, "a") # concurrent, same origin (after 'x'): A (2,"A")o2=b.local_insert(1, "b") # B (2,"B")a.apply(dup(o2)); b.apply(dup(o1))
asserta.text() ==b.text(), f"diverged: {a.text()!r} vs {b.text()!r}"asserta.text() =="xba", f"concurrent order rule: expected 'xba', got {a.text()!r}"ok("concurrent_order")
# out-of-order + duplicate delivery, bufferinga=Replica("A"); b=Replica("B")
o1=a.local_insert(0, "1")
o2=a.local_insert(1, "2")
o3=a.local_insert(2, "3")
od=a.local_delete(1) # deletes '2'asserta.text() =="13"b.apply(dup(od)) # delete before its insert arrivesb.apply(dup(o3)) # insert whose origin hasn't arrivedassertb.text() in ("", "3"), "buffering should hold od/o3 or show only what is placeable"b.apply(dup(o1))
b.apply(dup(o2))
assertb.text() =="13", f"after full delivery expected '13', got {b.text()!r}"foropin (o1, o2, o3, od):
b.apply(dup(op)) # duplicatesassertb.text() =="13", "idempotence violated"ok("out_of_order")
# three-replica randomized convergence (deterministic seed)random.seed(20260816)
reps= [Replica(s) forsin ("A", "B", "C")]
log= []
forstepinrange(120):
r=random.choice(reps)
ifr.text() andrandom.random() <0.3:
log.append(r.local_delete(random.randrange(len(r.text()))))
else:
pos=random.randrange(len(r.text()) +1)
log.append(r.local_insert(pos, random.choice("abcdefg")))
# occasionally deliver a random subset in random order to a random replicaifrandom.random() <0.5:
tgt=random.choice(reps)
batch=random.sample(log, min(len(log), random.randrange(1, 12)))
foropinbatch:
tgt.apply(dup(op))
# full delivery, shuffled differently per replica, with duplicatesforrinreps:
order=log[:]
random.shuffle(order)
foropinorder:
r.apply(dup(op))
ifrandom.random() <0.2:
r.apply(dup(op))
texts= [r.text() forrinreps]
asserttexts[0] ==texts[1] ==texts[2], f"divergence: {[t[:40] fortintexts]}"assertlen(texts[0]) >10, "fuzz produced implausibly short text"ok("convergence_fuzz")
print("ALL_TESTS_PASSED")
8. Async DAG Orchestrator (cancellation semantics)
Criterion
Points
basic_dag
15
true_concurrency
20
failure_skip
20
timeout_cancel
20
validation
10
code_quality
15
total
100
Prompt
Implement an async task orchestrator in Python (pure stdlib, asyncio only).
API:
- `class Orchestrator:`
- `add_task(name: str, fn, deps: list[str] = []) -> None`
`fn` is an async callable invoked as `await fn(results)` where `results` is a
dict {dep_name: dep_result} containing ONLY that task's declared deps.
Re-adding an existing name raises `ValueError`. A dep that was never added
by the time `run()` is called raises `ValueError` from `run()`.
- `async def run(self, task_timeout: float | None = None) -> dict`
Executes the whole DAG and returns {name: outcome} for EVERY task, where
outcome is one of:
{"status": "ok", "result": <return value>}
{"status": "failed", "error": <the exception instance>}
{"status": "cancelled"} # exceeded task_timeout
{"status": "skipped"} # any transitive dep not "ok"
RULES — read carefully, they are exactly graded:
1. CONCURRENCY IS REAL: tasks whose deps are satisfied run concurrently
(the tests wall-clock this). A task starts as soon as ALL its deps are "ok"
— not in topological "levels"/batches: if A takes 0.3s and B takes 0.1s and
C depends only on B, C must start ~0.1s in, while A is still running.
2. A task failure (exception) marks it "failed"; every transitive dependent
becomes "skipped" (never started). Unrelated tasks keep running to completion.
3. `task_timeout` applies per task: a task exceeding it is cancelled
(asyncio-cancelled, not left running) and reported "cancelled"; its
dependents are "skipped".
4. Cycles: `run()` raises `ValueError` BEFORE starting any task.
5. `run()` never raises for task failures/timeouts — they are reported in the
returned dict.
Output only the Python code, no explanation.
Implement an incremental (streaming) JSON value parser in Python — pure stdlib, and you may NOT import `json` or any parsing library. It must produce complete top-level JSON values as they finish arriving, no matter how the input is split into chunks.
API:
- `class StreamParser:`
- `feed(chunk: str) -> list`
Consume the next chunk of the stream and return a list of the top-level
JSON values COMPLETED by this chunk (usually empty or one; may be several
if one chunk contains several values). Top-level values are separated by
arbitrary whitespace (spaces, tabs, newlines) in the stream.
- `close() -> None`
Signal end of stream. Raises `ValueError` if a value is incomplete
(mid-string, unbalanced brackets, dangling literal, etc.). Trailing
whitespace is fine.
Supported JSON subset (returned as native Python values):
- objects {} -> dict, arrays [] -> list, arbitrarily nested
- strings with escapes: \" \\ \/ \b \f \n \r \t and \uXXXX -> str
- numbers: integers, decimals, exponents, leading minus (e.g. -1.5e-3).
Integers (no '.', no exponent) -> int, otherwise -> float
- true/false/null -> True/False/None
HARD REQUIREMENTS — exactly graded:
1. Chunks split ANYWHERE: mid-string, mid-escape (even between the backslash
and the 'u', or between \u digit hex chars), mid-number, mid-literal
(e.g. 'tr' then 'ue'), mid-key. The tests feed a corpus split at EVERY
single character boundary, one char at a time, and in random chunkings —
the outputs must be identical every time.
2. Malformed input raises `ValueError` at the earliest chunk where the text
cannot be a prefix of any valid stream (e.g. `{"a": tru5}` on the '5';
`[1,]` on the ']'). You do NOT need mid-number strictness beyond: a number
must not be immediately followed by an alphanumeric character.
3. A number at top level is only complete once a non-number character or
close() confirms it (e.g. feed("12") feed("3 ") -> [123]).
Output only the Python code, no explanation.