Part I — Foundations · Chapter 5 · Lesson 5 of 5 · 8 min read
Chapter 5 Checkpoint: Inventory Analyzer
Checkpoint level: Foundation
Purpose: Integrate core values, collections, indexing, mutation, copying, equality, traversal, transformation, filtering, aggregation, and portable boundary design in one complete inventory-analysis program.
Checkpoint outcomes
By completing this checkpoint, you will demonstrate that you can:
- represent inventory records with string-keyed maps inside a list;
- validate required keys and value ranges before using a record;
- traverse a collection without exceeding its bounds;
- separate invalid, valid, and selected records;
- derive independent output maps without corrupting the source;
- calculate counts, totals, minima, maxima, and grouped summaries;
- preserve accounting invariants throughout the pipeline;
- return a portable result suitable for a host application; and
- test empty, malformed, boundary, and ordinary cases systematically.
Project scenario
A small warehouse needs a command-line analyzer for source-defined inventory records. The program validates each item, identifies active stock that requires attention, derives a report record, aggregates operational totals, and returns one portable summary map.
The checkpoint remains intentionally local: it does not read files, call a database, access a network, or use process execution. A production host would obtain and validate external data, invoke the analysis, validate the result, and perform authorized actions.
5C.1 Required input shape
Declare an inventory list. Each item is a string-keyed map with these fields:
| Field | Meaning | Validation |
|---|---|---|
| sku | Stable stock identifier | Nonempty string |
| category | Grouping label | Nonempty string |
| quantity | Units currently on hand | Number at least zero |
| reorder_point | Attention threshold | Number at least zero |
| unit_price | Value of one unit | Number at least zero |
| active | Whether the item participates | Boolean |
Use at least eight records in the primary test set. Include several categories, active and inactive items, one exact reorder boundary, one zero-quantity item, and at least two invalid records.
5C.2 Required validation behavior
- Inspect every input item exactly once.
- Confirm that every required key exists before accessing dependent values.
- Reject empty identifiers or categories.
- Reject negative quantity, reorder point, or unit price.
- Reject values whose expected category is wrong.
- Record a stable reason code for each invalid item.
- Do not include invalid items in valid totals, selected records, or category summaries.
- Continue analyzing later records after a recoverable validation failure.
Use reason codes such as MISSING_FIELD, INVALID_SKU, INVALID_CATEGORY, INVALID_QUANTITY, INVALID_REORDER_POINT, INVALID_PRICE, and INVALID_ACTIVE.
5C.3 Selection rule
Select an item when all of these conditions are true:
- the record is valid;
- the item is active; and
- quantity is less than or equal to reorder_point.
The exact boundary is included. An active item with quantity equal to its reorder point must be selected.
5C.4 Required transformation
For every selected item, create a new report map containing:
- sku;
- category;
- quantity;
- reorder_point;
- shortfall, calculated as reorder_point minus quantity;
- unit_price;
- stock_value, calculated as quantity multiplied by unit_price;
- replenishment_value, calculated as shortfall multiplied by unit_price; and
- reason_code set to AT_OR_BELOW_REORDER.
Do not reuse an original item map as the report record. Construct an independent map so the source collection remains unchanged.
5C.5 Required aggregates
Calculate and report:
- inspected_count;
- valid_count;
- invalid_count;
- selected_count;
- valid_quantity_total;
- valid_inventory_value;
- selected_shortfall_total;
- selected_replenishment_value;
- minimum valid quantity and its SKU;
- maximum valid stock value and its SKU; and
- a string-keyed category summary map.
Each category entry must contain valid item count, quantity total, inventory value, selected count, shortfall total, and replenishment value.
5C.6 Empty-result policy
Minima and maxima require an explicit empty policy. If no valid item exists, set both associated SKU fields and values to null. Do not invent zero as a minimum or maximum merely because accumulators need initialization.
If valid records exist but none is selected, selected lists remain empty and selected totals remain zero.
5C.7 Required result contract
Build one result map with this conceptual shape:
{
"valid": true,
"summary": { ... },
"selected_items": [ ... ],
"invalid_items": [ ... ],
"products": { ... },
"invariants_ok": true
}
Every value in the result must remain portable: null, boolean, integer, float, string, list, or string-keyed map.
5C.8 Required invariants
- inspected_count = valid_count + invalid_count.
- selected_count never exceeds valid_count.
- The sum of category valid counts equals valid_count.
- The sum of category selected counts equals selected_count.
- The sum of category quantity totals equals valid_quantity_total.
- The sum of category inventory values equals valid_inventory_value.
- The sum of selected shortfalls equals selected_shortfall_total.
- The source inventory remains equal to a preserved pre-analysis copy.
- Every selected item is valid, active, and at or below its reorder point.
Calculate invariants_ok from these relationships rather than setting it to true unconditionally.
5C.9 Pipeline design
- Preserve: create a comparison copy of the source before analysis.
- Initialize: create output lists, category map, counters, totals, and null extrema.
- Inspect: traverse each record once and increment inspected_count.
- Validate: calculate validity and a reason code before dependent access.
- Separate: append invalid summaries or continue with valid processing.
- Aggregate valid data: update global and category totals.
- Select: apply the active and reorder-boundary predicate.
- Transform: construct an independent selected report map.
- Aggregate selected data: update selected and category totals.
- Finalize: calculate invariants and construct the portable result.
5C.10 Reference algorithm
Attempt the checkpoint before reading this high-level reference.
let inspected_count = 0
let valid_count = 0
let invalid_count = 0
let selected_items = []
let invalid_items = []
let categories = {}
let valid_quantity_total = 0
let valid_inventory_value = 0
let selected_shortfall_total = 0
let selected_replenishment_value = 0
let minimum_quantity = null
let minimum_quantity_sku = null
let maximum_stock_value = null
let maximum_stock_value_sku = null
for item in inventory {
inspected_count += 1
# Validate required fields and values before calculations.
# Append an invalid summary and continue when validation fails.
# Update valid totals, extrema, and category aggregates.
# When selected, build a new report map and append it.
}
The final implementation must replace each comment with explicit logic. Keep validation decisions visible; do not collapse the whole pipeline into one dense condition.
5C.11 Required test matrix
| Case | Input characteristic | Expected emphasis |
|---|---|---|
| A | Empty inventory | All counts zero; extrema null |
| B | One valid active item above reorder point | Valid but not selected |
| C | One active item exactly at reorder point | Selected with zero shortfall |
| D | One active item below reorder point | Positive shortfall and replenishment value |
| E | Inactive item below reorder point | Valid but not selected |
| F | Missing required key | Invalid; later items still processed |
| G | Negative quantity or price | Invalid range reason |
| H | Several categories | Grouped totals reconcile |
| I | All records invalid | No valid totals; extrema null |
| J | Mixed primary dataset | All outputs and invariants |
5C.12 Prediction worksheet
Before execution, record for every case:
- inspected, valid, invalid, and selected counts;
- selected SKUs in source order;
- quantity, inventory-value, shortfall, and replenishment totals;
- minimum and maximum records;
- category totals; and
- the expected value of every invariant.
For floating-point totals, define an acceptable comparison tolerance and record it with the prediction.
5C.13 Source-preservation test
Keep an independent pre-analysis copy and compare it with the source after the pipeline. The comparison should demonstrate that selected report maps and category summaries were constructed separately.
Also mutate one derived report record in a temporary test. Confirm that the corresponding source item does not change. If it changes, the implementation has retained an unintended shared reference.
5C.14 Diagnostic exercises
Create temporary defective versions demonstrating:
- accessing a missing key before validation;
- using < instead of <= at the reorder boundary;
- including invalid records in valid totals;
- reusing and mutating the original map as a report record;
- initializing a minimum to zero;
- failing to initialize a new category before updating it;
- updating global selected totals but not category selected totals;
- using a non-string key in a boundary result; and
- setting invariants_ok without evaluating the invariants.
For each defect, record the symptom, broken invariant, root cause, minimal correction, and regression test.
5C.15 Validation workflow
- Prepare the test inventory and prediction worksheet.
- Format the source.
- Run the formatting check.
- Run source checking.
- Run the analyzer.
- Compare selected records and all aggregate fields.
- Reconcile category values with global values.
- Verify source preservation.
- Confirm every invariant.
- Record pass or fail with the exact discrepancy.
5C.16 Acceptance criteria
- The program formats and checks successfully.
- Every required field is validated before dependent use.
- All invalid records have stable reason codes.
- Every valid record contributes exactly once to valid aggregates.
- The exact reorder boundary is selected.
- Inactive records are never selected.
- Derived records do not mutate source records.
- Global and category aggregates reconcile.
- Empty and all-invalid inputs follow the documented null policy.
- The final result contains only portable values.
- No file, network, process, credential, or unrestricted host capability is required.
- All invariants evaluate to true for valid implementations.
5C.17 Submission package
- inventory_analyzer.pea in canonical formatting;
- an input data dictionary;
- a pipeline diagram or ordered workflow;
- predictions and actual results for cases A through J;
- global and per-category reconciliation tables;
- source-preservation evidence;
- the diagnostic exercise table;
- a boundary contract for a future host; and
- a brief security statement.
5C.18 Assessment rubric
| Area | Evidence of mastery |
|---|---|
| Data modeling | Lists and string-keyed maps represent the domain clearly. |
| Validation | Shape, required fields, categories, and ranges are checked safely. |
| Traversal | Every item is inspected once in source order. |
| Transformation | Selected report maps are independent and complete. |
| Aggregation | Counts, totals, extrema, and category summaries are accurate. |
| Invariants | Accounting relationships are calculated and verified. |
| Testing | Empty, boundary, malformed, mixed, and preservation cases pass. |
| Portability | The final contract uses only portable values. |
| Security | No unnecessary capability or sensitive data is exposed. |
Completion standard: Every acceptance criterion is met, all required tests pass, category and global summaries reconcile, and the learner can explain why the source collection remains unchanged.
5C.19 Reflection questions
- Which validation order prevented the most dangerous failure?
- Why is the exact reorder boundary selected?
- Why should invalid records not contribute to minima or maxima?
- Which invariant best reveals a missed aggregate update?
- How does building a new report map protect the source?
- Which fields must a host validate again before acting?
- What changes would be required for very large inventories?
- Which parts of this checkpoint remain useful when a DataFrame replaces lists and maps?
Chapter 5 summary
You can now model core values and collections, access and update them deliberately, reason about copying and equality, traverse data, filter and transform records, compute aggregates, and design portable host boundaries. The Inventory Analyzer combines these skills into a validated pipeline whose outputs reconcile through explicit invariants.
Transition to Part II
Part II begins with Chapter 6: Errors, Exceptions, and Diagnostics. The next lesson examines failure categories and useful error messages, building on the validation and diagnostic practices used throughout the foundation projects.
Checkpoint status: Ready for review.