Example

Wire a scheduler and cache into one admission path

Submit five requests through a bounded queue and a cache, then inspect which requests were scheduled, which hit, and which were cleaned up.

Scheduling and caching are separate mechanisms, but they meet at admission. A request may be rejected because the queue is full, or admitted and then find a cached prefix. The order matters: checking the cache before admission can waste work on a request that will be refused; admitting before checking can reserve a slot for a request that is already complete.

This example runs a miniature integration. A scheduler with a queue limit of four receives five requests, so four are scheduled and one is refused. A cache is consulted for each scheduled request id. Because every id is new, there are zero hits. One scheduled request is completed and cleaned. The output is a wiring check, not a hit-rate or throughput result.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch42/integration.py --json

Python 3.11 or later, standard library only. No model, network, GPU or credentials. It finishes immediately.

Implementation

MiniScheduler stores request ids up to a maximum queue length and removes one on completion. MiniCache is a dictionary. run_demo submits five ids, puts a value on the first miss, and counts a hit only when the id is already present.

class MiniScheduler:
    def __init__(self, max_queue: int = 4) -> None:
        self.max_queue = max_queue
        self.queue: List[str] = []

    def submit(self, rid: str) -> bool:
        if len(self.queue) >= self.max_queue:
            return False
        self.queue.append(rid)
        return True

    def complete(self, rid: str) -> None:
        if rid in self.queue:
            self.queue.remove(rid)


class MiniCache:
    def __init__(self) -> None:
        self.store: Dict[str, str] = {}

    def get(self, key: str) -> str | None:
        return self.store.get(key)

    def put(self, key: str, value: str) -> None:
        self.store[key] = value


def run_demo(flags: dict) -> IntegrationResult:
    scheduler = MiniScheduler()
    cache = MiniCache()
    cached_hits = 0
    scheduled = 0
    for i in range(5):
        rid = f"r{i}"
        if scheduler.submit(rid):
            scheduled += 1
            if flags.get("cache", False):
                if cache.get(rid) is None:
                    cache.put(rid, "value")
                else:
                    cached_hits += 1
    # Cancel one.
    scheduler.complete("r0")
    cleaned = "r0" not in scheduler.queue

Expected outcome

Observed with the command above (exit 0):

{
  "feature_flags": {
    "cache": true,
    "scheduler": true
  },
  "scheduled": 4,
  "cached_hits": 0,
  "cancelled_cleaned": true,
  "metadata": {}
}

Four of five requests were scheduled; the fifth was refused by the queue limit. No cache hits occurred because each request id was unique. Completing r0 removed it from the queue. These values are exactly what the fixture encodes, not a production measurement.

Mechanism and limitations

Documented: MiniScheduler.submit refuses when the queue is full and complete removes a known id. MiniCache gets and puts string values. run_demo submits five ids, conditionally uses the cache, completes one request and reports the counts. The test file checks queue refusal, cache get/put, the demo and JSON serialisation.

Observed: the command exited 0 with scheduled: 4, cached_hits: 0 and cancelled_cleaned: true. The targeted tests.test_ch42_integration is part of the canonical suite; no independent test count is claimed here.

Not shown: a real scheduler, a prefix cache, eviction, copy-on-write, queue latency, concurrency, cancellation of in-flight work, or a model. The cache key is the request id, so this fixture cannot produce a prefix hit; it only shows where a hit would be counted. The scheduler also does not reject duplicate ids, which a real admission path would need to handle.

Challenge this result

Change the loop so the same request id is submitted twice. Predict what MiniScheduler.submit does and whether the second lookup produces a cache hit. Then fix the scheduler to reject a duplicate id and decide which component should own that check. Finally, replace the request-id cache key with a prefix key and explain why the scheduler and cache must agree on what “the same request” means.

Source and verification

Canonical source: examples/ch42/integration.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch42_integration.py . Chapter: Implementing Scheduling and Caching . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it uses in-process fixtures, not a serving engine.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.