About Skills Projects Blog Contact View my CV ↗ Español
Data forensics on Windows: 3 network drives, SQL Server, and a lakehouse on your PC

Data forensics on Windows: 3 network drives, SQL Server, and a lakehouse on your PC

Hands-on Windows case: share 3 disks over SMB, configure SQL Server, sync with robocopy, and unify everything with DuckDB, Polars, and Parquet.

By Omar Flores
Table of Contents

It is Monday morning at the plant. The quality manager messages you: “Piece P-000123 is not in block B-20261101-0042. The customer reported it missing. Can you check what happened?” You work on a Windows 11 PC connected to the company’s internal network. The data is not on your machine: it lives on three SMB file shares and in a SQL Server database.

  • \\PLANT-FS01\blocks$: the JSON blocks generated by the machine.
  • \\PLANT-FS02\movements$: movements between stations.
  • \\PLANT-FS03\quality-logs$: quality measurements and text logs.
  • PLANT-SQL01: a SQL Server database with events and audit records.

None of them talk to each other. And you need to reconstruct the story of one piece. This post is the Windows version of that work: how to prepare the environment, connect to the shares, configure SQL Server, sync with robocopy, convert everything to Parquet, and ask forensic questions with DuckDB, Polars, and SQL.

It does not assume you are a sysadmin. Every command is explained, with the “what it does” and the “why”. If something fails, there is a troubleshooting section at the end.


The case and the network map

Before touching a single file, draw the map. A typical plant internal network looks like this:

graph TB
    PC["Analyst PC<br/>Windows 11<br/>D:\\PlantOps"]
    FS1["PLANT-FS01<br/>\\\\PLANT-FS01\\blocks$<br/>Block JSON"]
    FS2["PLANT-FS02<br/>\\\\PLANT-FS02\\movements$<br/>Movement CSV"]
    FS3["PLANT-FS03<br/>\\\\PLANT-FS03\\quality-logs$<br/>Quality CSV + logs"]
    SQL["PLANT-SQL01<br/>SQL Server<br/>PlantQuality"]
    PC ---|"SMB 445"| FS1
    PC ---|"SMB 445"| FS2
    PC ---|"SMB 445"| FS3
    PC ---|"TCP 1433"| SQL

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

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

The trap: the data lives in four systems. Blocks are JSON with nested arrays. Movements and quality are CSV. Logs are text. And SQL Server has events that are not in the files.

The solution is not a giant script that reads everything. It is a layered pipeline: bring, normalize, join, and ask.


Prepare Windows: tools and base configuration

Always work in an elevated console when installing or configuring services. For daily analysis, a normal console is enough.

1. Open PowerShell as administrator

Start-Process powershell -Verb RunAs

What it does: opens a new PowerShell window with administrator permissions. You will need it to install services, create shares, and open firewall ports.

2. Allow local scripts

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

What it does: allows .ps1 scripts that you created or that are signed. RemoteSigned is a reasonable balance: it does not run downloaded unsigned scripts.

Why: without this, PowerShell blocks your own scripts with an “execution policy” error.

3. Install the tools

On Windows 11 and Windows Server with winget:

winget install Python.Python.3.13
winget install DuckDB.cli
winget install Microsoft.msodbcsql.18
winget install Microsoft.SQLServerManagementStudio
winget install Microsoft.SQLServer.2022.Express
winget install Git.Git
winget install Microsoft.VisualStudioCode

What each one installs:

  • Python 3.13: the interpreter for Polars, DuckDB, and pyodbc.
  • DuckDB CLI: the duckdb.exe executable for terminal queries.
  • ODBC Driver 18 for SQL Server: the driver pyodbc uses to talk to SQL Server.
  • SQL Server Management Studio (SSMS): the GUI to administer SQL Server.
  • SQL Server 2022 Express: a free local instance for development. In production you will use Developer, Standard, or Enterprise.
  • Git: to version scripts and queries.
  • VS Code: editor with Python, SQL, and PowerShell extensions.

If winget is not available on your Windows Server, download the official installers or use Chocolatey. The idea is the same: Python, DuckDB, ODBC 18, SSMS, and SQL Server.

4. Install uv

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

What it does: downloads and installs uv, the Rust-based Python package manager. It is much faster than pip and manages per-project virtual environments.

5. Create the project

New-Item -ItemType Directory -Force -Path D:\PlantOps, D:\PlantCache, D:\PlantLake, D:\PlantLake\bronze, D:\PlantLake\silver | Out-Null
Set-Location D:\PlantOps
uv init
uv add duckdb polars pyarrow pyodbc

What it does:

  • New-Item -ItemType Directory -Force: creates the folders if they do not exist.
  • Set-Location: moves you to the working directory.
  • uv init: creates pyproject.toml and .venv.
  • uv add: installs dependencies and records them in the project.

Why D:\: it separates data (PlantCache), code (PlantOps), and lakehouse (PlantLake) from the system disk. On a Windows Server, D: is usually the data disk.

6. Enable long paths

New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" `
  -Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -Force

What it does: allows paths longer than 260 characters. Plant data often has deep paths (machine=...\date=...\...), and classic Windows breaks on them.

Why: it avoids PathTooLongException errors while syncing or reading files.


Configure the 3 network sources and SQL Server

This is the part that does not appear in Python tutorials: the data lives on another machine. You need permissions, credentials, and network.

1. Create the folders on the file servers

On PLANT-FS01, as administrator:

New-Item -ItemType Directory -Force -Path D:\Shares\Blocks | Out-Null
New-SmbShare -Name "blocks$" -Path "D:\Shares\Blocks" -FullAccess "PLANT\svc-data"
Grant-SmbShareAccess -Name "blocks$" -AccountName "PLANT\DataAnalysts" -AccessRight Read

What it does:

  • New-Item: creates the physical folder.
  • New-SmbShare: publishes the folder as an SMB share. The trailing $ hides it from the network resource list.
  • -FullAccess "PLANT\svc-data": gives full control to the service account that writes the files.
  • Grant-SmbShareAccess: gives read-only access to the analyst group.

Why: analysts must not write to the source. Only the capture service writes. That is least privilege.

Repeat on PLANT-FS02 for movements$ and on PLANT-FS03 for quality-logs$.

2. Adjust NTFS permissions

The share controls network access; NTFS controls disk access. You need both.

icacls "D:\Shares\Blocks" /grant "PLANT\svc-data:(OI)(CI)M" /T
icacls "D:\Shares\Blocks" /grant "PLANT\DataAnalysts:(OI)(CI)RX" /T

What it means:

  • (OI): inherits to files.
  • (CI): inherits to folders.
  • M: modify (read/write) for the service.
  • RX: read/execute for analysts.
  • /T: applies to the whole tree.

3. Verify the shares

Get-SmbShare | Where-Object Name -like "*$"
Get-SmbSession | Select-Object ClientComputerName, ClientUserName, NumOpens

What it does: lists published shares and connected sessions. If an analyst cannot see the share, start debugging here.

4. Map the drives on your PC

New-SmbMapping -LocalPath "Z:" -RemotePath "\\PLANT-FS01\blocks$" -Persistent $true
New-SmbMapping -LocalPath "Y:" -RemotePath "\\PLANT-FS02\movements$" -Persistent $true
New-SmbMapping -LocalPath "X:" -RemotePath "\\PLANT-FS03\quality-logs$" -Persistent $true

What it does: creates Z:, Y:, and X: drives pointing to the shares. -Persistent $true reconnects them at sign-in.

If you need different credentials:

$cred = Get-Credential
New-SmbMapping -LocalPath "Z:" -RemotePath "\\PLANT-FS01\blocks$" `
  -UserName $cred.UserName -Password $cred.GetNetworkCredential().Password -Persistent $true

What it does: asks for a username and password and uses them to mount the drive. Do not write passwords in scripts; use Windows Credential Manager or a service account.

5. Verify connectivity

Test-Path Z:\
Test-Path Y:\
Test-Path X:\
Get-ChildItem Z:\ -Directory | Select-Object -First 10 Name

What it does: Test-Path returns True if the path exists. Get-ChildItem lists folders. If Test-Path returns False, check credentials, firewall, or the share name.

6. Install and configure SQL Server

If you used winget, SQL Server Express is installed as the SQLEXPRESS instance. For local development that is fine; for production, plan a dedicated instance.

During the graphical installation:

  1. Select Database Engine Services.
  2. Configure Mixed Mode authentication (Windows + SQL Server).
  3. Set a strong password for sa.
  4. Add your Windows user as administrator.
  5. Finish the installation.

Enable TCP/IP and port 1433:

  1. Open SQL Server Configuration Manager.
  2. Go to SQL Server Network Configuration > Protocols for MSSQLSERVER.
  3. Enable TCP/IP.
  4. Under IP Addresses > IPAll, set TCP Port to 1433 and leave TCP Dynamic Ports empty.
  5. Restart the SQL Server (MSSQLSERVER) service.

Open the firewall (only for your subnet):

New-NetFirewallRule -DisplayName "SQL Server 1433 - Plant LAN" `
  -Direction Inbound -Protocol TCP -LocalPort 1433 `
  -RemoteAddress 10.20.0.0/16 -Action Allow

What it does: allows connections to port 1433 only from the internal network 10.20.0.0/16. Do not expose 1433 to the Internet.

Verify from your PC:

Test-NetConnection PLANT-SQL01 -Port 1433

What it does: tries to open a TCP connection to port 1433. If it fails, check firewall, service, and server name.

7. Create the database and read-only user

Open SSMS or sqlcmd and run:

CREATE DATABASE PlantQuality;
GO
USE PlantQuality;
GO

CREATE TABLE dbo.PieceEvents (
    event_id BIGINT IDENTITY PRIMARY KEY,
    event_ts DATETIME2(3) NOT NULL,
    piece_id VARCHAR(20) NOT NULL,
    block_id VARCHAR(30) NOT NULL,
    station VARCHAR(10) NULL,
    event_type VARCHAR(30) NOT NULL,
    operator_id VARCHAR(20) NULL
);
GO

INSERT INTO dbo.PieceEvents (event_ts, piece_id, block_id, station, event_type, operator_id)
VALUES
    ('2026-11-01T06:10:00', 'P-000011', 'B-20261101-0001', 'ST-03', 'audit_ok', 'op-17'),
    ('2026-11-01T09:20:00', 'P-000011', 'B-20261101-0005', 'ST-02', 'audit_warning', 'op-17');
GO

CREATE LOGIN data_reader WITH PASSWORD = 'ChangeThisPassword!2026';
GO
CREATE USER data_reader FOR LOGIN data_reader;
GO
GRANT SELECT ON dbo.PieceEvents TO data_reader;
GO

What it does:

  • Creates the PlantQuality database.
  • Creates the events table.
  • Creates a SQL login data_reader with read-only permissions.
  • Grants SELECT only on PieceEvents.

Why: the analyst does not need sa. A read-only user limits the damage if a script makes a mistake.


Reconnaissance with PowerShell

Do not start by reading files. First look at the terrain.

1. Count files and sizes per share

$shares = @{
    "Blocks"      = "Z:\"
    "Movements"   = "Y:\"
    "QualityLogs" = "X:\"
}

foreach ($name in $shares.Keys) {
    $path = $shares[$name]
    $files = Get-ChildItem -Path $path -Recurse -File -ErrorAction SilentlyContinue
    $sum = $files | Measure-Object -Property Length -Sum
    [pscustomobject]@{
        Share = $name
        Files = $sum.Count
        GB    = [math]::Round($sum.Sum / 1GB, 2)
    }
}

What it does:

  • Get-ChildItem -Recurse -File: lists every file recursively.
  • Measure-Object -Property Length -Sum: sums sizes and counts.
  • [pscustomobject]: creates a nice table in the console.

Why: if a share has 2 million 1 KB files, the strategy is different from 2,000 50 MB files.

2. Look at the largest files

Get-ChildItem Z:\ -Recurse -File |
  Sort-Object Length -Descending |
  Select-Object -First 20 FullName, @{n='MB';e={[math]::Round($_.Length/1MB,2)}}

What it does: sorts by size and shows the top 20. Those are usually logs or blocks with many pieces.

3. Look at the folder structure

Get-ChildItem Z:\ -Directory |
  Select-Object -First 10 Name

Get-ChildItem Z:\machine=M07 -Directory |
  Select-Object -First 10 Name

What it does: lists first- and second-level folders. You should see machine=M07 and date=2026-11-01, etc.

4. Count by extension

Get-ChildItem Z:\ -Recurse -File |
  Group-Object Extension |
  Sort-Object Count -Descending |
  Select-Object Count, Name

What it does: groups by extension (.json, .csv, .log) and counts. It tells you which parsers you need.

5. Verify a specific path

Test-Path "Z:\machine=M07\date=2026-11-01\blocks"
Get-ChildItem "Z:\machine=M07\date=2026-11-01\blocks" | Select-Object -First 5 Name

What it does: confirms the path exists and that you can read it. If Test-Path is False, do not continue: check permissions.


Local cache with robocopy

You can read the shares directly with DuckDB, but on an internal network it is better to sync to a local disk for speed and reproducibility. robocopy is the native Windows tool for that.

1. Create the local cache

New-Item -ItemType Directory -Force -Path `
  D:\PlantCache\blocks, `
  D:\PlantCache\movements, `
  D:\PlantCache\quality-logs, `
  D:\PlantOps\logs | Out-Null

What it does: creates the destination folders. -Force avoids errors if they already exist.

2. Sync the three shares

robocopy "\\PLANT-FS01\blocks$" "D:\PlantCache\blocks" /MIR /Z /R:2 /W:2 /MT:16 /LOG:"D:\PlantOps\logs\robocopy-blocks.log" /TEE
robocopy "\\PLANT-FS02\movements$" "D:\PlantCache\movements" /MIR /Z /R:2 /W:2 /MT:16 /LOG:"D:\PlantOps\logs\robocopy-movements.log" /TEE
robocopy "\\PLANT-FS03\quality-logs$" "D:\PlantCache\quality-logs" /MIR /Z /R:2 /W:2 /MT:16 /LOG:"D:\PlantOps\logs\robocopy-quality.log" /TEE

What each flag does:

  • /MIR: mirrors the source to the destination. Careful: deletes anything in the destination that is not in the source. Use it only on a dedicated cache.
  • /Z: restartable mode; if the network drops, it resumes.
  • /R:2: retries twice.
  • /W:2: waits 2 seconds between retries.
  • /MT:16: uses 16 threads to copy many files.
  • /LOG: writes the log.
  • /TEE: shows the log in the console and the file.

Why: reading 10 GB over SMB on every query is slow and fragile. Copy once and query locally. If the dataset is small, you can read directly from Z:\.

3. Verify the copy

Get-ChildItem D:\PlantCache -Recurse -File | Measure-Object -Property Length -Sum

What it does: confirms the cache has files and sums their size.

4. Schedule the sync

At the end of the post you will see how to create a scheduled task. For now, run robocopy manually when you need fresh data.


SQL Server: read the fourth source

SQL Server is not a file: it is a service. You have two ways to integrate it.

Option A: DuckDB with the mssql extension

DuckDB can connect directly to SQL Server with the community mssql extension:

INSTALL mssql FROM community;
LOAD mssql;

ATTACH 'Server=PLANT-SQL01,1433;Database=PlantQuality;User Id=data_reader;Password=ChangeThisPassword!2026;TrustServerCertificate=yes;Encrypt=yes'
AS sqlsrv (TYPE mssql);

SELECT COUNT(*) FROM sqlsrv.dbo.PieceEvents;

What it does:

  • INSTALL mssql FROM community: installs the extension.
  • LOAD mssql: loads it into the session.
  • ATTACH: opens a connection to SQL Server as the sqlsrv catalog.
  • SELECT: queries the table as if it were local.

Advantage: you can join SQL Server tables with Parquet in the same query.

Risk: the password ends up in history or the script. In production, use a read-only user and environment variables; never store the password in the repository.

Option B: pyodbc + Polars

If you prefer full control or need Windows authentication:

import os
import pyodbc
import polars as pl

conn = pyodbc.connect(
    "DRIVER={ODBC Driver 18 for SQL Server};"
    "SERVER=PLANT-SQL01,1433;"
    "DATABASE=PlantQuality;"
    "UID=data_reader;"
    f"PWD={os.environ['SQL_PASSWORD']};"
    "Encrypt=yes;TrustServerCertificate=yes;"
)

events = pl.read_database(
    "SELECT event_id, event_ts, piece_id, block_id, station, event_type, operator_id "
    "FROM dbo.PieceEvents",
    conn,
)

events.write_parquet("D:/PlantLake/bronze/events.parquet", compression="zstd")

What it does:

  • pyodbc.connect: opens the connection using ODBC driver 18.
  • pl.read_database: runs the SQL and returns a DataFrame.
  • write_parquet: saves the result to Parquet so you do not query SQL Server on every analysis.

Why: SQL Server is great for transactions, but you do not want to hit it with heavy analytical queries. Extract once to Parquet and analyze locally.

Verify the connection

Test-NetConnection PLANT-SQL01 -Port 1433
SELECT TOP 5 * FROM sqlsrv.dbo.PieceEvents;

What it does: confirms network and data. If Test-NetConnection fails, check the firewall; if the query fails, check login, database, and permissions.


Bronze: turn the shares into Parquet

Now that you have the local cache, convert everything to Parquet.

1. Create the DuckDB database

import duckdb

con = duckdb.connect("D:/PlantLake/plant.duckdb")
con.execute("SET threads = 8")
con.execute("SET memory_limit = '8GB'")
con.execute("SET TimeZone = 'UTC'")
con.execute("SET temp_directory = 'D:/PlantCache/temp'")

What it does:

  • threads: uses 8 cores.
  • memory_limit: prevents DuckDB from consuming all RAM.
  • TimeZone: fixes UTC so dates are reproducible.
  • temp_directory: sends temporary files to the data disk, not the system disk.

2. Load the blocks

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

What it does: read_json_auto reads every JSON in the glob and turns it into a table. The machine=* and date=* paths are Hive partitions: DuckDB adds them as columns.

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

3. Load movements and quality

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

CREATE OR REPLACE TABLE bronze_quality AS
SELECT *
FROM read_csv_auto('D:/PlantCache/quality-logs/machine=*/date=*/quality/*.csv');

What it does: reads the CSVs from the other two shares. read_csv_auto detects the header, types, and delimiter.

4. Load SQL Server events

If you used pyodbc and saved events.parquet, create it as a table:

CREATE OR REPLACE TABLE bronze_events AS
SELECT *
FROM read_parquet('D:/PlantLake/bronze/events.parquet');

If you used the mssql extension, you can create the table directly:

CREATE OR REPLACE TABLE bronze_events AS
SELECT *
FROM sqlsrv.dbo.PieceEvents;

Why materialize: so forensic queries do not depend on the network or SQL Server. Once in Parquet, everything is local.

5. Write Bronze to partitioned Parquet

New-Item -ItemType Directory -Force -Path D:\PlantLake\bronze | Out-Null
COPY bronze_blocks
TO 'D:/PlantLake/bronze/blocks'
(FORMAT PARQUET, PARTITION_BY (date), COMPRESSION ZSTD, OVERWRITE_OR_IGNORE);

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

COPY bronze_quality
TO 'D:/PlantLake/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 much smaller than JSON/CSV.


Silver: normalize blocks and logs

1. Unnest the blocks

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. A block with 4 pieces becomes 4 rows.

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 the struct (piece.piece_id) and the array (piece.dims[1]). In DuckDB arrays start at 1.

2. Parse the logs

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

What it does: read_text reads each file as a string, string_split splits it by newlines, and unnest turns each line into a row.

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 timestamp, level, block, piece, and event. If it does not find the pattern, it returns an empty string.

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 null. NULL means “not applicable”; '' means “the regex found nothing”. NULLIF turns noise into explicit nulls.

3. Save Silver to Parquet

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

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

What it does: saves the working tables to partitioned Parquet. Forensic analysis runs on Silver, not on raw files.


Gold: the timeline of one piece

Now you join the four sources: blocks, movements, quality, logs, and SQL Server events.

1. 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 practice dataset, P-000123 does not exist on purpose. To see a real timeline, we use P-000011, the duplicate piece.

2. Reconstruct the 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'

    UNION ALL

    SELECT
        'sql_event',
        event_ts,
        block_id,
        piece_id,
        event_type
    FROM bronze_events
    WHERE piece_id = 'P-000011'
)
SELECT *
FROM timeline
ORDER BY ts;

What it does: UNION ALL stacks the five 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, the machine records it in logs, and SQL Server stores the event.

3. Cross the piece with SQL Server

SELECT
    p.piece_id,
    p.block_id,
    p.slot,
    e.event_ts,
    e.station,
    e.event_type
FROM silver_pieces_flat p
LEFT JOIN bronze_events e USING (piece_id)
WHERE p.piece_id = 'P-000011'
ORDER BY e.event_ts;

What it does: joins the piece with SQL Server events. If there are no events, the piece did not pass through audit; if there are, you have the official sequence.


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

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

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: generates the expected slots and 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 several blocks. 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.

5. Pieces without quality

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: pieces without dimensions. They 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. Pieces missing from SQL Server

SELECT p.piece_id, p.block_id
FROM silver_pieces_flat p
LEFT JOIN bronze_events e USING (piece_id)
WHERE e.piece_id IS NULL
ORDER BY p.block_id, p.piece_id;

What it finds: pieces that exist in the files but not in the audit database. It could be an ingestion lag or a real loss.


Windows performance: SMB, antivirus, and memory

The pipeline is the same as on Linux, but Windows has its own bottlenecks.

1. Local cache, not SMB on every query

robocopy once, query locally. SMB is excellent for transfer, but not for scanning millions of files on every query.

2. Exclude the cache from antivirus

Add-MpPreference -ExclusionPath "D:\PlantCache"
Add-MpPreference -ExclusionPath "D:\PlantLake"

What it does: tells Windows Defender not to scan those directories in real time. Careful: exclude only controlled data folders, not the whole disk.

Why: antivirus scanning every Parquet file can double read time.

3. Use a local SSD for the cache

If D: is an HDD, Parquet reads will be slower. An NVMe SSD for D:\PlantCache and D:\PlantLake changes the experience.

4. Tune DuckDB

SET threads = 8;
SET memory_limit = '8GB';
SET preserve_insertion_order = false;
SET temp_directory = 'D:/PlantCache/temp';

What it does: uses available cores, limits memory, allows aggregations without order, and sends temporary files to a disk with space.

5. Measure with EXPLAIN ANALYZE

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

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

6. Measure time with PowerShell

Measure-Command {
    duckdb D:\PlantLake\plant.duckdb -c "SELECT count(*) FROM read_parquet('D:/PlantLake/silver/pieces/**/*.parquet');"
}

What it does: Measure-Command measures how long the command takes. Use it before and after every optimization.

7. Watch long paths

If robocopy fails with long paths, verify LongPathsEnabled and use the \\?\D:\... extended path prefix. You can also shorten the folder structure.

8. Check SMB performance

Get-SmbMultichannelConnection
Get-SmbSession | Select-Object ClientComputerName, NumOpens

What it does: shows whether SMB is using multiple channels and how many sessions are open. If the network is the bottleneck, no engine will fix it.


Production: scheduled tasks and operations

1. Create a pipeline script

D:\PlantOps\run_pipeline.ps1:

$ErrorActionPreference = "Stop"
$log = "D:\PlantOps\logs\pipeline-$(Get-Date -Format yyyyMMdd-HHmm).log"
Start-Transcript -Path $log

robocopy "\\PLANT-FS01\blocks$" "D:\PlantCache\blocks" /MIR /Z /R:2 /W:2 /MT:16 /LOG+:"$log"
robocopy "\\PLANT-FS02\movements$" "D:\PlantCache\movements" /MIR /Z /R:2 /W:2 /MT:16 /LOG+:"$log"
robocopy "\\PLANT-FS03\quality-logs$" "D:\PlantCache\quality-logs" /MIR /Z /R:2 /W:2 /MT:16 /LOG+:"$log"

Set-Location D:\PlantOps
uv run python pipeline.py

Stop-Transcript

What it does: syncs the three shares, runs the Python pipeline, and saves a log with Start-Transcript.

2. Schedule the task

$action = New-ScheduledTaskAction `
  -Execute "powershell.exe" `
  -Argument "-NoProfile -ExecutionPolicy Bypass -File D:\PlantOps\run_pipeline.ps1"

$trigger = New-ScheduledTaskTrigger -Daily -At 2:00AM

$cred = Get-Credential "PLANT\svc-data"

Register-ScheduledTask `
  -TaskName "PlantDataPipeline" `
  -Action $action `
  -Trigger $trigger `
  -User $cred.UserName `
  -Password $cred.GetNetworkCredential().Password `
  -RunLevel Highest

What it does: creates a daily task at 2:00 AM that runs as the PLANT\svc-data service account.

Why a service account: it does not depend on your user being logged in, and you can give it minimal permissions.

3. Verify the task

Get-ScheduledTask -TaskName "PlantDataPipeline"
Get-ScheduledTaskInfo -TaskName "PlantDataPipeline"

What it does: shows the task definition and its last result. If it failed, check the log and Event Viewer.

4. Monitor

  • Task Scheduler: execution history.
  • Event Viewer: SQL Server, SMB, and task errors.
  • robocopy logs: copied files, failures, time.
  • Python logs: rows processed, nulls, parsing errors.
  • SQL Server: backups, database size, connections.

5. Security

  • Read-only share for analysts; write access only for svc-data.
  • SQL Server read-only login; no sa in scripts.
  • Passwords in Windows Credential Manager or environment variables, not in the repository.
  • Firewall limited to the plant subnet.
  • Access audit with Get-SmbOpenFile and SQL Server logs.

6. Backups

  • SQL Server: daily full backup and log backups according to RPO.
  • D:\PlantLake: copy to a NAS or another disk.
  • Scripts and queries: Git repository.

Forensic checklist on Windows

Before saying “there is no data”, check:

  • Are the Z:, Y:, X: shares mapped and accessible?
  • Does Test-NetConnection to port 1433 work?
  • Did robocopy finish without errors?
  • Are the files in D:\PlantCache?
  • Did you convert JSON/CSV to Parquet?
  • Did you normalize the nested arrays?
  • Did you parse the logs?
  • Did you extract SQL Server to Parquet or query it via mssql?
  • Did you search the piece across all five sources?
  • Did you check slot gaps, duplicates, and nulls?
  • Did you measure time between movements?
  • Did you cross the piece with logs and events?
  • Did you document the finding with a reproducible query?
  • Did you schedule the daily task?

On Windows, forensic analysis does not start in Python. It starts in Test-Path, a correctly permissioned share, and a robocopy that finishes without errors. When the network, permissions, and data are in order, DuckDB does the rest. The piece did not disappear: it was on three disks and a database that nobody had joined.