Lawfare Academy ยท Complete Data Management and SQL edition 6
Validate the report, the analytical dataset and the system that delivers them
A report is an executable chain of claims
Write the eligible population, output grain, measures, source cutoff, status policy, missingness policy and currency before optimizing a query. The preserved Cedar job report has three rows with billed 730,paid 390,open 340 dollars; its counterexamples expose fan-out and equal-priced legitimate lines. The separate preserved paid-order cumulative dossier has billed 6500,settled 6500,posted refunds 800 and net billed 5700 cents, excluding draft 700 and pending 500 under explicit policies. Do not combine those independent fixtures or call either a universal revenue-recognition rule.
Validation needs both totals and keyed facts. Check unique output keys, intended parent coverage, unmatched relationships, duplicate input identities, unknown amounts and boundary timestamps. Compare source-to-target facts in both directions and inspect multiplicity. A correct grand total can hide offsetting account errors. An optimization is acceptable only if the complete promised result remains unchanged; a changed execution plan is not a correctness proof. The preserved 10,000-event and WAL examples separate semantics, access strategy and snapshot visibility without promising universal speed.
Prepare data for learning without leaking the answer
Big-data problems concern volume, arrival speed, varied representations, reliability and practical usefulness, not a magic row-count threshold. A small sensitive dataset can be harder to govern than a large public one. Integration aligns identities, units and timing across sources; it must preserve uncertainty about unresolved matches. Batch pipelines process bounded groups, while streams process arriving events with policies for ordering, late data, replay and failure recovery. A streaming output is not automatically complete for an event-time period just because no new row arrived in the last minute.
Supervised learning uses labeled examples to predict a target; classification predicts categories or probabilities, regression predicts a quantitative outcome. Unsupervised methods, such as clustering, seek structure without the same provided outcome labels. A clustering label is not ground truth or a causal explanation. A shallow model may use explicit features and a relatively simple decision structure, such as linear/logistic models or trees. A deep neural model learns multiple layers of representation through fitted parameters; image, text and sequence applications may benefit when appropriate data and compute exist. Complexity does not remove the need for quality, an admissible target or honest validation.
Tools operate at different layers. SQL constructs eligible cohorts and features; Python/R libraries implement transformations and model estimation; distributed query engines or massively parallel processing(MPP) divide work across workers; deep-learning frameworks support tensor operations, automatic differentiation and accelerated training. Naming a tool does not make a result verified. MPP can distribute table partitions and partial aggregates, then combine results. Data skew, network shuffles, coordination and failure retries limit speedup. If 80%of a workload is parallelizable and four workers are otherwise ideal, Amdahl's simplified speedup is 1/(.2+.8/4)=2.5, not 4. That model omits real overhead and is an upper-bound reasoning exercise under its assumptions.
Feature construction needs a decision-time contract. To predict next-month late payment at month-end, a feature called eventual_collection_date contains future information and must not enter a historical forecast. Split by time and, where the target is new accounts, by account; repeated rows from the same entity can otherwise leak identity-specific patterns. Fit imputation, category encodings and scaling only within training. Preserve labels, feature definitions, source versions and the model version. Evaluate against a simple admissible baseline on the same targets, not against a deliberately weak comparator with less information.
Worked classification and changed threshold
Use a separate synthetic frozen holdout of 100 invoices:20 ultimatelylate and 80 on time. A fixed threshold flags 25:15 true late and 10 false alarms. The remaining 75 contain 5 missed late and 70 true negatives. Accuracy 85%,precision 15/25=60%,recall 15/20=75%,specificity 70/80=87.5%. A never-late baseline has 80%accuracy but zero recall. These are observed holdout proportions, not guaranteed population rates. Report the selection and threshold process, sample size and costs.
Suppose a missed late invoice costs 100 units and a false alarm costs 10. This threshold has loss 5*100+10*10=600. Another frozen threshold catches 18 of 20 late but falsely flags 25 of 80 on-time invoices, giving loss 2*100+25*10=450 and accuracy 73%. Lower accuracy can accompany lower declared loss. If costs become 20 for a miss and 20 for a false alarm, losses are 300 and 540, reversing the preference. Declare costs before choosing a winner, and retain an independent evaluation after threshold selection. If all thresholds were selected using this holdout, call it development evidence rather than untouched final testing.
Informatics connects users, workflow and information
Informatics examines how people and technical systems collect, interpret and use information in a domain. A correct query that staff cannot understand can produce unsafe workflow decisions; a helpful interface built on incomplete records can mislead just as seriously. For a collections screen, show the measure's unit, cutoff, unresolved amounts, evidence and authorized next action. Distinguish a model flag from a verified late payment, and give a way to inspect and correct source errors. The user's role, decision deadline and ability to contest a record are design inputs, not cosmetic additions after coding.
An information-system lifecycle includes understanding the problem and stakeholders, feasibility and requirements, design, implementation, validation, deployment, operation/change and eventual retirement or migration. A health, sports or financial application uses different domain vocabularies and consequences even if all store tables. Text instruction and synthetic tests do not establish clinical competency, regulatory approval or authority over real people. This course's examples support business-data reasoning; they do not make automated eligibility or care decisions.
Engineer a small reporting service as a maintained system
Software engineering applies organized design, construction, evaluation and maintenance to a useful system. Requirements include functional behavior(one row per eligible order, an authorized refund operation) and quality constraints(correctness, availability, security, accessibility, latency and recoverability). Make each testable. 'Fast and secure' is not an acceptance criterion. 'A reporting identity cannot update source orders' and 'the report retains accounts without payments and exposes unknown amounts' have observable consequences. Include data contracts, interfaces and external dependencies in the design.
A layered design can separate ingestion validation, persistence/transaction operations, report queries, service authorization and presentation. A repository abstraction can isolate data-access details, while an outbox pattern coordinates committed events with later message delivery. Patterns are reusable structures for recurring problems, not proof that every project needs a framework. Keep responsibilities clear enough to test failure boundaries. Refactoring changes internal structure while intending to preserve externally promised behavior; a change from current-price to historical-price reporting is a semantic correction and must be described as such, even if it accompanies refactoring.
Process choice depends on risk and feedback. A staged plan can make stable interfaces and formal approvals explicit; an iterative or agile process delivers small tested increments and revises requirements through feedback. Neither means skipping documentation, security or preservation. A risk-driven spiral emphasizes resolving major uncertainties through successive cycles. Prototypes can test workflow or feasibility but require a clear boundary before becoming relied-upon production systems. Source control, code review, automated builds, dependency tracking and issue histories provide traceability across methods. Continuous delivery prepares verified changes for release; it is not permission to deploy every experiment without the relevant authority.
Testing has complementary scopes. Unit tests check an isolated transformation; integration tests exercise actual interfaces/transactions; system tests verify the connected workflow; user acceptance assesses whether real users can accomplish the intended task. Static analysis and review inspect code without running it. Black-box tests focus on specified behavior; white-box tests consider implementation paths. Boundary, property-based and adversarial fixtures can expose errors that ordinary examples miss. Regression tests protect earlier promises. Code coverage records which code was exercised, not whether expectations were correct. Agent-run tests are not observed human learner or subject review.
Worked requirements-to-release ledger
For the preserved paid-order case, requirement R 1 is one row per paid order with billed 6500,settled 6500,refund 800 and net 5700; R 2 excludes draft 700 and pending 500 but keeps them in exception checks; R 3 applies refund command R 3=400 exactly once and rejects a changed payload; R 4 preserves orders, line prices and settled payments; R 5 exposes a consistent read cutoff. Test R 1 with independent event arithmetic and exact rows, R 2 with status boundaries, R 3 with replay/conflict/over-limit/failure injection, R 4 with before/after keyed comparisons and R 5 with the documented snapshot fixture.
A release ledger connects each requirement to design, test evidence, method/schema version, review status, rollback strategy and monitoring. A rollback to an old application may not undo a destructive schema migration; plan backward/forward compatibility and preserve recoverable data. A canary or limited rollout can reduce exposure while monitoring known invariants, but a passing small slice does not prove all workloads. Keep an incident and correction record. The actual Academy learner database is outside every laboratory in this course.
Reuse includes libraries, modules, services and tested domain components. Review license, provenance, version, maintenance, interfaces and security exposure before adoption. Free/open-source availability does not mean no obligations or no risk. A permissive library and a reciprocal license can impose different conditions; the concrete license text and intended distribution matter. This lesson makes no specific legal conclusion. Professional ethics includes accurate evidence claims, respect for privacy and accessibility, reporting known limits and avoiding deceptive metrics. AI-assisted generation can speed drafting or code suggestions, but output still requires source checking, tests and accountable review; a confident generated query can duplicate money.
Optional progressive practice
Guided model: test a learning-data claim
The first holdout hasTP 15,FP 10,FN 5,TN 70:accuracy 85%,precision 60%,recall 75%,specificity 87.5%. Declared miss 100/false-alarm 10 loss 600. Changed fact: the alternative frozen threshold givesTP 18,FP 25,FN 2,TN 55. Accuracy 73%butloss 450. Name the cost target and threshold-selection history rather than declaring the larger accuracy universally better.
Independent model: scale and leakage are distinct
The simplified 80%-parallel/four-worker speedup is 2.5. It says nothing about whether an eventual collection-date feature was available at issue time. Changed fact: a thousand workers make the leaked model run faster. The evidence remains invalid for the historical forecast; remove future information and reconstruct the admissible evaluation before interpreting speed or accuracy.
Transfer model: passing tests is not human acceptance
Exact SQL and transaction fixtures can establish their own stated results, while staff usability and independent academic review remain separate. Changed fact: a user observes that a zero and an unknown amount look identical. Treat that as a real presentation requirement defect, preserve the old evidence and revise display and tests. Do not call a new test a retroactive human review of all courses.
Unit rubric: 20 points
Four points each for exact report/lineage/snapshot validation; learning-data eligibility and threshold metrics; informatics and testable requirements; connected design/process/testing/release preservation; and ethical changed-fact reasoning. Complete model retains the original 6500/6500/800/5700 report, post-refund 1200/5300, all replay and historical-price boundaries, and separately calculates 85%/600 versus 73%/450 for the independent classifier. It declines both false software and false human-review claims.
Optional source summaries: OpenStax's learning-data section and informatics section were read for their data/pipeline and human-system scope. Its software fundamentals, process and testing/reuse/ethics topics informed the topic boundaries. The methods, classifier, requirements ledger and complete models above are original on-site teaching, not assigned external chapters or copied textbook prose.