Tag: Data Eng

  • CD0044 AI Feature Flag Rollout

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

  • CD0040 Debug Normalization Leakage

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

  • CD0034 AI Resumable Iterator

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

  • CD0031 Debug ERP Reconciliation

    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.

  • CD0027 AUC-ROC From Scratch

    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
  • CD0023 GPU Stall Triage

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

  • CD0022 Softmax Cross-Entropy

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

  • CD0018 Slow Pipeline Triage

    Mode C · Incident Triage 30 Min Spark SQL · Delta Lake 5 Telemetry Clues

    A data-ML team on Databricks runs a nightly job, nightly_features, that builds the per-user training table for a churn model: it joins feature_store.events (2.0 billion rows over a 28-day window, a streaming-ingested Delta table) to feature_store.users (40 million rows) on user_id and aggregates per user. What lands on your desk is not a whiteboard prompt but an incident ticket.

    Incident Ticket INC-4471: The job took 8m 04s on 2024-05-02 and 41m 12s last night (2024-05-23). The training table now lands after the 03:00 deadline. There have been no commits to the job since 2024-04-11 and no new columns, and the cluster is unchanged at 40 executors with 4 cores each. The on-call engineer proposes doubling the cluster to 80 executors tonight.

    Walk through your 30-minute diagnostic tree before anyone touches hardware. Name the candidate causes (data growth, join-key skew, stale or refreshed statistics, file-layout decay) and say what each one predicts. Then inspect the 5 clues below in order, isolate the compound root cause, and specify the fix plus a regression guard. An optional Patch Lab in the workspace asks you to implement four small stabilization helpers against hidden checks.

    Job Query (Unchanged Since 2024-04-11):

    SELECT e.user_id, u.segment,
           COUNT(*)        AS n_events,
           SUM(e.dwell_ms) AS dwell_ms_sum
    FROM feature_store.events e
    JOIN feature_store.users u
      ON e.user_id = u.user_id
    JOIN feature_store.training_event_types t
      ON e.event_type = t.event_type
    WHERE t.is_training = true
      AND e.event_date >= date_sub(current_date(), 28)
    GROUP BY e.user_id, u.segment
    Line chart of nightly_features end-to-end runtime over 22 nights, rising from 8 minutes on night 0 to 41 minutes on night 21, with a dashed reference line at the night-0 runtime and notes that there were zero code commits and that the on-call proposal is to add executors

    Figure 1: Nightly runtime of nightly_features over the 22 nights since its last 8-minute run. Code, schema, and cluster size were unchanged across the whole window.

    Incident Telemetry: 5 Clues (Inspect In Order)
    #1Clue #1: EXPLAIN Plan, Night 0 vs Night 21
    -- job run 2024-05-02 02:00, 8m 04s, plan hash 7f3a91
    HashAggregate(keys=[user_id#40, segment#90], functions=[count(1), sum(dwell_ms#43)])
    +- SortMergeJoin [user_id#40], [user_id#88], Inner
       :- Exchange hashpartitioning(user_id#40, 2000)
       :  +- BroadcastHashJoin [event_type#41], [event_type#70], Inner, BuildRight
       :     :- FileScan parquet feature_store.events[user_id#40,event_type#41,dwell_ms#43,event_date#44] DataFilters: [isnotnull(user_id#40), dynamicpruningexpression(event_type#41 IN dynamicpruning#912)], PartitionFilters: [(event_date#44 >= 2024-04-04)]
       :     +- BroadcastExchange HashedRelationBroadcastMode
       :        +- Filter (is_training#71 = true)
       :           +- FileScan parquet feature_store.training_event_types[event_type#70,is_training#71]
       +- Exchange hashpartitioning(user_id#88, 2000)
          +- FileScan parquet feature_store.users[user_id#88,segment#90]
    
    -- job run 2024-05-23 02:00, 41m 12s, plan hash c19e04
    HashAggregate(keys=[user_id#40, segment#90], functions=[count(1), sum(dwell_ms#43)])
    +- BroadcastHashJoin [event_type#41], [event_type#70], Inner, BuildRight
       :- SortMergeJoin [user_id#40], [user_id#88], Inner
       :  :- Exchange hashpartitioning(user_id#40, 2000)
       :  :  +- FileScan parquet feature_store.events[user_id#40,event_type#41,dwell_ms#43,event_date#44] DataFilters: [isnotnull(user_id#40), isnotnull(event_type#41)], PartitionFilters: [(event_date#44 >= 2024-04-25)]
       :  +- Exchange hashpartitioning(user_id#88, 2000)
       :     +- FileScan parquet feature_store.users[user_id#88,segment#90]
       +- BroadcastExchange HashedRelationBroadcastMode
          +- Filter (is_training#71 = true)
             +- FileScan parquet feature_store.training_event_types[event_type#70,is_training#71]
    
    -- plan hash history: 7f3a91 (05-02 .. 05-09), c19e04 (05-10 .. 05-23)
    -- catalog audit: 2024-05-09 03:10 ANALYZE TABLE feature_store.users COMPUTE STATISTICS FOR ALL COLUMNS (auto-maintenance)
    -- git log jobs/nightly_features: last commit 2024-04-11

    Your read: What differs between the two plans, and does anything in the catalog line up with the night the plan hash changed?

    #2Clue #2: Per-Task Time Histogram, Stage 14
    Stage 14: SortMergeJoin + HashAggregate, run 2024-05-23
    tasks 2000   wall 22m 05s
    task duration   min 9s   p25 14s   median 18s   p75 22s   p90 27s   p99 720s   max 1290s
    shuffle read    median 312 MB   p99 7.1 GB   max 9.8 GB (task 1377)
    spill (disk)    median 0 B      p99 18 GB    max 41 GB  (task 1377)
    executor timeline: 40 of 40 busy until 6m 10s, 12 of 40 busy at 10m 00s,
                       1 of 40 busy from 13m 40s until 22m 05s
    AQE: skewed partitions split = 0, coalesced partitions = 0
    
    Stage 14 on 2024-05-02: wall 4m 01s, median 7s, p99 11s, max 14s

    Your read: How does the slowest task compare with the median one, and how busy is the cluster for most of this stage?

    #3Clue #3: Table Growth Metrics
    metric                          2024-05-02     2024-05-23     ratio
    events rows (28-day window)     0.67 B         2.00 B         2.99x
      source = consumer_app         0.67 B         0.79 B         1.18x
      source = partner_api          0 B            1.21 B         new (onboarded 2024-05-03)
    events distinct user_id         8.1 M          12.0 M         1.48x
    events bytes on disk            63 GB          186 GB         2.95x
    events columns                  14             14             +0
    users rows                      39.2 M         40.0 M         1.02x
    cluster                         40 x 4 cores   40 x 4 cores   unchanged

    Your read: If runtime tracked row count alone, what would last night have cost, and along which dimension did the table actually grow?

    #4Clue #4: Join-Key Cardinality Distribution
    user_id share of events rows (window ending 2024-05-23)
    band              keys        rows      share
    top 8             8           190 M     9.5%
    top 0.01%         1,200       360 M     18.0%
    top 1%            120,000     610 M     30.5%
    remaining 99%     11.88 M     1.39 B    69.5%
    
    hottest key: user_id 90000017 (partner-ingest-svc-01): 31 M rows
    event_type mix, top 1,200 keys: api_heartbeat 70%, view 21%, click 8%, purchase 1%
    event_type mix, all rows:       api_heartbeat 31%, view 46%, click 19%, purchase 3%, add_to_cart 1%
    training_event_types where is_training: view, click, purchase, add_to_cart

    Your read: How many rows does the hottest key send to a single task, and how much of that volume does the query’s output actually use?

    #5Clue #5: Small-File Count and Table Maintenance
    DESCRIBE DETAIL feature_store.events
      numFiles 60,412   sizeInBytes 186 GB   avg 3.1 MB per file
      (2024-05-02: numFiles 1,210, avg 53 MB per file)
    
    DESCRIBE HISTORY feature_store.events, last 21 days
      STREAMING UPDATE   30,240 commits   writer partner_api_ingest, trigger 60 s
      WRITE (batch)      21 commits       writer consumer_app_daily
      OPTIMIZE           0 commits        last OPTIMIZE 2024-04-30
    
    Jobs: events_optimize_weekly
      runs 2024-05-07, 2024-05-14, 2024-05-21: SKIPPED (cluster policy "maint-v1" not found)
    
    Driver log, stage 0 (file listing + footer reads): 6m 20s   (2024-05-02: 31s)

    Your read: What does the file layout cost before a single row is joined, and why did nothing correct it?

    Incident Triage Workspace: Switch to the split-screen workspace to inspect the raw telemetry in the triage console and, optionally, write the stabilization patch in the sandbox.

    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Plan Contract: Compare a fast night’s physical plan with a slow night’s, operator by operator, and note where every filter sits relative to the first shuffle.
    (2) Stage Critical Path: A stage finishes when its slowest task finishes, so compare the task-time tail with the median before reasoning about cluster size.
    (3) Growth Accounting: Turn the row-count ratio into a predicted runtime and treat any gap between prediction and observation as a separate cause to explain.
    (4) Key Distribution: A hash shuffle sends every row of one key to one task, so check what share of rows the heaviest keys hold.
    (5) File Layout: Check files per gigabyte and whether the table maintenance that should bound it actually ran.

    2Visual Review Map (Figure 2)
    Review map of the pipeline stages optimizer plan, scan events, shuffle by user_id, join and aggregate tasks, and nightly runtime, each linked to the clue that inspects it, with a uniform question mark on every clue box

    Figure 2: Each clue inspects one stage of the pipeline. Every box carries the same “?” marker: decide what each clue shows before reading the answer.

    3Interviewer Nudge (Per Clue)

    Answer each Socratic check from the raw telemetry before naming a root cause:

    Clue #1 (Plan Diff): On the events side, which operators sit below the Exchange on night 0 and which sit below it on night 21, and what ran in the catalog a few hours before the first c19e04 run?
    Clue #2 (Task Tail): If stage wall time equals the slowest task, how much would doubling executors shorten a stage whose slowest task runs 1,290 s on a single core?
    Clue #3 (Growth Budget): If runtime scaled linearly with rows, what would 2.99x the night-0 runtime be, and how many minutes of the observed 41 remain unexplained?
    Clue #4 (Key Shares): How many rows does user_id 90000017 send to one task compared with the roughly 1.0M rows of a median task, and which of its event types does the query actually keep?
    Clue #5 (File Tax): At 3.1 MB per file, how many files does a 186 GB scan open, and what per-file fixed cost on 160 cores turns that count into minutes?
    +Patch Lab Nudges (Optional Sandbox)

    The Patch Sandbox is optional, and the protected walkthrough carries the full verified patch. Pin each helper’s contract before writing code:

    Blank 1 (Key Share Threshold): With 12.0M distinct keys, at most how many keys can exceed a share of 1e-4, and should a key sitting exactly at the threshold be included?
    Blank 2 (Events-Side Key): Read dim_join_keys first: for every events row, which single string must you emit so that it matches exactly one users-side key?
    Blank 3 (File Packing): When the next small file would push the open bin past target_mb, do you close the bin before or after appending it, and what happens to a 200 MB file in the middle of the list?
    Blank 4 (Guard Rules): Why does the runtime rule divide by rows_b, and which of the four rules should stay silent on a night where the data simply tripled under a healthy plan?
    Answer
    Login to view more content