The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Computer Science: Algorithms, Systems and Software

Weeks 9–12

Software design, data and testing

Learning objectives

  • Explain the mechanisms and distinctions in software design, data and testing.
  • Apply the assigned concepts to the supplied fictional record and justify each inference.
  • Revise a conclusion when evidence, assumptions or constraints change.

Develop the concepts

Software design decomposes a problem into responsibilities and interfaces. A useful interface states what a component promises and what it requires. Internal details can change without affecting callers when the contract remains stable. Decomposition should reduce reasoning burden rather than scatter one responsibility across many places. Separate data validation, domain rules and presentation where those distinctions aid understanding.

A data model identifies entities, relationships and constraints. In a relational model, keys identify records and support references; a name is often a poor identifier because names can repeat or change. Normalization addresses some redundancy and update anomalies, but practical design also considers workload and integrity rules. A database constraint can protect an invariant across multiple entry paths more reliably than a check in one screen alone.

Testing should target behavior and failure modes. Unit tests focus on components, integration tests examine interactions and end-to-end tests follow a user-visible flow. A test mirroring the implementation can preserve the same mistaken assumption. Include boundaries, invalid inputs, repeated actions and concurrency where relevant. Logging can aid diagnosis without exposing sensitive information. A system’s reliability depends on specification, implementation, storage and operation together, not on the existence of a large test count.

Worked record

A fictional course platform uses learner names as the key for completion records. Two learners named Alex Rivera enroll, and one later changes their display name.

Reason through the record

The name is not a stable unique identifier. It can merge two people’s records or detach a person from their own history. Introduce an internal learner identifier, keep the display name as an attribute and relate completion records to the identifier. A migration must preserve evidence about which record belongs to whom; guessing based on names can corrupt existing data. Add integrity constraints and test duplicate names, name changes and repeated completion actions. The design problem is not solved by merely changing the visible label. The identity relationship must remain consistent across storage, APIs and user interfaces.

Deeper explanation: Data invariants, transactions and tests that expose failures

A database design protects relationships that must remain true across operations. A customer display name can change and can be shared by different customers. A stable identifier distinguishes identity from presentation. A foreign key can require that an order references an existing customer; a unique constraint can prevent duplicate event identifiers. Application checks are useful for feedback, but they cannot replace database constraints when concurrent requests race.

A transaction groups changes that must succeed or fail together. Suppose an event changes a ledger, increments a version and creates an audit record. Committing only the ledger creates a state that cannot be reconciled with its recorded history. A deliberate failure after each internal step is a stronger test than checking only the successful path. The test should inspect persisted state after the exception, not merely assert that an exception was raised.

Optimistic concurrency compares the version a client read with the current version. If both clients read version 7, the first successful update can create version 8. The second client must not silently overwrite it using the old assumptions. The version comparison and write need one atomic database operation or a protected transaction. A separate read followed later by an unprotected write leaves a race window.

Idempotency concerns the identity of an operation, not just equality of its amount. Two legitimate purchases for the same amount can be distinct events. An identical retry of one event must not charge twice. Reusing an event ID with changed contents should produce a conflict rather than quietly return success. Test the operation through the actual request boundary, including authorization and input parsing, because unit tests of a helper function cannot establish that the server invokes it correctly.

Fully worked investigation

Start with balance 10,000 cents and version 7. Client A sends event E1, amount −2,000, expected version 7. A transaction records E1, balance 8,000 and version 8. Client B sends E2, amount −1,000, also expecting 7: it must receive a stale-state conflict and leave balance at 8,000. An exact retry of E1 can return the previously committed result. E1 with amount −3,000 is a conflicting reuse, not a harmless retry. E3 with amount −2,000 can be a distinct valid event after the client refreshes to version 8.

Independent transfer problem

Design a test where audit insertion fails after ledger insertion. Specify the expected ledger, audit and version state. Then run two simultaneous writes using the same expected version and distinct event IDs.

Reasoning and limitations

After the forced audit failure, no event or audit row should remain and the version must be unchanged. In the concurrent versioned-write test exactly one fresh write should commit; the other must conflict. An exact retry is tested separately because returning a previous result is not a second commit.

Unit 3: software structure, relational data and credible tests

Requirements become observable behavior

A requirement describes a needed behavior or constraint. 'Reliable reporting' becomes reviewable when the design states which records appear, whose permissions apply, how stale data are labeled and what happens after a partial failure. Functional requirements concern what the system does; quality constraints include response time, availability, accessibility and recoverability under specified conditions. They can conflict. A design review should expose the tradeoff rather than attach every desirable adjective to an unspecified service.

Separate responsibilities so changes have understandable boundaries. A parser converts a representation into validated values. A domain operation checks the application's rules. A storage adapter preserves the required state transition. A presentation component communicates its result. A failed operation must not be rendered as success merely because the screen loaded. Interfaces should describe input/output types, errors, mutation and timing assumptions. Encapsulation reduces callers' dependence on internal details, while excessive coupling makes one change propagate across unrelated components.

A lifecycle connects investigation, design, implementation, review, testing, release and maintenance. Iteration revises assumptions using evidence rather than treating the first requirement as permanently correct. Version control records identifiable changes and their relationships; an isolated branch can help review work before combining it with another line of development. A clean merge resolves text relationships, not every semantic conflict. Two independently passing changes can fail when combined if they alter the same behavior under incompatible assumptions. Release evidence should therefore identify the actual combined version tested.

Entities, relationships and normalization

A relational design represents entities and relationships through tables, rows, attributes and constraints. A primary key identifies a row; a foreign key constrains a reference to another table. A key should express identity rather than a convenient display label. A repeated organization name inside every job row creates an update problem when the name changes in only some rows. Store the organization identity and its current name in one organization relation, then reference that identity from jobs. This reduces a particular redundancy; it does not mean every repeated value is inherently wrong.

Normalization reasons about dependencies. If job ID determines organization ID, and organization ID determines organization name, storing all three in one table repeats an organization fact across jobs. Splitting the organization facts from job facts avoids inconsistent name updates. Relationship tables represent many-to-many associations without squeezing an arbitrary number of references into one text field. Constraints still need an explicit business interpretation: a foreign key can establish that an organization exists, but not that the current caller is allowed to read it.

NULL represents missing or inapplicable information under SQL's rules; it is not generally the same as zero or an empty string. A comparison with an unknown value does not behave like an ordinary true/false comparison with a known number. A query must intentionally handle missing values. Avoid converting missing completion time to zero and then reporting that the job completed instantly. A schema also needs units and permitted ranges, not just column names. A database can store a perfectly valid integer that the application interprets in the wrong currency or time unit.

Queries combine, filter and summarize

A selection filters rows; a projection chooses output attributes; a join combines matching rows from related sources. SQL query plans can implement these operations in different orders while preserving the language's specified result. Do not mistake an instructional processing sequence for a promise that the engine executes precisely that sequence. An index can accelerate some access patterns but also costs storage and update work. A query's actual workload determines whether a particular index is useful.

Original Harbor job record: Organizations contains(O1, North), (O2, South), (O3, West), with unique organization IDs. Jobs contains(J1, O1, open), (J2, O1, closed), (J3, O2, open), (J4, O2, open). Joining Jobs to Organizations on organization ID and filtering status=open yields(J1, North), (J3, South), (J4, South). Grouping those open rows by organization gives North 1 and South 2. West has zero jobs but disappears from an inner join; that is not evidence that West does not exist.

To report every organization including zero counts, begin with all organizations and preserve unmatched rows using a left join. Put the desired open-job restriction in the join condition or otherwise handle unmatched rows explicitly. Count the matched job identifier, which is non-NULL for real matched jobs, rather than blindly counting the synthetic joined row. Then the result is North 1, South 2, West 0. Moving status=open to a WHERE clause that rejects the NULL-extended rows can remove West again. This changes the meaning of the report even though the query remains syntactically valid.

Changed facts: an imported organization source contains a second O2 row named South-copy and the uniqueness constraint was not enforced. Each O2 job can join twice, inflating South-associated totals. DISTINCT is not a universal repair: it can remove legitimate repeated observations or hide inconsistent identity data. First establish which relation should own the authoritative organization identity, detect the duplicate and reconcile it according to evidence. The valid earlier count relied on unique organization IDs. A result table alone cannot demonstrate that this premise held.

Integrity across time and concurrent requests

A transaction groups related state changes according to a database's guarantees. Atomicity concerns all-or-nothing effects at the transaction boundary. Consistency depends on the invariants the database and application actually enforce. Isolation governs the interactions visible among concurrent operations; durability concerns persistence after a successful commit under the configured failure model. These properties do not mean that every transaction implements the right business rule or that a local commit also commits a remote service action.

The retained native ledger/version/audit investigation supplies the detailed optimistic-concurrency and operation-identity cases. A database-specific implementation must also handle errors correctly. In SQLite, for example, only one write transaction can proceed at a time, and a busy result is a real outcome to handle. Do not assume that every statement error automatically undoes every preceding statement in a manually controlled transaction. Specify rollback behavior, verify the persisted state and distinguish a new operation from a retry. These explanations concern fictional local designs; no learner or production database should be used for practice.

Test evidence must challenge the implementation

A test fixture supplies known inputs, initial state and cleanup. A test oracle supplies the expected behavior. If both the implementation and its test compute 'first arrival' by sorting identifiers, they can share the same mistake. An independent small record with explicitly stated expected output is often more revealing than a large random fixture whose expected result is another copy of the algorithm.

Unit tests isolate a component; integration tests inspect interactions such as parsing, authorization and persistence; end-to-end tests follow a visible workflow. A mock can make a dependency predictable but does not demonstrate that the actual dependency behaves that way. Code coverage measures which code was exercised under a definition; it does not prove that assertions address the important risks. Inspect failures by category, including boundary inputs, conflicting requests, missing data, authorization denials and recovery after interrupted work. A passing test suite supports the tested claims, not every possible workload.

Original failure record: a fictional asset service begins with job J7=open, revision 4 and audit entry A0. Operation K would close J7, set revision 5 and append audit entry A1. A controlled failure is injected after the job change but before A1 insertion, inside a transaction intended to include all three effects. The required recovered state is J7=open, revision 4, with A0 preserved and A1 absent. Saying 'the audit table should be empty' would incorrectly delete or ignore the pre-existing history. Inspect the reopened persisted state after failure; observing an exception alone is insufficient.

Changed facts: the job update commits through one connection before a second connection attempts A1. Failing the audit insertion can now leave J7=closed and revision 5 without A1. The single-transaction claim does not apply across those independently committed operations. Repair the transaction boundary or supply a deliberate recoverable protocol with detectable incomplete state. Repeating the same successful-path test cannot establish recovery from this altered failure boundary.

Optional test-design practice with full model

Question: a dashboard displays North 1, South 2 and omits West. A unit test compares the display against a fixture that also omits West. Does it establish the 'every organization, including zero' requirement? Supply a stronger check.

Model reasoning: no. The oracle encodes the same omission. Use the complete three-organization/four-job fixture above and require all three organization IDs, with counts 1, 2, 0 and no extra IDs. Also test an organization with only closed jobs and a dataset with no jobs. Verify both the underlying query and the rendered report, because a correct query can be followed by a presentation filter that drops zero values. Changed facts: the requirement is explicitly revised to list only organizations with at least one open job. The earlier omission is now consistent with the new scope, but label the revised report clearly and retain the version of the requirement under which the tests were evaluated.

Complete original cumulative application and rubric: https://www.lawfaregroup.com/knowledge/academy/developed-studies/computing-contracts-machines-and-evidence.html#cumulative

Apply the idea

A fictional course platform uses learner names as the key for completion records. Two learners named Alex Rivera enroll, and one later changes their display name.

The user interface prevents duplicate names, but a data-import endpoint does not. Is the invariant protected?

Additional worked record — a separate fictional scenario: Start with balance 10,000 cents and version 7. Client A sends event E1, amount −2,000, expected version 7. A transaction records E1, balance 8,000 and version 8. Client B sends E2, amount −1,000, also expecting 7: it must receive a stale-state conflict and leave balance at 8,000. An exact retry of E1 can return the previously committed result. E1 with amount −3,000 is a conflicting reuse, not a harmless retry. E3 with amount −2,000 can be a distinct valid event after the client refreshes to version 8.

Progressive transfer problem: Design a test where audit insertion fails after ledger insertion. Specify the expected ledger, audit and version state. Then run two simultaneous writes using the same expected version and distinct event IDs.

Read the worked reasoning

No. One interface’s validation cannot protect every write path. Enforce the relevant identity constraints at the shared service or data layer, then test the import as well as the screen.

Transfer reasoning: After the forced audit failure, no event or audit row should remain and the version must be unchanged. In the concurrent versioned-write test exactly one fresh write should commit; the other must conflict. An exact retry is tested separately because returning a previous result is not a second commit.

Check understanding

What distinguishes an idempotent retry from a second purchase?

  1. A matching amount alone
    Feedback

    Incorrect. Equal amounts can belong to different legitimate events.

  2. The same operation identifier with matching validated contents
    Feedback

    Correct. The operation identity and content contract let the server recognize one previously committed action.

  3. Arrival within the same minute
    Feedback

    Incorrect. Timing does not establish identity and can misclassify either retries or legitimate separate actions.

Further reading

Study the complete native lesson and matching original on-site reader unit with the preserved quantitative investigation, then the complete Harbor cumulative case and rubric. All practice, local laboratory execution and publisher chapters are optional; no external learning departure is required.

My learning →