File Boundaries, Global Identity and Failure Recovery
Original source corrections, complete worked mechanisms and optional independent experiments. Read the complete assigned file, exception, CSV and JSON chapters alongside the native lesson.
Turn a file example into a stated boundary
The retained read_amounts example demonstrates quoted fields and integer conversion. It is not a complete customer-record validator. It currently accepts a third field without inspecting it and accepts a blank customer; int also accepts spellings such as +1, surrounding spaces and some non-ASCII digits. Whether those spellings are permitted is a contract decision. The new read_validated_amounts laboratory deliberately chooses a stricter contract, rather than implying that merely calling DictReader validates every record.
Its header must be exactly customer,cents in that order. Each data record has exactly two fields. A customer must contain some non-whitespace text and have at most80 code points; its spelling is preserved without trimming. The amount is an optional minus sign followed by either zero or an ASCII nonzero digit and further ASCII digits. It has at most13 digits and absolute value at most10**12 cents. Refunds and zero are valid; +1, 01, whitespace-padded amounts, fractions and non-ASCII digit spellings are rejected. The complete decoded teaching input is limited to10000 UTF-8 bytes. This small parser returns a list after complete validation, so its memory use grows with the input. It is not the later large-file design.
Use csv.reader with the selected dialect and strict=True, and separately check field counts and domain rules. The strict option makes particular malformed quoting fail; it does not define every possible CSV convention or replace schema validation. A syntactically parsed row can still have the wrong number of fields or an invalid customer. The earlier corrected ledger companion remains the event/customer/amount parser for the course's separate three-column performance study; these two interfaces should not be mixed without an explicit conversion.
Logical records are not physical lines
CSV quoting permits a field to contain a newline. With the text customer,cents followed by a quoted customer spanning the next two physical lines, the following bad record is the third logical record including the header but ends on physical line4. enumerate(reader,start=2) counts logical records; labelling that counter as a physical line misdirects the learner. The new BoundaryError records both the logical record ordinal and reader.line_num, which reports the physical line at the end of the parsed record. It does not claim that an ending-line number is always the location of the precise offending character.
For the actual fixture 'customer,cents\n"Ada\nInc",500\nBad,x\n', record2 ends on physical line3 and is valid. Record3 ends on line4 and fails the chosen amount grammar. The previous tiny parser reports line3 because it counts records. The new parser reports record3, ending physical line4. A broken quoted header is record1, rather than record2; a separate test protects that first-record boundary. CSV syntax failures retain their csv.Error cause, while a domain-rule failure is a distinct BoundaryError. This preserves the distinction between parsing and validation in executable behavior.
Reading, decoding and closing are different operations
The complete beginner Files chapter uses useful small filters and copying examples. Apply several qualifications when extending them. Relative paths resolve from the process's working directory, which need not be the directory containing the script. Mode w truncates an existing file when it is opened, even if no write follows. The plus sign modifies a base mode such as r+; '+' by itself is not a valid mode. A path such as /usr/share/dict/words is an example, not a promised file on every Unix installation. Platform rules for separators differ; a backslash is a separator on Windows but can be an ordinary filename character on POSIX systems.
readline returns a blank line as '\n' and end of input as ''. The last nonempty line need not end with a newline, so the source's 'always includes' wording is too strong. The synthetic stream '\nlast' yields '\n', then 'last', then ''. Those observations explain why a blank line is not the end marker. Reading a whole file or all lines materializes it; iterating lines avoids that particular allocation, but one unusually large record or an ever-growing identity map can still consume substantial memory.
For bytes, str(raw) gives a representation such as the visible b-prefix and escape sequences, not decoded text. Use raw.decode with the chosen encoding and error policy. The source's web example therefore does not perform the promised text decoding merely by wrapping returned bytes in str. Prefer the public response read interface, a context manager, a timeout and a bounded byte policy when writing an actual retrieval function. The offline laboratory needs no historical network endpoint: it demonstrates UTF-8 decoding and an invalid-byte failure directly. Ignoring decoding errors would silently discard information and is a different contract.
The current assigned reference snapshot describes a UTF-8 default. In the tested Python3.12 environment, text defaults can depend on locale/UTF-8 mode; an explicit non-UTF8 locale was reproduced. Specify encoding='utf-8' when UTF-8 is the chosen representation, and newline='' for CSV files so the CSV module controls embedded/newline handling. Closing and flushing make resource state observable; they do not establish every storage durability property.
Handle the failure that actually occurred
The beginner Exceptions chapter's bare except catches more than a bad filename or exhausted recursion. It can catch KeyboardInterrupt and SystemExit, concealing a user's intended termination. A failed open can also mean a permission problem rather than an absent file. Choose the narrow exception type at the operation whose failure you understand. A path existence test is not a guarantee that a later open will succeed: the filesystem can change between those observations. Perform the needed operation and handle its actual result.
In the turtle cleanup example, win is assigned only after resource construction succeeds. If that construction fails, finally: win.bye() tries to use an unbound local and reports UnboundLocalError, masking the original acquisition error in the active exception. The new non-GUI fixture reproduces this with a deliberately failing resource constructor. A with acquire() block never enters its body if acquisition fails; an entered context's exit method can then perform its documented cleanup for a later body failure. If __enter__ itself partly acquires resources and fails, it is responsible for its own partial cleanup. Cleanup can also fail; inspect chained context rather than assuming the final reported error was the first failure.
Finally does not mean successful completion, rollback or survival of process termination/power loss. A return in finally can suppress an exception or override a return value. Prefer cleanup without a control-flow return. The newer reference's unparenthesized multi-exception syntax does not compile on the tested3.12 interpreter; use except (RuntimeError,TypeError,NameError): for that version. The earlier explanation of exception chaining, else scope, exception groups and notes remains part of the complete assigned study; inspect which failures propagate rather than catching every exception and returning a monetary zero.
Bound memory without abandoning event identity
The earlier changed-case solution's streaming output and small counters are sufficient only when no other state grows with distinct records. Under the separate global event-ID contract, a seen dictionary retains one payload for every distinct ID, so Python memory grows with U unique events. Sampling old identities or forgetting them cannot preserve arbitrary later identical/conflicting retry checks. Either change the contract explicitly or move the identity state to an external index or external sorting process. The index still exists; its storage did not disappear because the output is streamed.
The new disk_total receives an iterator of pairs (event_id,cents). Its ID is exact UTF-8-encodable text of length1..80 code points, with no implicit normalization; cents is a built-in int excluding bool, with absolute value at most10**12. A private temporary SQLite table maps each ID to its accepted amount. Parameterized lookups distinguish an absent ID, an identical retry and a changed amount under an existing ID. A new ID adds once, an identical retry adds nothing, and a conflict rejects the batch. The invariant after each accepted prefix is that the index has precisely its distinct identity/payload pairs and total is their sum. Successful exhaustion establishes the full-batch result; a failed iterator or validation cannot justify publishing a prefix as complete.
The implementation retains the current bounded-size record and counters rather than a Python map of all IDs, and stores O(U) identity state on disk. Indexed lookups add database work; they are not free constant-time operations. Integer counters/totals also need more bits as the stream grows. SQLite cache configuration reduces a source of growth but is not an independently measured hard resident-memory bound for every database/interpreter implementation. A real deployment needs field limits, disk quotas, failure policy and measurement in its target environment. The executable generator fixture delivers5000 distinct events twice each and checks its result against the independent arithmetic-series total n*(n-1)/2; it is not a claim that ten million records were benchmarked.
This index is private and disposable. Committing batches of its rows limits a transaction's footprint without publishing an incomplete business ledger. Each invocation reconstructs a total from its supplied batch. Replaying the same full batch gives the same report; that is not a claim of durable idempotence across arbitrarily different future imports. A persistent production ledger needs a separate transaction and identity-lifetime contract.
Publish a complete candidate and test failure paths
export_disk_total first finishes the disk-index calculation. Only then does it write a same-directory temporary candidate, flush, fsync the file, close it and call os.replace. The existing report is not opened with w during validation. A bad late value, a conflicting ID, an injected pre-replacement error and a simulated replacement denial must each leave the previous report unchanged. The tests inspect exact destination bytes and temporary cleanup, then verify a valid180-cent result and the same result on replay.
os.replace can replace an existing file with permission and may fail across filesystems. A successful atomic name change does not choose between competing writers, prove that the upstream source was complete or guarantee power-loss recovery of all file/directory metadata. File fsync is not a complete multi-file or distributed transaction. The laboratory deliberately makes those limits part of the explanation; additional guarantees need additional mechanisms and experiments.
Validate JSON behavior and interpreter capability
Parsing JSON is not schema validation. Python's default decoder accepts repeated object names with the last value winning and accepts nonfinite token extensions. strict_json uses object_pairs_hook to reject repeated names, parse_constant to reject NaN/Infinity tokens, and a finite-result float parser to reject overflow such as1e400. The last case matters because it is valid numeric syntax and does not pass through parse_constant. Its size limit is a small teaching boundary, not a complete adversarial resource guarantee. Valid JSON true remains a bool; an integer-cents schema must separately reject it with the appropriate type rule. Consecutive JSON documents are not one framed JSON document, so repeated dump calls need a chosen framing format or an enclosing collection.
The mapped snapshot's array_hook/frozendict examples require newer Python features, and python -m json was added later than the tested3.12 interpreter. Use python -m json.tool there and do not pass array_hook to its decoder. Likewise the modern CSV snapshot's QUOTE_NOTNULL/QUOTE_STRINGS reader description does not describe3.12's known bug: empty unquoted fields were reproduced as empty strings rather than None, matching the versioned primary documentation's notice of a3.13 fix. Feature names alone do not establish their behavior on an installed interpreter.
An exact large Python integer may also change when converted to an IEEE754 double-precision float. The laboratory demonstrates that with2**53+1. If an ID must survive consumers with that numerical representation, a string ID and an explicit schema can preserve its digits; JSON's successful parsing in one Python process does not establish every consumer's numeric fidelity.
Independent changed record with complete rules
Use the two-column grammar above and the exact input 'customer,cents\n"Ada\nInc",500\nBad,x\n'. Count the header as logical record1; reader.line_num reports the ending physical line. State the failing logical record and physical line, and explain why substituting0 for x violates the all-or-nothing parser contract. Predict the result for a third field and for a blank customer under these chosen rules. Then decode UTF-8 bytes for 'café' and contrast that result with str applied to those bytes.
For the separate event-index interface, process [('A',100),('B',100),('A',100),('C',-20)]. IDs are exact UTF-8 text, identical ID/amount retries are ignored and changed amounts under an existing ID reject the whole batch. The destination initially contains the bytes 'previous valid report\n'. Predict its bytes after a valid run, after a late ('D','bad') row, after ('A',101), and after an injected pre-replacement failure. Each run begins again with the stated sentinel for the failure comparisons. Explain why two distinct equal100-cent events contribute twice and why global conflict checks require identity storage even when output is streamed. Finally predict strict_json for '{"id":"A","cents":100,"cents":101}', '1e400' and 'true'. State which observations concern parsing and which require a further domain rule. Produce your reasoning before opening the complete solution; all practice remains optional.
Compare the complete boundary reasoning
The quoted customer occupies physical lines2 and3 but is one CSV record, logical record2. The malformed amount x is in logical record3, ending physical line4. The selected grammar rejects it and returns no completed list. Replacing x with0 would invent a successful value and conceal a rejected input. A third field violates the exact two-field rule and a blank customer violates the nonblank-customer rule. These are explicit choices of the new boundary, not facts supplied automatically by CSV parsing. UTF-8 decoding returns café; str(bytes) instead displays a bytes representation including a b-prefix and escapes.
The four event deliveries represent distinct IDs A,B,C. Their accepted amounts sum100+100-20=180; the identical A retry contributes nothing. A successful export contains exactly the UTF-8 bytes '180\n'. Under each separately reset failure comparison the destination remains 'previous valid report\n': a bad late type, conflicting A amount or pre-replacement exception prevents publication of a complete candidate. A successful retry of the same full batch again produces180; it does not add180 to an existing report. Distinct IDs A andB remain distinct despite equal amounts. A global identity map grows with distinct IDs; a disk index retains those identities externally, while a pure line-by-line counter cannot detect every later conflicting reuse.
The duplicate cents JSON names are rejected before the result can become an ordinary mapping. The numeric token1e400 is rejected because the chosen float result would be nonfinite; parse_constant alone would not catch that overflow. JSON true successfully parses as bool, but that does not satisfy the event interface's built-in-int cents rule. File resource cleanup and atomic replacement do not decide among competing writers or establish power-loss recovery; their guarantees require separate contracts and tests.
Complete executable laboratory
Copy the entire source into boundary_contracts.py and run python boundary_contracts.py with Python3.12 or later. The recorded execution used Python3.12.14; eight test groups passed, including a5000-identity/two-delivery generator, exact independent arithmetic total, quoted/multiline CSV and injected publication failures. No ten-million-row benchmark, real mobile-device test or production durability certification is claimed. Source SHA256: eff1216ff7df778a99f8cfc261b361f01ecb467fe1afbf2f2ef0b865e6edc57b. All filesystem experiments use temporary fictional data, with no network or learner accounts.
Primary references and retained sources
- Complete retained beginner file and exception chapters
- Python3.12 csv reference, including version-specific reader bug notice
- Python3.12 JSON reference
- Python3.12 exception tutorial
- Python3.12 open contracts
- os.replace contract
Lawfare Academy is part of the Knowledge Institute, a Lawfare Group free education initiative. All practice remains optional.