Prescriptive Analytics & Decision Intelligence
Overview / Module 1 / Day 6
Module 1 · Decision Modelling and Linear Programming · Day 6 of 80

Data-Driven Models from DuckDB

So far the numbers lived in Python dictionaries you typed. Real models read their data from the company's database, check it, solve, and write the plan back. Today you build that loop: one model, fed by SQL, that plans the 3-product bakery and the full 30-product range without changing a line of model code.

▶
Video for Day 6 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
6.1 One database for the course; the full bakery range
0:45–1:45
6.2 Load, check, build, solve: the bakery module
1:45–2:00
Break
2:00–2:45
6.3 Same code, 3 products or 30
2:45–3:45
6.4 Plans back into the database; a bad forecast file
3:45–4:00
Break
4:00–4:45
Mini-project: is a third packing shift worth it?
4:45–5:00
Commit with Git + checklist

6.1 One database for the course

From today, the course data lives in one DuckDB database file, northbound.duckdb, next to your code. Add it to .gitignore (it is rebuilt from the CSV files, so it does not belong in Git):

printf "*.duckdb\n*.duckdb.wal\n" >> .gitignore

Create day06/load_tables.py:

import glob
import os

import duckdb

con = duckdb.connect("northbound.duckdb")
for path in sorted(glob.glob("data/*.csv")):
    table = os.path.splitext(os.path.basename(path))[0]
    con.sql(f"CREATE OR REPLACE TABLE {table} AS SELECT * FROM read_csv('{path}')")
print(con.sql("""
    SELECT table_name, estimated_size AS n_rows
    FROM duckdb_tables() ORDER BY table_name"""))
con.close()
┌───────────────────────┬────────┐
│      table_name       │ n_rows │
│        varchar        │ int64  │
├───────────────────────┼────────┤
│ bakery_current_plan   │      3 │
│ bakery_disruptions    │      2 │
│ bakery_investments    │      4 │
│ bakery_machines       │      8 │
│ bakery_night_jobs     │     18 │
│ bakery_operations     │     72 │
│ bakery_oven_log       │    780 │
│ bakery_products       │      3 │
│ bakery_range          │     30 │
│ bakery_range_forecast │     30 │
│         ·             │      · │
│         ·             │      · │
│         ·             │      · │
│ store_week_actual     │    160 │
│ store_week_forecast   │    160 │
│ stores                │     40 │
│ stress_scenarios      │      6 │
│ trip_log              │   1872 │
│ truck_orders          │     24 │
│ truck_spec            │      2 │
│ yule_log_economics    │      5 │
│ yule_log_forecast     │     40 │
│ yule_log_history      │    118 │
└───────────────────────┴────────┘

Every CSV becomes a table with the same name (your list grows as later lessons add data). CREATE OR REPLACE makes the script safe to rerun.

The full bakery range

The bakery actually makes 30 products in four categories (bread, viennoiserie, cakes, cookies), on 4 resources:

resource,unit,weekly_capacity,note
oven_hours,hours,600,12 deck ovens x 50 usable hours
baker_hours,hours,560,14 bakers x 40 hours
packing_hours,hours,300,2 packing lines x 150 hours
sourdough_starter,batches,60,starter culture can feed at most 60 batches a week

bakery_range.csv has the products (the three Module 1 products keep their numbers), bakery_range_recipe.csv has 94 rows of use per batch (4 sourdough products use starter), and bakery_range_forecast.csv has next week's demand cap for each product. The model is the one from Day 4; only the data are bigger.

6.2 Load, check, build, solve: the bakery module

We put the model in a module, day06/bakery.py, with one function per step:

FunctionJob
load_data(con, …)Read the input tables with SQL, check them, return dictionaries
build_model(d)Build the Pyomo model from the dictionaries; no numbers inside
solve(m)Solve with HiGHS; raise an error unless the result is optimal
plan_table, resource_tableTurn the solution into tables people can read
save_run(con, …)Store the plan in the database
"""Day 6: a data-driven bakery model. The same code plans 3 products or 30.

Import it:  from bakery import load_data, build_model, solve, plan_table
"""
import duckdb
import pandas as pd
import pyomo.environ as pyo


class DataError(Exception):
    """The input tables are inconsistent: fix the data, don't solve."""


def load_data(con, products="bakery_range", recipe="bakery_range_recipe",
              resources="bakery_range_resources", forecast="bakery_range_forecast"):
    """Read the four input tables with SQL and return plain Python dictionaries."""
    p = con.sql(f"""
        SELECT sku, product_name, category,
               units_per_batch * (transfer_price - ingredient_cost) AS profit_per_batch
        FROM {products} ORDER BY sku""").df()
    r = con.sql(f"SELECT resource, weekly_capacity FROM {resources} ORDER BY resource").df()
    u = con.sql(f"SELECT sku, resource, use_per_batch FROM {recipe}").df()
    f = con.sql(f"SELECT sku, demand_cap_batches FROM {forecast}").df()

    problems = []
    skus, res = set(p.sku), set(r.resource)
    for sku in sorted(skus - set(f.sku)):
        problems.append(f"{sku} has no forecast")
    for sku in sorted(set(f.sku) - skus):
        problems.append(f"forecast row for unknown product {sku}")
    for sku in sorted(skus - set(u.sku)):
        problems.append(f"{sku} has no recipe rows (it would use no resources)")
    for sku in sorted(set(u.sku) - skus):
        problems.append(f"recipe row for unknown product {sku}")
    for rr in sorted(set(u.resource) - res):
        problems.append(f"recipe uses unknown resource {rr}")
    if (u.use_per_batch < 0).any() or (f.demand_cap_batches < 0).any() or (r.weekly_capacity < 0).any():
        problems.append("negative use, forecast or capacity")
    if problems:
        raise DataError("; ".join(problems))

    return {
        "products": p.sku.tolist(),
        "resources": r.resource.tolist(),
        "name": dict(zip(p.sku, p.product_name)),
        "category": dict(zip(p.sku, p.category)),
        "profit": dict(zip(p.sku, p.profit_per_batch)),
        "capacity": dict(zip(r.resource, r.weekly_capacity)),
        "use": {(row.resource, row.sku): row.use_per_batch for row in u.itertuples()},
        "cap": dict(zip(f.sku, f.demand_cap_batches)),
    }


def build_model(d):
    m = pyo.ConcreteModel(name="bakery_plan")
    m.P = pyo.Set(initialize=d["products"])
    m.R = pyo.Set(initialize=d["resources"])
    m.profit = pyo.Param(m.P, initialize=d["profit"])
    m.capacity = pyo.Param(m.R, initialize=d["capacity"])
    m.use = pyo.Param(m.R, m.P, initialize=d["use"], default=0)
    m.cap = pyo.Param(m.P, initialize=d["cap"])
    m.x = pyo.Var(m.P, within=pyo.NonNegativeReals)
    m.demand = pyo.Constraint(m.P, rule=lambda m, p: m.x[p] <= m.cap[p])
    m.capacity_limit = pyo.Constraint(m.R, rule=lambda m, r: sum(m.use[r, p] * m.x[p] for p in m.P) <= m.capacity[r])
    m.total_profit = pyo.Objective(expr=sum(m.profit[p] * m.x[p] for p in m.P), sense=pyo.maximize)
    return m


def solve(m, tee=False):
    """Solve with HiGHS; raise unless the answer is optimal."""
    result = pyo.SolverFactory("highs").solve(m, tee=tee, load_solutions=False)
    tc = result.solver.termination_condition
    if tc != pyo.TerminationCondition.optimal:
        raise RuntimeError(f"no optimal plan: {tc}")
    m.solutions.load_from(result)
    return result


def plan_table(m, d):
    rows = []
    for p in m.P:
        x = pyo.value(m.x[p])
        status = "zero" if x < 1e-6 else ("at cap" if x > d["cap"][p] - 1e-6 else "partial")
        rows.append((p, d["name"][p], d["category"][p], round(x, 4), d["cap"][p], status, round(d["profit"][p] * x, 2)))
    return pd.DataFrame(rows, columns=["sku", "product_name", "category", "batches", "demand_cap", "status", "profit"])


def resource_table(m):
    rows = []
    for r in m.R:
        used = pyo.value(m.capacity_limit[r].body)
        rows.append((r, round(used, 4), pyo.value(m.capacity[r]), round(pyo.value(m.capacity[r]) - used, 4)))
    return pd.DataFrame(rows, columns=["resource", "used", "capacity", "slack"])


def save_run(con, run_name, plan, resources):
    """Keep every plan in the database, so plans can be compared and audited."""
    con.sql("CREATE SEQUENCE IF NOT EXISTS run_seq")
    con.sql("""CREATE TABLE IF NOT EXISTS plan_runs (
                 run_id INTEGER PRIMARY KEY, run_name VARCHAR, solved_at TIMESTAMP, total_profit DOUBLE)""")
    con.sql("""CREATE TABLE IF NOT EXISTS plan_lines (
                 run_id INTEGER, sku VARCHAR, batches DOUBLE, demand_cap DOUBLE, status VARCHAR, profit DOUBLE)""")
    con.sql("""CREATE TABLE IF NOT EXISTS plan_resources (
                 run_id INTEGER, resource VARCHAR, used DOUBLE, capacity DOUBLE, slack DOUBLE)""")
    run_id = con.sql("SELECT nextval('run_seq')").fetchall()[0][0]
    con.execute("INSERT INTO plan_runs VALUES (?, ?, now()::TIMESTAMP, ?)", [run_id, run_name, float(plan.profit.sum())])
    con.sql("INSERT INTO plan_lines SELECT $run_id, sku, batches, demand_cap, status, profit FROM plan", params={"run_id": run_id})
    con.sql("INSERT INTO plan_resources SELECT $run_id, resource, used, capacity, slack FROM resources", params={"run_id": run_id})
    return run_id

Points worth slowing down for:

  • Table names are arguments. load_data defaults to the full range, but any four tables (or views) with the same columns work.
  • Checks before the model. Every product needs a forecast and at least one recipe row; every recipe row needs a known product and resource; nothing may be negative. A DataError stops the run with a list of every problem, not just the first. A model fed bad data still returns "optimal": the checks are your only protection.
  • solve refuses non-optimal results. load_solutions=False lets us look at the status first; only then m.solutions.load_from(result) puts the values into the variables. Code that calls solve never sees a half-answer.
  • save_run gives every run an id from a sequence and stores the plan and resource use. Parameters ($run_id) pass values into SQL safely instead of pasting them into the string.

Decision it supports: a weekly plan that runs from the database, every week, with the same checks.

Other decisions you can support the same way: any model that must be rerun when the data change, which is every model in production.

6.3 Same code, 3 products or 30

Create day06/run_plans.py. First the 3-product bakery from Days 1–4: two small views give its tables the column names load_data expects.

import sys

import duckdb
import pandas as pd

sys.path.insert(0, "day06")
from bakery import build_model, load_data, plan_table, resource_table, save_run, solve

pd.set_option("display.width", 120)
pd.set_option("display.max_rows", 40)
con = duckdb.connect("northbound.duckdb")

# The Module 1 bakery: forecast_next_week.csv (from Day 1) has the demand caps
con.sql("CREATE OR REPLACE VIEW bakery_products_view AS SELECT *, 'module 1' AS category FROM bakery_products")
con.sql("CREATE OR REPLACE VIEW forecast_view AS SELECT sku, demand_cap_batches FROM forecast_next_week")
small = load_data(con, "bakery_products_view", "bakery_recipe", "bakery_resources", "forecast_view")
m = build_model(small)
solve(m)
plan, res = plan_table(m, small), resource_table(m)
print(plan[["sku", "batches", "status", "profit"]])
print(f"3-product profit ${plan.profit.sum():,.2f}")
save_run(con, "three products", plan, res)
     sku  batches   status  profit
0  BK-CR     10.0  partial  2500.0
1  BK-SD     20.0  partial  6000.0
2  BK-WW     45.0   at cap  9000.0
3-product profit $17,500.00

The same $17,500, now from SQL. Then the full range, with the defaults:

# The full range: same functions, different tables
full = load_data(con)
m = build_model(full)
solve(m)
plan, res = plan_table(m, full), resource_table(m)
print(plan[["sku", "product_name", "batches", "demand_cap", "status"]].to_string(index=False))
print(res.to_string(index=False))
print(f"30-product profit ${plan.profit.sum():,.2f}")
  sku                   product_name  batches  demand_cap  status
BK-03                       Rye loaf     25.0          25  at cap
BK-04                Multigrain loaf     18.0          18  at cap
BK-05                Baguette 2-pack      7.0           7  at cap
BK-06             Country white loaf      8.0           8  at cap
BK-07                Olive sourdough      0.0          29    zero
BK-08               Seeded sourdough      0.0          19    zero
BK-09                Ciabatta 4-pack      8.0           8  at cap
BK-10                   Raisin bread     20.0          20  at cap
BK-12        Pain au chocolat 4-pack     15.0          15  at cap
BK-13        Almond croissant 4-pack     27.0          27  at cap
BK-14           Cinnamon roll 4-pack     26.0          26  at cap
BK-15                  Danish 4-pack      0.0           8    zero
BK-16                   Brioche loaf      9.0           9  at cap
BK-17          Apple turnover 4-pack      9.0           9  at cap
BK-18             Butter tart 6-pack     25.0          30 partial
BK-19                    Carrot cake      0.0          24    zero
BK-20                Lemon loaf cake      0.0          24    zero
BK-21              Black forest cake      0.0          18    zero
BK-22                     Cheesecake      0.0           9    zero
BK-23                   Banana bread     20.0          20  at cap
BK-24               Maple layer cake      0.0          28    zero
BK-25        Oatmeal cookies 12-pack     16.0          16  at cap
BK-26 Chocolate chip cookies 12-pack      1.6           9 partial
BK-27            Nanaimo bars 6-pack     25.0          25  at cap
BK-28            Date squares 6-pack     20.0          20  at cap
BK-29             Shortbread 12-pack     19.0          19  at cap
BK-30                Brownies 6-pack     20.0          20  at cap
BK-CR               Croissant 6-pack     31.0          31  at cap
BK-SD                 Sourdough loaf     35.0          35  at cap
BK-WW               Whole-wheat loaf     45.0          45  at cap
         resource   used  capacity  slack
      baker_hours 539.62       560  20.38
       oven_hours 600.00       600   0.00
    packing_hours 300.00       300   0.00
sourdough_starter  60.00        60   0.00
30-product profit $108,351.28

The full plan earns $108,351.28 a week. Read it the way a planner would:

  • 22 products are baked, 8 are not. Oven, packing and starter are full; 20 baker hours are spare.
  • Only 2 products are "partial" (butter tarts and chocolate chip cookies). With 4 resources, at most 4 products can sit strictly between 0 and their cap in a corner solution; the rest are at a bound. That is Day 3's geometry in 30 dimensions.
  • Olive and seeded sourdough are not baked: the starter is full, and the starter goes to sourdough loaves and rye, which earn more per batch of starter.

Then the plan goes into the database, and SQL reports on it:

run_id = save_run(con, "full range", plan, res)

print(con.sql(f"""
    SELECT p.category, count(*) AS n_products,
           count(*) FILTER (WHERE l.status = 'at cap') AS at_cap,
           count(*) FILTER (WHERE l.status = 'zero') AS not_baked,
           round(sum(l.profit), 2) AS profit
    FROM plan_lines l JOIN bakery_range p USING (sku)
    WHERE l.run_id = {run_id}
    GROUP BY p.category ORDER BY profit DESC"""))
print(con.sql("SELECT run_id, run_name, round(total_profit, 2) AS total_profit FROM plan_runs ORDER BY run_id"))
con.close()
┌──────────────┬────────────┬────────┬───────────┬──────────┐
│   category   │ n_products │ at_cap │ not_baked │  profit  │
│   varchar    │   int64    │ int64  │   int64   │  double  │
├──────────────┼────────────┼────────┼───────────┼──────────┤
│ bread        │         10 │      8 │         2 │  44366.0 │
│ viennoiserie │          8 │      6 │         1 │  36404.0 │
│ cookie       │          6 │      5 │         0 │ 21869.28 │
│ cake         │          6 │      1 │         5 │   5712.0 │
└──────────────┴────────────┴────────┴───────────┴──────────┘

┌────────┬────────────────┬──────────────┐
│ run_id │    run_name    │ total_profit │
│ int32  │    varchar     │    double    │
├────────┼────────────────┼──────────────┤
│      1 │ three products │      17500.0 │
│      2 │ full range     │    108351.28 │
└────────┴────────────────┴──────────────┘

Five of six cakes are not baked. That is a finding for the category manager, not a bug: cakes need the most baker and oven time per dollar. If the cakes must stay on the shelf for other reasons, that is a rule to add (Day 7 does exactly that).

Try it 6.1

Write a SQL query over plan_lines (run 2) and the recipe that lists the products not baked, with their profit per batch and their oven, packing and starter use. Why isn't black forest cake baked, with $256 profit per batch?

Solution
print(con.sql("""
    SELECT l.sku, p.product_name,
           round(p.units_per_batch * (p.transfer_price - p.ingredient_cost), 1) AS profit_per_batch,
           any_value(u.use_per_batch) FILTER (WHERE u.resource = 'oven_hours') AS oven,
           any_value(u.use_per_batch) FILTER (WHERE u.resource = 'packing_hours') AS packing,
           any_value(u.use_per_batch) FILTER (WHERE u.resource = 'sourdough_starter') AS starter
    FROM plan_lines l JOIN bakery_range p USING (sku) JOIN bakery_range_recipe u USING (sku)
    WHERE l.run_id = 2 AND l.status = 'zero'
    GROUP BY ALL ORDER BY profit_per_batch DESC"""))
┌─────────┬───────────────────┬──────────────────┬────────┬─────────┬─────────┐
│   sku   │   product_name    │ profit_per_batch │  oven  │ packing │ starter │
│ varchar │      varchar      │      double      │ double │ double  │ double  │
├─────────┼───────────────────┼──────────────────┼────────┼─────────┼─────────┤
│ BK-21   │ Black forest cake │            256.0 │    1.8 │     1.0 │    NULL │
│ BK-08   │ Seeded sourdough  │            248.0 │    1.9 │     0.6 │     1.0 │
│ BK-22   │ Cheesecake        │            245.4 │    1.7 │     0.9 │    NULL │
│ BK-07   │ Olive sourdough   │            227.0 │    1.2 │     0.6 │     1.0 │
│ BK-20   │ Lemon loaf cake   │            219.2 │    2.3 │     0.9 │    NULL │
│ BK-15   │ Danish 4-pack     │            208.0 │    1.6 │     0.7 │    NULL │
│ BK-19   │ Carrot cake       │            199.0 │    2.3 │     1.0 │    NULL │
│ BK-24   │ Maple layer cake  │            193.8 │    1.5 │     1.2 │    NULL │
└─────────┴───────────────────┴──────────────────┴────────┴─────────┴─────────┘

FILTER (WHERE …) picks one resource's value inside the aggregate, turning the long recipe into columns. Black forest cake earns $256 a batch but uses 1.8 oven hours and 1.0 packing hour, both full. The products that are baked earn more per hour of the full resources they use. Profit per batch alone never decides; Day 11's reduced costs measure exactly how far each product is from being worth baking.

6.4 A bad forecast file

Next Monday, the forecast file arrives with bk-04 instead of BK-04: one typo in one row. day06/drill_bad_forecast.py builds the model twice: once the quick way, where a missing cap silently becomes "no cap" (.get() returns None), and once through load_data.

con = duckdb.connect()   # in memory: the drill must not touch northbound.duckdb
for t in ("bakery_range", "bakery_range_recipe", "bakery_range_resources", "bakery_range_forecast"):
    con.sql(f"CREATE TABLE {t} AS SELECT * FROM 'data/{t}.csv'")
con.sql("UPDATE bakery_range_forecast SET sku = 'bk-04' WHERE sku = 'BK-04'")   # the typo

# 1. Without the checks: build the model the quick way, with .get() for missing caps
d = {
    "products": [r[0] for r in con.sql("SELECT sku FROM bakery_range").fetchall()],
    "cap": dict(con.sql("SELECT sku, demand_cap_batches FROM bakery_range_forecast").fetchall()),
}
profit = dict(con.sql("SELECT sku, units_per_batch * (transfer_price - ingredient_cost) FROM bakery_range").fetchall())
use = {(r, s): u for s, r, u in con.sql("SELECT sku, resource, use_per_batch FROM bakery_range_recipe").fetchall()}
capacity = dict(con.sql("SELECT resource, weekly_capacity FROM bakery_range_resources").fetchall())
m = pyo.ConcreteModel()
m.P = pyo.Set(initialize=d["products"])
m.R = pyo.Set(initialize=list(capacity))
m.x = pyo.Var(m.P, bounds=lambda m, p: (0, d["cap"].get(p)))       # None = no upper bound
m.c = pyo.Constraint(m.R, rule=lambda m, r: sum(use.get((r, p), 0) * m.x[p] for p in m.P) <= capacity[r])
m.obj = pyo.Objective(expr=sum(profit[p] * m.x[p] for p in m.P), sense=pyo.maximize)
print(pyo.SolverFactory("highs").solve(m).solver.termination_condition)
print(f"profit ${pyo.value(m.obj):,.2f}; BK-04 Multigrain: {pyo.value(m.x['BK-04']):.2f} batches (forecast was 18)")

# 2. With the checks in load_data
try:
    load_data(con)
except DataError as e:
    print("DataError:", e)
optimal
profit $121,309.40; BK-04 Multigrain: 255.47 batches (forecast was 18)
DataError: BK-04 has no forecast; forecast row for unknown product bk-04

Without the checks the solver says "optimal" and plans 255 batches of multigrain against a forecast of 18, for a profit $13,000 higher than reality. Nobody would see an error; the stores would see 23,700 extra loaves. With the checks, the run stops and names both halves of the problem. The drill uses an in-memory database, so northbound.duckdb stays clean.

Decision it supports: whether this week's data are fit to plan with, before anyone acts on the plan.

Other decisions you can support the same way: rejecting a price file with a missing product · stopping a roster built on last month's staff list.

Try it 6.2

What other mistakes in the input tables would produce a plausible but wrong plan? Name two that load_data already catches and one it does not.

Solution

Caught: a recipe row for a product that doesn't exist (a typo in the recipe file); a product with no recipe rows (it would use no resources and be unbounded, Day 7); a negative forecast. Not caught: a wrong but valid number, like Day 4's 15 oven hours instead of 1.5, or a forecast of 180 instead of 18. Range checks help ("no product uses more than 5 oven hours a batch", "a forecast more than 3 times last week's sales needs a human"), and Day 9 adds known-answer tests.

Mini-project: is a third packing shift worth it?

Packing is full. The plant manager can add a third shift on one line: 40 more packing hours, for 340 in total. Without changing bakery.py:

  1. Plan with 340 packing hours, using a view over bakery_range_resources and load_data(con, resources=…).
  2. Save the run as "packing 340".
  3. Compare it with the "full range" run in SQL: which products change, and by how much?
  4. How much more profit per week? Are all 40 hours used? What is the most the shift could cost and still pay?
Solution
import sys

import duckdb

sys.path.insert(0, "day06")
from bakery import build_model, load_data, plan_table, resource_table, save_run, solve

con = duckdb.connect("northbound.duckdb")
con.sql("""CREATE OR REPLACE TEMP VIEW resources_more_packing AS
           SELECT resource, CASE WHEN resource = 'packing_hours' THEN 340 ELSE weekly_capacity END AS weekly_capacity
           FROM bakery_range_resources""")
d = load_data(con, resources="resources_more_packing")
m = build_model(d)
solve(m)
plan, res = plan_table(m, d), resource_table(m)
print(res.to_string(index=False))
new_run = save_run(con, "packing 340", plan, res)
base_run = con.sql("SELECT max(run_id) FROM plan_runs WHERE run_name = 'full range'").fetchall()[0][0]

print(con.sql(f"""
    SELECT sku, p.product_name, round(a.batches, 2) AS before, round(b.batches, 2) AS after,
           round(b.batches - a.batches, 2) AS change
    FROM (SELECT * FROM plan_lines WHERE run_id = {base_run}) a
    FULL JOIN (SELECT * FROM plan_lines WHERE run_id = {new_run}) b USING (sku)
    JOIN bakery_range p USING (sku)
    WHERE abs(b.batches - a.batches) > 1e-6
    ORDER BY change"""))
print(con.sql(f"""
    SELECT run_id, run_name, round(total_profit, 2) AS total_profit,
           round(total_profit - lag(total_profit) OVER (ORDER BY run_id), 2) AS gain
    FROM plan_runs WHERE run_id IN ({base_run}, {new_run}) ORDER BY run_id"""))
con.close()
         resource     used  capacity   slack
      baker_hours 560.0000       560  0.0000
       oven_hours 600.0000       600  0.0000
    packing_hours 317.8459       340 22.1541
sourdough_starter  60.0000        60  0.0000
┌─────────┬────────────────────────────────┬────────┬────────┬────────┐
│   sku   │          product_name          │ before │ after  │ change │
│ varchar │            varchar             │ double │ double │ double │
├─────────┼────────────────────────────────┼────────┼────────┼────────┤
│ BK-SD   │ Sourdough loaf                 │   35.0 │    6.0 │  -29.0 │
│ BK-18   │ Butter tart 6-pack             │   25.0 │  29.09 │   4.09 │
│ BK-22   │ Cheesecake                     │    0.0 │    5.2 │    5.2 │
│ BK-26   │ Chocolate chip cookies 12-pack │    1.6 │    9.0 │    7.4 │
│ BK-07   │ Olive sourdough                │    0.0 │   29.0 │   29.0 │
└─────────┴────────────────────────────────┴────────┴────────┴────────┘

┌────────┬─────────────┬──────────────┬─────────┐
│ run_id │  run_name   │ total_profit │  gain   │
│ int32  │   varchar   │    double    │ double  │
├────────┼─────────────┼──────────────┼─────────┤
│      2 │ full range  │    108351.28 │    NULL │
│      3 │ packing 340 │     109906.6 │ 1555.32 │
└────────┴─────────────┴──────────────┴─────────┘

1–3. The extra shift raises profit by $1,555.32 a week, and the plan changes in a way no one would guess: sourdough drops from 35 to 6 batches and olive sourdough goes from 0 to 29. Both use one batch of starter, but olive sourdough needs 1.2 oven hours against sourdough's 2.0. The 23.2 oven hours this frees go to butter tarts, cheesecake and cookies, which now have packing time. Sourdough earns the most per batch, yet it is the product the model cuts.

  1. Only 17.8 of the 40 hours are used: the bakers (560 hours) are now full. The shift pays if it costs less than $1,555 a week. Better: book about 18 hours, not 40, and price an extra baker next.

The FULL JOIN … USING (sku) keeps a product that appears in only one of the two runs; lag() puts each run's profit next to the one before.

Commit

git add .
git commit -m "Day 6: bakery module fed by DuckDB, data checks, plan runs"
git push

Day 6 checklist

  • I loaded every course CSV into northbound.duckdb.
  • My model reads its data with SQL and contains no numbers.
  • The same code plans 3 products ($17,500) and 30 products ($108,351.28).
  • load_data refuses inconsistent data and lists every problem.
  • Plans are stored with a run id, and I can compare two runs in SQL.
  • I can explain why a product with high profit per batch may not be baked.