Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 58 / SCENARIO-BASED QUESTIONS

Scenario: an async endpoint stalls every request

An async endpoint calls a blocking library operation. While it runs, unrelated requests stop progressing even though they are implemented with async def. Adding more coroutine tasks does not reduce the stall.

AdvancedScenario 18 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 18 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Build a diagnosis from evidence
  • Compare a repair with its trade-offs
  • Test the changed behaviour
DIAGNOSTIC CASE FILE

Follow the evidence.

An async endpoint calls a blocking library operation. While it runs, unrelated requests stop progressing even though they are implemented with async def. Adding more coroutine tasks does not reduce the stall.

Observed evidence

  • The blocking operation runs on the event-loop thread.
  • A lightweight heartbeat is delayed during the operation.
  • The library call does not yield to the event loop.

Investigation sequence

  1. Separate CPU-bound work from blocking I/O.
  2. Use loop-lag measurements and stack/profiling evidence to locate the synchronous call.
  3. Use an async client or bounded thread offload for appropriate I/O; test cancellation and resource ownership.

Challenge the repair

  • Add a test that concurrently runs a heartbeat and the adapter without depending on exact timing.
  • What happens if the caller times out but the thread keeps running?
01

Read the incident, not just the error

An event loop lets several waiting operations make progress on one thread. A synchronous call that keeps that thread occupied prevents the loop from choosing another ready task.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use this explanation when unrelated async requests stall together. Know ordinary calls, loops and lists first. The evidence must locate the occupied thread; a large task count alone does not explain lost progress.

Words you will see

Event loop
The coordinator that resumes ready asynchronous tasks.
Yield
Give control back so another task may run.
Heartbeat
A small independent operation used to observe whether progress remains possible.

Read the progress evidence

The incident reports a delayed heartbeat while a synchronous library call runs on the event-loop thread. That supports the hypothesis that the library prevents cooperative progress. A slow database, exhausted connection pool or CPU loop could produce similar symptoms; a stack sample and the location of the call distinguish them.

The program below is a sequential scheduling model. It records which task owns each turn; it creates no asynchronous tasks and measures no elapsed time. The two work turns before the heartbeat represent a period without a scheduling opportunity, not a measured production delay.

Make a reproduction that can challenge the hypothesis

In a supported local CPython lab, coordinate a controlled blocking adapter with events. Hold it until the test has checked whether an independent heartbeat can run. Avoid a test that merely sleeps briefly and hopes the operating system chooses the intended order.

If heartbeat progress also fails after removing the suspected call, investigate another cause rather than declaring the first hypothesis proven. Here the browser-local model only explains the ordering counterexample. It does not reproduce real I/O or prove a repair's speed.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. turns = []

    Start a new evidence list.

  2. for owner in ['work', 'work', 'heartbeat']:

    Supply a chosen order, not a scheduler observation.

  3. turns.append(owner)

    Record each owner in that order.

  4. print(turns.index('heartbeat'))

    Position two means two model turns preceded the heartbeat.

An async endpoint calls a blocking library operation. While it runs, unrelated requests stop progressing even though they are implemented with async def. Adding more coroutine tasks does not reduce the stall.

Conceptual cause of shared request stalls

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. OccupyA synchronous operation holds the loop thread.
  2. ExcludeOther ready coroutines cannot resume on that thread.
  3. ObserveIndependent heartbeat progress is delayed.
Predict before you run

Where does the heartbeat appear in the model?

Model a missing scheduling opportunityPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Model an earlier opportunity.

Try: Move 'heartbeat' between the two work strings.

Its index becomes one; this changes the chosen model order, not runtime scheduling.

Model additional uninterrupted work.

Try: Insert another 'work' before 'heartbeat'.

The index becomes three because another model turn precedes it.

Before you move on

A heartbeat stalls even when there is only one request. Does that rule out a blocked event loop?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. A single synchronous call can occupy the loop thread. Request count is not the mechanism; the question is whether control returns to the loop while the call is active.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Investigate before changing code

Choose an execution boundary from the work's behavior. Native asynchronous I/O, blocking I/O and CPU work do not need the same repair.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

An appropriate async client can yield while waiting. A bounded thread adapter can isolate suitable blocking I/O. CPU-heavy Python work may need a process or native implementation instead of more coroutine wrappers.

Words you will see

Blocking I/O
A synchronous call that waits for an external resource while occupying its calling thread.
Offload
Run work outside the event-loop thread.
Capacity
The maximum number of underlying operations allowed to remain active.

State the policy before the mechanism

The browser model maps declared work categories to plans. An async operation stays on the loop only if its implementation really cooperates. A blocking I/O call is a candidate for bounded thread offload. A CPU calculation needs a separate evaluation of process startup, serialization and native code options.

A conventional GIL-enabled CPython thread is not a general promise of parallel Python CPU throughput. Free-threaded builds and libraries that release the GIL change the analysis. Classify the actual implementation rather than making a universal claim from the word Python.

Account for costs and ownership

Each offload consumes a worker and may retain a connection, request body and result. Limit outstanding work as well as running workers; an unbounded waiting queue can still grow. Decide whether the library client is safe to share across threads.

Use the model to review a routing decision, not to simulate execution. A dictionary lookup expresses three choices with small storage proportional to the policy entries. Real offload latency, resource limits and exception propagation need separate integration tests.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. routes = {'async': 'loop', 'io': 'bounded-thread', 'cpu': 'evaluate-process'}

    Declare three policy choices.

  2. kind = 'io'

    Supply the diagnosed category.

  3. plan = routes[kind]

    Look up a plan; no thread starts.

  4. print(len(routes))

    There are three policy entries, not three workers.

Separate CPU-bound work from blocking I/O. Use loop-lag measurements and stack/profiling evidence to locate the synchronous call. Use an async client or bounded thread offload for appropriate I/O; test cancellation and resource ownership.

Predict before you run

What does selecting io do in this program?

A work-routing policy modelPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Review the CPU decision.

Try: Change kind to 'cpu'.

The plan becomes evaluate-process, which calls for further evaluation rather than promising a speedup.

Check an unsupported category.

Try: Change kind to 'unknown'.

Lookup raises KeyError rather than silently selecting a potentially unsafe execution plan.

Before you move on

Would routing a long pure-Python calculation to 'bounded-thread' prove better CPU throughput?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. It changes where the call runs, not the interpreter's CPU execution guarantees. Evaluate processes or native work with real workload measurements and explicit data-transfer costs.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

A repair you can explain

asyncio.to_thread runs a synchronous callable in a thread and lets the coroutine await its result. It is an adapter boundary, not a timeout or a worker-cancellation guarantee.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

This preserved original is a local CPython thread lab. Browser WebAssembly may reject threading; use a supported local Python runtime for the original source. legacy_read returns immediately, so this fixture demonstrates result forwarding, not responsiveness or performance.

Words you will see

Coroutine
A resumable computation created by calling an async function.
Await
Wait for an awaitable result; other progress depends on whether the operation actually yields.
Adapter
A boundary connecting an existing interface to another execution style.

Follow the original source

legacy_read is an ordinary def that returns the string record. main is async; it passes the callable itself to asyncio.to_thread and awaits the result. Calling legacy_read first would run it on the current thread before the adapter could help.

asyncio.run creates and manages a loop for this standalone script. The print occurs after the awaited result arrives. The output record proves that a returned value crossed the boundary in this fixture; because there is no held I/O, it supplies no loop-lag measurement.

Repair the actual incident separately

Replace an appropriate blocking-I/O integration with a well-behaved async client or a bounded adapter. Include library-level timeouts and a shutdown owner for outstanding work. Do not silently substitute a sequential browser fallback for this original program.

The adapter has worker, scheduling and retained-data costs. Verify returned values and exceptions, observe actual active count, and test a heartbeat while the controlled adapter is held. A passing print alone does not establish cancellation safety or the production library's thread safety.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. import asyncio

    Load the standard asynchronous coordination library.

  2. return 'record'

    The synchronous fixture returns immediately without external I/O.

  3. result = await asyncio.to_thread(legacy_read)

    Pass the callable for thread execution, then await its returned string.

  4. print(result)

    Display the returned value after awaiting.

  5. asyncio.run(main())

    Run the standalone coroutine in a managed loop.

The adapter demonstrates thread offload without making a real external call. A production integration must bound concurrent offloads and configure its own I/O timeout.

Predict before you run

What output does the unchanged local lab produce?

Offload a small blocking-I/O adapterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Change the returned fixture.

Try: Replace 'record' with 'page'.

The local lab prints page; the adapter preserves the returned value.

Check exception propagation locally.

Try: Replace the return with raise ValueError('adapter failed').

The await raises the error; there is no successful record print.

Before you move on

If legacy_read raises ValueError, should the adapter return record as a fallback?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. Awaiting to_thread propagates that exception. A fabricated successful value would hide the failure. Catch only declared failures at a boundary whose response contract is explicit.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Reproduce lost progress instead of counting tasks

Run a lightweight heartbeat alongside the affected endpoint and observe whether it can progress while the library operation runs. The incident predicts loop lag because the synchronous call occupies the event-loop thread without yielding. More coroutine objects do not create more opportunities to schedule if execution never returns to the loop. Capture a stack or profile at the stall and identify the blocking call before replacing unrelated async functions.

Separate blocking I/O from CPU computation. Waiting inside a synchronous socket or file library differs from a long Python calculation, although both can stall the loop. A controlled reproduction should coordinate when work starts and when it may finish rather than assert an exact elapsed duration. The existing legacy_read fixture returns immediately, so it demonstrates the adapter boundary but does not itself reproduce a slow external operation or establish a real latency improvement.

Explain cooperative progress and the offload boundary

async def creates a coroutine function, not an automatically parallel function. Progress switches when an awaited operation actually yields control. Calling a synchronous function inside the coroutine runs that function on the loop thread unless explicitly moved elsewhere. Even an await expression can complete immediately without meaningful suspension, so reasoning must follow the actual operation rather than count the number of await keywords in the source.

The reference awaits asyncio.to_thread around legacy_read and prints record. Appropriate blocking I/O can run outside the loop while the coroutine waits for its result. The thread still consumes a resource, and its library operation still needs its own timeout. Moving CPU-heavy Python work to a thread may continue to contend under a conventional GIL-enabled runtime; process or native execution can be alternatives with different startup, serialization, and cancellation costs.

Repair with bounded ownership and realistic cancellation

Prefer a well-behaved async client when it fits the integration contract, or put a concurrency cap around thread offloads so a burst cannot queue unbounded work. Determine whether the legacy client is thread-safe and who owns its connections. A shared client that was safe on one event-loop thread may not be safe across several worker threads. Keep resource creation and cleanup aligned with the actual library's ownership rules.

Cancelling the awaiting coroutine does not guarantee that an already running thread stops. If the caller times out, the underlying operation may still finish and may still perform an external side effect. Avoid immediately starting an unlimited replacement for the same work. Use library-level deadlines, stable operation identities where needed, and shutdown policy for outstanding calls. A semaphore is useful only if its permit lifetime accurately represents active work, including any offload that outlives its original waiter.

Verify responsiveness, failure and shutdown separately

Use events to hold a controlled blocking adapter and prove that the event-loop heartbeat progresses before the adapter is released. Assert that returned data and exceptions pass through correctly. Test a concurrency limit by observing active adapter count, not by hoping a short sleep produces a particular schedule. Add cancellation before start, cancellation during execution, and adapter timeout cases, recording whether underlying work remains active after the caller has stopped waiting.

On shutdown, stop accepting new requests, account for outstanding offloads, and apply the documented drain or abandonment policy. Verify that late results do not update a closed resource or produce a success response for a cancelled request. An async fixture does not establish real process-pool behavior, external networking, or safe cancellation of arbitrary native libraries. Report those as separate integration requirements and preserve the original loop-lag reproduction as a regression check.

Transfer question: A timed-out request releases its concurrency permit, but its offloaded thread continues. Why can this defeat the intended bound?

The permit now counts waiting coroutines rather than active blocking operations. Repeated timeouts can release permits and launch replacements while old threads continue consuming connections and performing work. Track actual offload completion separately, retain capacity until it finishes, and configure a library-level timeout that can bound the operation itself. Decide how late results and exceptions are observed during shutdown. Test with an adapter held by an event: cancel its waiter, submit another request, and verify that active operations never exceed the intended limit. Cancellation of a coroutine is not proof of cancellation of its thread.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

What should you do before adopting this repair?
TRANSFER THE IDEA

Recreate the repair independently

Add a test that concurrently runs a heartbeat and the adapter without depending on exact timing. Start from the symptoms and write your own regression assertion before opening the reference.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Guided: classify an execution plan

Return policy labels only. This browser-local task does not start threads, processes or coroutines.

The contract

  • kinds is a list containing only 'async', 'io' and 'cpu'. Return a new list mapping them to 'loop', 'bounded-thread' and 'evaluate-process'.
  • Preserve input order and repeated occurrences. Empty input returns a new empty list.
  • Do not mutate kinds or perform I/O. Labels are recommendations, not executed concurrency.
Guided: classify an execution planPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. blocking I/O
    r = route_work(['io'])
    assert type(r) is list and r == ['bounded-thread']
  2. async operation
    assert route_work(['async']) == ['loop']
  3. CPU evaluation
    assert route_work(['cpu']) == ['evaluate-process']
  4. empty ownership
    x = []
    r = route_work(x)
    assert type(r) is list and r == [] and r is not x
  5. order and duplicates
    assert route_work(['io', 'async', 'io']) == ['bounded-thread', 'loop', 'bounded-thread']
  6. input preservation
    x = ['cpu', 'io']
    r = route_work(x)
    assert type(r) is list and r == ['evaluate-process', 'bounded-thread'] and x == ['cpu', 'io'] and r is not x
    Why is a passing routing task not proof of responsiveness?

    It performs only dictionary lookups and O(n) output construction for n categories. No scheduler or blocking call runs. Real responsiveness needs a coordinated local adapter/heartbeat test.

    GUIDED PRACTICE

    Guided: bounded admission with a remainder

    Split request IDs into an admitted prefix and an explicit remainder without running work.

    The contract

    • requests is a list of strings; capacity is an integer. Negative capacity raises ValueError.
    • Return a tuple of two new lists: at most capacity leading IDs, then all remaining IDs. Preserve duplicates and order.
    • Empty input and zero capacity are valid. Do not mutate requests; either output must be independently editable.
    Guided: bounded admission with a remainderPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. normal split
      r = admit_prefix(['a', 'b', 'c'], 2)
      assert type(r) is tuple and r == (['a', 'b'], ['c']) and all(type(x) is list for x in r)
    2. zero capacity
      assert admit_prefix(['a'], 0) == ([], ['a'])
    3. empty input
      r = admit_prefix([], 2)
      assert type(r) is tuple and r == ([], []) and r[0] is not r[1]
    4. oversized capacity
      assert admit_prefix(['a', 'a'], 5) == (['a', 'a'], [])
    5. negative capacity
      raised = False
      try:
          admit_prefix(['a'], -1)
      except ValueError:
          raised = True
      assert raised
    6. ownership
      x = ['a', 'b']
      r = admit_prefix(x, 1)
      assert type(r) is tuple and r == (['a'], ['b']) and r[0] is not x and r[1] is not x
      r[0].append('z')
      r[1].append('y')
      assert x == ['a', 'b']
      What does this function cost, and what must the caller do with the remainder?

      The two slices copy n references in O(n) time and space. The caller must implement a visible reject, bounded wait or handoff policy; the returned remainder is not an unlimited production queue.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: cancelled waiters still occupy workers

      Change admission accounting from caller lifetime to actual operation lifetime.

      The contract

      • operations is a list of (id, waiter_live, finished) tuples with Boolean flags; limit is a nonnegative integer.
      • Return an exact int: max(0, limit minus the number of operations with finished False). Count every occurrence, even if its waiter is cancelled.
      • Finished operations consume no slot. Preserve input and perform no real scheduling or cancellation.
      Transfer: cancelled waiters still occupy workersPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. ordinary active work
        r = free_slots([('a', True, False)], 3)
        assert type(r) is int and r == 2
      2. cancelled waiter
        assert free_slots([('a', False, False)], 1) == 0
      3. completed work
        r = free_slots([('a', True, True), ('b', False, True)], 2)
        assert type(r) is int and r == 2
      4. empty
        r = free_slots([], 4)
        assert type(r) is int and r == 4
      5. overflow and zero
        r = free_slots([('a', False, False), ('a', True, False)], 1)
        assert type(r) is int and r == 0 and free_slots([], 0) == 0
      6. preserve operation evidence
        x = [('a', False, False), ('b', True, True)]
        r = free_slots(x, 3)
        assert type(r) is int and r == 2 and x == [('a', False, False), ('b', True, True)]
        Why did the changed requirement invalidate waiter-based counting?

        A timed-out caller can leave a running thread behind. One O(n) scan and O(1) counters model active work without pretending to cancel it. A real supervisor must retain and observe underlying completion.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        The underlying mechanism

        Cancelling a coroutine that waits for a thread does not necessarily stop the running thread. Capacity should follow underlying work, not only the lifetime of its waiter.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A caller timeout can end the response while work still consumes resources. Releasing a permit too early lets replacements exceed the intended active-operation bound.

        Words you will see

        Waiter
        The coroutine waiting for a result.
        Permit
        An accounting token for limited capacity.
        Completion
        The underlying operation has actually stopped running, successfully or otherwise.

        Separate two lifetimes

        The model starts with one running operation and a live caller. Caller cancellation changes waiting to False but leaves running at one. With capacity one, another operation must not start yet. These assignments model state; they are not a real cancellation experiment.

        An awaiter's cancellation may prevent queued work from starting, but it does not forcibly interrupt an arbitrary already-running library call. Establish the exact point at which the adapter started before deciding whether capacity can be released.

        Assign a completion owner

        A supervisor can retain the running operation, observe its late result or exception and release capacity on actual completion. Configure the library's own deadline. During shutdown, stop admission and decide how to drain or account for operations that outlive callers.

        The model's capacity comparison is constant work with a few integer and Boolean values. A real supervisor additionally retains task handles and resources until completion. If cancellation discards every reference, neither a semaphore nor a hopeful timeout describes the real active count.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. capacity = 1

          Allow one underlying operation.

        2. running = 1

          That capacity is occupied.

        3. waiting = False

          Model the caller ceasing to wait, without decrementing running.

        4. print(running < capacity)

          No new work fits until actual completion.

        Cooperative scheduling progresses at await points of operations that actually yield. A synchronous CPU loop does not become nonblocking merely by being inside async def. Moving CPU-heavy Python work to a thread may still contend under a conventional GIL.

        Predict before you run

        Does caller cancellation create available capacity here?

        Cancellation lifetime policy modelPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Model real completion.

        Try: Set running = 0 after waiting = False.

        Admission becomes possible because the underlying count now falls.

        Increase the allowed active bound.

        Try: Change capacity to 2 while keeping running = 1.

        There is room for one more modeled operation, not an unlimited queue.

        Before you move on

        Capacity is two; two threads are active and both callers cancel. How many replacements fit before either thread finishes?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        Zero under an actual-active-work bound. Both operations still occupy capacity. The supervisor must observe their completion before allowing replacements.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Alternatives and operational trade-offs

        Backpressure means declining or delaying new work when capacity is full. A bounded policy must also describe what happens to queued work and late results.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Moving a stall out of the loop can move the failure into memory or worker exhaustion. An explicit admission policy makes that trade-off visible before a burst arrives.

        Words you will see

        Backpressure
        Restraining incoming demand when a downstream resource cannot accept more.
        Admission
        The decision to accept work now.
        Queue bound
        A maximum number of operations retained for later work.

        Choose a visible overload response

        The example models accepted and deferred identifiers without executing any of them. A slice takes the first capacity items; the remaining suffix represents callers that must receive a documented delay or rejection. Keeping that suffix forever would itself be unbounded buffering.

        In production, a queue limit, a timeout and a shutdown policy complement a worker limit. Choose reject, wait with a bound, or durable handoff based on whether the work can safely be retried. Avoid claiming an operation failed if it may already be running.

        Test policy and integration separately

        Policy tests can check zero capacity, repeated IDs and input preservation without a scheduler. The transfer exercise changes the rule: cancelled waiters still consume capacity while their operations remain active. That tests whether lifetime reasoning transfers beyond a simple queue slice.

        Slicing n requests takes O(n) total work and extra reference storage for the two output lists. That is a model cost, not a throughput estimate. Verify actual active counts and controlled heartbeat progress separately in the supported local integration lab.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. requests = ['a', 'b', 'c']

          Supply ordered request identifiers.

        2. capacity = 2

          Set an admission budget, not a thread pool.

        3. accepted = requests[:capacity]

          Copy the admitted prefix.

        4. deferred = requests[capacity:]

          Copy the remainder for an explicit caller policy.

        Prefer a well-behaved async library when possible. Thread offload needs a concurrency cap and does not guarantee running code can be forcibly cancelled. CPU workloads may need a process/native implementation, with serialization and cancellation costs.

        Predict before you run

        Which identifiers are admitted?

        Admission model with an explicit remainderPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Model overload.

        Try: Set capacity = 0.

        accepted becomes empty and deferred retains all three identifiers.

        Check duplicate handling.

        Try: Change requests to ['a', 'a', 'b'].

        Both occurrences of a stay in order; admission does not silently deduplicate.

        Before you move on

        If capacity is zero, should this model drop the three requests silently?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. It returns an empty admitted prefix and all requests in the remainder. The caller must implement a visible reject or bounded-wait policy rather than inventing success.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.