Review the prerequisites
Suitable for: Backend developers learning Agent applications.
- Fair scheduling, resource quotas, and backpressure across tenants
- The total concurrency limit protects system capacity, and tenant scheduling protects resource allocation. Both are indispensable. Fairness must be measured based on actual consumption and waiting. The number of requests or the global average delay cannot be regarded as an isolation guarantee.
How does the mechanism work?
Step-by-step explanation
- Why is setting a global Semaphore not enough?
Move from protecting total capacity to allocating resources among tenants.
- What should I do if the Token cost cannot be accurately estimated in advance?
Fair request allocation must also account for unknown and unequal costs.
- Can a priority queue starve low-priority tasks?
Priority design must handle starvation and tasks whose capacity requirements cannot be met.
Implementation · Build it
Implement budgeted tenant round-robin
Objectives of this level: Implement plan_round independently and distinguish planned cost from real settlement.
Visual guide · Rotate tenants within budgets
This local scheduler uses fixture costs, not measured tokens. Global slots do not ensure fairness; actual shared reservations need atomic commit-time rechecks. Select the figure to open it at full size.
Three programming levels in the after-sales Agent
Junior, intermediate and senior describe progressively stronger local contracts. The four course tracks produce different evidence. Passing fixed public checks is not a job-level or hiring certification. Download the ZIP, extract it and enter agent-career-levels-v1; career_lab.py and career-cases.json must remain together. Python 3.9+, standard library only. Implement progressively in one career_student.py; scaffold refuses overwrites. Regress all three levels after senior changes.
- https://ai.lwkjob.com/lab/career-levels/README.md
- https://ai.lwkjob.com/lab/career-levels/career_lab.py
- https://ai.lwkjob.com/lab/career-levels/career-cases.json
- https://ai.lwkjob.com/downloads/agent-career-levels-v1.zip
python3 career_lab.py scaffold --out career_student.py
python3 career_lab.py grade --module career_student.py --level junior --out report-junior.json
python3 career_lab.py grade --module career_student.py --level intermediate --out report-intermediate.json
python3 career_lab.py grade --module career_student.py --level senior --out report-senior.json
Implement budgeted tenant round-robin
The input below alternates A/B. cursor names the last selected tenant, not an array index. Sorting request IDs cannot replace tenant scheduling; absent old tenants and blocked FIFO heads are separate negatives.
tasks = [
{"id": "a1", "tenant": "A", "units": 3},
{"id": "a2", "tenant": "A", "units": 3},
{"id": "b1", "tenant": "B", "units": 2},
{"id": "b2", "tenant": "B", "units": 2},
]
budgets, cursor, slots = {"A": 10, "B": 10}, None, 4
expected = {"selected": ["a1", "b1", "a2", "b2"],
"cursor": "B", "remaining": {"A": 4, "B": 6}}
def validate_task(task, principal):
raise NotImplementedError
def plan_round(tasks, budgets, cursor, slots):
raise NotImplementedError
def migrate_state(snapshot):
raise NotImplementedError
def run_step(runtime, lease, action):
raise NotImplementedError
Worked difficulty: planning does not reserve capacity
Visual guide · Four planning turns, then actual reservation accounting
Turns 1–4 are an authored fixed probe, not an executed learner scheduler. Cards 5–6 are a separate actual local demo with different IDs. Synthetic units only; no token cost. Sources: worked-probes.json and runtime-demo.json. Select the figure to open it at full size.
The existing A/B input is a planning fixture. Follow the queue head and cursor after each choice; remaining is a copied plan budget, not a reservation ledger. Fixed probe output records an authored decision order, not execution of a learner's plan_round.
| Choice | Pending A / B | cursor | remaining A / B |
|---|---|---|---|
| start | a1,a2 / b1,b2 | None | 10 / 10 |
| a1 | a2 / b1,b2 | A | 7 / 10 |
| b1 | a2 / b2 | B | 7 / 8 |
| a2 | empty / b2 | A | 4 / 8 |
| b2 | empty / empty | B | 4 / 6 |
With A=3/B=2, the first two choices exhaust both budgets; a2 and b2 stay queued. An expensive FIFO head cannot be skipped to find a cheaper tail. Persisting the selected IDs does not itself reserve a shared slot. Recheck capacity and current authority atomically when committing an admission.
Now use the separate actual process demo, evidence.competition. It prepares acme-a, acme-b and other-a, each with reserve=5; total budget is 1000 per tenant. Two worker processes deliberately wait at a barrier after admission. This creates a reproducible overlap, not a measurement of naturally arriving traffic or fair scheduling.
| Observed checkpoint | Queued | held slots | acme reserved / spent / available | other reserved / spent / available |
|---|---|---|---|---|
| simultaneous_reservations | acme-b | 2 | 5 / 0 / 995 | 5 / 0 / 995 |
| final, after all three finish | empty | 0 | 0 / 6 / 994 | 0 / 3 / 997 |
Calculate available=total-reserved-spent. Completion removes the whole reservation 5 and charges verified actual 3; only 2 becomes unused budget. acme has two completed tasks, hence spent=6. reserved_units=5 on a completed task is retained history; a non-null reservation_id marks a current hold. Read budgets and reservation_id together rather than summing historical reserved_units. Source: runtime.py acquire/settle and senior_lab.py demo. Units and limits are authored teaching assumptions, not tokens, money or a production capacity claim.
Independent contracts and authority
JSON arguments and Lease are immutable. run_step may change the supplied runtime only through runtime.commit. Pure-function results must not share dict/list containers with their arguments. JSON types are exact: True is not integer 1. Exception class and message are exact. principal and runtime policy are trusted server facts supplied by the exercise. A submitted task, historical approval or model text cannot grant authority. Import only learner modules you trust; a subprocess hang guard is not a hostile-code sandbox.
validate_task(task, principal): task has exactly id, tenant, units; the first two are nonempty str; units is strict int in 1..100. principal has exactly nonempty str tenant and strict bool enabled. Validate every shape first: ValueError("input_shape"). Then tenant mismatch: PermissionError("tenant_mismatch"). Then disabled: PermissionError("tenant_disabled"). Success returns a deep copy of task. Self-reported enabled fields cannot grant authority.
plan_round(tasks, budgets, cursor, slots): tasks is a list of the above task records with unique IDs; budgets maps nonempty str tenants to strict nonnegative int, and may be empty; cursor is None or nonempty str; slots is strict nonnegative int. Any malformed input raises ValueError("input_shape"). Do not schedule tenants absent from budgets or borrow another tenant's budget. Sort tenant names lexically, start immediately after cursor and wrap. Choose one affordable tenant head, debit planned remaining units, then continue after that selected tenant. Preserve FIFO within each tenant: an unaffordable head blocks its cheap tail. Stop at slots or when no head is affordable. Return exactly selected (ID list), cursor (last selected tenant, unchanged if none), remaining (planned budgets). This is request round-robin with integer estimated cost, not elapsed-time fairness, real token settlement or production quotas.
migrate_state(snapshot): v1 has exactly schema/id/tenant/status/approval/budget_used/operation_key/extensions. schema is strict int; unsupported values other than 1/2 raise ValueError("unsupported_schema"); other shape failures raise ValueError("input_shape"). id/tenant are nonempty str; budget_used is strict nonnegative int; operation_key is None or nonempty str; extensions is a JSON dict preserved through deep copy. approval has exactly matching tenant, strict positive int epoch, and decision pending/approved/denied. v1 statuses are waiting/running/unknown/completed. Map waiting to awaiting_approval/ready/blocked respectively; unknown to reconcile_required; preserve running/completed. unknown/reconcile_required requires operation_key. v2 adds migration={"from_schema":1,"to_schema":2} with strict integers and allows the new statuses plus running/completed. Valid v2 returns unchanged through deep copy. Preserve approval epoch, consumed budget, business key and extensions. Migration creates no business side effect.
run_step(runtime, lease, action): import career_lab.Lease and CommitConflict; legal dataclass/future annotations and canonical exception identity are supported. Check action first: only dispatch/migrate, otherwise ValueError("action"). Require a Lease instance with nonempty str task_id/tenant, strict positive int worker_epoch and strict nonnegative int expires_at, otherwise ValueError("lease_shape"). Both checks precede read. runtime.read(task_id) raises ValueError("unknown_task") for a missing task. Then reject in order: tenant mismatch→tenant_mismatch; expires_at<=now→lease_expired; worker_epoch mismatch→worker_fenced; current disabled policy→tenant_disabled. A rejection returns exactly {"status":"blocked","reason":reason} without commit.
For migrate, reject view.running as running_requires_old_executor; v2 returns {"status":"unchanged","reason":"already_v2"}; otherwise call your migrate_state, units=0, success migrated/schema_v2. For dispatch require schema2/status ready, otherwise ready_required; approval must be approved with epoch equal to current policy epoch, otherwise approval_stale. Then test global_running>=capacity, tenant_running>=tenant_limit, extensions.units>budget_remaining in that order, returning backpressure/tenant_limit/budget_exhausted. Valid dispatch deep-copies the snapshot, changes status to running, and reserves extensions.units. Both committing paths call runtime.commit(lease, view["policy"]["epoch"], updated, units). Catch canonical CommitConflict and return blocked/str(exc). Dispatch success is started/reserved. Runtime initial snapshots and extensions.units in these fixtures are valid; malformed stored runtime state beyond missing tasks is outside this exercise's contract.
runtime.read returns snapshot, worker_epoch, running, now, policy, global_running, tenant_running, capacity, tenant_limit, budget_remaining. Runtime.commit rechecks tenant, lease, worker epoch, current authority and resources in one SQLite transaction before updating state/budget/ledger. Every successful commit increments worker_epoch. environment_hook injects revocation, worker replacement or zero capacity between read and commit; it is deterministic simulation, not measured cross-host concurrency. Do not write runtime.db directly, change capacity, call external_write or bypass commit.
Evidence and limits
There are 14 junior, 17 intermediate and 41 senior public checks, 72 total. grade imports and calls the learner's functions, records each input/expected/actual/error, audited state, learner/source/cases SHA and Python version. Exit0 means all selected contracts pass; exit1 is failure; missing CLI arguments or scaffold overwrite exit2. Exceptions and invalid return types fail, including SystemExit/KeyboardInterrupt during import or calls. The parent binds the complete packet to the current case, actual values/ledger and process exit; a claimed passed flag is insufficient. The five-second limit only detects hung workers, not latency. Changed inputs and negative cases are public, not hidden tests or unseen transfer.
This is one process with in-memory SQLite and an integer logical clock. Budgets/capacity are teaching assumptions. A reserve ledger entry is local reservation, not a completed external refund. Completion settlement, resource release, remote cancellation, multi-host shared leases and production capacity measurements are not implemented. Local cancellation/release cannot undo an unknown external write; a real system needs receipt reconciliation and a preserved operation_key. Pure migration maps running structurally; run_step retains the old executor and refuses switching it. Recovery/rollback, dual-read windows and distributed fencing need separate validation. Green fixed checks cannot be reported as production experience or real model quality.
Submit your source, first failed report, personal diff, rerun report and a 300-word tradeoff note, disclosing assistance. Published expected outputs make the contract reviewable; they are not proof of independent authorship. Sources: Python sqlite3, Python importlib. Actual behavior is defined by this source and its public inputs.
Provided storage/loader/grader source · 提供的存储、导入器与验收源码
#!/usr/bin/env python3
"""Python 3.9+ authored local career exercises; no model/provider/business service.
Public cases are reproducible contracts, not unseen tests or career certification.
Only import learner modules you trust: this program is not a security sandbox.
"""
import argparse
import copy
from dataclasses import dataclass
import hashlib
import importlib.util
import json
from pathlib import Path
import sqlite3
import subprocess
import sys
if __name__ == "__main__":
sys.modules["career_lab"] = sys.modules[__name__]
CASES = Path(__file__).with_name("career-cases.json")
VERSION = "career-lab-v1"
@dataclass(frozen=True)
class Lease:
task_id: str
tenant: str
worker_epoch: int
expires_at: int
class CommitConflict(RuntimeError):
pass
class Runtime:
"""One SQLite database, integer logical clock, deterministic interleaving hooks.
commit is the guarded atomic storage API, not a learner orchestration solution.
A reserve is LOCAL capacity/budget state; it is not an external write receipt.
"""
def __init__(self, states, policies, budgets, capacity=2, tenant_limit=1, now=10, hook=None):
self.db = sqlite3.connect(":memory:")
self.db.executescript("CREATE TABLE runs(id TEXT PRIMARY KEY,tenant TEXT,epoch INTEGER,state TEXT,running INTEGER);"
"CREATE TABLE policy(tenant TEXT PRIMARY KEY,epoch INTEGER,enabled INTEGER);"
"CREATE TABLE budget(tenant TEXT PRIMARY KEY,remaining INTEGER);"
"CREATE TABLE ledger(kind TEXT,task_id TEXT,tenant TEXT,units INTEGER,epoch INTEGER);")
for row in states:
s = row["snapshot"]
self.db.execute("INSERT INTO runs VALUES(?,?,?,?,?)", (s["id"],s["tenant"],row["worker_epoch"],json.dumps(s),int(row["running"])))
for tenant,p in policies.items():
self.db.execute("INSERT INTO policy VALUES(?,?,?)", (tenant,p["epoch"],int(p["enabled"])))
self.db.executemany("INSERT INTO budget VALUES(?,?)", list(budgets.items()))
self.db.commit()
self.capacity,self.tenant_limit,self.now,self.hook = capacity,tenant_limit,now,hook
self.events = []
def read(self, task_id):
self.events.append(["read",task_id])
row = self.db.execute("SELECT tenant,epoch,state,running FROM runs WHERE id=?",(task_id,)).fetchone()
if row is None:
raise ValueError("unknown_task")
tenant,epoch,state,running = row
policy = self.db.execute("SELECT epoch,enabled FROM policy WHERE tenant=?",(tenant,)).fetchone()
budget = self.db.execute("SELECT remaining FROM budget WHERE tenant=?",(tenant,)).fetchone()
return {"snapshot":json.loads(state),"worker_epoch":epoch,"running":bool(running),"now":self.now,
"policy":{"epoch":policy[0],"enabled":bool(policy[1])},
"global_running":self.db.execute("SELECT SUM(running) FROM runs").fetchone()[0],
"tenant_running":self.db.execute("SELECT SUM(running) FROM runs WHERE tenant=?",(tenant,)).fetchone()[0],
"capacity":self.capacity,"tenant_limit":self.tenant_limit,"budget_remaining":budget[0]}
def commit(self, lease, expected_policy_epoch, snapshot, units=0):
"""Atomically guard authority/revision/capacity and install caller's state.
The caller supplies the state transition and handles any conflict.
"""
self.events.append(["commit_attempt",lease.task_id,units])
if self.hook:
if self.hook == "revoke":
self.db.execute("UPDATE policy SET epoch=epoch+1,enabled=0 WHERE tenant=?",(lease.tenant,))
elif self.hook == "worker_change":
self.db.execute("UPDATE runs SET epoch=epoch+1 WHERE id=?",(lease.task_id,))
elif self.hook == "capacity_zero":
self.capacity = 0
self.db.commit()
self.events.append(["environment_hook",self.hook])
self.hook = None
self.db.execute("BEGIN IMMEDIATE")
try:
row = self.db.execute("SELECT tenant,epoch,state FROM runs WHERE id=?",(lease.task_id,)).fetchone()
policy = self.db.execute("SELECT epoch,enabled FROM policy WHERE tenant=?",(row[0],)).fetchone()
def reject(reason):
raise CommitConflict(reason)
if row[0] != lease.tenant or snapshot["tenant"] != row[0]: reject("tenant_mismatch")
if lease.expires_at <= self.now: reject("lease_expired")
if row[1] != lease.worker_epoch: reject("worker_fenced")
if policy[0] != expected_policy_epoch or not policy[1]: reject("authority_changed")
if type(units) is not int or units < 0: reject("invalid_units")
if units:
used = self.db.execute("SELECT SUM(running) FROM runs").fetchone()[0]
tenant_used = self.db.execute("SELECT SUM(running) FROM runs WHERE tenant=?",(row[0],)).fetchone()[0]
budget = self.db.execute("SELECT remaining FROM budget WHERE tenant=?",(row[0],)).fetchone()[0]
if used >= self.capacity: reject("backpressure")
if tenant_used >= self.tenant_limit: reject("tenant_limit")
if budget < units: reject("budget_exhausted")
self.db.execute("UPDATE budget SET remaining=remaining-? WHERE tenant=?",(units,row[0]))
epoch = row[1]+1
self.db.execute("UPDATE runs SET epoch=?,state=?,running=? WHERE id=?",(epoch,json.dumps(snapshot),int(bool(units)),lease.task_id))
self.db.execute("INSERT INTO ledger VALUES(?,?,?,?,?)",("reserve" if units else "migrate",lease.task_id,row[0],units,epoch))
self.db.commit()
return epoch
except BaseException:
self.db.rollback()
raise
def external_write(self, task_id):
"""Forbidden simulated effect; no real external request occurs."""
self.db.execute("INSERT INTO ledger VALUES('external_write',?,'unknown',0,0)",(task_id,))
self.db.commit()
self.events.append(["external_write",task_id])
def audit(self):
return {"runs":[{"id":i,"tenant":t,"worker_epoch":e,"snapshot":json.loads(s),"running":bool(r)} for i,t,e,s,r in self.db.execute("SELECT * FROM runs ORDER BY id")],
"budgets":dict(self.db.execute("SELECT * FROM budget ORDER BY tenant")),
"ledger":[dict(zip(["kind","task_id","tenant","units","epoch"],r)) for r in self.db.execute("SELECT * FROM ledger")],
"policies":{t:{"epoch":e,"enabled":bool(v)} for t,e,v in self.db.execute("SELECT * FROM policy ORDER BY tenant")},
"events":copy.deepcopy(self.events),"capacity":self.capacity}
def close(self):
self.db.close()
TEMPLATE = '''"""Implement progressively. Cases are public; disclose any assistance used."""
def validate_task(task, principal):
raise NotImplementedError("junior contract")
def plan_round(tasks, budgets, cursor, slots):
raise NotImplementedError("intermediate contract")
def migrate_state(snapshot):
raise NotImplementedError("senior pure migration contract")
def run_step(runtime, lease, action):
raise NotImplementedError("senior guarded orchestration contract")
'''
def load_module(path):
spec = importlib.util.spec_from_file_location("career_student",path)
if spec is None or spec.loader is None:
raise ValueError("module_path")
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
def exact(a, b):
"""Compare both JSON values and their exact types."""
if type(a) is not type(b):return False
if type(a) is dict:return set(a)==set(b) and all(exact(a[k],b[k]) for k in a)
if type(a) is list:return len(a)==len(b) and all(exact(x,y) for x,y in zip(a,b))
return a==b
def case_fields(case):
return {"name":case["name"],"function":case["function"],"input":copy.deepcopy(case["args"]),
"runtime_input":copy.deepcopy(case.get("runtime")),"expected":copy.deepcopy(case.get("expected")),
"expected_error":case.get("error"),"expected_audit":copy.deepcopy(case.get("audit"))}
def result_passes(case, row):
"""Recompute contract success from measured values, not a claimed passed flag."""
if row["controlled_failure"]:return False
if not all(row[k] for k in ("arguments_unchanged","result_alias_free","return_json_valid")):return False
if not exact(row["error"],case.get("error")):return False
if "error" not in case and not exact(row["actual"],case["expected"]):return False
if not exact(row["audit"],case.get("audit")):return False
if row["audit"] and any(item["kind"]=="external_write" for item in row["audit"]["ledger"]):return False
return True
def validate_worker_report(case, row, returncode):
"""Bind a complete child packet to this case and its real process exit.
This prevents accidental/spurious stdout from becoming a grading result.
It does not turn trusted learner execution into a hostile-code sandbox.
"""
fields=case_fields(case)
required=set(fields)|{"passed","actual","error","audit","arguments_unchanged",
"result_alias_free","return_json_valid","controlled_failure"}
if type(row) is not dict or set(row)!=required:raise ValueError("worker_packet_shape")
if any(not exact(row[k],v) for k,v in fields.items()):raise ValueError("worker_packet_case")
if any(type(row[k]) is not bool for k in ("passed","arguments_unchanged","result_alias_free","return_json_valid","controlled_failure")):
raise ValueError("worker_packet_types")
if row["error"] is not None and type(row["error"]) is not str:raise ValueError("worker_packet_error")
try:
json.dumps(row,allow_nan=False)
passed=result_passes(case,row)
except (TypeError,ValueError,KeyError,RecursionError):raise ValueError("worker_packet_values")
if row["passed"]!=passed:raise ValueError("worker_packet_claim")
if type(returncode) is not int or returncode!=(0 if passed else 1):raise ValueError("worker_packet_exit")
return passed
def one_case(path, case):
arguments=copy.deepcopy(case["args"])
before=copy.deepcopy(arguments)
rt=None
actual,error,controlled_failure=None,None,False
module_loaded=False
try:
module=load_module(path)
module_loaded=True
if case["function"]=="run_step":
rt=Runtime(**case["runtime"])
actual=[]
for call in arguments:
actual.append(module.run_step(rt,Lease(**call["lease"]),call["action"]))
else:
actual=getattr(module,case["function"])(*arguments)
except BaseException as exc:
error=type(exc).__name__+":"+str(exc)
# SystemExit/KeyboardInterrupt are failures, never successful case exits.
controlled_failure=not module_loaded or not isinstance(exc,Exception)
audit=rt.audit() if rt else None
if rt:rt.close()
def containers(value):
ids=set()
if type(value) in (dict,list):
ids.add(id(value))
for child in (value.values() if type(value) is dict else value):ids.update(containers(child))
return ids
def json_values(value):
if type(value) is dict:return all(type(k) is str and json_values(v) for k,v in value.items())
if type(value) is list:return all(json_values(v) for v in value)
return type(value) in (str,int,float,bool,type(None))
try:
arguments_unchanged=exact(arguments,before)
result_alias_free=not bool(containers(actual)&containers(arguments))
except RecursionError:arguments_unchanged,result_alias_free=False,False
try:
return_json_valid=json_values(actual)
json.dumps(actual,allow_nan=False)
except (ValueError,TypeError,RecursionError):return_json_valid=False
if not return_json_valid:actual={"invalid_return_type":type(actual).__name__}
row=case_fields(case)
row.update(actual=actual,error=error,audit=audit,arguments_unchanged=arguments_unchanged,
result_alias_free=result_alias_free,return_json_valid=return_json_valid,controlled_failure=controlled_failure)
row["passed"]=result_passes(case,row)
return row
def grade(path, level):
data=json.loads(CASES.read_text())
selected=[c for c in data["checks"] if c["level"]==level]
rows=[]
for index,case in enumerate(data["checks"]):
if case["level"]!=level:continue
r=None
try:
r=subprocess.run([sys.executable,str(Path(__file__).resolve()),"_case","--module",str(Path(path).resolve()),"--index",str(index)],text=True,capture_output=True,timeout=5)
row=json.loads(r.stdout.splitlines()[-1])
validate_worker_report(case,row,r.returncode)
except (ValueError,IndexError,TypeError,KeyError,OSError,subprocess.TimeoutExpired) as exc:
row=case_fields(case)
row.update(actual=None,error=None,audit=None,passed=False,arguments_unchanged=False,result_alias_free=False,return_json_valid=False,controlled_failure=True,
worker_error=type(exc).__name__+":"+str(exc),worker_stderr=r.stderr[-1000:] if r else str(exc)[-1000:],worker_returncode=r.returncode if r else None)
rows.append(row)
return {"source":"public_fixed_local_contracts","version":VERSION,"level":level,"passed":bool(selected) and bool(rows) and all(r["passed"] for r in rows),"no_cases":not bool(selected),
"passed_checks":sum(r["passed"] for r in rows),"total_checks":len(selected),"checks":rows,
"student_sha256":hashlib.sha256(Path(path).read_bytes()).hexdigest(),"source_sha256":hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
"cases_sha256":hashlib.sha256(CASES.read_bytes()).hexdigest(),"python":sys.version,
"limits":"local SQLite/logical-time fixtures; no provider/production/hidden-test/role certification; 5s worker hang guard is not a latency gate"}
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("command",choices=["scaffold","grade","_case"])
parser.add_argument("--out")
parser.add_argument("--module")
parser.add_argument("--level",choices=["junior","intermediate","senior"])
parser.add_argument("--index",type=int)
args=parser.parse_args()
if args.command=="scaffold":
if not args.out:parser.error("scaffold requires --out")
try:
with Path(args.out).open('x') as handle:handle.write(TEMPLATE)
except FileExistsError:parser.error("refusing to overwrite learner module")
print(json.dumps({"created":args.out,"source":"unimplemented_scaffold"}));return 0
if not args.module:parser.error("requires --module")
if args.command=="_case":
result=one_case(args.module,json.loads(CASES.read_text())["checks"][args.index])
print(json.dumps(result,sort_keys=True));return 0 if result["passed"] else 1
if not args.level or not args.out:parser.error("grade requires --level and --out")
result=grade(args.module,args.level)
Path(args.out).write_text(json.dumps(result,sort_keys=True,indent=2)+'\n')
print(json.dumps({k:v for k,v in result.items() if k!='checks'},sort_keys=True))
return 0 if result["passed"] else 1
if __name__=="__main__":
sys.exit(main())
Run the resource boundary with real worker processes
Use the multiprocess project extension and source ZIP after the seven-stage baseline. It connects actual Agent preparation and approved return execution to shared admission, tenant/global limits, reservation settlement, worker epochs and original-key receipt reconciliation. Inspect distinct worker PIDs, persisted state and merchant HTTP before claiming a boundary passed. The merchant and runtime use separate processes/connections to one local SQLite file; this is a declared shared-storage experiment. Synthetic work units and local measured execution windows are not provider tokens, production quotas or the route's hypothetical 300/1200 tasks/minute. The supplied implementation is a reference; complete the separate learner hook, red baseline, personal diff and regression. Use ADR_GUIDE.md for alternatives, failure windows and migration/rollback proposals, labeling unexecuted proposals planned.
Continue in one runnable project: admission before an uncertain return
Follow Harness Journey from a tenant queue to the final merchant receipt. Start with the walkthrough and the source ZIP. Admission is part of the actual return path: reserve shared capacity and synthetic units, retain that hold when the HTTP result becomes unknown, and release or settle only from verified evidence. The persisted scheduler cursor matters after reopening; an in-memory alternation printout does not establish admission fairness. The same task later passes the reducer, fallback, approval and merchant gates.
Run python3 -B journey.py scenario --name fair_queue --work /tmp/journey-fair. A scenario can pass because it rejects a forbidden admission. Read the queue and reservation observations rather than interpreting exit 0 as every submitted task completing. These are declared local fixtures; request round-robin does not establish elapsed-time or cost fairness for arbitrary workloads.
Continue the connected project article and inspect the executable entrypoint.
code example
Implement budgeted tenant round-robin
The input below alternates A/B. cursor names the last selected tenant, not an array index. Sorting request IDs cannot replace tenant scheduling; absent old tenants and blocked FIFO heads are separate negatives.
tasks = [
{"id": "a1", "tenant": "A", "units": 3},
{"id": "a2", "tenant": "A", "units": 3},
{"id": "b1", "tenant": "B", "units": 2},
{"id": "b2", "tenant": "B", "units": 2},
]
budgets, cursor, slots = {"A": 10, "B": 10}, None, 4
expected = {"selected": ["a1", "b1", "a2", "b2"],
"cursor": "B", "remaining": {"A": 4, "B": 6}}
Acceptance task for this level
Derive selected/cursor/remaining first, implement plan_round, grade intermediate and regress junior. Record an actual changed-ID/cost return.
Reading this browser’s record…
Hide the answer and check your understanding
A head costs8, its tail1, with budget3. May the tail run?
Expand reference derivation
Not under this contract. A is blocked while another tenant may run. Splitting or cost-based reordering requires a different policy contract.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (1 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.
- AWS:Retry with backoff pattern
- Python:Coroutines and tasks
- Amazon SQS: The role and boundaries of fair queues
- Multiprocess resource and recovery lab
- Independent settlement assignment
- Migration, incident and ownership decisions
- Observed learner pilot and rubric calibration
- Source ZIP
- Harness Journey: one connected practical project
- Bilingual project guide and fault exercises
- Harness Journey source ZIP