DB Olympics

Queries · q187 · Director of Fulfilment Operations · week 1, night 2

Stock movement magnitude by kind, 2025

“Is the finding that every recorded cycle-count discrepancy is exactly 1 unit (not a range of sizes) real, or does it only show up because other movement kinds behave differently — i.e., is quantity magnitude on stock_movements generally variable, or is ±1 specific to cycle_count?”

Manager · asked the questionTomasz NowakDirector of Fulfilment Operations. Ran warehouses for a large retailer before joining.
Analyst · planned the reportFatima ZahraDefinition-minded: checks what each field really records before relying on it.
Engineer · wrote the SQLOmarPragmatic: the shortest correct query, aggregates first and joins dimensions afterwards, FILTER clauses for conditional counts.

Fictional people at a fictional company, each played by a language-model agent. Who they are and what they are told

  1. A business event lands on the Director of Fulfilment Operations's desk

    Week 1; shared with Tobias Lindqvist, Chief Financial Officer

    Auditors and merchants question inventory accuracy. How often do counts, adjustments and reservations disagree with recorded stock, where, and why?

  2. Tomasz Nowak writes to Fatima Zahra

    The manager, at the start of week 1

    Subject: Inventory accuracy — what I need for Friday's memo

    Fatima,

    Tobias and I need to give the auditors (and our bigger merchants) a credible answer on how trustworthy our stock numbers are, where it breaks down, and whether it's getting better or worse. This feeds the joint audit response and will likely shape where we invest in warehouse process fixes next quarter — so I'd rather have three sharp answers than ten partial ones. Please use your nightly slots on these, in rough priority order:

    1. How big is the gap between what we think we have and what's actually there? Across our warehouses, how often do physical counts come back different from the stock we had on record, and how large are those differences in units (and ideally value)? I want a sense of scale before anything else.
    2. Where is it worst? Does the mismatch concentrate in particular warehouses, or particular kinds of storage locations (e.g. bulk shelving vs. pick bins)? If a handful of sites or location types account for most of the problem, that tells us where to send help first.
    3. Is it a product or a process problem? Are the discrepancies spread evenly across products, or concentrated in certain categories, high-velocity items, or items we handle in lots/serials? This will tell Tobias and me whether this is a handling issue or a tracking-method issue.
    4. Are our "soft holds" on stock reliable? When we reserve stock for an order, does that reservation actually get fulfilled as expected, or do we see a lot of stuck/expired holds that quietly overstate what's available to sell? This matters for whether we're overpromising stock to customers.
    5. Is this getting better or worse over time? A simple trend over the last several months would tell us whether recent process changes are helping or whether the problem is growing — useful context for the auditors either way.

    If you can only get to three this week, do 1, 2 and 3 — those are the ones Tobias and I will lean on most heavily in the audit conversation. Happy to talk through trade-offs before you lock in Monday night's requests.

    Thanks, Tomasz

    A note from the Chief Financial Officer, Tobias Lindqvist

    Subject: Finance questions for the inventory accuracy review

    Hi Fatima,

    A few things from the finance side as you dig into this with Tomasz:

    1. Do stock discrepancies cluster around particular merchants or warehouses in a way that could point to a write-off or valuation exposure we need to flag in the annual accounts?
    2. When counts don't match recorded stock, is it skewed more toward unexplained losses (shrinkage) versus unexplained gains — and has that pattern shifted over the year? That matters for how we size a shrinkage provision.
    3. Are the mismatches concentrated in slower-moving or higher-value goods, or spread evenly? That shapes how material this is for the merchants we'd flag to auditors.

    Keep it high level for now — happy to go deeper once you have an initial read.

    Thanks, Tobias

  3. Fatima Zahra plans the night

    The analyst · week 1, night 2, request 1 of 3

    Reading night 1 critically, two things jump out before I trust the headline numbers, plus one new question worth opening.

    (1) Suspicious invariant: in report 1, abs_units_variance equals cycle_count_events exactly in every single month (e.g. Jan 764=764), and avg_abs_units_per_event is 1.0 in all 12 months. Report 3 shows the same identity for every one of 105 categories (Bikes 102=102, Tops 1086=1086, etc). That means every recorded cycle-count discrepancy is off by exactly one unit, with zero variation — never 2, never 5. That's either a real and important finding (our "size of discrepancy" story is really a "frequency of single-unit misses" story, which changes the materiality narrative for Tobias) or a sign that stock_movements.quantity isn't what I think it is for this kind. I want to verify this against other movement kinds before I put it in the memo as fact.

    (2) Report 2's top 50 rows (ranked by value) are all location_kind='pick' — not one bulk/overflow/other row appears. That's a strong concentration signal for Tomasz's "particular kinds of storage locations" question, but I need a company-wide total by location_kind (not filtered to top-50-by-warehouse) to confirm it isn't just pick locations dominating the value ranking while other kinds still carry meaningful event counts further down the list.

    (3) Tomasz's Q4 (reservation reliability) hasn't been touched yet. With two slots going to validate/sharpen findings 1 and 2 above, I have a free slot to open Q4 tonight rather than wait, since nights 3-4 will still be needed for deeper drill-down and the trend view (Q5).

    Tonight's three requests: (A) movement-magnitude distribution by kind, to sanity-check the ±1 pattern and see if 'adjustment'-kind movements (a different, less formal correction path) carry larger swings; (B) a clean location-kind-only rollup (not crossed with warehouse) so kinds with little/no cycle-count activity are visible as explicit zero/low rows; (C) a first read on stock reservation reliability — how often holds are released normally vs. left stuck past their expiry, which overstates sellable availability.

    Stock movement magnitude by kind, 2025
    Question
    Is the finding that every recorded cycle-count discrepancy is exactly 1 unit (not a range of sizes) real, or does it only show up because other movement kinds behave differently — i.e., is quantity magnitude on stock_movements generally variable, or is ±1 specific to cycle_count?
    One row per
    stock_movements.kind (one row per kind: receipt, shipment, adjustment, transfer, return, cycle_count)
    Columns
    • kind
    • event_count (rows in 2025)
    • min_abs_qty
    • max_abs_qty
    • avg_abs_qty (rounded 2dp)
    • median_abs_qty
    • pct_abs_qty_eq_1 (% of rows where abs(quantity)=1, rounded 1dp)
    • total_abs_qty (sum of abs(quantity) for the kind)
  4. Omar writes the SQL

    The engineer · 1 dry run on the empty schema, then the submission

    Dry run 1 · STATUS: COMPILES (dry run on the empty schema, no data read)
    SELECT
      kind,
      count(*) AS event_count,
      min(abs(quantity)) AS min_abs_qty,
      max(abs(quantity)) AS max_abs_qty,
      round(avg(abs(quantity)), 2) AS avg_abs_qty,
      percentile_cont(0.5) WITHIN GROUP (ORDER BY abs(quantity)) AS median_abs_qty,
      round(100.0 * count(*) FILTER (WHERE abs(quantity) = 1) / count(*), 1) AS pct_abs_qty_eq_1,
      sum(abs(quantity)) AS total_abs_qty
    FROM stock_movements
    WHERE occurred_at >= timestamp '2025-01-01' AND occurred_at < timestamp '2026-01-01'
    GROUP BY kind
    ORDER BY kind

    “Query compiles correctly.”

    Submitted · the SQL of the last dry run, unchanged · Submitted to tonight's batch. Your work on this request is done.

    “Submitted. The report groups stock_movements by kind for 2025, computing count, min/max/avg/median of abs(quantity), the percentage of rows with abs(quantity)=1, and the total absolute quantity — directly answering whether the ±1 pattern is unique to cycle_count or common across movement kinds.”

  5. The report comes back overnight

    As Fatima Zahra saw it, from the small dataset the agents worked on

    kind        | event_count | min_abs_qty | max_abs_qty | avg_abs_qty | median_abs_qty | pct_abs_qty_eq_1 | total_abs_qty
    ------------+-------------+-------------+-------------+-------------+----------------+------------------+--------------
    adjustment  |         407 |           1 |         192 |        9.99 |            2.0 |             38.6 |          4067
    cycle_count |       10193 |           1 |           1 |         1.0 |            1.0 |            100.0 |         10193
    receipt     |       32687 |           1 |         397 |        4.36 |            3.0 |              0.6 |        142469
    return      |        3899 |           1 |          46 |        1.34 |            1.0 |             90.2 |          5220
    shipment    |       40177 |           1 |         236 |        2.14 |            1.0 |             81.3 |         86074
    (5 rows)
  6. What came of it

    The memo and the queries that followed; links found by title, so inferred

    Later queries that build on this report:

    It builds on:

  7. It becomes benchmark query q187

    Changed only where the benchmark needs the same result on every system

    • numericsdocs/NUMERICS.md: rounding removed; results keep full precision; AVG over an integer computed as a decimal: AVG(CAST(x AS NUMERIC(18,6)))
    • numericsdocs/NUMERICS.md: rounding removed; results keep full precision
    • placeholderpercentile cont
    • determinismthe standard leaves the place of NULLs in a sort to the implementation: NULLS LAST ascending, NULLS FIRST descending, as in the reference results
    The benchmark text, against the submitted SQL
    SELECT  kind,  count(*) AS event_count,  min(abs(quantity)) AS min_abs_qty,  max(abs(quantity)) AS max_abs_qty,  round(avg(abs(quantity)), 2) AS avg_abs_qty,  percentile_cont(0.5) WITHIN GROUP (ORDER BY abs(quantity)) AS median_abs_qty,  round(100.0 * count(*) FILTER (WHERE abs(quantity) = 1) / count(*), 1) AS pct_abs_qty_eq_1,  avg(cast(abs(quantity) as numeric(18,6))) AS avg_abs_qty,  {{percentile_cont(0.5, abs(quantity))}} AS median_abs_qty,  100.0 * count(*) FILTER (WHERE abs(quantity) = 1) / count(*) AS pct_abs_qty_eq_1,  sum(abs(quantity)) AS total_abs_qtyFROM stock_movementsWHERE occurred_at >= timestamp '2025-01-01' AND occurred_at < timestamp '2026-01-01'GROUP BY kindORDER BY kindORDER BY kind NULLS LAST
    SELECT
      kind,
      count(*) AS event_count,
      min(abs(quantity)) AS min_abs_qty,
      max(abs(quantity)) AS max_abs_qty,
      avg(cast(abs(quantity) as numeric(18,6))) AS avg_abs_qty,
      PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY abs(quantity)) AS median_abs_qty,
      100.0 * count(*) FILTER (WHERE abs(quantity) = 1) / count(*) AS pct_abs_qty_eq_1,
      sum(abs(quantity)) AS total_abs_qty
    FROM stock_movements
    WHERE occurred_at >= timestamp '2025-01-01' AND occurred_at < timestamp '2026-01-01'
    GROUP BY kind
    ORDER BY kind NULLS LAST
    100 ms1 s10 sHyper1.63 sDuckDB206 msGizmoSQL151 msclickhouse_brew350 msFirebolt331 msDataFusion211 msClickHouse243 ms
  8. Everything, as recorded

    The agents' own records, as the role play wrote them; only the personal data of the person who ran it is redacted

    Omar's whole session, 7 turns
    • The request, as Omar received it
      Report request from Fatima Zahra (analyst for the Director of Fulfilment Operations):
      
      Title: Stock movement magnitude by kind, 2025
      Question: Is the finding that every recorded cycle-count discrepancy is exactly 1 unit (not a range of sizes) real, or does it only show up because other movement kinds behave differently — i.e., is quantity magnitude on stock_movements generally variable, or is ±1 specific to cycle_count?
      Grain: stock_movements.kind (one row per kind: receipt, shipment, adjustment, transfer, return, cycle_count)
      Columns:
      - kind
      - event_count (rows in 2025)
      - min_abs_qty
      - max_abs_qty
      - avg_abs_qty (rounded 2dp)
      - median_abs_qty
      - pct_abs_qty_eq_1 (% of rows where abs(quantity)=1, rounded 1dp)
      - total_abs_qty (sum of abs(quantity) for the kind)
      Details: Source: stock_movements, occurred_at between 2025-01-01 and 2025-12-31 inclusive, across all tenants. Group by kind. abs_qty = abs(quantity). Compute min, max, average, median and the total sum of abs(quantity), plus the percentage of rows per kind where abs(quantity) equals exactly 1. No joins needed beyond stock_movements itself. Order by kind alphabetically for determinism.
      
      Check your query with the warehouse's dry_run tool, then hand it in with submit.
    • Omar calls dry_run
      SELECT
        kind,
        count(*) AS event_count,
        min(abs(quantity)) AS min_abs_qty,
        max(abs(quantity)) AS max_abs_qty,
        round(avg(abs(quantity)), 2) AS avg_abs_qty,
        percentile_cont(0.5) WITHIN GROUP (ORDER BY abs(quantity)) AS median_abs_qty,
        round(100.0 * count(*) FILTER (WHERE abs(quantity) = 1) / count(*), 1) AS pct_abs_qty_eq_1,
        sum(abs(quantity)) AS total_abs_qty
      FROM stock_movements
      WHERE occurred_at >= timestamp '2025-01-01' AND occurred_at < timestamp '2026-01-01'
      GROUP BY kind
      ORDER BY kind
    • The warehouse answers
      STATUS: COMPILES (dry run on the empty schema, no data read)
      COLUMNS: kind, event_count, min_abs_qty, max_abs_qty, avg_abs_qty, median_abs_qty, pct_abs_qty_eq_1, total_abs_qty
    • OmarQuery compiles correctly.
    • Omar calls submit
      SELECT
        kind,
        count(*) AS event_count,
        min(abs(quantity)) AS min_abs_qty,
        max(abs(quantity)) AS max_abs_qty,
        round(avg(abs(quantity)), 2) AS avg_abs_qty,
        percentile_cont(0.5) WITHIN GROUP (ORDER BY abs(quantity)) AS median_abs_qty,
        round(100.0 * count(*) FILTER (WHERE abs(quantity) = 1) / count(*), 1) AS pct_abs_qty_eq_1,
        sum(abs(quantity)) AS total_abs_qty
      FROM stock_movements
      WHERE occurred_at >= timestamp '2025-01-01' AND occurred_at < timestamp '2026-01-01'
      GROUP BY kind
      ORDER BY kind
    • The warehouse answers
      Submitted to tonight's batch. Your work on this request is done.
    • OmarSubmitted. The report groups `stock_movements` by `kind` for 2025, computing count, min/max/avg/median of `abs(quantity)`, the percentage of rows with `abs(quantity)=1`, and the total absolute quantity — directly answering whether the ±1 pattern is unique to `cycle_count` or common across movement kinds.