About Skills Projects Blog Contact View my CV ↗ Español
Data forensics in a factory: 18 months of files, one missing piece, and a lakehouse on your laptop

Data forensics in a factory: 18 months of files, one missing piece, and a lakehouse on your laptop

Hands-on case: date folders, nested blocks, movements, and logs. Unify, normalize, and trace a piece with DuckDB, Polars, and Parquet.

By Omar Flores
Table of Contents

It is 9:14 AM and the quality manager sends you a message: “Piece P-000123 is not in block B-20261101-0042. The customer reported it missing. Can you check what happened?”

You have 18 months of files from a manufacturing machine. Each day has its own folder. Each folder has blocks, movements, quality, and logs. Blocks are JSON files with an array of pieces, and each piece has another array with its dimensions. Movements are CSV. Logs are text files with more than 100,000 lines. Opening that in Excel is not an option: it does not even fit.

This post is the manual for solving that case as a data analyst. It is not theory: we will build a practice dataset, convert it into a local lakehouse, normalize the nested data, parse the logs, and ask the forensic questions. All with the modern stack: Parquet, DuckDB, Polars, and SQL. By the end you will have a repeatable method for any plant, folder, or machine.


The case: one missing piece in a sea of files

Before writing a single query, define the question and the scope.

The question: where was piece P-000123, which block created it, which stations did it pass through, and why did it not reach the end?

The scope: 18 months of data, one machine (M07), three shifts per day. Millions of rows. The goal is not to read everything: it is to read only what is necessary and reconstruct a story.

The trap: the information is spread across four systems that do not talk to each other:

  • blocks/: the piece is born inside a block, in a nested array.
  • movements/: the piece moves between stations.
  • quality/: the piece is measured.
  • logs/: the machine narrates what happens, in free text.

No single file answers the question. The answer is in the union.


The terrain: what a machine data lake looks like

A real layout usually looks like this:

data/raw/
  machine=M07/
    date=2026-11-01/
      blocks/
        block_0001.json
        block_0002.json
      movements/
        movements_0600.csv
        movements_1400.csv
      quality/
        quality_0600.csv
      logs/
        machine_0600.log

Three important decisions:

  1. The date is in the path. That allows partitioning and discarding entire folders without reading them.
  2. The machine is in the path. If tomorrow there is M08, M09, the same pipeline works.
  3. Each file type has its own folder. Do not mix JSON, CSV, and logs in the same place; parsing becomes fragile.

Scout the terrain before touching it

Do not start by reading files. First look at the map:

# How many files are there?
find data/raw -type f | wc -l

# How much does everything weigh?
du -sh data/raw

# Which are the largest files?
find data/raw -type f -printf '%s %p\n' | sort -nr | head -20

# What structure does it have?
tree -L 5 data/raw | head -100

What each command does:

  • find data/raw -type f: lists every file.
  • wc -l: counts lines in that list, that is, files.
  • du -sh: total size in human-readable format.
  • find ... -printf '%s %p\n': prints size and path.
  • sort -nr: sorts from largest to smallest.
  • tree -L 5: draws the tree up to 5 levels.

Why it matters: if there are 2,000 files of 10 MB, the problem is different from 2 million files of 1 KB. The strategy changes.

Count by type and by date

# Files by extension
find data/raw -type f | sed 's/.*\.//' | sort | uniq -c | sort -nr

# Available days
find data/raw -type d -name 'date=*' | sed 's/.*date=//' | sort | head

This tells you whether the dataset is complete or if days are missing. A forensic analysis starts by knowing what is not there.


Prepare the lab: synthetic dataset and stack

So you can follow the post without private data, we will generate a small dataset with the same traps as a real one: nested blocks, missing pieces, duplicates, null dimensions, incomplete movements, and logs with errors.

Install the stack

uv init plant-lab
cd plant-lab
uv add duckdb polars pyarrow

If you do not have uv, pip install duckdb polars pyarrow also works. I explained the speed difference in the Polars guide.

Generate the files

Create generate_data.py:

from pathlib import Path
from datetime import datetime, timedelta, timezone
import json
import csv
import random

random.seed(7)

ROOT = Path("data/raw")
MACHINE = "M07"
START = datetime(2026, 11, 1, 6, 0, tzinfo=timezone.utc)
DAYS = 3
BLOCKS_PER_DAY = 8
PIECES_PER_BLOCK = 4

def write_json(path: Path, data: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2), encoding="utf-8")

for day in range(DAYS):
    date = START + timedelta(days=day)
    date_dir = ROOT / f"machine={MACHINE}" / f"date={date:%Y-%m-%d}"
    for sub in ("blocks", "movements", "quality", "logs"):
        (date_dir / sub).mkdir(parents=True, exist_ok=True)

    for block_no in range(1, BLOCKS_PER_DAY + 1):
        created = date + timedelta(hours=block_no - 1, minutes=block_no * 3)
        block_id = f"B-{date:%Y%m%d}-{block_no:04d}"

        pieces = []
        for slot in range(1, PIECES_PER_BLOCK + 1):
            # Anomaly 1: block 2 loses the piece in slot 2
            if block_no == 2 and slot == 2:
                continue

            piece_id = f"P-{day * 1000 + block_no * 10 + slot:06d}"

            # Anomaly 2: block 5 duplicates a piece from block 1
            if block_no == 5 and slot == 1:
                piece_id = "P-000011"

            dims = [
                round(random.uniform(10.0, 13.0), 2),
                round(random.uniform(4.0, 5.0), 2),
                round(random.uniform(7.0, 9.0), 2),
            ]

            # Anomaly 3: block 7 has null dimensions
            if block_no == 7 and slot == 3:
                dims = [None, None, None]

            pieces.append({
                "piece_id": piece_id,
                "slot": slot,
                "status": "NOK" if (block_no == 6 and slot == 4) else "OK",
                "dims": dims,
            })

        write_json(
            date_dir / "blocks" / f"block_{block_no:04d}.json",
            {
                "block_id": block_id,
                "created_at": created.isoformat().replace("+00:00", "Z"),
                "machine_id": MACHINE,
                "recipe": "R-17",
                "piece_count": PIECES_PER_BLOCK,
                "pieces": pieces,
            },
        )

        # Movements: 2 per piece, with one piece missing movements in block 4
        movement_rows = []
        for piece in pieces:
            if block_no == 4 and piece["slot"] == 3:
                continue
            for step in range(2):
                ts = created + timedelta(minutes=5 + step * 7)
                movement_rows.append([
                    ts.isoformat().replace("+00:00", "Z"),
                    piece["piece_id"],
                    block_id,
                    f"ST-{step + 1:02d}",
                    f"ST-{step + 2:02d}",
                    "op-17",
                ])

        with (date_dir / "movements" / f"movements_{block_no:02d}00.csv").open("w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["timestamp", "piece_id", "block_id", "from_station", "to_station", "operator"])
            writer.writerows(movement_rows)

        # Quality: one piece without a measurement in block 6
        quality_rows = []
        for piece in pieces:
            if block_no == 6 and piece["slot"] == 4:
                continue
            value = None if (block_no == 7 and piece["slot"] == 4) else round(random.uniform(9.8, 12.5), 2)
            quality_rows.append([
                (created + timedelta(minutes=4)).isoformat().replace("+00:00", "Z"),
                piece["piece_id"],
                block_id,
                "diameter_mm",
                value,
                "mm",
            ])

        with (date_dir / "quality" / f"quality_{block_no:02d}00.csv").open("w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["timestamp", "piece_id", "block_id", "measurement", "value", "unit"])
            writer.writerows(quality_rows)

    # Machine logs: one file per day
    log_lines = []
    for block_no in range(1, BLOCKS_PER_DAY + 1):
        created = date + timedelta(hours=block_no - 1, minutes=block_no * 3)
        block_id = f"B-{date:%Y%m%d}-{block_no:04d}"
        log_lines.append(f"{created.isoformat().replace('+00:00', 'Z')} INFO block={block_id} event=block_start pieces=4")
        if block_no == 2:
            log_lines.append(f"{(created + timedelta(seconds=30)).isoformat().replace('+00:00', 'Z')} ERROR block={block_id} piece=P-{day * 1000 + 22:06d} event=piece_missing station=ST-02")
        if block_no == 5:
            log_lines.append(f"{(created + timedelta(seconds=40)).isoformat().replace('+00:00', 'Z')} WARN block={block_id} piece=P-000011 event=duplicate_piece")
        if block_no == 7:
            log_lines.append(f"{(created + timedelta(seconds=50)).isoformat().replace('+00:00', 'Z')} WARN block={block_id} piece=P-{day * 1000 + 73:06d} event=dimension_missing")
        if block_no == 8:
            log_lines.append(f"{(created + timedelta(minutes=30)).isoformat().replace('+00:00', 'Z')} ERROR block={block_id} event=machine_stopped duration_s=420")

    (date_dir / "logs" / "machine.log").write_text("\n".join(log_lines) + "\n", encoding="utf-8")

Run:

uv run python generate_data.py

What it does: creates three days, eight blocks per day, four pieces per block, movements, quality, and logs. It plants anomalies on purpose so you can find them later.

Why three days: the example is small enough to see the results, but the pipeline is the same for 18 months. Scale changes the engine, not the logic.


The four data types and their traps

1. Blocks: the birth of the piece

A block is a JSON with an array of pieces:

{
  "block_id": "B-20261101-0001",
  "created_at": "2026-11-01T06:03:00Z",
  "machine_id": "M07",
  "recipe": "R-17",
  "piece_count": 4,
  "pieces": [
    {
      "piece_id": "P-000011",
      "slot": 1,
      "status": "OK",
      "dims": [11.2, 4.4, 8.1]
    }
  ]
}

The trap: pieces is an array of structs, and dims is another array inside each struct. It is a 2D table with 2D content. To analyze it you need to unnest two levels.

2. Movements: the journey

timestamp,piece_id,block_id,from_station,to_station,operator
2026-11-01T06:08:00Z,P-000011,B-20261101-0001,ST-01,ST-02,op-17

The trap: a piece can have zero, one, or many movements. A normal JOIN makes pieces without movements disappear. You need a LEFT JOIN or a timeline with UNION ALL.

3. Quality: the measurement

timestamp,piece_id,block_id,measurement,value,unit
2026-11-01T06:07:00Z,P-000011,B-20261101-0001,diameter_mm,10.84,mm

The trap: value can be NULL. AVG ignores nulls, but forensic analysis does not: the null is the signal.

4. Logs: the narrative

2026-11-01T06:03:00Z INFO block=B-20261101-0001 event=block_start pieces=4
2026-11-01T06:03:30Z ERROR block=B-20261101-0002 piece=P-000022 event=piece_missing station=ST-02

The trap: it is free text. You cannot do WHERE piece_id = ... until you parse it. And parsing 100,000 lines on every query wastes time. Parse once and store columns.


First contact: read without dying in the attempt

Look at one file, not all of them

ls data/raw/machine=M07/date=2026-11-01/blocks | head
cat data/raw/machine=M07/date=2026-11-01/blocks/block_0001.json | head -40
head -5 data/raw/machine=M07/date=2026-11-01/movements/movements_0100.csv
head -5 data/raw/machine=M07/date=2026-11-01/logs/machine.log

Why: before automating, confirm you understand the format. A head saves hours of debugging.

Read one block with Polars

import polars as pl

df = pl.read_json("data/raw/machine=M07/date=2026-11-01/blocks/block_0001.json")
print(df.schema)
print(df.select("block_id", "piece_count", "pieces").head())

What you see: pieces appears as List(Struct(...)). That is the nested array. Do not ignore it: it is the key to the analysis.

Read a CSV with DuckDB

SELECT *
FROM read_csv_auto('data/raw/machine=M07/date=2026-11-01/movements/*.csv')
LIMIT 5;

Why DuckDB and not pandas: DuckDB reads the whole glob, infers types, and applies projection. You do not need to load everything into memory.


Bronze: turn chaos into Parquet

The first rule of a lakehouse: do not analyze the raw format over and over. Convert once to Parquet and query the Parquet.

Create the DuckDB database

import duckdb

con = duckdb.connect("plant.duckdb")
con.execute("SET threads = 8")
con.execute("SET memory_limit = '8GB'")
con.execute("SET TimeZone = 'UTC'")

What it does: SET threads uses 8 cores; memory_limit prevents DuckDB from eating all RAM; TimeZone fixes UTC so dates are reproducible. Tune the first two to your machine.

Load the blocks

CREATE OR REPLACE TABLE bronze_blocks AS
SELECT *
FROM read_json_auto('data/raw/machine=*/date=*/blocks/*.json');

What it does: read_json_auto reads every JSON matching the glob and turns it into a table. The machine=* and date=* paths are Hive partitions: DuckDB adds them as columns (machine, date), so the later partitioning works without extra calculations.

Expected result: one row per block, with pieces as a nested list and a date column.

Load movements and quality

CREATE OR REPLACE TABLE bronze_movements AS
SELECT *
FROM read_csv_auto('data/raw/machine=*/date=*/movements/*.csv');

CREATE OR REPLACE TABLE bronze_quality AS
SELECT *
FROM read_csv_auto('data/raw/machine=*/date=*/quality/*.csv');

What it does: reads all movement and quality CSVs. read_csv_auto detects the header, types, and delimiter.

Convert to partitioned Parquet

First create the destination folders (DuckDB creates the last one, not the parents):

mkdir -p data/bronze data/silver

Now write Parquet:

COPY bronze_blocks
TO 'data/bronze/blocks'
(FORMAT PARQUET, PARTITION_BY (date), COMPRESSION ZSTD, OVERWRITE_OR_IGNORE);

COPY bronze_movements
TO 'data/bronze/movements'
(FORMAT PARQUET, PARTITION_BY (date), COMPRESSION ZSTD, OVERWRITE_OR_IGNORE);

COPY bronze_quality
TO 'data/bronze/quality'
(FORMAT PARQUET, PARTITION_BY (date), COMPRESSION ZSTD, OVERWRITE_OR_IGNORE);

What it does: writes Zstd-compressed Parquet and creates folders by date. Why: future queries read only the necessary dates, and Parquet is 5-10x smaller than the original JSON/CSV. If you want to understand the format in depth, read the Parquet post.


Silver: normalize the nested blocks

Here is the heart of the post. You have a table with an array of structs and another array inside each struct. You need to turn it into a flat table, one row per piece.

Unnest the first level

CREATE OR REPLACE TABLE silver_pieces AS
SELECT
    block_id,
    created_at,
    machine_id,
    recipe,
    piece_count,
    unnest(pieces) AS piece
FROM bronze_blocks;

What it does: unnest(pieces) turns each array element into a row. If a block has 4 pieces, it now has 4 rows. The piece column is still a struct.

Unnest the second level

CREATE OR REPLACE TABLE silver_pieces_flat AS
SELECT
    block_id,
    created_at,
    machine_id,
    recipe,
    piece_count,
    piece.piece_id AS piece_id,
    piece.slot AS slot,
    piece.status AS status,
    piece.dims[1] AS dim_x,
    piece.dims[2] AS dim_y,
    piece.dims[3] AS dim_z
FROM silver_pieces;

What it does: accesses struct fields (piece.piece_id) and array elements (piece.dims[1]). In DuckDB arrays start at 1, not 0.

Expected result: one row per piece, with dimensions in separate columns.

Verify the result

SELECT *
FROM silver_pieces_flat
ORDER BY block_id, slot
LIMIT 10;

Save Silver to Parquet

COPY (
    SELECT *, created_at::DATE AS date
    FROM silver_pieces_flat
)
TO 'data/silver/pieces'
(FORMAT PARQUET, PARTITION_BY (date), COMPRESSION ZSTD, OVERWRITE_OR_IGNORE);

Why save Silver: forensic analysis runs on Silver, not Bronze. Bronze is the historical archive; Silver is the working table.


Silver: parse the logs once

Logs are the most underrated and most useful data for forensics. But they are text. The trick is to parse them once and turn them into columns.

Read the logs with DuckDB

CREATE OR REPLACE TABLE bronze_logs AS
SELECT
    filename,
    unnest(string_split(content, chr(10))) AS line
FROM read_text('data/raw/machine=*/date=*/logs/*.log')
WHERE content IS NOT NULL;

What it does:

  • read_text reads each file as a single string.
  • string_split(content, chr(10)) splits it by newlines.
  • unnest turns each line into a row.
  • filename tells you which file it came from.

Why not use read_csv: logs are not CSV. They have timestamps, levels, messages, and spaces. read_text is the right tool.

Parse the fields

CREATE OR REPLACE TABLE silver_logs AS
SELECT
    filename,
    regexp_extract(line, '^(\d{4}-\d{2}-\d{2}T[0-9:.]+Z)', 1) AS ts_raw,
    regexp_extract(line, '\b(INFO|WARN|ERROR|DEBUG)\b', 1) AS level,
    regexp_extract(line, 'block=([A-Z0-9-]+)', 1) AS block_id,
    regexp_extract(line, 'piece=([A-Z0-9-]+)', 1) AS piece_id,
    regexp_extract(line, 'event=([a-z_]+)', 1) AS event,
    line
FROM bronze_logs
WHERE line <> '';

What it does: regexp_extract captures the group inside parentheses. If it does not find the pattern, it returns an empty string.

Cast the timestamp and filter noise

CREATE OR REPLACE TABLE silver_logs_clean AS
SELECT
    filename,
    CAST(ts_raw AS TIMESTAMP) AS ts,
    level,
    NULLIF(block_id, '') AS block_id,
    NULLIF(piece_id, '') AS piece_id,
    NULLIF(event, '') AS event,
    line
FROM silver_logs
WHERE ts_raw <> '';

Why NULLIF: an empty string is not the same as null. For forensic analysis, NULL means “not applicable”; '' means “the regex found nothing.” NULLIF turns noise into explicit nulls.

Save the logs to Parquet

COPY (
    SELECT *, ts::DATE AS date
    FROM silver_logs_clean
)
TO 'data/silver/logs'
(FORMAT PARQUET, PARTITION_BY (date), COMPRESSION ZSTD, OVERWRITE_OR_IGNORE);

Gold: the timeline of one piece

Now you have four clean tables: pieces, movements, quality, and logs. The forensic question is answered by joining them.

Find the piece

SELECT *
FROM silver_pieces_flat
WHERE piece_id = 'P-000123';

If it does not appear, it does not exist in the block you think. That is the first finding. In the synthetic dataset, P-000123 does not exist: the query returns empty on purpose. To see a real timeline, we use P-000011, the duplicate piece.

Reconstruct its story

WITH piece AS (
    SELECT *
    FROM silver_pieces_flat
    WHERE piece_id = 'P-000011'
),
timeline AS (
    SELECT
        'block' AS source,
        created_at AS ts,
        block_id,
        piece_id,
        status AS detail
    FROM piece

    UNION ALL

    SELECT
        'movement',
        timestamp,
        block_id,
        piece_id,
        from_station || ' -> ' || to_station
    FROM bronze_movements
    WHERE piece_id = 'P-000011'

    UNION ALL

    SELECT
        'quality',
        timestamp,
        block_id,
        piece_id,
        measurement || '=' || COALESCE(CAST(value AS VARCHAR), 'NULL')
    FROM bronze_quality
    WHERE piece_id = 'P-000011'

    UNION ALL

    SELECT
        'log',
        ts,
        block_id,
        piece_id,
        level || ' ' || COALESCE(event, '')
    FROM silver_logs_clean
    WHERE piece_id = 'P-000011'
)
SELECT *
FROM timeline
ORDER BY ts;

What it does: UNION ALL stacks the four sources into one chronological table. COALESCE prevents a null from breaking the concatenation.

Expected result: a movie of P-000011: it is born in a block, moves, is measured, and the logs tell you if something failed.

Find the piece’s block

SELECT
    p.piece_id,
    p.block_id,
    p.slot,
    p.status,
    p.dim_x,
    p.dim_y,
    p.dim_z,
    b.created_at,
    b.recipe
FROM silver_pieces_flat p
JOIN bronze_blocks b USING (block_id)
WHERE p.piece_id = 'P-000123';

Why JOIN and not LEFT JOIN: here you expect the piece to have a block. If it does not, the query returns nothing, and that is also information.


Forensic quality: gaps, duplicates, missing data, and downtime

A data analyst does not only search; they also find what should not be there. These are the queries that do the dirty work.

1. Blocks with fewer pieces than declared

SELECT
    block_id,
    piece_count,
    count(*) AS actual_pieces
FROM silver_pieces_flat
GROUP BY block_id, piece_count
HAVING piece_count <> count(*)
ORDER BY block_id;

What it finds: block 2 declares 4 pieces but has 3. The piece in slot 2 was never created.

2. Slot gaps inside a block

WITH slots AS (
    SELECT block_id, unnest(generate_series(1, piece_count)) AS slot
    FROM bronze_blocks
)
SELECT s.block_id, s.slot
FROM slots s
LEFT JOIN silver_pieces_flat p USING (block_id, slot)
WHERE p.piece_id IS NULL
ORDER BY s.block_id, s.slot;

What it does: generate_series(1, piece_count) generates the expected slots; unnest turns them into rows. The LEFT JOIN finds which ones have no piece. It is the cleanest way to find gaps.

3. Duplicate pieces

SELECT piece_id, count(*) AS times, count(DISTINCT block_id) AS blocks
FROM silver_pieces_flat
GROUP BY piece_id
HAVING count(*) > 1
ORDER BY times DESC;

What it finds: P-000011 appears in more than one block. It could be a machine error or a badly recorded recycle.

4. Pieces without movements

SELECT p.piece_id, p.block_id, p.slot
FROM silver_pieces_flat p
LEFT JOIN bronze_movements m USING (piece_id)
WHERE m.piece_id IS NULL
ORDER BY p.block_id, p.slot;

What it finds: pieces that were born but never moved. In the dataset, the piece in block 4 slot 3.

5. Pieces without quality measurements

SELECT p.piece_id, p.block_id, p.slot
FROM silver_pieces_flat p
LEFT JOIN bronze_quality q USING (piece_id)
WHERE q.piece_id IS NULL
ORDER BY p.block_id, p.slot;

What it finds: pieces that skipped quality control.

6. Null dimensions

SELECT piece_id, block_id, slot, dim_x, dim_y, dim_z
FROM silver_pieces_flat
WHERE dim_x IS NULL OR dim_y IS NULL OR dim_z IS NULL;

What it finds: block 7 slot 3. A piece without dimensions cannot be validated.

7. Time gaps between movements

SELECT
    piece_id,
    timestamp,
    timestamp - lag(timestamp) OVER (
        PARTITION BY piece_id ORDER BY timestamp
    ) AS gap
FROM bronze_movements
ORDER BY gap DESC NULLS LAST
LIMIT 20;

What it does: lag brings the previous movement of the same piece. The subtraction gives the time between steps. A huge gap can be a machine stop, a clock error, or a lost piece.

8. Blocks with errors in logs

SELECT
    block_id,
    count(*) FILTER (WHERE level = 'ERROR') AS errors,
    count(*) FILTER (WHERE level = 'WARN') AS warnings
FROM silver_logs_clean
WHERE block_id IS NOT NULL
GROUP BY block_id
HAVING errors > 0 OR warnings > 0
ORDER BY errors DESC, warnings DESC;

What it finds: the blocks the machine flagged as problematic. Use it as an index for investigation.

9. Cross the piece with its logs

SELECT
    p.piece_id,
    p.block_id,
    p.slot,
    l.ts,
    l.level,
    l.event,
    l.line
FROM silver_pieces_flat p
LEFT JOIN silver_logs_clean l USING (piece_id)
WHERE p.piece_id = 'P-000011'
ORDER BY l.ts;

What it does: joins the piece with the logs that mention it. If there are no logs, the piece left no trace; if there are errors, you have a clue.


Performance: why this flies on your laptop

The practice dataset is small, but the method scales to millions of rows. These are the decisions that make the difference.

1. Parquet instead of JSON/CSV

SELECT count(*) FROM read_parquet('data/silver/pieces/**/*.parquet');

Parquet is columnar, compressed, and typed. Reading 10 GB of Parquet is orders of magnitude faster than 10 GB of JSON. If you want the details, they are in the Parquet post.

2. Partition by date and machine

data/silver/pieces/date=2026-11-01/data_0.parquet
data/silver/pieces/date=2026-11-02/data_0.parquet

A one-day query reads one folder, not 18 months. A machine query can filter by machine_id if you also partition by machine.

3. Filter and project early

SELECT piece_id, block_id
FROM read_parquet('data/silver/pieces/**/*.parquet')
WHERE date = DATE '2026-11-01'
  AND piece_id = 'P-000123';

What it does: DuckDB applies predicate pushdown (filters at scan time) and projection pushdown (reads only piece_id and block_id). It does not read the columns you do not use.

4. Measure with EXPLAIN ANALYZE

EXPLAIN ANALYZE
SELECT count(*)
FROM read_parquet('data/silver/pieces/**/*.parquet')
WHERE date = DATE '2026-11-01';

What to look for: the PARQUET_SCAN operator, the projected columns, and the number of rows read. If it reads more than expected, the filter is not being applied.

5. Use Polars streaming for what does not fit

import polars as pl

result = (
    pl.scan_parquet("data/silver/pieces/**/*.parquet")
    .filter(pl.col("date") == pl.date(2026, 11, 1))
    .group_by("block_id")
    .agg(pl.len().alias("pieces"))
    .collect(engine="streaming")
)

Why: scan_parquet does not load everything; streaming processes in batches. For 18 months, this is the difference between working and running out of RAM. If you want the Polars details, they are in the Polars guide.

6. Do not parse logs on every query

Bad:

SELECT *
FROM read_text('data/raw/**/*.log')
WHERE content LIKE '%P-000123%';

Good:

SELECT *
FROM read_parquet('data/silver/logs/**/*.parquet')
WHERE piece_id = 'P-000123';

Why: the LIKE over full text reads every log and does a linear scan. The Silver table already has piece_id as a column, and Parquet can skip blocks.

7. Tune DuckDB

SET threads = 8;
SET memory_limit = '8GB';
SET preserve_insertion_order = false;

What it does: uses the available cores, limits memory, and allows aggregations without keeping order. On machines with little RAM, memory_limit prevents the OOM killer.

8. Measure before and after

import time

start = time.perf_counter()
result = duckdb.sql("SELECT count(*) FROM read_parquet('data/silver/pieces/**/*.parquet')").fetchone()
print(result, f"{time.perf_counter() - start:.3f}s")

Why: without measurement, you do not know if the optimization worked. Performance intuition is usually wrong.


Production: from your laptop to the plant

The flow above works locally. For production, add these layers:

1. Lakehouse with Iceberg or Delta

Store Silver and Gold in an open table format so multiple engines can read and write without copying. If only you query, partitioned Parquet is enough. If there are several teams, Iceberg. I explain it in the Iceberg post.

2. Daily orchestration

A job that runs every day:

  1. Detects new files.
  2. Converts to Parquet.
  3. Normalizes.
  4. Runs quality checks.
  5. Publishes Gold.

With Dagster, Airflow, or Prefect. The details are in the orchestration post.

3. Data contracts

Define the expected schema for blocks, movements, and quality. If the machine changes a column, the pipeline should fail with a clear message, not silently generate incorrect data. I cover it in the data contracts post.

4. Observability

Measure:

  • files processed per day,
  • rows per table,
  • nulls per column,
  • pieces without movement,
  • execution time,
  • parsing errors.

If something breaks, you want to know before the customer does. OpenTelemetry and Grafana give you the signals; the details are in the observability post.

5. Semantic layer for business questions

Once you have Gold, define clear metrics: pieces produced, scrap rate, time between stations, OEE. A semantic layer prevents every analyst from calculating “pieces produced” differently. I explain it in the semantic layer + MCP post.

  • A dashboard for the quality manager: missing pieces per day, blocks with errors, average time between stations.
  • A piece_id search for the support team.
  • A weekly anomaly report.

The goal is not for everyone to know SQL. It is for the answer to be one click away.


Forensic checklist

Before saying “there is no data,” check:

  • Do you know how many files and days there are?
  • Do you have a stable layout (machine=, date=)?
  • Did you convert JSON/CSV to Parquet?
  • Did you normalize the nested arrays?
  • Did you parse the logs into columns?
  • Do you have a piece table with one row per piece?
  • Did you search the piece across all four sources?
  • Did you check slot gaps, duplicates, and nulls?
  • Did you measure the time between movements?
  • Did you cross the piece with the logs?
  • Did you document the finding with a reproducible query?
  • Did you automate the pipeline for next time?

Data forensics is not finding the answer in a file. It is reconstructing the story from pieces that do not talk to each other. The piece did not disappear: the story was scattered. And the analyst’s job is to put it back together, piece by piece.