02 / MAKE EXECUTION DEPENDABLE · LESSON 08

Resume only a matching scan

Bind saved completion to the exact ordered plan and timeout policy.

20 min · learn at your pace

A checkpoint belongs to a specific job

A saved list of completed endpoints is not enough to resume safely. The target list, ports or timeout may have changed. Bind a checkpoint to a canonical representation of the complete ordered plan and its timeout. A SHA-256 digest is a compact equality marker for that representation, not proof that the file is trustworthy or authentic.

This lesson defines the serialization precisely: sorted JSON keys, compact separators, UTF-8, schema version one and no non-finite numbers. The plan has already been validated and sorted by scan_plan. Its ordering remains part of the checkpoint identity, so a different plan cannot silently inherit completion.

Validate the saved rows too

A matching digest does not validate the rest of the file. Every completed row must refer to an endpoint in the current plan, without duplicate identities. This exercise resumes only open or refused observations; transient timeout and error results remain eligible for a fresh attempt rather than becoming permanently skipped work.

Missing checkpoints start with the full plan. A malformed or mismatched checkpoint raises ValueError instead of quietly discarding information. The caller can offer a deliberate fresh start while retaining the old file for review. Never silently merge unrelated saved runs.

The function returns pending endpoints in their original plan order and leaves both inputs unchanged. Later report generation may store richer result records, but the checkpoint's narrow purpose remains deciding what work is still pending under the same rules.

Try an example.py
import hashlib, json
payload = {"schema":1,"plan":[{"address":"192.0.2.10","port":443}],"timeout_ms":500}
print(hashlib.sha256(json.dumps(payload,sort_keys=True,separators=(",",":")).encode()).hexdigest())
YOUR TURN

Put it into practice.

Implement plan_digest(plan, timeout_ms) as SHA-256 of UTF-8 JSON {schema:1, plan, timeout_ms}, sort_keys=True, separators=(",",":"), ensure_ascii=False and allow_nan=False. plan and timeout are already validated. Implement resume_plan(plan, timeout_ms, checkpoint). None returns a new list of all endpoints. Otherwise require a dict with integer non-bool schema=1, matching digest and completed list. Each completed item needs string address, integer non-bool port, a unique identity present in plan, and state open/refused. Extra fields are ignored. Invalid checkpoints raise ValueError. Return pending rows in plan order without modifying inputs.

See an explained solution
One way to solve it.py
import json, hashlib

def plan_digest(plan, timeout_ms):
    payload={"schema":1,"plan":plan,"timeout_ms":timeout_ms}
    encoded=json.dumps(payload,sort_keys=True,separators=(",",":"),ensure_ascii=False,allow_nan=False).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()

def resume_plan(plan, timeout_ms, checkpoint):
    if checkpoint is None:return list(plan)
    if not isinstance(checkpoint,dict) or type(checkpoint.get("schema")) is not int or checkpoint["schema"]!=1 or checkpoint.get("digest")!=plan_digest(plan,timeout_ms):
        raise ValueError("Checkpoint does not match this scan")
    completed=checkpoint.get("completed")
    if not isinstance(completed,list):raise ValueError("Invalid checkpoint rows")
    keys={(row["address"],row["port"]) for row in plan};seen=set()
    for row in completed:
        if not isinstance(row,dict) or not isinstance(row.get("address"),str) or type(row.get("port")) is not int:
            raise ValueError("Invalid completed endpoint")
        key=(row["address"],row["port"])
        if key not in keys or key in seen or row.get("state") not in ("open","refused"):
            raise ValueError("Invalid completed endpoint")
        seen.add(key)
    return [row for row in plan if (row["address"],row["port"]) not in seen]

if __name__ == "__main__":
    plan=[{"address":"192.0.2.10","port":443}]
    print(resume_plan(plan, 500, {"schema":1,"digest":plan_digest(plan,500),"completed":[]}))

The checkpoint prevents accidental reuse across changed plans and rejects corrupted completion rows. It is a consistency check, not an authentication mechanism.