1. Start a product you can resume
You will build a tool that runs two text tasks and can be paused and reopened. Each task converts text to uppercase and saves a separate result file. Here, that completed file acts as the checkpoint: a saved record used to resume work.
Python 3 and a text editor are enough. Check with python3 --version; if unavailable, install Python 3 and reopen the terminal. The actual tests used Python 3.14.4. No account, extra package or network call is required.
Create is-davami-v1. Save the four files in the tree as UTF-8; do not save the tree itself. Avoid hidden .txt extensions. The program creates results; that folder name must be unused for the first exercise.
is-davami-v1/
demo.json
jobs.py
app.py
test_app.py
2. Define the tasks in demo.json
Save the complete example as demo.json. JSON stores data in named fields. version identifies the accepted structure and jobs is the task list. Each task contains id and text; a and b are invented identifiers.
The first task converts demo one to DEMO ONE; the second converts demo two to DEMO TWO. We will not silently reuse a result name for different input. The existing result must first match the expected record.
{"version":1,"jobs":[{"id":"a","text":"demo one"},{"id":"b","text":"demo two"}]}
3. Implement validation and storage in jobs.py
Save the complete code as jobs.py. prepare validates all tasks and computes expected records. inputSha256 is a fingerprint of the input bytes, helping reject an old result when text changes. It does not authenticate the author.
run checks all existing results against expected records first. A matching file is not rewritten; a missing result is created using x mode. Each filename uses the task id. An unknown or damaged file in the folder stops the run with an error.
"""Resume a local text task list using one result file per task."""
import hashlib
import json
import os
from pathlib import Path
import re
def invalid(*args):
raise ValueError("Invalid JSON")
def fields(pairs):
result = {}
for key, value in pairs:
if key in result:
invalid()
result[key] = value
return result
def decode(raw):
return json.loads(raw.decode("utf-8-sig"), object_pairs_hook=fields,
parse_constant=invalid)
def prepare(data):
if not isinstance(data, dict) or set(data) != {"version", "jobs"}:
raise ValueError("Expected version and jobs")
if type(data["version"]) is not int or data["version"] != 1:
raise ValueError("Expected version 1")
rows = data["jobs"]
if not isinstance(rows, list) or len(rows) > 100:
raise ValueError("Expected at most 100 jobs")
seen, records = set(), []
for row in rows:
if not isinstance(row, dict) or set(row) != {"id", "text"}:
raise ValueError("Expected id and text")
ident, text = row["id"], row["text"]
if not isinstance(ident, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,31}", ident) or ident in seen:
raise ValueError("Use unique lowercase job ids")
if not isinstance(text, str) or not text.strip() or len(text) > 1000:
raise ValueError("Text must contain 1 to 1000 characters")
seen.add(ident)
records.append(dict(id=ident, inputSha256=hashlib.sha256(text.encode()).hexdigest(), result=text.upper()))
return records
def run(data, folder, stop_after=0):
records = prepare(data)
if type(stop_after) is not int or stop_after < 0:
raise ValueError("stop-after must be nonnegative")
root = Path(folder)
if root.is_symlink():
raise ValueError("Output folder cannot be a symlink")
root.mkdir(exist_ok=True)
allowed = {r["id"] + ".json" for r in records}
for path in root.iterdir():
if path.name not in allowed or path.is_symlink() or not path.is_file():
raise ValueError("Unexpected output entry; use a new folder")
pending, reused = [], 0
for record in records:
path = root / (record["id"] + ".json")
if path.exists():
with path.open("rb") as source:
raw = source.read(12001)
if len(raw) > 12000 or decode(raw) != record:
raise ValueError("Result conflicts with input; use a new folder")
reused += 1
else:
pending.append((path, record))
created = 0
for path, record in pending:
with path.open("x", encoding="utf-8") as target:
target.write(json.dumps(record, ensure_ascii=False, indent=2) + "\n")
target.flush()
os.fsync(target.fileno())
created += 1
if stop_after and created >= stop_after and created < len(pending):
return created, reused, True
return created, reused, False
4. Pause and resume with app.py
Save the complete code as app.py. Run python3 app.py demo.json results --stop-after 1. Expect Created: 1; reused: 0; paused: true and only results/a.json. Exit code 2 means a deliberate pause in this exercise. In a.json, result should be DEMO ONE.
Now run python3 app.py demo.json results. Expect Created: 1; reused: 1; paused: false, with DEMO TWO in b.json. Repeat it: Created: 0; reused: 2; paused: false. Existing results remain unchanged. For empty input, save {"version":1,"jobs":[]} in a new empty.json and use a new empty-results folder; both counts will be 0.
In a copy of demo, change task a’s text to changed and use the same results folder. Expect Error: Result conflicts with input; use a new folder, with no replaced results. Choose results-new for new input. A partial result is not automatically repaired either: keep it for inspection and start in a new folder.
import argparse
from pathlib import Path
import sys
from jobs import decode, run
def main():
parser = argparse.ArgumentParser(description="Resume local demo text tasks")
parser.add_argument("input", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--stop-after", type=int, default=0)
args = parser.parse_args()
try:
with args.input.open("rb") as source:
raw = source.read(1024 * 1024 + 1)
if len(raw) > 1024 * 1024:
raise ValueError("Input exceeds 1 MiB")
created, reused, paused = run(decode(raw), args.output, args.stop_after)
except (OSError, ValueError, RecursionError) as error:
print(f"Error: {error}", file=sys.stderr)
return 1
print(f"Created: {created}; reused: {reused}; paused: {str(paused).lower()}")
return 2 if paused else 0
if __name__ == "__main__":
sys.exit(main())
5. Check repeats with test_app.py
Save the complete tests as test_app.py. Run python3 -m unittest -v test_app.py. The finished product passed 5 tests; expect Ran 5 tests and OK. Tests work only in their own temporary folders.
Checks verify that the first result’s bytes remain unchanged across pause, resume and repeat. They cover empty input, conflicting input, incomplete results and unknown files. The actual CLI is launched separately; this does not test a broker crash in Qwen.
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from jobs import decode, prepare, run
DEMO = {"version": 1, "jobs": [{"id": "a", "text": "demo one"}, {"id": "b", "text": "demo two"}]}
class Tests(unittest.TestCase):
def test_resume(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder) / "results"
self.assertEqual(run(DEMO, root, 1), (1, 0, True))
before = (root / "a.json").read_bytes()
self.assertEqual(run(DEMO, root), (1, 1, False))
self.assertEqual(run(DEMO, root), (0, 2, False))
self.assertEqual((root / "a.json").read_bytes(), before)
self.assertEqual(json.loads(before)["result"], "DEMO ONE")
def test_empty_and_validation(self):
with tempfile.TemporaryDirectory() as folder:
self.assertEqual(run({"version":1,"jobs":[]}, Path(folder)/"out"), (0,0,False))
for value in [None, {"version":True,"jobs":[]}, {"version":1,"jobs":[{"id":"../x","text":"x"}]}, {"version":1,"jobs":[{"id":"a","text":" "}]}, {"version":1,"jobs":DEMO["jobs"]*2}]:
with self.assertRaises(ValueError):
prepare(value)
for raw in [b"{", b'{"version":1,"version":1,"jobs":[]}', b'[NaN]']:
with self.assertRaises(ValueError):
decode(raw)
def test_conflict_preserves_files(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)/"out"
run(DEMO, root, 1)
before = (root/"a.json").read_bytes()
changed = {"version":1,"jobs":[{"id":"a","text":"different"},DEMO["jobs"][1]]}
with self.assertRaises(ValueError):
run(changed, root)
self.assertEqual((root/"a.json").read_bytes(), before)
self.assertFalse((root/"b.json").exists())
def test_incomplete_and_unknown(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)/"out"
root.mkdir()
(root/"a.json").write_text("{")
with self.assertRaises(ValueError):
run(DEMO, root)
self.assertFalse((root/"b.json").exists())
(root/"extra.txt").write_text("keep")
with self.assertRaises(ValueError):
run(DEMO, root)
self.assertEqual((root/"extra.txt").read_text(), "keep")
def test_actual_cli(self):
with tempfile.TemporaryDirectory() as folder:
src, out = Path(folder)/"demo.json", Path(folder)/"out"
src.write_text(json.dumps(DEMO))
before = src.read_bytes()
cmd = [sys.executable, str(Path(__file__).with_name("app.py")), str(src), str(out)]
first = subprocess.run(cmd+["--stop-after","1"], capture_output=True, text=True)
self.assertEqual(first.returncode, 2)
second = subprocess.run(cmd, capture_output=True, text=True)
self.assertEqual(second.returncode, 0)
self.assertIn("Created: 1; reused: 1; paused: false", second.stdout)
self.assertEqual(src.read_bytes(), before)
src.write_bytes(b"\xff")
self.assertEqual(subprocess.run(cmd, capture_output=True).returncode, 1)
if __name__ == "__main__":
unittest.main()
6. Add a third task after completion
Exercise: after both tasks finish, append {"id":"c","text":"demo three"} to jobs in a copy of demo. Add a comma after the previous element. Save as exercise.json and run python3 app.py exercise.json results. Expect Created: 1; reused: 2; paused: false and DEMO THREE in c.json.
Limits are 1 MiB input, 100 tasks and text of 1–1000 characters that is not whitespace-only. id uses 1–32 lowercase ASCII letters, digits, underscores or hyphens and must start with a letter or digit. Keep the original input and results. Use a new result folder for changed text or removed tasks.
This local tool does not guarantee exactly-once email, payment or other external actions. The deliberate pause happens after a complete write. A crash during writing may leave a partial file, which is not overwritten. Concurrent runs and real crash recovery were not separately tested.

