Category: AI-Assisted

  • CD0034 AI Resumable Iterator

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0029 AI DistributedSampler

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0024 AI Rate-Limiter Retry

    Mode D · AI-Assisted 60 Min Python 3.10+ 3 Phases · 3 Draft Flaws

    Shopify’s REST Admin API meters every app with a leaky bucket. Standard plans get a burst of 40 requests per store and a steady leak of 2 requests per second, and a request that overflows the bucket comes back as HTTP 429 with a Retry-After header. An inventory-sync team that talks to thousands of stores keeps a small Python client, rate_client.py. It holds a client-side token bucket sized to the same 2 req/s and burst of 40, plus a retry_call helper that every worker uses. The AI-enabled coding round built on this client runs 60 minutes in three phases, and the AI assistant becomes available from Phase 2 onward.

    Phase 1 (Unaided Warm-Up): the starter bucket carries one planted refill bug. In a 60-second soak test where one worker polls try_acquire() every 250 ms, the client admits its 40-request opening burst and then nothing for the remaining 59 seconds. A sync job that wakes every 1.5 s and drains the bucket gets about 1.3 req/s instead of 2. Find and fix the bug by hand. Phase 2 (AI-Delegated Build): pick the one prompt out of three that pins the full retry contract below. Phase 3 (Audit): the assistant’s draft passes a 503-then-200 smoke test but violates the contract in three places. Find them, patch them in place, and prove every fix on a scripted clock.

    Phase 2 Target Contract:
    (1) Retryable Set: retry HTTP 429, any 5xx, and a raised ConnectionError or TimeoutError. Return every other status to the caller at once.
    (2) Wait Source: wait the Retry-After value in seconds when the response carries one. Otherwise use exponential backoff d_n = \min(c, \beta 2^n) with full jitter, so that clients failing together spread across the whole window.
    (3) Budget Bound: each call has a budget (default 60 s) on a monotonic clock and at most max_attempts attempts. If a wait would cross the deadline, give up and surface the last response or error instead of sleeping.

    Phase 1 Starter (rate_client.py):

    01  import time
    02
    03
    04  class RateLimiter:
    05      """Client-side token bucket: rate tokens/s, at most capacity held."""
    06
    07      def __init__(self, rate, capacity, clock=time.monotonic):
    08          self.rate = float(rate)
    09          self.capacity = float(capacity)
    10          self.clock = clock
    11          self.tokens = float(capacity)
    12          self.last = clock()
    13
    14      def try_acquire(self):
    15          now = self.clock()
    16          elapsed = now - self.last
    17          self.tokens = min(self.capacity, self.tokens + int(elapsed) * self.rate)
    18          self.last = now
    19          if self.tokens >= 1.0:
    20              self.tokens -= 1.0
    21              return True
    22          return False
    23
    24
    25  def retry_call(send, limiter, sleep=time.sleep, poll=0.05):
    26      """Wait for a token, then send once. Phase 2 adds retries here."""
    27      while not limiter.try_acquire():
    28          sleep(poll)
    29      return send()
    Request lifecycle of the rate-limited client: caller, token bucket at 2 requests per second with burst 40, send to the Admin API, then two question-marked steps (classify outcome, choose wait) and a return-or-raise box, with a dashed retry arc back to the bucket; below, three contract boxes list the retryable set, the wait source, and the 60 second budget

    Figure 1: the Phase 1 token bucket gates every attempt. The two question-marked steps are what the AI builds in Phase 2 and you audit in Phase 3, and the bottom row is the Phase 2 Target Contract every prompt must pin.

    Interactive Python Workspace: Switch to the split-screen workspace to fix the starter, steer the simulated AI Copilot, and audit its draft against the hidden test suite.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Refill Accounting: Replay one poller on a fake clock at 250 ms, 1 s, and 1.5 s cadences, and compare the admitted count with burst plus rate times duration.
    (2) Contract Checklist: Score each Phase 2 prompt line by line against the retryable set, the wait source, the jitter form, and the budget bound. One contradicted line disqualifies a prompt.
    (3) Hostile Inputs: Drive the draft with a scripted clock and a matrix of status codes, raised errors, and Retry-After values from 0 up to far beyond the budget, recording attempts and total sleep.
    (4) Crowd Behavior: Start many seeded clients that fail at the same instant and measure how widely their later retries spread.

    2Visual Review Map (Figure 2)
    Review map with the same question mark on every region: three regions of the Phase 1 listing (init state, try_acquire, retry_call), the Phase 2 prompt choice, and three regions of the Phase 3 draft (backoff helper, attempt loop, wait selection)

    Figure 2: Every region of the listing and the draft carries the same question mark. Walk each one with a scripted clock rather than guessing from the code which one hides a defect.

    3Interviewer Nudge & Line Focus

    Answer each phase’s Socratic check with numbers before editing:

    Phase 1 (Token Crediting): A poller calls try_acquire() every 250 ms against a 2 req/s bucket. How many tokens should four consecutive calls credit in total, and how many does the starter credit? What should a 60-second run admit, counting the 40-token burst?
    Phase 2 (Spotting Flawed Prompts): Turn the contract into four checkboxes: retryable set, wait source, jitter form, budget bound. Which prompt ticks all four, and which ones state a status rule, a jitter rule, or a sleep rule that sounds reasonable but contradicts a checkbox?
    Phase 3 (Auditing the Retry Draft): With 60 s of budget left, how long does the draft sleep for a 429 carrying Retry-After: 3600? If 200 clients all fail at t = 0, how wide is the window in which their fourth attempt lands? How many requests does a single 404 cost the shared bucket?
    Answer
    Login to view more content
  • CD0020 AI Code Comprehension

    Mode D · AI-Assisted 60 Min NumPy · Python 3 3 Phases · 3 AI Flaws

    Picture a retrieval-evaluation codebase on a Google team. An offline harness ranks a few hundred thousand stored document embeddings against each eval query by cosine similarity and reports recall@k. This round follows the code-comprehension format reported for Google’s 2026 interviews. You receive a module you did not write, an AI assistant is available, and the grade depends on how you read, steer, and audit, not on typing speed.

    Phase 1 (Read & Explain, unaided, no AI): trace what SimilarityIndex computes and name the lines where its cost lives. Then fix the one correctness issue your trace exposes. After an ingest batch in which the upstream encoder timed out on a few documents, every ranking the harness prints contains nan scores, the order is visibly non-monotone, and NumPy emits a RuntimeWarning about an invalid value encountered in a divide.

    Phase 2 (AI-Assisted Optimize): write the prompt that gets the assistant to vectorize the row-wise similarity loop and add a top-k API. Phase 3 (Audit the AI’s Rewrite): the assistant’s draft runs and returns arrays of the right shape, yet it violates the contract below in exactly three places. Find them, fix them in place, and write one verification test proving that the vectorized path matches the reference loop within tolerance.

    Phase 2 Target Contract:
    (1) score(queries): accepts an (n_queries, d) or (d,) input and returns an (n_queries, n_vecs) float64 matrix. Its values must equal the reference loop’s values within 10^{-12}, and no Python loop over stored rows is allowed.
    (2) topk(queries, k): returns (ids, scores), each of shape (m, \min(k, n)), with the best match first. Equal scores are broken by insertion order, exactly as rank() breaks them today, and scores are float64.
    (3) rank(query, k): keeps its current return format, a list of (id, score) pairs, and delegates to topk().

    Starter Module (42 Lines, Read Before You Touch):

    01  import numpy as np
    02
    03
    04  class SimilarityIndex:
    05      """Cosine-similarity index over an in-memory vector store."""
    06
    07      def __init__(self, dim: int):
    08          self.dim = dim
    09          self.ids = []
    10          self.vecs = np.empty((0, dim), dtype=np.float64)
    11
    12      def add(self, ids, vecs):
    13          vecs = np.asarray(vecs, dtype=np.float64)
    14          assert vecs.ndim == 2 and vecs.shape[1] == self.dim
    15          assert len(ids) == vecs.shape[0]
    16          self.ids.extend(ids)
    17          self.vecs = np.vstack([self.vecs, vecs])
    18
    19      def score(self, queries):
    20          """Return an (n_queries, n_vecs) matrix of cosine similarities."""
    21          queries = np.asarray(queries, dtype=np.float64)
    22          n_queries, n_vecs = queries.shape[0], self.vecs.shape[0]
    23          sims = np.zeros((n_queries, n_vecs), dtype=np.float64)
    24          for i in range(n_queries):
    25              q = queries[i]
    26              query_norm = np.linalg.norm(q)
    27              for j in range(n_vecs):
    28                  v = self.vecs[j]
    29                  vec_norm = np.linalg.norm(v)
    30                  sims[i, j] = np.dot(q, v) / (query_norm * vec_norm)
    31          return sims
    32
    33      def rank(self, query, k=None):
    34          """Return top-k (id, score) pairs, best match first."""
    35          sims = self.score(np.asarray(query)[None, :])[0]
    36          order = sorted(range(len(sims)), key=lambda j: -sims[j])
    37          if k is not None:
    38              order = order[:k]
    39          return [(self.ids[j], sims[j]) for j in order]
    40
    41      def __len__(self):
    42          return len(self.ids)
    Three-phase round: Phase 1 read and explain the starter module unaided, Phase 2 prompt the AI to vectorize score() and add topk(), Phase 3 audit a draft containing three unnamed flaws shown as question marks; below, three contract boxes for score(), topk(), and the loop-versus-vectorized parity oracle

    Figure 1: The round runs read, steer, audit in that order. The Phase 2 target contract along the bottom is the yardstick for both your prompt and the AI’s draft.

    Interactive PyTorch Workspace: Switch to the split-screen workspace to run the Phase 1 warm-up, steer the simulated assistant, and audit its draft against the hidden parity, ordering, and dtype checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Explain Before You Touch: State in one sentence what sims[i, j] means and what rank() returns, including how it orders equal scores.
    (2) Complexity Hot Spot: Count how many times the innermost lines run for m queries and n stored rows, and which per-row work repeats for every query.
    (3) Degenerate Rows: Decide what a cosine score should be when a vector has no magnitude, before trusting any ranking built on it.
    (4) Same Quantity, Fewer Loops: A vectorized score must reproduce every factor of line 30, not just the part that looks like a matmul.
    (5) Output Contract: Order, tie-break, shape, and dtype are all part of the API that downstream tests pin.

    2Visual Review Map (Figure 2)
    Stage map with two rows: the starter's reference loop (input queries, norms in the loop marked with a question mark, per-pair score, sort, rank output) and the AI draft pipeline (input queries, input prep, score matrix, and ordering each marked with a question mark, then the topk and rank output), joined by a parity check arrow

    Figure 2: The reference loop (top) and the AI draft (bottom) as stage maps. Every ? marks a stage to audit, and deciding what each stage should do is the exercise.

    3Interviewer Nudge & Line Focus

    Work the three phases in order using the stage checks below:

    Phase 1 (Read & Explain): How many times do lines 29-30 execute for n_queries queries and n_vecs stored rows, which norm gets recomputed once per query, and what does line 30 evaluate to when a stored row has no magnitude at all?
    Phase 2 (Spotting Flawed Prompts): Do not judge prompts by coverage of the score formula alone. Check whether the spec pins all three contracts: row normalization, descending order with stable ties, and float64 end to end. A contract the prompt drops comes back dropped in the regenerated draft.
    Phase 3 (Auditing the Cosine Scorer): Scale one stored row by 10: should its cosine score change, and does it in the draft’s score()? Which direction does np.argsort order each row by default, and which of two tied rows must come first? Then trace the dtype of every intermediate: what does a float64 golden-score assertion receive?
    Answer
    Login to view more content
  • CD0019 AI-Assisted Tokenizer Fix

    Mode D · AI-Assisted 60 Min Python 3.10+ 1 Warm-Up Bug + 3 AI Flaws

    Inside Meta’s text-preprocessing layer in front of a byte-level text classifier sits a small multi-file repository with a red test suite and an AI assistant in the editor sidebar; the exercise is how you split the work between yourself and the model. tokenizer.py defines ByteTokenizer, whose vocab maps 96 byte values (printable ASCII plus newline) to ids 4 to 99, with PAD = 0, BOS = 1, EOS = 2, UNK = 3. batching.py defines encode_batch, a legacy chunked encoder that was written for a cross-chunk merge pass, and that merge pass has since been removed.

    CI reports one failing test, test_encode_batch_lengths, run with chunk size 4. It prints len 4: expected 5 ids, got 4 and len 8: expected 9 ids, got 8, while lengths 0, 1, 2, 3, 5, 6, and 7 pass. Phase 1 (unaided, with the assistant switched off): make that test green. Phase 2: steer the assistant to add a streaming API. Phase 3: the assistant’s first draft contains 3 subtle flaws. Audit it, repair it, and write a verification suite that covers batch/streaming equivalence and vocab integrity.

    Phase 2 Target Contract: encode_iter(text, *, add_bos=False, add_eos=True, special_map=None) is a generator method on ByteTokenizer. It walks text.encode("utf-8") in self.chunk-byte slices and yields one id at a time.
    (1) Stream Equals Batch: With default flags, list(tok.encode_iter(t)) == encode_batch(tok, [t])[0] must hold for every text and every chunk size n \geq 1.
    (2) Framing Flags: add_bos=True prepends BOS, and add_eos=False drops the trailing EOS.
    (3) Per-Call Specials: special_map routes chosen byte values (for example newline) to special ids for that call only, and tok.vocab stays unchanged.
    (4) Unknown Bytes: A byte outside the vocab keeps its position in the stream and becomes unk_id.

    Starter Code (tokenizer.py + batching.py):

    01  # ---- tokenizer.py ----
    02  class ByteTokenizer:
    03      def __init__(self, vocab, pad_id, bos_id, eos_id, unk_id, chunk=4):
    04          self.vocab = vocab  # byte value -> token id
    05          self.pad_id, self.bos_id = pad_id, bos_id
    06          self.eos_id, self.unk_id = eos_id, unk_id
    07          self.chunk = chunk
    08
    09      def encode_chunk(self, chunk: bytes) -> list:
    10          return [self.vocab.get(b, self.unk_id) for b in chunk]
    11
    12
    13  # ---- batching.py ----
    14  def encode_batch(tok, texts, add_eos=True):
    15      n, out = tok.chunk, []
    16      for text in texts:
    17          data = text.encode("utf-8")
    18          ids, pending = [], None
    19          for i in range(0, len(data), n):
    20              row = tok.encode_chunk(data[i:i + n])
    21              if pending is not None:
    22                  ids.append(pending)
    23              if len(row) < n:  # tail chunk
    24                  ids.extend(row)
    25                  pending = None
    26              else:
    27                  ids.extend(row[:-1])
    28                  pending = row[-1]
    29          if add_eos:
    30              ids.append(tok.eos_id)
    31          out.append(ids)
    32      return out
    Three-phase flow of the round: Phase 1 is an unaided fix of encode_batch where some input lengths fail, marked with a question mark; Phase 2 is choosing one of three prompts for encode_iter; Phase 3 is auditing the AI draft for three subtle flaws, marked with question marks. Below are three contract boxes: the stream must equal the batch output, tok.vocab must never change, and unknown bytes become unk_id in place while ids are yielded one at a time

    Figure 1: The round has three graded phases. Every phase is checked against the same Phase 2 Target Contract, and the question marks show what you have to find.

    Interactive Python Workspace: Switch to the split-screen workspace to run all three phases. First fix encode_batch unaided, then pick a steering prompt, then audit the assistant’s draft against the hidden checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Tail-Chunk Contract: For every byte length L, including 0, n, and 2n, the output holds exactly L byte ids followed by EOS.
    (2) Deferred-Id Ownership: Any id held back at a chunk boundary must be written exactly once, and by exactly one code path.
    (3) Shared-State Contract: A per-call option may change what one call yields. It must never change the tokenizer object that other callers share.
    (4) Unknown-Byte Contract: An OOV byte keeps its position in the stream and carries the id the tokenizer designates for unknowns.

    2Visual Review Map (Figure 2)
    Review map of the two files with identical question-mark markers. In batching.py, the marker sits next to the tail-chunk test with its deferred boundary id. In the AI draft of encode_iter in tokenizer.py, markers sit next to the lookup table setup, the per-byte id lookup, and the chunk loop with its tail flush

    Figure 2: Each question mark labels a stage worth a hand trace. Working out what is wrong there is the exercise.

    3Interviewer Nudge & Line Focus

    Work the three phases in order using the stage checks below:

    Phase 1 (Tail-Chunk Predicate): Trace L = 4 and L = 5 with n = 4 by hand. On each iteration, where does the deferred id end up? For which length is there no later iteration left to write it?
    Phase 2 (Spotting Flawed Prompts): Do not judge prompts by keyword coverage. Check whether the spec pins every contract clause: a per-call vocab copy, the unk policy, stream-equals-batch at every length, and the batch oracle’s own tail flush. A clause left unpinned comes back broken in the regenerated draft.
    Phase 3 (Auditing the Stream Loop): Dry-run the stream twice — once with special_map={10: 100}, then again on plain text: which table did the update mutate? Feed a byte outside the vocab: which id does the stream emit versus encode_chunk? And at a byte length of exactly 2n, how many times does the final id come out?
    Answer
    Login to view more content
  • CD0006 AI-Assisted KV Cache GQA

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.