# Four prerequisite diagnostics

Python 3.9+ and its standard library. These fixed public exercises diagnose prerequisites for the existing Agent route. They are not a complete Python/backend course, an unseen interview, or an official hiring threshold. Use an empty scratch directory and only run learner modules you trust; the grader imports local Python, not a sandbox for hostile code. No credentials, network or model requests are needed.

Download prerequisite_lab.py from https://ai.lwkjob.com/lab/interview-practice/prerequisite_lab.py. Save it with the filename unchanged. Read the contracts below, create a scaffold, implement the four functions, and keep the failing baseline, your diff, and your actual after report. The scaffold deliberately has no completed implementations. Existing output files are not proof of your execution; the report records the imported module SHA256.

```sh
python3 prerequisite_lab.py scaffold --out prerequisite_student.py
python3 prerequisite_lab.py grade --module prerequisite_student.py --out prerequisite-before.json
```

The initial grade exits 1; this is the expected incomplete starting point. Execute grading as its own command so a shell's stop-on-error setting does not prevent you from saving the baseline. After implementing your own functions:

```sh
python3 prerequisite_lab.py grade --module prerequisite_student.py --out prerequisite-after.json
```

Exit 0 requires all four skills to pass, not a majority of individual cases. A partial report gives the case and observed error to revisit. Python, module hash, source and case counts remain visible. Passing these public cases means this diagnostic contract passed; code review and a reviewer-chosen new condition remain separate.

## 1. JSON integer boundary

Implement parse_quantity(value) -> int. Accept only exact built-in int values from 1 through 100 inclusive. Return the unchanged integer. Boolean, string, float, None and list inputs raise TypeError; exact ints outside the range raise ValueError. Do not coerce inputs. The supplied cases include 1, 100, 7, True, False, "1", 1.0, None, [], 0, -1 and 101. In Python, Boolean values participate in the integer hierarchy; explicitly decide the JSON boundary rather than letting that fact grant a valid quantity.

If stuck, revisit the type validation and counterexamples in https://ai.lwkjob.com/learn/tool-contracts/?level=implementation. Explain the distinction in your own words and rerun your actual module.

## 2. Parameterized SQL and tenant isolation

Implement find_visible(conn, tenant, ids) -> list[str]. conn is an open in-memory SQLite connection. Inputs tenant and each ID are strings; ids is a list which may be empty. The grader supplies this schema: resources(id TEXT PRIMARY KEY, tenant TEXT NOT NULL, body TEXT NOT NULL). Return distinct IDs present in both the requested list and the exact tenant, sorted lexicographically. Return [] when no row matches. Never modify rows, expose body, close the caller's connection or broaden tenant scope. Bind values as query parameters; SQL syntax and bound values have different jobs.

The first fixture is (r1,t1,mine), (r2,t2,private), (r3,t1,other). t1 with [r2,r1] returns [r1]; t1 with [r3,r1,r1] returns [r1,r3]; t2 with [r3,r2] returns [r2]. Empty IDs return []. The literal tenant "t1' OR 1=1 --" and literal ID "x') OR 1=1 --" return [], without broadening the query. A second fixture changes all IDs and tenants: (z9,org-a,one), (a4,org-a,two), (b8,org-b,private); org-a requesting all three returns [a4,z9]. The grader checks database rows after each call, too.

If stuck, revisit https://ai.lwkjob.com/learn/memory-scopes/?level=implementation. Tenant is a trusted fixture argument here; this exercise does not implement production authentication.

## 3. HTTP observation and unknown writes

Implement next_action(observation) -> dict with exactly action and operation_key. The prevalidated fixture has kind=read/write, status=ok/timeout/rate_limited/invalid_arguments/forbidden, operation_key=None for reads or a nonempty string for writes, receipt=None or a trusted fixture business receipt, and positive integer attempts/max_attempts. attempts is calls already attempted; retries are permitted only while attempts < max_attempts. This is an authored conservative recovery policy, not a universal provider retry rule.

For a write receipt, require receipt.operation_key to match observation.operation_key; a mismatch raises ValueError. A matching receipt returns complete with the same operation key. Permanent invalid_arguments or forbidden returns stop, retaining the original write key (None for reads). Without a receipt, any nonpermanent write observation, including ok, returns reconcile_original with the original key. Hitting the retry limit does not make an unknown write uncommitted; retain the key for reconciliation/manual review. Read ok returns complete; a read timeout/rate_limited returns retry_read below the limit and stop at the limit. Never mutate the input, create a new operation key or issue any request from this function.

Examples: read timeout attempts=1/max_attempts=3 -> {action:retry_read, operation_key:null}; the same at 3/3 -> stop. write timeout with op-a -> reconcile_original/op-a. write ok without receipt -> reconcile_original/original key. write ok with matching trusted receipt -> complete/original key. stop means stop issuing a new call; it does not erase a prior effect or prove a remote rollback. No live HTTP service is used in this diagnostic.

If stuck, revisit https://ai.lwkjob.com/learn/agent-fault-injection/?level=implementation and the distinction between local status and an independently confirmed business receipt.

## 4. Durable unique claim under concurrent calls

Implement claim_once(db_path, operation_key) -> bool. The grader creates a disk SQLite database with claims(operation_key TEXT PRIMARY KEY, created_tag TEXT NOT NULL DEFAULT 'claimed'). Each invocation must open and close its own connection. Atomically insert exactly one row for a new key, commit it, return True only for that successful first claim, and return False for a previously claimed key. Preserve all older rows and their created_tag. Use a bounded SQLite lock timeout; the fixture permits 5 seconds. Inputs are valid nonempty strings, including an apostrophe in one key. Do not recreate/clear the table, rely on a process-local set, or report success without a durable row.

The grader launches six independent worker processes with the same key, checks exactly one True plus one persistent row, repeats with a different key while retaining the first, then opens another process for a replay which must return False. It reports facts from both function results and the database. This verifies a local durable claim only: it does not run an external business action or establish distributed exactly-once execution.

If stuck, revisit https://ai.lwkjob.com/learn/run-state-outbox/?level=implementation and its local transaction boundaries. Explain what the unique claim proves and which external commit still needs a separate contract.

## Returning to the main route

Keep prerequisite-before.json, your source commit/diff, prerequisite-after.json and one short explanation per failed skill. Fix and rerun the indicated skill; then run all four together so one correction does not break another. If the fundamentals remain unclear, study Python types/exceptions, parameter binding, transactions and concurrency before the Agent capstone. Record the diagnostic as pending or mechanically_passed, separately from the main project's engineering, real API and mock-interview states. A reviewer selects a different input or requirement for live assessment and states tool permissions beforehand.

# 四项面试先备诊断

使用 Python 3.9+ 标准库。这些公开固定题用于检查现有 Agent 路线的先备，不是完整 Python/后端课程、未见面试题或企业官方合格线。在空白草稿目录练习，只运行可信的学员模块：检查器会导入本地 Python，不是执行恶意代码的沙箱。不需要密钥、网络或模型请求。

从 https://ai.lwkjob.com/lab/interview-practice/prerequisite_lab.py 下载并保留原文件名。先读下列协议，生成模板，自己实现四个函数，并保留失败起点、本人 diff 与实际重跑报告。模板故意没有完整实现；已有报告不能代替自己的运行，报告会记录实际导入模块的 SHA256。

```sh
python3 prerequisite_lab.py scaffold --out prerequisite_student.py
python3 prerequisite_lab.py grade --module prerequisite_student.py --out prerequisite-before.json
```

初次检查退出 1，是未实现的正常起点。把检查作为单独命令执行，避免 shell 的遇错停止设置影响保存起点。完成自己的函数后：

```sh
python3 prerequisite_lab.py grade --module prerequisite_student.py --out prerequisite-after.json
```

退出 0 要求四项全部通过，不按子案例多数通过判达标。部分报告给出案例与实际错误，便于回读；Python、模块摘要、来源和分母可核对。通过只证明公开诊断协议通过，代码质量和评审选的新条件仍须单独验证。

## 1. JSON 整数边界

实现 parse_quantity(value) -> int。只接受内置 int 精确类型且在 1 到 100 闭区间的值，原样返回整数。布尔、字符串、浮点、None、列表报 TypeError；内置整数越界报 ValueError。不自动转换类型。固定输入含 1、100、7、True、False、"1"、1.0、None、[]、0、-1、101。Python 中布尔与整数类型有继承关系，需要明确 JSON 数量边界，不能据此放行布尔数量。

不会时回读 https://ai.lwkjob.com/learn/tool-contracts/?level=implementation 的类型校验与反例，再用自己的话解释并重跑本人模块。

## 2. 参数 SQL 与租户隔离

实现 find_visible(conn, tenant, ids) -> list[str]。conn 是已打开的内存 SQLite 连接；tenant 与每个 ID 都是字符串，ids 是可为空的列表。检查器建表 resources(id TEXT PRIMARY KEY, tenant TEXT NOT NULL, body TEXT NOT NULL)。只返回同时属于请求 ID 和精确租户的去重 ID，按字典序排序；没有匹配返回 []。不改行、不返回 body、不关闭调用方连接、不扩大租户范围。值用参数绑定，明确 SQL 语法与输入值的分工。

第一组数据为 (r1,t1,mine)、(r2,t2,private)、(r3,t1,other)。t1 请求 [r2,r1] 得 [r1]；t1 请求 [r3,r1,r1] 得 [r1,r3]；t2 请求 [r3,r2] 得 [r2]。空 ID 得 []。字面租户 "t1' OR 1=1 --" 与字面 ID "x') OR 1=1 --" 得 []，不能扩大查询。第二组全部更换 ID/租户：(z9,org-a,one)、(a4,org-a,two)、(b8,org-b,private)；org-a 请求三者得 [a4,z9]。每次调用后还核对数据库行未变。

不会时回读 https://ai.lwkjob.com/learn/memory-scopes/?level=implementation。这里 tenant 是可信夹具参数，此题没有实现生产认证。

## 3. HTTP 观察与未知写入

实现 next_action(observation) -> dict，返回且仅返回 action 和 operation_key。输入是已验证夹具：kind=read/write，status=ok/timeout/rate_limited/invalid_arguments/forbidden；读的 operation_key=None，写为非空字符串；receipt=None 或可信业务回执夹具；attempts/max_attempts 是正整数。attempts 表示已经尝试的次数，只有 attempts < max_attempts 才可重试。这是作者制定的保守恢复协议，不是所有提供方通用重试规则。

写回执要求 receipt.operation_key 匹配输入操作键，否则报 ValueError；匹配则 complete 并保留原键。永久 invalid_arguments/forbidden 返回 stop，并保留写的原键，读仍为 None。无回执时任何非永久写观察，包括 ok，都返回 reconcile_original/原键；达到重试上限不能证明未知写未提交，保留键以便核对或人工处理。读 ok 返回 complete；读 timeout/rate_limited 在上限前 retry_read，到上限 stop。函数不改输入、不生成新键、不发网络请求。

例如：读 timeout 且 1/3 -> {action:retry_read, operation_key:null}，3/3 -> stop；写 timeout/op-a -> reconcile_original/op-a；写 ok 无回执 -> reconcile_original/原键；写 ok 且可信匹配回执 -> complete/原键。stop 只表示停止新增调用，不抹除旧效果，也不证明远端回滚。本诊断没有真实 HTTP 服务。

不会时回读 https://ai.lwkjob.com/learn/agent-fault-injection/?level=implementation，复核本地状态与独立业务回执的区别。

## 4. 并发下持久唯一领取

实现 claim_once(db_path, operation_key) -> bool。检查器创建磁盘 SQLite 表 claims(operation_key TEXT PRIMARY KEY, created_tag TEXT NOT NULL DEFAULT 'claimed')。每次调用自己打开并关闭连接；新键原子插入并提交一行，仅成功首次领取返回 True，已领取键返回 False。保留旧行及 created_tag。锁等待有界，夹具允许 5 秒；输入均为有效非空字符串，其中一个键含单引号。不重建/清空表，不依赖进程内 set，不在无持久行时报告成功。

检查器为同一键启动六个独立工作进程，核对恰一 True 和一持久行；换另一键再做，第一行必须保留；最后另开进程重放第一键，应为 False。函数返回与数据库事实分别核对。这里只验证本地持久领取，不执行外部业务动作，也不证明分布式恰好一次。

不会时回读 https://ai.lwkjob.com/learn/run-state-outbox/?level=implementation 的本地事务范围，并解释唯一领取证明了什么、哪一个外部提交还需新合同。

## 回到主路线

保留 prerequisite-before.json、本人源码提交/diff、prerequisite-after.json 与每项失败的简短解释。按失败项回读、修复，再一起复跑四项防止改一项破坏另一项。基础仍不清楚时先补 Python 类型/异常、参数绑定、事务与并发，再做 Agent 项目。先备记录 pending 或 mechanically_passed，和主项目的工程、真实接入、模拟面试状态分开。现场由评审另选输入或新约束，并事先说明工具许可。

## Shared primary references / 共用技术依据

Python type and Boolean behavior: https://docs.python.org/3.10/library/stdtypes.html#boolean-values

SQLite parameter binding, transactions and lock timeout: https://docs.python.org/3.10/library/sqlite3.html

Local worker scheduling: https://docs.python.org/3.10/library/concurrent.futures.html

HTTP choices and grading cases above are authored teaching policies; these references do not validate a learner, external provider or hiring threshold. HTTP 判据与评分案例为作者教学协议，技术文档不证明学员能力、真实提供方效果或录用门槛。
