Ch.32: System Design: Build a Safe LeetCode Judge
Transcript
0:00 Take Mina submitting a solution to an online coding judge. It forks children forever, allocates memory, floods standard output, reads process files, and tries a network connection. Then the worker crashes after the last test. We'll make both the execution and its retry safe. Two failures hide here. The code can attack its neighbors, and a retry can publish a different answer. What does Mina see if attempt one reports time limit but attempt two says runtime error? Yeah. The common mistake is one a lot of us would make: put the code in a container, add a retry key, and feel finished.
0:37 I would not trust either phrase yet. A normal container shares a host kernel, and an execution job has too many observations to become safe just because it carries a deduplication token. Fair. We'll pin one recipe, run it inside a throwaway sandbox, preserve capped observations, and reduce retries to one stable verdict. We'll test those choices against official docs as we go; the direct links are in the description. Contain the code; explain the answer. That double failure gives us one path. The Submission API persists Mina's code and durable launch record.
1:13 The scheduler holds the job until an eligible Python runner takes it. The Runner Manager starts one sandbox from the frozen recipe. Mina's compiler and program stay inside. A host monitor stays outside and sends one bounded receipt to the Attempt Evidence Store. Then the Verdict Reducer decides whether that receipt may publish. The Status API shows the result, and a Rejudge Controller can open a later evaluation generation. So the trust line wraps the compiler and submitted program, not the whole worker. Scheduler, monitor, evidence store, and reducer remain outside.
1:45 Good. Now every box needs a promise we can test against Mina's failure. Now turn that architecture into two promises that survive Mina's crash. First, the functional requirements: accept source, language, and problem; return a durable ID; run hidden tests; show queued, running, then one verdict. A correction launches a rejudge instead of editing history. The same source can behave differently next week unless we preserve the exact execution recipe. The non-functional requirements: isolate hostile code; bound CPU, memory, descendants, time, disk, and output; never lose source or dispatch after returning an ID. Duplicate work is allowed; an unexplained screen change is not.
2:24 As a concrete case, our fictional peak can overlap 50,000 attempts before retries, so isolation must scale. Next, pin retry identity. Those requirements lead to the identity question. Mina's request says Python and names a problem. Is that enough to reproduce her verdict next week? My instinct was source plus runtime version. But that still lets the judge change around identical source. What else belongs in the identity? Let's hear it. The whole recipe. Store the source hash, problem version, hidden test-bundle hash, checker digest, language-image digest, policy version, and a deterministic seed where one applies. Together they identify one generation's execution recipe.
3:00 Why pin the checker separately from the tests? Because the checker decides whether observed output is correct. For example, Mina can print the same decimal twice, yet a tighter tolerance in a replacement checker changes the result. A rebuilt image can also carry another compiler, runtime, or library. Oh, that's more fragile than a language label suggests. The row names the recipe; content-addressed storage keeps the larger artifacts by hash. That gives every retry a verifiable identity. With the recipe defined, Mina taps Submit.
3:36 The API validates the request, stores her source by hash, and commits both the submission row and a dispatch intent before returning the ID. One outbox guarantee matters: if Mina receives an ID, dispatch is durable. A crash between the database and queue cannot strand accepted source. The relay may publish twice, and her client may retry the request, but both point to the existing submission. That only makes delivery durable. Execution still cannot roll back like a row update. Right. Every run becomes a separate immutable attempt.
4:09 That is the evidence we will compare when a worker dies after doing real work. Next, Mina enters the contest spike. Admission caps active attempts. For example, during a contest, her Python job can wait while idle Java machines cannot run its frozen recipe, so her start latency rises. Oh, so a half-idle fleet can leave Mina waiting. Schedule by queue age in compatible pools, reserve practice starts, and slow Python admission when no template is free. Then a matching runner receives the recipe, and hostile work begins.
4:41 Next, fair scheduling ends at an eligible runner, not at trusted source. It receives Mina's recipe and copies the source into the sandbox. We have not earned permission to compile on the host. An infrastructure lead staring at peak startup cost might say, “Keep compilation on the host and save the sandbox startup.” Imagine Mina's source triggering a compiler parser bug before her program exists. The build toolchain belongs inside the sandbox too. Sure. Mina controls the compiler's input, so calling compilation setup does not make it trusted.
5:13 Compile and execute inside the same one-use sandbox using the pinned image, with no host sockets or writable shared caches. Seal the build output read-only when compilation finishes. Each hidden case gets a fresh contestant process and scratch. The runner streams only that case through standard input, kills every descendant afterward, then discards the scratch. The full test bundle never enters Mina's filesystem; the trusted checker compares captured output outside. A compile failure still produces a limited record and destroys the sandbox.
5:44 The same boundary now covers source parsing through the last hidden test. That leaves the boundary choice: if compilation stays off the host, what is strong enough to run it? Keeping the compiler off the host forces a boundary choice. A plain container still shares the host kernel. We default to a microVM with a private guest kernel, accepting lower density for stronger isolation. A gVisor pool is a later optimization for validated toolchains. It checks many system calls before they reach the common kernel, with compatibility and performance tradeoffs documented by the project.
6:20 One is a private room; the other is a checkpoint on every crossing. We choose the room first. Consider one inherited scratch file from the previous occupant: isolation already failed even if neither program escaped. Preboot clean templates, but never reuse writable state. That buys isolation between occupants. Next, the host still needs authority to stop a sandbox that refuses to leave. That isolation choice opens the live-control question. Destroying the guest afterward is too late if it can run forever.
6:49 Who owns the stop button while Mina's program is still forking and allocating? Not any process Mina controls. I mean, once her code can fork, the timer cannot live in her process tree. Asking hostile code to police itself is not a control plane. The trusted host monitor enforces wall time. Linux cgroup version 2, the host's resource-control layer, caps aggregate CPU and memory; guest-side process and open-file limits add another layer. Wait, output is the loophole a lot of us forget. Mina can write as fast as the runtime allows while staying under the CPU cap, filling storage or overwhelming log processing while the compute gauge still looks healthy. Oh, right.
7:32 The CPU gauge can look healthy while output is eating the worker. At 10 seconds, the monitor kills the whole sandbox. At the byte cap, it stops accepting output and records which limit fired. Killing only the parent process leaves children behind. Yeah. Network denial belongs at the host boundary, not only within the sandbox. A program should not reach package registries, another runner, or a cloud metadata service because it ignored a friendly configuration. These layers bound direct damage, not every hardware timing or cache side channel.
8:04 The result is narrower but testable: block forbidden interfaces and preserve trusted evidence that explains why Mina's run stopped. Okay, let's unpack this. One receipt makes the evidence path concrete. For attempt A, the outside monitor records the attempt ID, recipe hash, start and stop times, processor time, peak memory, output bytes, the stop reason, and whether the worker stayed healthy through evidence upload. The external checker adds its observation. Mina's process supplies output, but it cannot declare its own memory peak or invent a trusted stop reason.
8:36 The monitor writes the receipt over a trusted channel outside the sandbox before the sandbox disappears. For test 37, suppose it says: wall time 10.01 seconds, processor time 9.87, peak memory 182 mebibytes, host healthy, whole sandbox killed at the wall limit. That supports time limit. Secret test input stays in judge storage. Its bundle hash proves identity while Mina gets a bounded explanation. That gives the reducer facts it can accept or reject. With that complete receipt stored, attempt A's worker dies before acknowledging the queue message.
9:13 The queue starts attempt B from the same recipe. A stays; B lands beside it. Before those, imagine attempt zero ended differently. Its last worker heartbeat was at 7.3 seconds, its evidence cuts off mid-test, and there is no monitor-issued stop record. A sandbox log claims time limit. Can that publish? My first thought is to keep its timeout label because the queue wants a result. But no. The vanished worker leaves us unable to separate contestant timeout from infrastructure failure. Keep the record for the incident, mark it infrastructure-invalid, and retry. It cannot blame Mina.
9:50 Right. A is eligible because its recipe matches, every required field is complete, the monitor recorded the stop, and the host remained healthy through upload. The reducer uses compare and set on an empty verdict slot. If A gets there first, it publishes time limit. Yeah. B cannot silently replace it. Stable publication means one visible answer per generation. Execution agreement is a different test. Now we can inspect the harder receipt. Now compare A with attempt B. It has the same recipe and complete trusted evidence, but its receipt says: 2.1 seconds, exit zero, checker accepted, host healthy.
10:26 Which receipt is invalid? Neither. Suppose Mina's program has a data race. The frozen source, tests, image, and limits repeat, while thread scheduling does not. One interleaving spins beyond 10 seconds; another prints the expected answer. The recipe narrows variation, but it cannot make arbitrary code deterministic. Wait, really? Exactly. Picking the friendlier result would hide the disagreement, and picking the faster worker would be arbitrary. A keeps the published slot, but the contradiction puts that generation under review.
10:56 Mina sees “Time Limit Under review,” not a silent flip. Right. Operators quarantine the implicated image or host pool and inspect both receipts. The incident runbook keeps both records. If policy calls for correction, the system opens another judging generation. That valid mismatch opens the correction path. Suppose operators confirm the configured time limit was wrong and open generation two with a corrected policy version. What is Mina allowed to see while that correction runs? Generation one's verdict stays visible with a Rejudging badge.
11:27 When generation two finishes with complete valid evidence, the status service atomically points current generation to two. So Mina's main screen becomes “Accepted Current.” History still shows “Time Limit Generation one Superseded after limit correction,” with both recipe hashes and receipts preserved. The correction event reaches the scoreboard, so its update is explicit. A failed rejudge never replaces the current pointer; a successful one advances it without rewriting the past. Yeah. That is the chosen behavior for this fictional design, not a claim about LeetCode's private backend.
11:59 Now the same map can close on Mina's actual screen instead of another vocabulary lap. Now trace that successful rejudge across the unchanged map once. Durable request, compatible runner, pinned sandbox, trusted receipt path, reducer. Every box exists to answer one question: may this receipt change Mina's current result? Her final screen says “Accepted Current,” with the superseded result one tap away. The system controlled hostile code without hiding the broken worker, contradictory replay, or correction that produced her answer.
12:28 Four labels carry the interview: pinned recipe, disposable boundary, trusted receipt, one current generation with preserved history. Confine the program; defend the answer. Thanks for listening to Learning Podcasts.