Advanced Python / Start here

Define the Willow Archive contract

Lesson 3 of 42. Open to read. No account needed.

Preserve the record, not just its value

Two archive sources can legitimately contain the same name and tags. An index that keeps only distinct names loses a source record even when its output looks neat. Before adding parsers, classes or concurrency, define what the result must preserve and make a small example expose that mistake.

By the end, you should be able to explain the archive input/output contract, predict the source order/count, preserve equal content from different sources, and diagnose a failing plain Python self-check without a test framework.

Lesson 1 established readiness and interpreter identity; lesson 2 established toolchain isolation. This checkpoint needs only the standard library and your approved final standard GIL-enabled CPython 3.15.1. Use a fresh owned root; no previous environment, cache, package install, network service or account is required. The exercised commands use macOS ARM64/zsh. Linux/Windows and other build routes remain unverified for this walkthrough.

A contract states accepted inputs, required results and unsuccessful states. The full archive contract below guides later lessons. Today's small starter implements the reporting example and its self-checks. It does not implement the later bounded JSON parser, package CLI, worker handling or every input rule.

Read the complete connected contract

In the later archive checkpoint, inputs/manifest.json names the records to read under the owned inputs directory. A JSON array is an ordered sequence, written with square brackets. A JSON object has named fields, written with braces. Python commonly represents those shapes as lists and dictionaries. For example, this original record shape is illustrative JSON, not a file you need to create in today's exercise:

{"name": "Oak ledger", "tags": ["local", "local"]}

The repeated tag is allowed. A record has exactly name and tags; the final report adds its source path. The filename and the record's name are different pieces of information.

BoundaryRequired contract
ManifestUTF-8 JSON array of zero to twelve distinct allowed source paths; at most 2,048 encoded bytes
Record fileOrdinary, non-symlink file below the owned inputs root; at most 1,024 encoded bytes before decoding
Record shapeExactly name and tags; reject missing/extra fields and wrong types without coercion
NameString of 1–80 Unicode code points; no hidden trimming or normalization
TagsList of zero to four strings, each 1–24 Unicode code points; preserve tag order and repeated values
Batch identityA source path appears once; equal content from two different sources remains two records
ResultExactly count and records; count equals the manifest length; records ordered by source-path string
Result itemsExactly source, name and tags; preserve the accepted name/tag values
Empty batchSuccess with count zero and an empty records list
Output budgetAt most 32,768 UTF-8 encoded bytes, including formatting and final newline

Later work is also bounded: at most two workers per pool, queue capacity two, and expansion to 384 in-memory measurement values. Those concepts are taught before their practical use; today creates no workers, queues or measurement workload.

These numeric budgets are course rules, not Python defaults or measured hardware limits. Character and byte budgets differ: é is one Unicode code point but uses two bytes in UTF-8. A displayed character can also contain several code points. Count name/tag lengths after decoding; count file/output bytes using their encoded contents. No normalization is implicitly permitted.

The fixed source allowlist is below. Paths are relative to inputs/, so the first names the later file inputs/records/oak-a.json. These are exact accepted path strings, not a recursive scan or a user-selected directory tree:

records/oak-a.json
records/oak-b.json
records/ash.json
records/elm.json
records/cedar.json
records/birch.json
records/malformed.json
records/wrong-schema.json
records/invalid-utf8.json
records/oversized.json
records/missing.json
records/extra.json

The normal later fixture uses the first six names. The additional names are reserved for controlled variations; a suggestive filename does not itself validate or invalidate its contents. Every requested source must still exist as an allowed ordinary file and satisfy the schema/byte limits. Future lessons supply the exact contents before a path is consumed. This lesson creates none of these JSON input files and does not claim to validate arbitrary manifests.

Library functions will receive explicit owned inputs. The eventual zero-argument console entry point uses inputs/manifest.json from its documented workspace and emits the JSON result only after validation. Its planned statuses are 0 success, 2 invalid input/shape/budget, 3 operational failure, and 130 handled POSIX interruption. Diagnostics use stderr; diagnosed groups preserve their constituent failures and prioritize operational status 3. The wrapper, exception and interruption behavior are taught and implemented in later checkpoints.

The current baseline is an ordinary Python script: success exits zero, while its guard/self-check failures exit nonzero. It does not implement those CLI status mappings. A failed or interrupted operation is not an empty success. Existing/incomplete output may remain after failure; output existence alone never establishes that the current run succeeded. No atomic-write, arbitrary forced-stop, hostile-filesystem or production-capacity guarantee is implied.

Create today's small checkpoint

Select the approved executable and create a fresh disposable root in zsh. The path shown is the author-tested existing installation; replace only that value if your already approved path differs. && continues only after a successful preceding command:

AP_PYTHON='/opt/homebrew/bin/python3.15' &&
"$AP_PYTHON" -VV &&
AP_ARCHIVE_ROOT="$(mktemp -d -t advanced-python-archive)" &&
printf '%s\n' 'advanced-python:lesson-3' > "$AP_ARCHIVE_ROOT/.advanced-python-owner" &&
cd "$AP_ARCHIVE_ROOT" &&
pwd

Stop on a failure. Retain the exact printed root and keep the variables in this terminal. If the terminal closes, restore those exact saved values before resuming. Do not search for a directory through a broad wildcard.

Use a plain UTF-8 editor to save the following two complete files in that root. Each contains one name line and its final newline. Both deliberately have the same contents. Save oak-a.txt:

Oak ledger

Save oak-b.txt:

Oak ledger

These tiny .txt fixtures are an explicit adapter for today's already-constructed records. Their corresponding logical source labels are records/oak-a.json and records/oak-b.json. Those labels appear in the result; the starter does not open JSON record paths or parse a manifest. This keeps the reporting contract small without pretending the later parser already exists.

Read the complete baseline

Save this complete original file as baseline.py:

import json
from pathlib import Path
import sys

if (sys.implementation.name != "cpython"
        or sys.version_info[:3] != (3, 15, 1)
        or sys.version_info.releaselevel != "final"):
    raise SystemExit("STOP: final CPython 3.15.1 required.")
if sys.abi_info.free_threaded or not sys._is_gil_enabled():
    raise SystemExit("STOP: standard GIL-enabled build required.")
if sys.flags.optimize:
    raise SystemExit("STOP: run these self-checks without -O or -OO.")

owner = Path(".advanced-python-owner")
if owner.is_symlink() or not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-3":
    raise SystemExit("STOP: use the marked lesson-3 root.")
for filename in ("oak-a.txt", "oak-b.txt"):
    path = Path(filename)
    if path.is_symlink() or not path.is_file():
        raise SystemExit("STOP: expected an ordinary supplied fixture: " + filename)
report_path = Path("report.json")
if report_path.is_symlink() or (report_path.exists() and not report_path.is_file()):
    raise SystemExit("STOP: report.json must be an ordinary owned output.")


def source_key(record):
    return record["source"]


def build_report(records):
    ordered = sorted(records, key=source_key)
    return {"count": len(ordered), "records": ordered}


name_a = Path("oak-a.txt").read_text(encoding="utf-8").removesuffix("\n")
name_b = Path("oak-b.txt").read_text(encoding="utf-8").removesuffix("\n")
records = [
    {"source": "records/oak-b.json", "name": name_b, "tags": ["local", "local"]},
    {"source": "records/oak-a.json", "name": name_a, "tags": ["local", "local"]},
]
expected_report = {
    "count": 2,
    "records": [
        {"source": "records/oak-a.json", "name": "Oak ledger", "tags": ["local", "local"]},
        {"source": "records/oak-b.json", "name": "Oak ledger", "tags": ["local", "local"]},
    ],
}
report = build_report(records)
assert report == expected_report, "batch differs from the predicted count/order/content"
assert build_report([]) == {"count": 0, "records": []}, "empty batch changed"

text = json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
if len(text.encode("utf-8")) > 32768:
    raise SystemExit("STOP: output exceeds the 32768-byte budget.")
report_path.write_text(text, encoding="utf-8")
print("self-checks: passed")
print("report:", report_path)
print("records:", report["count"])

Check the execution context before effects

The first guards require the implementation, final release and build used in lesson 1. The optimization guard refuses -O/-OO, because Python can omit assert statements when optimization is enabled. The marker check then requires this lesson root. Neither is implemented as an assert: these guards must still execute when assertions would be disabled.

The two fixed fixture names must be ordinary files rather than symlinks. An existing report.json must also be an ordinary owned output. These checks catch ordinary path mistakes in this disposable exercise; the marker is not a sandbox for untrusted directories. No command installs tools or changes the base Python.

Separate source identity from data and ordering

Each text read returns a string. removesuffix("\n") removes exactly the fixture's single line terminator; it does not strip other name whitespace. This is the explicit tiny-fixture decoding rule, not permission to trim names in the later JSON schema. name_a and name_b both become Oak ledger.

The records list places oak-b before oak-a on purpose. Each dictionary contains a distinct source label, the supplied name and a tag list with a repeated value. source_key returns the field used for comparison. Passing that function as key=source_key tells sorted to obtain a comparison key from each record. It returns a new ordered list; it neither removes equal content nor makes independent copies of every nested value. Reference/copy behavior is the next lesson's topic.

build_report therefore returns count two and the two records in source order. It is a reporting function over trusted constructed inputs, not an input schema validator. A direct set of these dictionaries would be unhashable; deduplicating their extracted names with a set is a different operation that silently loses one valid source in the supplied failure case.

Use a prediction as a self-check

An assert condition, message raises AssertionError when its condition is false. The expected_report literal is a prediction of this fixture's entire result, including order and repeated tags. Dictionary equality compares its fields; list equality also requires the same element order. A second assertion checks the reporting function's empty batch. No pytest or annotation/checker knowledge is needed here.

An assertion is a developer self-check, not production input validation, an exhaustive proof or an independently graded assessment. Do not replace a failed prediction with the current output merely to obtain a pass. Explain which contract rule changed and repair the implementation or a justified prediction. Do not use optimized execution to make a failing assertion disappear.

Write only after checks pass

json.dumps encodes the Python result as JSON text. ensure_ascii=False retains Unicode characters instead of requiring ASCII escape sequences; UTF-8 encoding is explicit at the file boundary. sort_keys=True orders object fields for a stable display; it does not sort the records array. That array's order already comes from build_report. indent=2 and a final newline make the file readable.

The explicit byte-budget check counts the encoded text, not Python string length. It runs before write_text, which replaces this owned report on a normal rerun and closes its own file operation. The success messages follow the write. A later output-write failure can still leave an old or partial file; the program does not promise atomic replacement. Full resource/error contracts come later.

Run, inspect and rerun

From the marked root, use the selected interpreter with isolated imports and no helper bytecode cache. The shell gate prevents cat from presenting an old report after a failed Python run:

"$AP_PYTHON" -I -B baseline.py &&
cat report.json

Illustrative program messages are:

self-checks: passed
report: report.json
records: 2

The following illustrative report has two records even though their name/tag values match. Source order differs from the initial records list:

{
  "count": 2,
  "records": [
    {"name": "Oak ledger", "source": "records/oak-a.json", "tags": ["local", "local"]},
    {"name": "Oak ledger", "source": "records/oak-b.json", "tags": ["local", "local"]}
  ]
}

Your formatter expands nested arrays/objects further; compare values and array order rather than this compact illustrative layout. Opening a file is not enough: require the current run's successful exit/messages and the expected contents. Rerun the unchanged command. It should replace the same report, not append a second JSON document. Record the actual root, interpreter and observations.

Expose the lost-record fault

Replace only build_report with this deliberate faulty function. This is a replacement excerpt, not another complete file:

def build_report(records):
    ordered = sorted(records, key=source_key)
    seen_names = set()
    kept = []
    for record in ordered:
        if record["name"] not in seen_names:
            seen_names.add(record["name"])
            kept.append(record)
    return {"count": len(kept), "records": kept}

The set tracks distinct names. Both source records share a name, so only the first is kept. Run the same Python-and-cat group: the complete-result assertion should fail, and cat should not run. The empty-batch assertion by itself would not detect this lost record. No successful report is written on this path; the previous successful report can still remain unchanged on disk.

Locate the failed assertion in the traceback and explain the source-identity violation. Restore the original build_report and rerun. Do not remove the assertion, change count two to one or deduplicate the expected fixture to hide the error. An alternative implementation is valid if it preserves every accepted source, the required order and the declared result values.

Check Your Understanding

Attempt before opening the reasoning. Preserve original files so recovery means restoring the supplied checkpoint, not remembering an unrecorded edit.

  1. Add this supplied third record to records before build_report is called. It is one record excerpt, not a complete program:

    {"source": "records/ash.json", "name": "Café register", "tags": ["history"]}
    

    Predict count, source order, names and tags. Edit expected_report to your predicted complete result before running; leave build_report unchanged. Verify the actual report, including literal Unicode under UTF-8. Explain why the original two Oak ledger records must both remain.

  2. Predict the empty reporting result. Test by replacing records with an empty list and expected_report with your predicted empty object, keeping the supplied files and other code. Explain what this checks and what it does not check about the future manifest/file parser.

  3. Classify these future archive inputs using the contract: the same source path twice; two different sources with equal content; an empty tag list; a string in place of a tag list; an extra record field. Explain each decision.

  4. Explain why an old report, a passed empty-batch assert or a zero exit under optimized execution would not prove the reporting contract. Identify which checks and current observations you would keep instead.

Answer and Reasoning

Hint 1: identify the unit being preserved

Count accepted source records rather than distinct names. Sort source strings, then carry the associated name/tag values into that order. A repeated tag inside a list is also part of the declared value, not a reason to apply a set.

Hint 2: separate the current checkpoint from the full path

The reporting function accepts constructed records. Today's .txt fixture reads still occur before records is built, even for your empty-report variation. A function's empty result does not implement an empty manifest's complete I/O path. Assertions are useful only when enabled and interpreted with their inputs.

Compare your prediction

The third-record result has count three and source order ash, oak-a, oak-b (using their full records/ paths). The first item has Café register and ["history"]; both Oak ledger items retain ["local", "local"] and their separate source labels. Only the input list and expected prediction change; the original reporting function already supports the additional record. The Unicode name's encoded bytes can exceed its code-point count; the writer uses UTF-8 and checks the serialized byte budget.

The empty reporting result is {"count": 0, "records": []}. It checks the reporting function/output shape for an empty constructed batch. It does not prove manifest size/shape, filename validation or the later parser's I/O behavior. Restore the original two records and expected_report after the variations.

A repeated source path is invalid. Different sources with equal content are valid and preserved separately. Empty tags are valid; a string is not a tag list, and an extra field violates the exact record schema. These are contract judgments, not claims that today's function validates arbitrary input.

An old file can survive failure. An empty-only check misses a deduplication bug. Python optimization can remove asserts, so this starter refuses optimized execution through an ordinary guard. Keep meaningful fixture predictions, normal/empty results, the fault's traceback/nonzero exit, repaired results and actual file contents. No self-reported lesson completion or copied output is an independent assessment of those explanations.

Recover and clean up the owned checkpoint

For a normal reset, restore baseline.py and both supplied text files, then rerun from this exact root. After a partial run, inspect the traceback/source/inventory; recreate a missing fixture from the complete content above. A missing or old report is not permission to change unrelated paths or broaden deletion.

Stop commands using this root, preserve wanted evidence outside it, and inspect:

cd "$AP_ARCHIVE_ROOT" &&
pwd &&
cat .advanced-python-owner &&
ls -a

Stop if cd fails, the printed path differs from your saved root, or the marker is not advanced-python:lesson-3. Investigate unexpected files first. Expected files are baseline.py, oak-a.txt, oak-b.txt, report.json and the marker. Only after confirming that inventory, remove those exact owned files and empty root:

rm baseline.py oak-a.txt oak-b.txt report.json .advanced-python-owner &&
cd .. &&
rmdir "$AP_ARCHIVE_ROOT"

If a partial attempt never created report.json, omit that absent name after inspection. rmdir refuses unexpected remaining files instead of recursively removing them. The base interpreter remains installed. Later lessons resupply their full input/checkpoint files; this disposable directory is not required carry-forward state.

References

The source examples, archive policy, fixture data and questions are original. Python documentation supports the language/API facts; it does not prescribe this fictional archive contract or its budgets.

Revisit this lesson in Revision or Quick Reference.

37 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy