Python engineer reviewing staged tarfile extraction after a filter error

Python Rejected the Archive. What Did Extraction Leave Behind?

Sat, Sep 26, 2026

A rejected archive can still have written files.

That is not an edge-case interpretation of Python’s extraction API. The Python 3.14 tarfile documentation explicitly says that when extraction raises an exception, the archive may be partially extracted and cleanup is the application’s responsibility. A callable extraction filter is invoked immediately before each member is extracted, so an earlier member can already be on disk when a later member is refused.

That distinction is the center of this acceptance playbook. Refusing a member is not rolling back extraction, and finishing extraction is not approving a payload.

The laboratory is deliberately benign: tiny self-created, uncompressed tar files; ordinary text filenames; no traversal payloads; no downloaded archives; no customer data; no privileged destination. The failure comes from an application policy that accepts allowed.txt, then refuses the ordinary basename blocked.txt, while second.txt remains later in the archive.

The engineering question is therefore narrower and more operational than a general archive-security survey: after refusal, what was actually written, did the candidate satisfy an independent approved manifest, did publication occur, and what does a fresh consumer resolve?

The research reference family is CPython 3.14 as of September 25, 2026. The protocol below is not a report of an executed CPython 3.14 laboratory. Every transcript outcome described as expected remains pending until a maintainer runs the procedure and retains its local evidence.

Define acceptance before opening the archive

Start with the consumer contract, not with extractall().

For this fixture, the new approved payload contains exactly two regular files:

Name

Authored expected size

Authored expected SHA-256

allowed.txt

25 bytes

08339c222737fffe22e60651ee02c32dc7d913bd6cfda2ce68d1354c81985a20

second.txt

24 bytes

9b9ce06c9561bd87a4386a4c3d75fc94aeec3792108b75a2cb8222c85387b1f5

Those numbers are fixture inputs, not measured production results. The authoritative bytes are also retained independently of the tar file so that acceptance does not depend on what the candidate claims about itself.

Three claims must stay separate.

Extraction completion means the extraction API returned without a fatal extraction error. Payload validation means the private candidate directory contains exactly the names and bytes authorized by the external manifest. Publication means the active pointer has been replaced with a pointer to a validated immutable version, and a fresh reader resolves that version.

A failure at the first claim must not silently erase evidence about files already written. Success at the first claim must not imply the second. Success at the second must not imply the third.

That separation complements broader automated security testing approaches, which discuss security checks and CI/CD gates; this playbook concentrates on a different proof: filesystem state and consumer visibility after an archive member is refused.

Finally, preserve an already approved version, v000-initial, before testing any candidate. The active pointer initially names that version. A rejected candidate passes this availability test only if a new reader still resolves v000-initial.

Pin the interpreter and the private workspace

Do not write “tested on Python 3.14” and stop there.

The version-selected Python 3.14 tarfile documentation page accessed for this article identified itself as Python 3.14.7 documentation, but that is a documentation reference, not evidence that a maintainer has that exact patched interpreter installed. The same documentation also notes that extraction filters were introduced in 3.12 and can be backported to older versions, so feature support should not be inferred solely from a minor-version string.

Record the installed runtime independently: sys.version, patch level, build tuple, compiler, executable path and executable digest. Python’s platform documentation provides python_build(), python_revision(), python_version() and OS-identification functions for this purpose; python_revision() can be empty on some installed builds, which should be recorded as empty rather than replaced by an invented revision.

Also record the test source itself by SHA-256, the operating system, filesystem type, device identifier and extraction configuration.

Run unprivileged. The example refuses UID 0 on POSIX and an elevated Windows token. It creates one private temporary workspace containing:

input/
staging/
versions/
state/
manifests/
evidence/

No archive is ever extracted into versions/, an application directory or the location a reader consumes directly.

Candidate directories are created underneath staging/ with tempfile.TemporaryDirectory. Python documents that TemporaryDirectory securely creates the directory and, when used as a context manager, removes it and its contents when the context finishes.

That cleanup behavior is useful, but it does not absolve the application from recording what existed before cleanup. Nor should a previous candidate directory be reused. Each run gets a new workspace, and each case gets a newly generated staging directory.

The protocol’s final evidence directory remains present until an explicitly scoped cleanup command removes the owned workspace.

Build harmless archives with an independent manifest

The complete fixture below is intended to be saved as playbook.py and run with the exact CPython 3.14 interpreter under review. It creates all inputs locally. It does not download, contact or modify any external system.

The healthy archive is ordered allowed.txt, second.txt. The failing archive is ordered allowed.txt, blocked.txt, second.txt. The tar mode is explicitly uncompressed, and the writer uses explicit TarInfo objects plus BytesIO rather than archiving arbitrary local paths.

from future import annotations

import ctypes
import hashlib
import io
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
from pathlib import Path

APPROVED = {
    "allowed.txt": b"approved allowed payload\n",
    "second.txt": b"approved second payload\n",
}
INITIAL = {
    "allowed.txt": b"initial approved allowed\n",
    "second.txt": b"initial approved second\n",
}
BLOCKED = b"harmless file refused by local policy\n"

MAX_MEMBERS = 4
MAX_FILE_BYTES = 128
MAX_TOTAL_BYTES = 512
MARKER = "refonte-tar-acceptance-workspace-v1\n"
VERSION_RE = re.compile(r"v[0-9]{3}-[a-z0-9-]+\Z")


def now_ns() -> int:
    return time.time_ns()


def digest(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def manifest(payload: dict[str, bytes]) -> dict[str, dict[str, object]]:
    return {
        name: {
            "size": len(data),
            "sha256": digest(data),
            "bytes_hex": data.hex(),
        }
        for name, data in sorted(payload.items())
    }


def write_json(path: Path, value: object) -> None:
    path.write_text(
        json.dumps(value, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )


def log(evidence: Path, event: str, fields: object) -> None:
    record = {"ts_ns": now_ns(), "event": event,
fields}
    with evidence.open("a", encoding="utf-8") as f:
        f.write(json.dumps(record, sort_keys=True) + "\n")


def assert_unprivileged() -> None:
    if os.name == "posix" and hasattr(os, "geteuid") and os.geteuid() == 0:
        raise SystemExit("Refusing to run as root.")
    if os.name == "nt" and bool(ctypes.windll.shell32.IsUserAnAdmin()):
        raise SystemExit("Refusing to run from an elevated Windows token.")


def filesystem_name(path: Path) -> str:
    system = platform.system()

    if system == "Linux":
        commands = (
            ["findmnt", "-T", str(path), "-n", "-o", "FSTYPE,SOURCE,TARGET"],
            ["stat", "-f", "-c", "%T", str(path)],
        )
        for command in commands:
            try:
                result = subprocess.run(
                    command,
                    text=True,
                    capture_output=True,
                    check=False,
                )
            except FileNotFoundError:
                continue
            if result.returncode == 0 and result.stdout.strip():
                return result.stdout.strip()

    elif system == "Darwin":
        result = subprocess.run(
            ["stat", "-f", "%T", str(path)],
            text=True,
            capture_output=True,
            check=True,
        )
        return result.stdout.strip()

    elif system == "Windows":
        root = Path(path.resolve().anchor)
        fs_buffer = ctypes.create_unicode_buffer(256)
        ok = ctypes.windll.kernel32.GetVolumeInformationW(
            str(root), None, 0, None, None, None,
            fs_buffer, len(fs_buffer),
        )
        if ok:
            return fs_buffer.value

    raise RuntimeError(
        "Filesystem type could not be identified; record it before testing."
    )


def file_sha256(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(1024 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def write_tar(path: Path, entries: list[tuple[str, bytes]]) -> None:
    with tarfile.open(path, "x:", format=tarfile.USTAR_FORMAT) as tf:
        for name, data in entries:
            info = tarfile.TarInfo(name)
            info.size = len(data)
            info.mode = 0o600
            info.mtime = 0
            info.uid = info.gid = 0
            info.uname = info.gname = "fixture"
            tf.addfile(info, io.BytesIO(data))


def inventory(directory: Path) -> list[dict[str, object]]:
    rows = []

    for path in sorted(directory.iterdir(), key=lambda item: item.name):
        row = {"name": path.name, "symlink": path.is_symlink()}

        if path.is_file() and not path.is_symlink():
            data = path.read_bytes()
            row.update(
                size=len(data),
                sha256=digest(data),
                bytes_hex=data.hex(),
            )
        else:
            row["kind"] = "non-regular"

        rows.append(row)

    return rows


def refuse(member: tarfile.TarInfo, reason: str) -> None:
    exc = tarfile.FilterError(reason)
    exc.tarinfo = member
    raise exc


def policy_filter():
    seen: set[str] = set()
    total = 0

    def check(
        member: tarfile.TarInfo,
        destination: str,
    ) -> tarfile.TarInfo | None:
        nonlocal total

        filtered = tarfile.data_filter(member, destination)
        if filtered is None:
            return None

        name = filtered.name

        if "/" in name or "\\" in name or name in {"", ".", ".."}:
            refuse(filtered, f"not an ordinary basename: {name!r}")

        if not filtered.isreg():
            refuse(filtered, f"not a regular file: {name!r}")

        if name == "blocked.txt":
            refuse(filtered, "local policy refuses blocked.txt")

        if name not in APPROVED:
            refuse(filtered, f"unexpected name: {name!r}")

        if name in seen:
            refuse(filtered, f"duplicate name: {name!r}")

        if len(seen) + 1 > MAX_MEMBERS:
            refuse(filtered, "local fixture member limit exceeded")

        if filtered.size > MAX_FILE_BYTES:
            refuse(filtered, "local fixture file-byte limit exceeded")

        total += filtered.size
        if total > MAX_TOTAL_BYTES:
            refuse(filtered, "local fixture total-byte limit exceeded")

        seen.add(name)
        return filtered

    return check


def skip_second(
    member: tarfile.TarInfo,
    destination: str,
) -> tarfile.TarInfo | None:
    filtered = tarfile.data_filter(member, destination)

    if filtered is not None and filtered.name == "second.txt":
        return None

    return filtered


def validate(
    payload_dir: Path,
    approved: dict[str, dict[str, object]],
) -> list[str]:
    errors = []

    actual_names = {path.name for path in payload_dir.iterdir()}
    expected_names = set(approved)

    if actual_names != expected_names:
        errors.append(
            f"name-set mismatch: actual={sorted(actual_names)}"
        )

    for name in sorted(expected_names & actual_names):
        path = payload_dir / name

        if path.is_symlink() or not path.is_file():
            errors.append(f"{name}: not a regular file")
            continue

        data = path.read_bytes()
        expected = approved[name]

        if len(data) != expected["size"]:
            errors.append(f"{name}: size mismatch")

        if digest(data) != expected["sha256"]:
            errors.append(f"{name}: digest mismatch")

        if data.hex() != expected["bytes_hex"]:
            errors.append(f"{name}: byte mismatch")

    return errors


def replace_pointer(state: Path, version: str) -> None:
    if not VERSION_RE.fullmatch(version):
        raise ValueError("invalid version name")

    candidate = state / f".active.{os.getpid()}.{now_ns()}"
    candidate.write_text(version + "\n", encoding="ascii")
    os.replace(candidate, state / "active")


def reader_snapshot(root: Path) -> dict[str, object]:
    # Resolve the pointer exactly once for this reader operation.
    version = (
        root / "state" / "active"
    ).read_text(encoding="ascii").strip()

    if not VERSION_RE.fullmatch(version):
        raise RuntimeError("invalid active pointer")

    version_dir = root / "versions" / version

    return {
        "pointer": version,
        "inventory": inventory(version_dir),
    }


def publish(payload_dir: Path, root: Path, version: str) -> None:
    target = root / "versions" / version

    if target.exists():
        raise FileExistsError(target)

    if os.stat(payload_dir).st_dev != os.stat(root / "versions").st_dev:
        raise RuntimeError(
            "staging and versions are not on the same filesystem"
        )

    # Move to a previously unused version name.
    os.rename(payload_dir, target)

    # Publication is the small pointer-file replacement.
    replace_pointer(root / "state", version)


def run_candidate(
    root: Path,
    archive: Path,
    label: str,
    filter_func,
    publish_as: str | None,
) -> str:
    evidence = root / "evidence" / "events.jsonl"
    approved = json.loads(
        (root / "manifests" / "candidate.json").read_text(
            encoding="utf-8"
        )
    )

    decision = "hold"

    try:
        with tempfile.TemporaryDirectory(
            prefix=f"{label}-",
            dir=root / "staging",
        ) as temp_name:
            payload = Path(temp_name) / "payload"
            payload.mkdir()

            extraction_ok = False

            try:
                with tarfile.open(
                    archive,
                    "r:",
                    errorlevel=2,
                ) as tf:
                    tf.extractall(payload, filter=filter_func)

                extraction_ok = True
                log(
                    evidence,
                    "extraction_completed",
                    case=label,
                    inventory=inventory(payload),
                )

            except tarfile.FilterError as exc:
                log(
                    evidence,
                    "extraction_refused",
                    case=label,
                    exception=type(exc).__name__,
                    message=str(exc),
                    refused=getattr(
                        getattr(exc, "tarinfo", None),
                        "name",
                        None,
                    ),
                    inventory=inventory(payload),
                )

            except (tarfile.TarError, OSError) as exc:
                log(
                    evidence,
                    "extraction_failed",
                    case=label,
                    exception=type(exc).__name__,
                    message=str(exc),
                    inventory=inventory(payload),
                )

            if extraction_ok:
                errors = validate(payload, approved)

                log(
                    evidence,
                    "validation",
                    case=label,
                    accepted=not errors,
                    errors=errors,
                )

                if not errors and publish_as is not None:
                    publish(payload, root, publish_as)
                    log(
                        evidence,
                        "publication",
                        case=label,
                        version=publish_as,
                        status="published",
                    )
                    decision = "accept"

                elif errors:
                    decision = "reject-and-clean"

                else:
                    decision = "hold"

            else:
                decision = "reject-and-clean"

    except Exception as exc:
        log(
            evidence,
            "cleanup_or_staging_failure",
            case=label,
            exception=type(exc).__name__,
            message=str(exc),
            decision="hold",
        )
        return "hold"

    log(
        evidence,
        "cleanup_completed",
        case=label,
        decision=decision,
    )
    return decision


def cleanup_workspace(root: Path) -> None:
    marker = root / ".owned-workspace"

    if marker.read_text(encoding="utf-8") != MARKER:
        raise SystemExit(
            "Refusing cleanup: workspace marker mismatch."
        )

    shutil.rmtree(root)


def main() -> None:
    assert_unprivileged()

    if len(sys.argv) == 3 and sys.argv[1] == "--cleanup":
        cleanup_workspace(Path(sys.argv[2]).resolve())
        return

    root = Path(
        tempfile.mkdtemp(prefix="refonte-tar-acceptance-")
    ).resolve()
    os.chmod(root, 0o700)

    for name in (
        "input",
        "staging",
        "versions",
        "state",
        "manifests",
        "evidence",
    ):
        (root / name).mkdir()

    (root / ".owned-workspace").write_text(
        MARKER,
        encoding="utf-8",
    )

    evidence = root / "evidence" / "events.jsonl"

    write_json(
        root / "manifests" / "candidate.json",
        manifest(APPROVED),
    )
    write_json(
        root / "manifests" / "initial.json",
        manifest(INITIAL),
    )

    initial_dir = root / "versions" / "v000-initial"
    initial_dir.mkdir()

    for name, data in INITIAL.items():
        (initial_dir / name).write_bytes(data)

    if validate(initial_dir, manifest(INITIAL)):
        raise RuntimeError(
            "initial approved version failed self-check"
        )

    replace_pointer(root / "state", "v000-initial")

    bad = root / "input" / "bad.tar"
    healthy = root / "input" / "healthy.tar"

    write_tar(
        bad,
        [
            ("allowed.txt", APPROVED["allowed.txt"]),
            ("blocked.txt", BLOCKED),
            ("second.txt", APPROVED["second.txt"]),
        ],
    )

    write_tar(
        healthy,
        [
            ("allowed.txt", APPROVED["allowed.txt"]),
            ("second.txt", APPROVED["second.txt"]),
        ],
    )

    source_path = Path(__file__).resolve()

    environment = {
        "commissioning_batch": "2026-09-25",
        "python_executable": sys.executable,
        "python_version": sys.version,
        "python_patch": platform.python_version(),
        "python_build": platform.python_build(),
        "python_compiler": platform.python_compiler(),
        "python_branch": platform.python_branch(),
        "python_revision": platform.python_revision(),
        "interpreter_sha256": file_sha256(Path(sys.executable)),
        "os": platform.uname()._asdict(),
        "filesystem": filesystem_name(root),
        "workspace_device": os.stat(root).st_dev,
        "source_revision_sha256": file_sha256(source_path),
        "config": {
            "tar_read_mode": "r:",
            "tar_write_mode": "x:",
            "archive_format": "USTAR_FORMAT",
            "errorlevel": 2,
            "base_filter": "tarfile.data_filter",
            "max_members": MAX_MEMBERS,
            "max_file_bytes": MAX_FILE_BYTES,
            "max_total_bytes": MAX_TOTAL_BYTES,
        },
    }

    write_json(
        root / "evidence" / "environment.json",
        environment,
    )

    with tarfile.open(bad, "r:") as tf:
        log(
            evidence,
            "archive_order",
            case="late-refusal",
            names=tf.getnames(),
        )

    log(
        evidence,
        "reader_before_failures",
        *reader_snapshot(root),
    )

    late = run_candidate(
        root,
        bad,
        "late-refusal",
        policy_filter(),
        None,
    )
    log(
        evidence,
        "reader_after_late_refusal",
        decision=late,
        reader_snapshot(root),
    )

    skipped = run_candidate(
        root,
        healthy,
        "silent-skip",
        skip_second,
        None,
    )
    log(
        evidence,
        "reader_after_silent_skip",
        decision=skipped,
       
reader_snapshot(root),
    )

    healthy_decision = run_candidate(
        root,
        healthy,
        "healthy",
        policy_filter(),
        "v001-healthy",
    )
    log(
        evidence,
        "reader_after_healthy_publish",
        decision=healthy_decision,
        reader_snapshot(root),
    )

    # Authorized restore demonstration.
    replace_pointer(root / "state", "v000-initial")
    log(
        evidence,
        "pointer_restored",
        version="v000-initial",
       
reader_snapshot(root),
    )

    print(root)
    print(f"Inspect: {root / 'evidence'}")
    print(
        f"Cleanup: {sys.executable} {source_path} "
        f"--cleanup {root}"
    )


if name == "__main__":
    main()

Run it explicitly with the installed CPython 3.14 executable being reviewed:

python3.14 playbook.py

Do not paste an expected transcript into evidence. The pathname printed by the actual run is the authoritative workspace for that run. Inspect evidence/environment.json and evidence/events.jsonl before cleanup.

Make a late policy refusal deterministic

The custom callable first invokes tarfile.data_filter(member, destination). Only then does the local policy examine the resulting member and deliberately raise tarfile.FilterError for blocked.txt.

That ordering matters. The test is exercising a real extraction filter composition pattern rather than bypassing the standard data policy.

The reader also sets errorlevel=2 explicitly. The Python 3.14 tarfile documentation states that error level 1 raises fatal OSError and FilterError failures, while level 2 additionally raises non-fatal TarError failures. The same documentation warns that an exception can leave partial extraction behind.

No malicious pathname is required. blocked.txt is an ordinary basename holding harmless text. The expected control flow is simply:

allowed.txt  -> filter accepts -> file is written
blocked.txt  -> data_filter passes -> local filter refuses -> FilterError
second.txt   -> never reached

That is enough to test partial output.

Keep manifest authority outside the candidate

candidate.json lives under manifests/, not in bad.tar, healthy.tar or a staging directory.

The fixture writes exact expected byte strings, sizes and SHA-256 digests there before validating candidates. Validation never learns the expected digest by reading the archive it is evaluating.

In a production system, manifest authority might come from a reviewed release record or another authenticated control plane. That broader trust architecture is outside this laboratory. The important local invariant is narrower: the candidate cannot make itself complete merely by including a file that declares itself complete.

Observe partial extraction before cleanup

The first negative control exists to answer a question that exception-only logging cannot: what was already on disk when refusal occurred?

Python’s extraction-filter contract permits a callable to return modified metadata, return None to skip a member, or raise an exception. The callable is invoked immediately before each member is extracted; the documentation states that an aborted extractall() can leave a partial destination and does not clean it automatically.

For the ordered failing archive, the expected pre-cleanup inventory is therefore:

allowed.txt

with exactly the approved 25 bytes. This is an expectation derived from the authored member order and documented per-member filter timing, not an observed result from this commissioned article.

The script records archive_order before extraction and, inside the except tarfile.FilterError block, inventories the staging payload while that directory still exists. The evidence should identify the refused member as blocked.txt, record the exception category and preserve names, sizes, hashes and exact hexadecimal bytes for files that were already written.

Only after that inventory is logged does execution leave the TemporaryDirectory context.

This gives a reviewer two independent facts to inspect:

extraction_refused: blocked.txt
pre-cleanup inventory: allowed.txt

The right conclusion is not “the bad archive was extracted.” Nor is it “nothing happened because extraction raised.” It is: the candidate was partially materialized in private staging and then rejected before publication.

The active consumer pointer is a separate object. At this stage there has been no call to publish(), so the expected reader result remains v000-initial.

Separate filter decisions from whole-payload validity

An extraction filter answers a per-member question. Acceptance answers a whole-payload question.

That distinction is central to the design established by PEP 706, which was created on February 9, 2023 for Python 3.12. It is historical design context, not a 2026 feature launch. PEP 706 defines filtering as a mechanism that may modify, skip or refuse archive members; the Python 3.14 tarfile documentation records that data became the default extraction filter in 3.14.

This laboratory still names tarfile.data_filter explicitly inside its callable instead of depending on the installed interpreter’s default. That makes the extraction configuration part of the evidence.

data_filter is useful but not a rollback mechanism. Python’s tarfile extraction guidance says that no supplied filter blocks every dangerous archive feature and recommends additional verification. Its guidance includes extracting into a new temporary directory and considering limits on counts and sizes. It also explicitly notes that tar archives can contain multiple occurrences of the same pathname.

The fixture’s four-member, 128-byte-per-file and 512-byte-total thresholds are therefore local test policy, not a claim of comprehensive resource containment.

The same boundary applies to broader validation and error-handling boundaries: rejecting one input operation is not equivalent to proving that a complete downstream object satisfies its contract.

Test a skipped required member without an exception

A second negative control makes this distinction unavoidable.

Python documents that returning None from a custom extraction filter skips that member. It does not mean the full candidate is complete.

skip_second() delegates to data_filter, then deliberately returns None for second.txt. Run it only against the harmless healthy archive.

The expected sequence is:

extractall() returns normally
allowed.txt exists
second.txt does not exist
manifest validation fails
publication does not occur
active pointer remains v000-initial

This is not a recommended production skip policy. It is a local negative control designed to prove why “no exception” is insufficient as an acceptance oracle.

The event ledger should therefore contain extraction_completed followed by validation with accepted: false. Treating the successful extraction call as acceptance would fail this test.

Treat duplicate and unexpected names as policy failures

The local policy also rejects duplicate basenames and names not present in the approved set.

That matters because tar permits the same path more than once. Python’s documentation explains that multiple occurrences of the same pathname are normally treated as newer when they appear later and may overwrite earlier material.

Two useful additional controls are:

allowed.txt, allowed.txt, second.txt
allowed.txt, second.txt, extra.txt

The first must be rejected when the second allowed.txt is considered, even if the bytes happen to match. The second must be rejected at extra.txt, even though the staging directory might already appear to contain both required files.

Do not inspect the final directory, see two correct names and retroactively declare either archive acceptable. The member-policy ledger is part of the evidence.

Validate staging against names, sizes and content

Whole-payload validation starts only after extraction has completed.

The approved manifest defines an exact set, not a minimum set. validate() therefore compares actual and expected names first. Missing second.txt fails. An extra file fails. Two files with the correct count but the wrong identities fail.

For each expected regular file, validation then compares three representations:

size
SHA-256
exact expected bytes

Using both bytes and a digest is intentionally redundant in this tiny laboratory. The digest makes the evidence compact and familiar to release tooling; the byte comparison makes it explicit that the oracle is exact fixture content, not merely a file count or filename match.

A successful manifest result should be recorded as its own validation event. A failed result should preserve the reason, such as:

name-set mismatch: actual=['allowed.txt']

Again, this is expected text until a real execution produces it.

The manifest comparison is sound only inside the declared scope: a private, application-owned staging directory with no hostile concurrent writer. Python’s extraction guidance notes that tarfile does not protect against an attacker changing live source or destination data during extraction. This playbook deliberately excludes that concurrency problem rather than implying that a manifest check solves it.

The acceptance gate is therefore:

extraction completed
AND
member policy did not fail
AND
manifest name set matches
AND
all expected size/content checks match

Anything less remains unaccepted.

Publish only the validated immutable version

Only a validated staging tree is eligible to leave staging.

The proposed single-publisher sequence is deliberately small:

1.     Choose a previously unused version name such as v001-healthy.

2.     Verify staging and versions/ are on the same filesystem.

3.     Rename the validated payload directory to versions/v001-healthy.

4.     Write a small candidate pointer file containing v001-healthy\n.

5.     Replace state/active with that file.

6.     Have readers load state/active once and use the resolved version directory for that operation.

The version directory is not replaced in place. It is created under a unique name and thereafter treated as immutable.

Publication is the pointer transition, not extraction and not the move into versions/.

Python’s os.replace documentation states that an existing file destination is replaced if permissions permit, that the operation may fail across filesystems and that, if successful, rename replacement is atomic under the documented POSIX requirement. It also says replacing a non-empty destination directory raises OSError.

That is why this pattern applies os.replace() to a small pointer file, not to an already populated release directory.

The reader contract is equally important. A reader resolves state/active once. It does not reread the pointer between opening allowed.txt and second.txt; doing so could mix versions if publication occurs between those reads. The resolved version name becomes that operation’s stable namespace.

Prove the consumer never adopted a rejected candidate

The consumer test starts before the failure.

v000-initial contains its own approved two-file payload, and state/active initially contains:

v000-initial

A fresh reader records that pointer and inventories the resolved directory. Then the late-refusal control runs.

Expected state transition:

Stage

Candidate state

Active pointer

Before refusal

no candidate

v000-initial

After allowed.txt was written privately

partial staging

v000-initial

After blocked.txt refusal

rejected staging

v000-initial

After cleanup

no failed staging

v000-initial

The same consumer check follows the silent-skip control. Extraction is expected to return normally in that case, but manifest validation fails because second.txt is absent. The active pointer must again remain v000-initial.

Only the healthy archive is allowed to reach publication. Its extraction must complete, its manifest must validate, and its payload must move to v001-healthy. After pointer replacement, a new reader is expected to resolve v001-healthy and verify the new approved bytes.

This fits broader software testing and delivery context, where build, testing and delivery are distinct activities; here the distinction is made concrete as extraction, validation and consumer-visible publication.

Capture extraction, validation and publication separately

Do not flatten all of these events into status=failed or status=success.

The sample uses distinct event names:

extraction_refused
extraction_failed
extraction_completed
validation
publication
cleanup_completed
reader_after_...
pointer_restored

Each record receives a timestamp from the same process. The pointer value and the resolved inventory are recorded together by the reader snapshot.

This gives an investigator an ordered explanation. For the skip case, for example, the interesting evidence is specifically:

extraction_completed
validation accepted=false
cleanup_completed decision=reject-and-clean
reader pointer=v000-initial

Without the validation event, the successful return from extractall() is dangerously easy to overinterpret.

Without the reader event, a correct validation result does not prove what consumers could actually reach.

State the limits of atomic pointer replacement

A small-file pointer replacement is a publication mechanism within stated assumptions, not a universal transaction system.

The test requires the candidate pointer and active pointer to share a filesystem and assumes one publisher. The os.replace() documentation explicitly warns that cross-filesystem operation can fail and that non-empty directory replacement is not the operation being promised here.

This playbook does not establish power-loss durability. It does not prove behavior for every filesystem implementation, network mount or storage appliance. It does not serialize multiple publishers. It does not claim atomic replacement of a populated application tree.

It proves something narrower: under the recorded filesystem and one-publisher/ordinary-reader model, no code path intentionally changes the active pointer until the new candidate has passed the independent manifest.

That boundary should appear in the review record, not just in comments.

Clean rejected staging without hiding cleanup failures

A rejected candidate remains private, but private garbage still needs an owner.

The preferred flow is to take the diagnostic inventory while the staging directory exists, retain the minimal evidence needed to explain the decision, and then allow TemporaryDirectory to remove the owned staging tree. Python documents both secure temporary-directory creation and context-managed cleanup.

The important ordering is:

refusal or validation failure
-> record candidate inventory
-> record decision basis
-> leave candidate context
-> confirm cleanup completed

Do not delete first and then try to reconstruct what happened from the exception string.

Conversely, do not retain every rejected payload indefinitely under the banner of diagnostics. For this tiny fixture, hashes, exact harmless bytes, member names, exception details and configuration are enough. Real retention rules require their own data-handling policy.

Cleanup failure is not equivalent to publication failure. Suppose state/active still safely names v000-initial, but the staging directory cannot be removed. Consumer visibility may remain correct while lifecycle ownership is unresolved. The correct decision is hold, with cleanup failure logged separately.

That is why run_candidate() catches an exception escaping the staging context and writes cleanup_or_staging_failure.

Avoid broad shell commands such as an unexplained recursive delete of a shared temporary root. The sample’s cleanup mode requires the exact workspace path and checks an ownership marker before calling shutil.rmtree():

python3.14 playbook.py --cleanup /exact/path/printed/by/the/run

The operator should copy that path from the actual run, inspect the evidence first and never replace it with a guessed wildcard.

Recover from an interrupted attempt conservatively

Recovery begins by observing what exists, not by guessing what the interrupted process “must have reached.”

This is where filesystem recovery benefits from the same discipline as backend error handling and operational practices: classify the partially completed state before choosing a compensating action.

There are three materially different states.

An unpublished staging candidate under staging/ is not a release. Inspect its ownership marker or run metadata, record its inventory if evidence is incomplete, and clean it only when ownership is established. Do not publish it merely because it appears complete.

A validated version directory not named by state/active may occur if the move into versions/ completed but pointer publication did not. That directory is an orphan release candidate, not an active release. Hold it while checking validation evidence, manifest identity and the current active pointer. It can later be retained or removed under release policy; it must not be adopted automatically.

A changed pointer is consumer-visible state. Resolve it once with a fresh reader and verify that the named version exists and matches the approved manifest. If evidence proves that publication completed normally, the release may be accepted. If the pointer is unauthorized or its target cannot be verified, hold and consider an authorized restore.

This procedure deliberately does not infer power-loss ordering from ordinary file API return values. Filesystem crash durability is outside scope. After an actual machine or storage interruption, evidence may be incomplete, which is itself a reason to hold rather than manufacture certainty.

Restore a known approved pointer when authorized

Keep the preceding immutable version and its independent manifest precisely so recovery does not require reconstructing an old payload in place.

The example’s final pointer change is an authorized restore demonstration:

replace_pointer(root / "state", "v000-initial")

It uses the same controlled pointer-file replacement path as forward publication. No files inside v000-initial are rewritten.

After restoration, a fresh reader must resolve the pointer once and compare the resulting payload with the approved initial manifest. The expected evidence is:

pointer_restored version=v000-initial
reader pointer=v000-initial
reader inventory matches initial.json

The restore decision requires positive evidence that v000-initial is known approved. “Previous directory” is not enough. Neither is “it used to work.”

Restoration also has an important visibility boundary. Replacing the pointer changes what future pointer resolutions select. It does not retroactively change a reader that already resolved v001-healthy. It cannot retract files that some external process copied elsewhere, reverse messages already emitted, undo database mutations or cancel unrelated side effects.

Those problems are intentionally excluded from this local publication model.

Accordingly, the claim is precise: under the reader contract used here, a newly starting consumer operation after authorized restoration should resolve the restored approved version. That result must be verified rather than inferred merely because os.replace() returned successfully.

Choose accept, reject-and-clean, hold or restore

The decision should fall out of evidence, not out of how severe an exception looked.

Evidence state

Consumer-visible pointer

Cleanup evidence

Decision

Extraction refused or failed; no validation approval

Still known approved version

Rejected staging removal confirmed

Reject-and-clean

Extraction returned normally; manifest missing, unexpected or mismatched content

Still known approved version

Rejected staging removal confirmed

Reject-and-clean

Extraction completed; manifest fully approved; unique version installed; pointer replacement recorded; fresh reader resolves and verifies it

New approved version

Staging lifecycle complete

Accept

Candidate ownership, manifest result, pointer state or reader visibility cannot be established

Unknown or insufficiently proven

Any

Hold

Cleanup fails even though active pointer appears unchanged

Known or apparently known approved version

Cleanup unresolved

Hold

Validated version exists but is not referenced

Existing approved pointer remains active

Known

Hold until orphan disposition is authorized

Active pointer is wrong or unauthorized, and a preceding immutable version plus manifest are known approved

Restore target known

Restore followed by fresh-reader verification

Restore pointer

The late FilterError case is therefore not “accept because allowed.txt was fine” and not merely “reject because Python threw.” It is reject-and-clean because extraction did not complete, pre-cleanup evidence proves partial staging, the active pointer was not changed, and cleanup is confirmed.

The skip case demonstrates the other path to the same decision. No exception is required. The independent oracle says the payload is incomplete, so it is rejected and cleaned.

The healthy case becomes accept only after the complete chain is proven:

extraction_completed
validation accepted=true
publication version=v001-healthy
fresh reader pointer=v001-healthy
reader content matches approved manifest

A hold is deliberately uncomfortable. It means there is not enough evidence to classify the candidate safely. That can happen after cleanup failure, an interrupted publication, an unrecognized filesystem, an unexpected pointer value or incomplete provenance.

“Restore pointer” is an authorized recovery action, not a euphemism for deleting the new version. Keep the candidate/version evidence long enough to explain why restoration occurred, then verify the restored consumer view.

Make ingestion and publication ownership explicit

The filesystem design becomes easier to review when responsibility is attached to each artifact.

Policy and manifest ownership belongs to the party authorized to define the accepted filename set, exact bytes or digests and local fixture limits. The extraction code must not silently weaken that record because an archive “looks reasonable.”

Candidate lifecycle ownership belongs to the ingestion process. It creates private staging, records pre-cleanup evidence and cleans rejected state. It never points consumers directly at staging.

Publication ownership belongs to the single publisher. It may move a validated payload to a unique version and replace the active pointer. Readers do not publish by opening files.

Consumer ownership means obeying the resolve-once rule: read the active version once per operation, validate the pointer syntax, then stay within that immutable version directory.

Those assignments extend the DevSecOps ownership and secure-delivery foundations discussed in Refonte Learning’s roadmap into a concrete ingestion boundary: someone must own the gate between “processed” and “released.”

A review handover should retain at least the environment record, source SHA-256, archive member order, approved manifests, extraction configuration, event ledger, rejected pre-cleanup inventory, publication record and reader snapshots.

Rerun the acceptance suite after a substantive change to the interpreter build, extraction filter, local member policy, manifest schema, filesystem/storage arrangement, staging-to-version move, pointer implementation or reader resolution logic.

Do not treat a Python minor-version label as permanent security approval. The Python 3.14 tarfile documentation records patch-level behavior changes inside the family. For example, the page accessed at the research cutoff notes additional pathname normalization in 3.14.7. Python also warns that filtering alone is incomplete protection.

The evidence belongs to the exact recorded build and configuration that produced it.

Develop the secure-delivery habits behind archive acceptance

This laboratory is small, but the habits are broadly useful: define an acceptance oracle before processing input, preserve evidence across partial failure, separate validation from publication, make consumer visibility explicit and design recovery around known approved state.

Refonte Learning’s Cybersecurity & DevSecOps page lists a three-month program at 12–14 hours per week and identifies curriculum areas including OWASP and threat modeling, SAST/DAST/IAST, secure CI/CD, infrastructure security, incident response, risk mitigation and security automation. It also describes practical work and potential internship opportunities. The page does not establish that this specific Python tarfile laboratory or filesystem-publication pattern is part of that curriculum.

For maintainers and DevSecOps reviewers, the durable lesson is narrower than any tool or course: a member refusal proves that one member was refused; it does not prove that earlier writes disappeared. A complete approved manifest proves candidate validity; it does not prove publication. Only the pointer and a fresh consumer view establish what was actually selected for use.