Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Fair scheduling, resource quotas, and backpressure across tenants

Examine multi-tenant queuing, fair scheduling, backpressure and multi-dimensional quotas.

Learning objectives: 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.

Content checked: 2026-10-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Foundation · Understand the concepts. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

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
  1. Why is setting a global Semaphore not enough?

    Move from protecting total capacity to allocating resources among tenants.

  2. 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.

  3. Can a priority queue starve low-priority tasks?

    Priority design must handle starvation and tasks whose capacity requirements cannot be met.

Foundation · Understand the concepts

Identify input and authority boundaries

Objectives of this level: Manually derive junior shape, type and authority error ordering.

Visual guide · Rotate tenants within budgets

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

Identify input and authority boundaries

A client cannot self-report its tenant budget or approval authority. Deep-copy output is part of the contract: returning task itself fails even when values match.

task = {"id": "a1", "tenant": "A", "units": 3}
principal = {"tenant": "A", "enabled": True}
# expected: {"id": "a1", "tenant": "A", "units": 3}
# task with tenant B: PermissionError("tenant_mismatch")
# units=True: ValueError("input_shape")

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.

code example

Identify input and authority boundaries

A client cannot self-report its tenant budget or approval authority. Deep-copy output is part of the contract: returning task itself fails even when values match.

task = {"id": "a1", "tenant": "A", "units": 3}
principal = {"tenant": "A", "enabled": True}
# expected: {"id": "a1", "tenant": "A", "units": 3}
# task with tenant B: PermissionError("tenant_mismatch")
# units=True: ValueError("input_shape")

Acceptance task for this level

Explain acceptance/rejection of the three inputs below, then independently implement validate_task and retain the first failed report.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Which error wins when shape and tenant are both wrong?

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.