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 65 / INTERVIEW PREPARATION

Interview bank: concurrency and production reasoning

A structured rehearsal with model explanations, evaluation signals and follow-up constraints. These are original representative questions, not a claimed company interview bank.

AdvancedInterview 30 min core+20 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: 30 minutes; optional deep dive: 20 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
  • Explain reasoning before implementation
  • Identify assumptions and edge cases
  • Assess an answer against explicit signals
ORIGINAL REPRESENTATIVE QUESTIONS

Interview rehearsal

30-minute suggested practice budget. No automatic timer or grading. Answer first, then compare the explanation and evaluation signals.

Common representative Python interview themes, not a measured frequency ranking or a claim about a particular company.

1. Choose an execution model for many socket waits, pure-Python CPU calculations, and native numerical kernels. What GIL caveats belong in the answer?

Reveal answer and evaluation signals

Choose from measured workload behavior rather than a blanket rule. Threads can overlap blocking I/O, asyncio can coordinate many cooperative I/O operations, and processes can isolate CPU work at serialization and startup cost. Conventional GIL-enabled CPython does not generally run Python bytecode in parallel across threads, but native extensions may release the GIL.

How it works

Concurrency overlaps progress; parallelism executes work simultaneously. Async tasks run until they await and do not automatically offload blocking calls. Processes have separate heaps, while threads share objects. Optional free-threaded CPython builds beginning with Python 3.13 change GIL assumptions, and extension compatibility or configuration can affect the actual runtime behavior.

Pure workload partition illustration, not a speed testPYTHON 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.

When to choose it and what it costs

Measure blocking time, CPU cost, payload size, and latency objectives before selecting an executor. Bound submitted work and include deployment CPU quotas. Check the actual Python implementation and build rather than inferring GIL behavior from the language name alone.

Pitfalls and edge cases

  • An async function containing blocking CPU work still blocks its event-loop thread.
  • More workers can reduce throughput through contention, serialization, or oversubscription.
Look for
  • Classifies blocking and CPU work
  • Qualifies GIL by implementation and build
  • Includes overhead and isolation

Follow-up: Does a free-threaded CPython build remove the need for application locks?

No. Shared invariants still require synchronization, and free-threaded execution can expose races previously masked by scheduling behavior. Verify library support and use documented synchronization primitives rather than relying on incidental atomicity of individual operations.

Interview-ready takeaway

Match execution model to blocking, CPU, ownership, and deployment constraints; GIL details are runtime-specific rather than universal Python guarantees.

2. Two workers perform a read-modify-write on shared totals. Why is the GIL not an invariant lock, and what should the critical section contain?

Reveal answer and evaluation signals

A logical update often consists of multiple operations whose combined invariant is not protected by an interpreter execution lock. Protect the entire read-check-update sequence with an application lock, or give one worker ownership of the state. Do not rely on a particular bytecode sequence or observed thread schedule for correctness.

How it works

Threads share references and can observe intermediate application states when access is not coordinated. A lock establishes mutually exclusive access for participants that consistently acquire it. Multiple fields forming one invariant need one coherent critical section; individually safe container operations do not make a larger transaction atomic.

Joined workers preserve one shared totalPYTHON 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.

When to choose it and what it costs

Keep critical sections small but complete. Avoid blocking network calls or arbitrary callbacks under a lock when possible. For complex shared state, a single-owner queue or transactional store can make ownership and failure recovery easier than many overlapping locks.

Pitfalls and edge cases

  • A lock protects nothing from code that accesses the same state without acquiring it.
  • Successful stress tests cannot prove the absence of a race across all schedules or interpreter builds.
Look for
  • Identifies compound operation race
  • Locks the full invariant
  • Avoids incidental atomicity claims

Follow-up: Would locking only the assignment be sufficient for a balance transfer?

No. Reading balances, checking available funds, and updating both accounts must be coordinated as one invariant-preserving operation. Protecting only the final assignment permits stale decisions and partial transfers even if each write is individually synchronized.

Interview-ready takeaway

Synchronize application invariants, not isolated lines. Correctness must survive different schedules and runtime builds without relying on the GIL.

3. Two operations acquire account locks in opposite orders. How would you prevent deadlock, and what other blocking risks remain?

Reveal answer and evaluation signals

Impose a global order on resource acquisition and have every operation follow it. Deadlock needs a cycle of waiting; consistent ordering prevents that cycle for the covered locks. Also avoid waiting on futures, callbacks, or external operations while holding locks, because those can create less visible dependency cycles.

How it works

A thread holding lock A while waiting for B can block forever if another holds B while waiting for A. Sorting lock identifiers makes all participants acquire in the same order. Context managers release acquired locks on exceptional exits. Ordering must be global and stable, not independently invented by each call site.

Ordered acquisition without constructing a deadlockPYTHON 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.

When to choose it and what it costs

Document ordering alongside the resource model and centralize acquisition when possible. If dynamic dependencies cannot be ordered, redesign ownership or use a transactional boundary. Timeouts help detect stalled work but require a rollback and retry policy rather than magically preventing inconsistency.

Pitfalls and edge cases

  • Using a timeout without releasing earlier acquisitions can still leak locks.
  • Calling user code under a lock can introduce undocumented lock dependencies and reentrant behavior.
Look for
  • Explains circular wait
  • Uses global lock ordering
  • Addresses exception-safe release

Follow-up: Does replacing Lock with RLock solve cross-thread deadlock?

No. RLock permits the same thread to acquire one lock repeatedly. It does not resolve a cycle in which different threads hold different locks and wait on each other. Ordering and ownership design remain necessary.

Interview-ready takeaway

Prevent wait cycles with consistent ordering and scoped release; reentrancy, timeouts, and stress tests do not replace a dependency model.

4. An asyncio request is cancelled while waiting for work. How should it clean up without converting cancellation into successful completion?

Reveal answer and evaluation signals

Cancellation is delivered cooperatively at suspension points as CancelledError. Put owned-resource cleanup in finally, and normally allow cancellation to propagate. If catching CancelledError for diagnostics or cleanup, re-raise it after finishing. A cancellation request is not proof that arbitrary external work was stopped or rolled back.

How it works

Task.cancel requests that a cancellation exception be injected when the coroutine resumes. A task may need to execute cleanup before it completes. Awaiting the cancelled task observes that completion. A coroutine performing long synchronous work cannot respond promptly because it has not returned control to the event loop.

Cancel only after deterministic readinessPYTHON 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.

When to choose it and what it costs

Give cleanup a bounded policy and identify resources owned by the cancelled scope. For remote writes, record an uncertain outcome and reconcile through an idempotency or status protocol. Do not label cancellation as failure-before-commit unless the external system guarantees that.

Pitfalls and edge cases

  • Swallowing cancellation can break TaskGroup and timeout behavior.
  • Repeated cancellation can interrupt awaited cleanup, so complex cleanup needs an explicit bounded strategy.
Look for
  • Explains cooperative delivery
  • Preserves CancelledError
  • Separates local cancellation from remote effects

Follow-up: When is shield useful, and what does it not guarantee?

shield can prevent a caller's cancellation from automatically cancelling a particular inner awaitable. The caller still receives cancellation, the inner task needs retained ownership, and shielding does not guarantee completion after process termination or protect remote consistency.

Interview-ready takeaway

Cancellation is a cooperative control signal, not rollback. Clean up owned state, await termination, and preserve uncertainty about external effects.

5. An async producer outpaces its consumers. How does a bounded queue apply backpressure, and why is queue length alone not a complete memory limit?

Reveal answer and evaluation signals

A bounded asyncio.Queue makes put await when capacity is exhausted, slowing a cooperating producer. This controls queued item count, not item byte size or work already held by producers and consumers. Bound concurrency and payload size as well, and define overload behavior when upstream cannot safely wait.

How it works

Each successful queue put increments unfinished-work accounting, and task_done decrements it. join waits until that accounting reaches zero. A sentinel can signal normal consumer shutdown, but it is still an enqueued item and must follow the same accounting discipline. Queue capacity does not automatically limit tasks created before they try to enqueue.

Bounded FIFO with accounted shutdownPYTHON 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.

When to choose it and what it costs

Choose capacity from payload size, acceptable queueing latency, and downstream throughput. Decide whether overload should wait, reject, shed low-priority work, or spill to a bounded durable broker. Instrument queue age and in-flight work, not only current depth.

Pitfalls and edge cases

  • Creating unlimited tasks around queue.put merely moves unbounded buffering into tasks.
  • Calling task_done before work is actually complete makes join misleading.
Look for
  • Explains awaited bounded put
  • Counts in-flight and buffered work
  • Defines overload and shutdown policy

Follow-up: What do task_done and join establish?

They establish that each accepted queue item has been marked complete by application code. They do not prove a remote transaction committed, that processing was correct, or that durable delivery exists after a crash.

Interview-ready takeaway

Backpressure must cover the whole pipeline. Queue capacity, payload budgets, worker limits, accounting, and overload policy are separate controls.

6. A long-running service's memory grows even after requests finish. How would you distinguish retained references, cycles, and allocator behavior?

Reveal answer and evaluation signals

Start with reproducible workloads and compare retained allocations, object ownership, and process memory rather than assuming every increase is a leak. Caches, queues, and callbacks may deliberately retain objects. Cyclic garbage collection handles some unreachable cycles, while freed Python objects do not guarantee immediate release of all allocator pages to the operating system.

How it works

Conventional CPython combines reference counting with cyclic garbage collection. Other implementations may use different strategies, so portable logic should not rely on immediate destruction. A strong reference from a global cache keeps an object reachable regardless of collection. Weak references permit observation without ownership, while tracemalloc helps attribute many Python allocations but is not a complete native-memory profiler.

An unreachable cycle and a weak observerPYTHON 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.

When to choose it and what it costs

Capture bounded allocation snapshots around equivalent workload phases and inspect retaining paths. Track native allocations and RSS separately when extensions are involved. Set cache and queue budgets before tuning collection thresholds, and avoid forcing frequent collection as a substitute for finding owners.

Pitfalls and edge cases

  • An object count increase does not reveal retained byte size by itself.
  • Finalizers and external resource release need explicit lifecycle management rather than reliance on collection timing.
Look for
  • Separates reachability and RSS
  • Uses bounded allocation evidence
  • Avoids collection-timing assumptions

Follow-up: Why is sys.getsizeof insufficient to estimate the full size of a nested structure?

getsizeof usually reports the object's own shallow storage, not recursively referenced objects. Recursive accounting must avoid double-counting shared references and cycles, and still may not include native buffers or allocator overhead.

Interview-ready takeaway

Diagnose ownership and allocation layers separately. Reachability, garbage collection, Python allocation traces, and operating-system memory describe different phenomena.

7. A microbenchmark claims a loop optimization is twice as fast. What evidence would you require before changing a production algorithm?

Reveal answer and evaluation signals

Verify equal semantics, representative inputs, repeated measurements, environment details, and end-to-end relevance. Profile first to locate meaningful cost. Distinguish algorithmic improvements from interpreter artifacts, warm caches, setup costs, or noise. Report distributions and uncertainty rather than treating one elapsed value as a universal performance fact.

How it works

Profiling attributes observed execution to functions or call paths and adds overhead. Benchmarking compares defined work under controlled conditions. A repeated linear membership scan performs more comparisons as both input dimensions grow, whereas building a set pays construction and hashing costs once. Operation counts can demonstrate the algorithmic difference without pretending to measure real elapsed speed.

Deterministic work-count illustrationPYTHON 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.

When to choose it and what it costs

Use cProfile for suitable function-level questions, timeit for isolated operations with controlled setup, and load tests for latency and throughput under concurrency. Record Python build and dependencies, including whether free-threading or native acceleration affects execution.

Pitfalls and edge cases

  • Benchmarking only successful early matches understates worst-case list scans.
  • Removing validation or changing ordering can make code faster by silently doing different work.
Look for
  • Checks equivalent work
  • Separates profiling and benchmarking
  • Controls setup and workload bias

Follow-up: Why can a lower asymptotic complexity still lose on a small input?

Constant factors, allocation, cache locality, and setup overhead dominate small cases. A set is valuable across enough lookups, but constructing it for one tiny search may cost more. Measure the actual size distribution and reuse pattern.

Interview-ready takeaway

Performance evidence requires equivalent semantics and representative conditions. Complexity guides hypotheses, while profiling and careful measurement decide practical tradeoffs.

8. A client times out after a payment-like write may already have committed. How can an idempotency key make retries safer without claiming exactly-once execution?

Reveal answer and evaluation signals

Record an idempotency key, a request fingerprint, and the committed result at the same durable boundary as the effect. A repeated matching request returns the recorded outcome; reuse with different content must be rejected. A timeout is an uncertain outcome, not proof of failure, and retries may execute more than once internally.

How it works

Idempotency concerns observable effects under repetition, not the number of handler invocations. Atomic coordination prevents a crash window between the effect and its deduplication record. Concurrent claims require uniqueness or conditional insertion. Retention and key scope must cover the retry horizon, and external side effects may need a transactional outbox or a cooperating downstream key.

In-memory uncertain-response model, not durable storagePYTHON 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.

When to choose it and what it costs

Specify key ownership, authorization scope, expiry, in-progress handling, and replayed response semantics. Reconcile uncertain outcomes before issuing a new key. Test crashes at transaction boundaries and duplicate concurrent submissions in the real persistence layer.

Pitfalls and edge cases

  • A process-local dictionary loses deduplication state on restart.
  • Using only a key without checking request content can replay an unrelated operation's result.
Look for
  • Models uncertain commit
  • Binds key to request content
  • Requires durable atomic boundary

Follow-up: What breaks if the effect commits before the idempotency record is saved?

A crash between those steps permits the retry to repeat the effect. Store them atomically where possible, or use a recovery protocol with durable intent, downstream idempotency, and reconciliation rather than asserting exactly-once delivery.

Interview-ready takeaway

Retries need stable identity and durable outcome tracking. Separate invocation count, committed effects, response delivery, and uncertainty.

9. A service proposes accepting pickled job objects from users because they preserve Python types. What safer boundary would you design?

Reveal answer and evaluation signals

Do not unpickle untrusted data: reconstruction can execute code. Accept a constrained data format such as JSON with explicit schema, version, limits, and authorization. Resolve a small allowlisted operation name to trusted local code instead of letting the input specify arbitrary Python classes, module paths, or callables.

How it works

Pickle is a Python object reconstruction protocol with capabilities beyond passive data parsing. JSON has a narrower data model but still needs size, type, and semantic checks. Even validated data must not be handed to eval, arbitrary import, shell execution, or an unrestricted dispatcher. A serialization format does not establish permission to perform an operation.

Allowlisted operation dispatch over validated dataPYTHON 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.

When to choose it and what it costs

Use data-only interchange across trust boundaries and minimize accepted shapes. For internal trusted snapshots that use pickle, explicitly document the trust assumption, producer controls, version compatibility, and storage integrity rather than exposing the format as a public API.

Pitfalls and edge cases

  • JSON schema validation does not make later eval or dynamic import safe.
  • A trusted signature cannot compensate for a compromised signer or an overly powerful producer.
Look for
  • Recognizes executable deserialization
  • Uses constrained schema
  • Separates authenticity and safety

Follow-up: Does signing a pickle make it universally safe to load?

It authenticates a producer under key-management assumptions, not the harmlessness of the encoded reconstruction. Load only when that producer is trusted to execute code in the consumer's environment; otherwise choose a constrained data protocol.

Interview-ready takeaway

Serialization safety depends on reconstruction power, trust, validation, and authorization. Prefer narrow data contracts over arbitrary object transport.

10. How do parameterized SQL statements protect values, and why can table names or ORDER BY directions not simply be passed as value parameters?

Reveal answer and evaluation signals

Bind data values through the database driver's parameter mechanism so they remain values rather than SQL syntax. Identifiers and keywords are part of statement structure and normally require a fixed query or strict allowlist. Parameterization prevents one injection class but does not establish authorization, correct transactions, or safe resource usage.

How it works

The driver binds parameters using its database protocol rather than concatenating user text into the SQL grammar. Placeholder syntax differs across drivers. The example uses sqlite3's question-mark placeholders and a trusted mapping for a sort choice. An in-memory connection demonstrates the boundary without touching disk or an external database.

Bound values and allowlisted SQL structurePYTHON 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.

When to choose it and what it costs

Keep statements fixed where practical and bind every external value. For dynamic structure, map a finite public option to trusted SQL fragments. Apply tenant and access predicates consistently, use least-privilege database roles, and bound result sizes and execution cost.

Pitfalls and edge cases

  • Escaping by manually replacing quote characters is not a substitute for driver binding.
  • Parameters do not turn an arbitrary column name into an identifier; they typically represent a literal value.
Look for
  • Separates values from syntax
  • Uses allowlists for structural choices
  • Includes transaction and authorization boundaries

Follow-up: Can a safely parameterized query still expose another tenant's rows?

Yes. A missing tenant filter or incorrect authorization policy can leak rows even when every parameter is bound safely. Injection prevention and data-access control are independent requirements and need separate tests.

Interview-ready takeaway

Bind values, constrain structure, and test authorization separately. Safe SQL composition is necessary but not a complete data-security boundary.

11. A feed ordered by score has duplicates and concurrent inserts. Design keyset pagination and explain the consistency guarantee it does not provide.

Reveal answer and evaluation signals

Use a total stable order such as (score, unique_id), and encode both fields in the cursor. The next page selects keys strictly beyond the last returned key under that order. This avoids many offset-shift problems, but it does not create a consistent snapshot if scores or eligible records change between requests.

How it works

Offset pagination counts rows from the beginning, so inserts and deletions before the offset can shift boundaries. Keyset pagination resumes after a concrete ordered key. A unique tie-breaker prevents skipping equal-score rows. Real database performance depends on compatible indexes, query direction, null handling, and filters, none of which a Python list demonstration measures.

Ascending composite keyset illustrationPYTHON 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.

When to choose it and what it costs

Specify whether the interface promises a live feed, a versioned snapshot, or best-effort traversal. If ordering fields can change, freeze them for a session or use snapshot/version mechanisms. Align indexes with filters and the full cursor order.

Pitfalls and edge cases

  • A score-only cursor can skip records tied at the page boundary.
  • An unsigned or unvalidated cursor can let clients change filters or request expensive scans.
Look for
  • Defines total composite order
  • Uses strict cursor comparison
  • Explains mutation and snapshot limits

Follow-up: What belongs in an opaque cursor besides the last key?

Include format version, ordering direction, filter identity, and any snapshot identifier or expiry required by the contract. Authenticate cursor contents when tampering matters, while still performing authorization on every page; opacity is not permission.

Interview-ready takeaway

Keyset pagination needs a total order and validated cursor contract. Stable traversal under mutation requires an additional consistency mechanism.

12. How would you test retries and timeouts operationally without sleeping, contacting services, or making a flaky timing assertion?

Reveal answer and evaluation signals

Inject the operation, clock, and waiting policy, then drive a deterministic sequence of outcomes. Assert attempt budgets, retry classification, delays requested, and final results or failures. Test ambiguous writes separately from safe reads. Integration tests should later verify that the real adapter honors deadlines and cancellation under controlled fault injection.

How it works

A retry controller is a state machine over attempts, outcomes, and remaining budget. A fake wait function can record intended delays without changing wall time. This proves policy logic but not scheduler behavior, socket timeouts, or downstream idempotency. Those boundaries need independent operational tests and observability with safe synthetic traffic.

Finite retry policy with an injected waitPYTHON 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.

When to choose it and what it costs

Classify retryable failures explicitly, cap attempts and elapsed budget, and honor upstream deadlines. Instrument attempts, exhausted budgets, and uncertain outcomes without logging sensitive payloads. Prevent retries at multiple layers from multiplying into an uncontrolled request storm.

Pitfalls and edge cases

  • Retrying every exception can repeatedly execute permanent failures or programming bugs.
  • A timeout after a write does not establish that the write failed.
Look for
  • Injects nondeterministic boundaries
  • Bounds attempts and total budget
  • Tests permanent and transient failures

Follow-up: Why add jitter in a real retry policy if deterministic tests use fixed delays?

Jitter spreads retry load so many clients do not synchronize their next attempts after a shared outage. Inject a seeded or scripted jitter source in tests and assert delay bounds and budgets instead of exact production randomness.

Interview-ready takeaway

Deterministic policy tests replace clocks and faults, not real boundary certification. Operational correctness includes budgets, classification, uncertainty, and observability.

13. Several async subtasks form one request. How does TaskGroup change failure handling compared with launching tasks and forgetting them?

Reveal answer and evaluation signals

TaskGroup gives child tasks a lexical lifetime: the scope waits for them and coordinates sibling cancellation when a child fails. Failures can be reported as an exception group, so callers should handle appropriate subsets deliberately. Detached tasks lack this automatic ownership and can outlive the request or lose observable failures.

How it works

An async with TaskGroup scope owns its created tasks. A non-cancellation failure triggers cancellation of remaining children and waits for their cleanup before leaving. Multiple failures may be grouped, and except* selects matching exception subsets. Cooperative cleanup and cancellation propagation are therefore essential for predictable group termination.

Group failure waits for sibling cleanupPYTHON 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.

When to choose it and what it costs

Use structured concurrency when child work belongs to one operation. For genuine background work, assign a separate lifecycle owner with shutdown, error reporting, and bounded admission. Decide which grouped failures are expected and let unhandled subsets remain visible.

Pitfalls and edge cases

  • Swallowing CancelledError in a child can delay or break group shutdown.
  • Handling one exception subset does not imply unrelated failures in the same group were handled.
Look for
  • Explains scoped task ownership
  • Understands sibling cancellation
  • Handles exception groups deliberately

Follow-up: Does TaskGroup roll back effects completed by a sibling before another child fails?

No. TaskGroup coordinates task lifetimes, not business transactions. Completed external effects require idempotency, compensation, or a transactional design. Cancellation of remaining siblings cannot retroactively undo a write that already committed.

Interview-ready takeaway

TaskGroup makes ownership and failure propagation explicit. Structured task lifetime is valuable but does not supply transactional rollback.

14. A process pool works locally but fails after deployment on another OS. What startup, serialization, and resource assumptions should be reviewed?

Reveal answer and evaluation signals

Do not assume workers inherit a usable parent state. Process start methods vary by OS and Python version, and spawn-style startup imports modules afresh. Worker functions and transferred arguments must satisfy the chosen serialization model. Protect executable entry points and explicitly manage worker count, shutdown, and external resource initialization.

How it works

Separate processes have independent Python heaps and communicate through serialized messages or explicit shared-memory mechanisms. Spawn requires reconstructing callable references and data in a new interpreter. Fork can inherit state that is unsafe to reuse, especially locks and library resources. Actual process, file-descriptor, and memory limits belong to the deployment environment, not this pure illustration.

Message boundary illustration, not a process launchPYTHON 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.

When to choose it and what it costs

Use small importable worker entry points and a main guard for executable startup. Initialize per-worker resources explicitly, bound queued tasks, and test the actual supported start method in a controlled environment. Include serialization and memory duplication costs in capacity planning.

Pitfalls and edge cases

  • Local closures and lambdas often cannot be sent through standard multiprocessing pickle paths.
  • Worker count based only on host CPU count can ignore container quotas and per-worker memory.
Look for
  • Acknowledges start-method variation
  • Uses importable worker functions
  • Accounts for serialization and OS limits

Follow-up: Why should database connections generally be initialized per worker rather than casually inherited?

Connection objects may contain sockets, locks, transaction state, and protocol buffers that are unsafe to share across process boundaries. Follow the driver's documented lifecycle and create or reconnect in each worker rather than assuming inherited state is valid.

Interview-ready takeaway

Process isolation changes startup and ownership contracts. Validate real deployment boundaries separately from a deterministic message-passing model.

15. Two users edit the same document from version 4. How can optimistic concurrency reject a lost update, and how is that different from idempotency?

Reveal answer and evaluation signals

Attach a version to the record and atomically update only if the stored version matches the caller's expected version. One edit advances the version; a competing stale edit receives a conflict. Idempotency detects repetition of one logical request, while optimistic concurrency detects incompatible updates based on an outdated state.

How it works

A read followed by an unconditional write permits the second writer to overwrite the first writer's changes. A conditional update combines checking and mutation at the storage boundary. The affected-row count or equivalent result identifies whether the expected version matched. A separate idempotency key can coexist with version checking to resolve response-loss retries.

Sequential model of a conditional updatePYTHON 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.

When to choose it and what it costs

Use optimistic concurrency where conflicts are relatively uncommon and users can merge or retry meaningful operations. Return enough safe state to support reconciliation. For invariants spanning several records, use appropriate transactions or stronger coordination instead of assuming one version field covers everything.

Pitfalls and edge cases

  • Checking version in application code and issuing a separate unconditional database update reintroduces the race.
  • A timestamp may lack the precision or monotonicity needed for a reliable version token.
Look for
  • Uses compare-and-swap semantics
  • Distinguishes conflict from duplicate
  • Requires atomic storage enforcement

Follow-up: Should the client automatically retry a conflict with the new version?

Not blindly. Reload the latest state and reapply only an operation whose semantics remain valid. Replacing the whole document with stale content under a fresh version defeats conflict detection. User-visible merge or domain-specific reconciliation may be required.

Interview-ready takeaway

Version checks prevent lost updates; idempotency prevents duplicate logical effects. Both need atomic persistence and clearly defined client recovery.

01

Run an honest rehearsal

A senior rehearsal begins with workload and ownership constraints. Concurrency overlaps progress; parallelism runs work at the same time.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

An executor choice depends on blocking, CPU work, payload transfer and deployment limits, not on a claim that one model is always faster.

Words you will see

Blocking I/O
Waiting for an external operation while the current thread cannot continue that call.
CPU-bound
Spending most work on computation rather than waiting.
Backpressure
Making producers slow down when downstream capacity is full.

Classify before proposing workers

The sample classifies explicitly supplied descriptions; it does not inspect or time a workload. Socket waits are candidates for bounded threads or cooperative async I/O. Pure-Python CPU calculations are candidates for processes when transfer and startup costs are justified.

A conventional GIL-enabled CPython build generally does not run Python bytecode in parallel across threads. Native extensions may release the GIL, and free-threaded builds change that constraint. Check the actual implementation, build and libraries before giving a performance answer.

Make ownership and failure part of the choice

Threads share objects and require a discipline for shared invariants. Processes use separate heaps and message boundaries; payloads must be transferable and costs include serialisation. Async code shares an event-loop thread and must not hide blocking work inside async def.

Bound both queued work and active work. A queue length alone does not bound total bytes if items vary in size or workers retain additional state. Choose measurements for throughput, latency, memory and cancellation instead of presenting this deterministic label table as benchmark evidence.

The original example, step by step

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

  1. choices = {"socket wait": "bounded I/O overlap", "Python CPU": "consider process isolation", "native kernel": "check GIL and library behaviour"}

    Store stated candidate decisions, not runtime measurements.

  2. for workload, choice in choices.items():

    Visit each explicit workload category in insertion order.

  3. print(workload + ": " + choice)

    Explain each candidate with a readable label.

  4. print(len(choices))

    Count categories, not workers or seconds.

Answer without the model response first. State your assumptions, give a small example and discuss an edge case. The suggested time is a practice budget, not an automatic timer, proctoring claim or hiring-readiness prediction.

Conceptual executor decision, not a speed comparison

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

  1. WorkloadIdentify waits, Python CPU or native kernels.
  2. BoundaryState shared state, message size and cancellation ownership.
  3. EvidenceMeasure bounded implementations under actual CPU and memory limits.
Predict before you run

What does the last number measure?

Classify a workload without inventing timingsPYTHON 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.

Add a new category.

Try: Add 'mixed work': 'measure each stage' to choices.

A fourth decision line appears and the count becomes four; no speed claim follows.

Change display order.

Try: Iterate sorted(choices.items()) instead.

Labels print in sorted order but the workload recommendations and category count stay unchanged.

Before you move on

An async function performs a long pure-Python calculation before any await. Does creating more tasks automatically parallelise that calculation?

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. That calculation blocks its event-loop thread. Consider bounded offloading or a different algorithm, then measure transfer and execution costs in the deployment.

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

Use the rubric, not keyword matching

A retry policy is a bounded state machine. A deadline must account for accumulated waiting and attempts, not just label every delay as small.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Repeatedly retrying a timed-out write may repeat an effect that already committed. Policy, idempotency and operational tests must be discussed separately.

Words you will see

Budget
The maximum cost allowed by a policy.
Attempt
One invocation of the operation.
Idempotency key
A stable request identifier used to recognise a repeated logical operation.

Trace the remaining budget

The policy starts with five units. Waiting two leaves three. Waiting three leaves zero. Waiting one would exceed the budget, so it is not added. The result is a plan, not actual sleeping or an elapsed-time measurement.

A real deadline must also include operation duration, scheduling and a monotonic clock. Limit attempts as well as total elapsed time. Inject the clock and wait function in tests so a timeout case does not require flaky real sleeping.

Discuss uncertain side effects

A client timeout does not prove the server rolled back. Retrying a write needs a documented idempotency-key scope, payload match and durable result handling. An in-memory dictionary illustration does not establish distributed exactly-once execution.

For n proposed delays, a prefix scan takes O(n) worst-case work and O(n) returned storage. It stops at the first delay that does not fit; skipping that delay to try later shorter waits is a different policy. State that choice explicitly.

The original example, step by step

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

  1. budget = 5

    Start with a fixed waiting budget.

  2. if delay > budget:

    Test the next cost against the remaining capacity.

  3. accepted.append(delay)

    Commit this accepted policy step.

  4. budget -= delay

    Carry reduced capacity into the next iteration.

An answer can be correct without matching the model wording. Evaluate whether the reasoning establishes the contract and handles follow-ups. A self-rating or revealed answer must not become an independently judged coding pass.

Predict before you run

Which delays are accepted?

A deterministic retry-budget 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.

Change one thing; explain the difference.

Allow one more unit.

Try: Set budget = 6.

All three waits fit and the remaining budget is zero.

Put a large wait first.

Try: Change delays to [6, 1, 1].

No delay is accepted; this policy does not skip the first rejected proposal.

Before you move on

For proposed waits [4, 2, 1] and budget five, which prefix fits this stop-at-first-overflow policy?

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

Only [4]. The two-unit wait does not fit the remaining one, so the scan stops and never considers the later one.

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

Pure workload partition illustration, not a speed test

Before distributing a computation, show that partitioning preserves its result. That proves a correctness precondition, not a speedup.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The original senior example computes a sum of squares in one piece and in two partitions without creating any workers.

Words you will see

Partition
A subset of the work assigned to one part of a computation.
Reduction
Combining partial results into one result.
Serialisation cost
The work and storage needed to encode values for a process boundary.

Trace the original reduction

range(8) supplies zero through seven. Squaring and summing gives 140. The two slices contain zero through three and four through seven. Each number appears exactly once, so adding their square sums also gives 140.

The empty list contributes zero, which is the identity for addition. Duplicating an element or omitting a partition changes the work and can invalidate the result. A test of equivalent results must precede any executor benchmark.

Name the costs the illustration omits

The program makes slices and executes sequentially. It contains no pool, process startup, transfer, cancellation or capacity measurement. Those costs can dominate small workloads, so do not interpret matching output as parallel speedup.

For n inputs the arithmetic uses O(n) operations. The two slices allocate O(n) reference slots in total. Processes have separate heaps and transfer contracts; threads share state. Integer arithmetic also grows with operand bit length, and different reductions such as floating-point sums can have order-sensitive rounding.

The original example, step by step

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

  1. return sum(value * value for value in values)

    Compute a pure sum with no shared mutation.

  2. partitions = [values[:4], values[4:]]

    Cover every input once with two separately allocated slices.

  3. combined = sum(calculate(part) for part in partitions)

    Reduce both partial results into one total.

  4. print(calculate([]))

    Verify zero as the empty partition's contribution.

Partitioned pure computation preserves the result, demonstrating a prerequisite for distributing CPU work. This example intentionally creates no workers and makes no performance or OS-capacity claim. Real parallel speedup also depends on overhead, memory traffic, and available CPU allocation.

Predict before you run

Why do the first two prints both show 140?

Pure workload partition illustration, not a speed testPYTHON 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 split point only.

Try: Use values[:2] and values[2:].

Both totals stay 140 because coverage is unchanged.

Introduce overlap.

Try: Use values[:4] and values[3:].

The combined total becomes 149, exposing duplicated work.

Before you move on

If partitions overlap at value three, can their reduction still be assumed equivalent?

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. Three squared is counted twice, so the combined result increases by nine. Correct partition coverage requires neither omissions nor unintended overlap.

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

Can you explain it?

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

What is the strongest next step after reading a model answer?
TRANSFER THE IDEA

Explain and implement

Predict the worked example before running it locally, then change one boundary input and explain the result without 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: plan a bounded retry prefix

Model the waiting portion of a retry policy without sleeping or calling a service.

The contract

  • delays is a finite list of nonnegative exact integers; budget is a nonnegative exact integer.
  • Return the longest prefix whose cumulative sum is at most budget. Stop at the first delay that does not fit; preserve zero delays and duplicates.
  • Return a fresh list and preserve delays. This is a waiting-cost model, not a real elapsed deadline, attempt executor or exactly-once guarantee.
Guided: plan a bounded retry prefixPYTHON 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. exact cumulative
    from copy import deepcopy
    source = [2, 3, 1]
    before = deepcopy(source)
    result = retry_plan(source, 5)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [2, 3]
    assert result == expected, "Wrong result value"
    def same_types(actual, expected):
        if type(actual) is not type(expected):
            return False
        if type(expected) in (list, tuple):
            return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
        if type(expected) is dict:
            return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
        return True
    assert same_types(result, expected), "Wrong nested result type"
    assert result is not source, "Result aliases caller input"
    
  2. empty
    from copy import deepcopy
    source = []
    before = deepcopy(source)
    result = retry_plan(source, 5)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = []
    assert result == expected, "Wrong result value"
    def same_types(actual, expected):
        if type(actual) is not type(expected):
            return False
        if type(expected) in (list, tuple):
            return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
        if type(expected) is dict:
            return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
        return True
    assert same_types(result, expected), "Wrong nested result type"
    assert result is not source, "Result aliases caller input"
    
  3. zero budget
    from copy import deepcopy
    source = [0, 0, 1, 0]
    before = deepcopy(source)
    result = retry_plan(source, 0)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [0, 0]
    assert result == expected, "Wrong result value"
    def same_types(actual, expected):
        if type(actual) is not type(expected):
            return False
        if type(expected) in (list, tuple):
            return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
        if type(expected) is dict:
            return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
        return True
    assert same_types(result, expected), "Wrong nested result type"
    assert result is not source, "Result aliases caller input"
    
  4. stop not skip
    from copy import deepcopy
    source = [4, 2, 1]
    before = deepcopy(source)
    result = retry_plan(source, 5)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [4]
    assert result == expected, "Wrong result value"
    def same_types(actual, expected):
        if type(actual) is not type(expected):
            return False
        if type(expected) in (list, tuple):
            return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
        if type(expected) is dict:
            return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
        return True
    assert same_types(result, expected), "Wrong nested result type"
    assert result is not source, "Result aliases caller input"
    
  5. first too large
    from copy import deepcopy
    source = [6, 1]
    before = deepcopy(source)
    result = retry_plan(source, 5)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = []
    assert result == expected, "Wrong result value"
    def same_types(actual, expected):
        if type(actual) is not type(expected):
            return False
        if type(expected) in (list, tuple):
            return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
        if type(expected) is dict:
            return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
        return True
    assert same_types(result, expected), "Wrong nested result type"
    assert result is not source, "Result aliases caller input"
    
  6. repeated waits
    from copy import deepcopy
    source = [2, 2, 2]
    before = deepcopy(source)
    result = retry_plan(source, 4)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [2, 2]
    assert result == expected, "Wrong result value"
    def same_types(actual, expected):
        if type(actual) is not type(expected):
            return False
        if type(expected) in (list, tuple):
            return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
        if type(expected) is dict:
            return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
        return True
    assert same_types(result, expected), "Wrong nested result type"
    assert result is not source, "Result aliases caller input"
    
    What is still needed for a production retry deadline?

    Include operation duration, a monotonic injected clock, bounded attempts, cancellation and uncertain side effects. An idempotency protocol must handle committed writes. This prefix model uses O(n) worst-case work and output storage.

    GUIDED PRACTICE

    Guided: retain score ties in a page

    Return an ascending page after a complete score-and-ID cursor, without sorting the caller's list in place.

    The contract

    • rows is a finite list of unique (integer score, string ID) tuples; scores may repeat and input order is arbitrary.
    • cursor is None or a complete (score, ID) tuple; return up to nonnegative limit rows in ascending composite-key order, strictly after cursor.
    • Return a new list, never mutate rows; empty input or limit zero returns []. A cursor is not a snapshot under concurrent updates.
    Guided: retain score ties in a pagePYTHON 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. score tie
      from copy import deepcopy
      source = [(11, 'c'), (10, 'b'), (10, 'a')]
      before = deepcopy(source)
      result = page_after(source, (10, 'a'), 2)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = [(10, 'b'), (11, 'c')]
      assert result == expected, "Wrong result value"
      def same_types(actual, expected):
          if type(actual) is not type(expected):
              return False
          if type(expected) in (list, tuple):
              return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
          if type(expected) is dict:
              return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
          return True
      assert same_types(result, expected), "Wrong nested result type"
      assert result is not source, "Result aliases caller input"
      
    2. empty
      from copy import deepcopy
      source = []
      before = deepcopy(source)
      result = page_after(source, None, 2)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = []
      assert result == expected, "Wrong result value"
      def same_types(actual, expected):
          if type(actual) is not type(expected):
              return False
          if type(expected) in (list, tuple):
              return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
          if type(expected) is dict:
              return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
          return True
      assert same_types(result, expected), "Wrong nested result type"
      assert result is not source, "Result aliases caller input"
      
    3. first page
      from copy import deepcopy
      source = [(2, 'b'), (1, 'z'), (2, 'a')]
      before = deepcopy(source)
      result = page_after(source, None, 2)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = [(1, 'z'), (2, 'a')]
      assert result == expected, "Wrong result value"
      def same_types(actual, expected):
          if type(actual) is not type(expected):
              return False
          if type(expected) in (list, tuple):
              return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
          if type(expected) is dict:
              return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
          return True
      assert same_types(result, expected), "Wrong nested result type"
      assert result is not source, "Result aliases caller input"
      
    4. zero limit
      from copy import deepcopy
      source = [(1, 'a')]
      before = deepcopy(source)
      result = page_after(source, None, 0)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = []
      assert result == expected, "Wrong result value"
      def same_types(actual, expected):
          if type(actual) is not type(expected):
              return False
          if type(expected) in (list, tuple):
              return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
          if type(expected) is dict:
              return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
          return True
      assert same_types(result, expected), "Wrong nested result type"
      assert result is not source, "Result aliases caller input"
      
    5. past end
      from copy import deepcopy
      source = [(1, 'a'), (1, 'b')]
      before = deepcopy(source)
      result = page_after(source, (2, 'a'), 4)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = []
      assert result == expected, "Wrong result value"
      def same_types(actual, expected):
          if type(actual) is not type(expected):
              return False
          if type(expected) in (list, tuple):
              return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
          if type(expected) is dict:
              return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
          return True
      assert same_types(result, expected), "Wrong nested result type"
      assert result is not source, "Result aliases caller input"
      
    6. negative scores
      from copy import deepcopy
      source = [(-1, 'b'), (-2, 'z'), (-1, 'a'), (0, 'c')]
      before = deepcopy(source)
      result = page_after(source, (-1, 'a'), 8)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = [(-1, 'b'), (0, 'c')]
      assert result == expected, "Wrong result value"
      def same_types(actual, expected):
          if type(actual) is not type(expected):
              return False
          if type(expected) in (list, tuple):
              return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
          if type(expected) is dict:
              return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
          return True
      assert same_types(result, expected), "Wrong nested result type"
      assert result is not source, "Result aliases caller input"
      
      What does this list model prove, and what does it not prove?

      It tests complete ordering and continuation without input mutation. Sorting n rows costs O(n log n) comparison work and O(n) storage. It proves neither indexed database cost nor a consistent snapshot during concurrent changes.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: make a pure conditional-update model

      Reject a stale writer and return an independent proposed record. Keep comparison and state transition visible.

      The contract

      • record is a flat dictionary with exact integer version >= 0 and string title; expected is an integer and title is a string.
      • Return (accepted_bool, fresh_record). On a matching version set title and increment version once; otherwise preserve all record fields.
      • Never mutate or return the caller's dictionary. This sequential pure model is not an atomic store operation or an idempotency implementation.
      Transfer: make a pure conditional-update 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.

      Inspect 6 public checks

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

      1. accepted
        from copy import deepcopy
        source = {'version': 4, 'title': 'draft'}
        before = deepcopy(source)
        result = versioned_update(source, 4, 'first')
        assert type(result) is tuple, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = (True, {'version': 5, 'title': 'first'})
        assert result == expected, "Wrong result value"
        def same_types(actual, expected):
            if type(actual) is not type(expected):
                return False
            if type(expected) in (list, tuple):
                return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
            if type(expected) is dict:
                return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
            return True
        assert same_types(result, expected), "Wrong nested result type"
        assert type(result[0]) is bool and type(result[1]) is dict, "Wrong transition component types"
        assert result[1] is not source, "Returned record aliases caller"
        result[1]["title"] = "caller edits result"
        assert source == before, "Returned record leaked ownership"
        
      2. stale
        from copy import deepcopy
        source = {'version': 5, 'title': 'first'}
        before = deepcopy(source)
        result = versioned_update(source, 4, 'second')
        assert type(result) is tuple, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = (False, {'version': 5, 'title': 'first'})
        assert result == expected, "Wrong result value"
        def same_types(actual, expected):
            if type(actual) is not type(expected):
                return False
            if type(expected) in (list, tuple):
                return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
            if type(expected) is dict:
                return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
            return True
        assert same_types(result, expected), "Wrong nested result type"
        assert type(result[0]) is bool and type(result[1]) is dict, "Wrong transition component types"
        assert result[1] is not source, "Returned record aliases caller"
        result[1]["title"] = "caller edits result"
        assert source == before, "Returned record leaked ownership"
        
      3. zero version empty title
        from copy import deepcopy
        source = {'version': 0, 'title': ''}
        before = deepcopy(source)
        result = versioned_update(source, 0, 'new')
        assert type(result) is tuple, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = (True, {'version': 1, 'title': 'new'})
        assert result == expected, "Wrong result value"
        def same_types(actual, expected):
            if type(actual) is not type(expected):
                return False
            if type(expected) in (list, tuple):
                return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
            if type(expected) is dict:
                return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
            return True
        assert same_types(result, expected), "Wrong nested result type"
        assert type(result[0]) is bool and type(result[1]) is dict, "Wrong transition component types"
        assert result[1] is not source, "Returned record aliases caller"
        result[1]["title"] = "caller edits result"
        assert source == before, "Returned record leaked ownership"
        
      4. future precondition
        from copy import deepcopy
        source = {'version': 2, 'title': 'old'}
        before = deepcopy(source)
        result = versioned_update(source, 3, 'future')
        assert type(result) is tuple, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = (False, {'version': 2, 'title': 'old'})
        assert result == expected, "Wrong result value"
        def same_types(actual, expected):
            if type(actual) is not type(expected):
                return False
            if type(expected) in (list, tuple):
                return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
            if type(expected) is dict:
                return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
            return True
        assert same_types(result, expected), "Wrong nested result type"
        assert type(result[0]) is bool and type(result[1]) is dict, "Wrong transition component types"
        assert result[1] is not source, "Returned record aliases caller"
        result[1]["title"] = "caller edits result"
        assert source == before, "Returned record leaked ownership"
        
      5. same title still updates
        from copy import deepcopy
        source = {'version': 7, 'title': 'same'}
        before = deepcopy(source)
        result = versioned_update(source, 7, 'same')
        assert type(result) is tuple, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = (True, {'version': 8, 'title': 'same'})
        assert result == expected, "Wrong result value"
        def same_types(actual, expected):
            if type(actual) is not type(expected):
                return False
            if type(expected) in (list, tuple):
                return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
            if type(expected) is dict:
                return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
            return True
        assert same_types(result, expected), "Wrong nested result type"
        assert type(result[0]) is bool and type(result[1]) is dict, "Wrong transition component types"
        assert result[1] is not source, "Returned record aliases caller"
        result[1]["title"] = "caller edits result"
        assert source == before, "Returned record leaked ownership"
        
      6. empty replacement title
        from copy import deepcopy
        source = {'version': 9, 'title': 'old'}
        before = deepcopy(source)
        result = versioned_update(source, 9, '')
        assert type(result) is tuple, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = (True, {'version': 10, 'title': ''})
        assert result == expected, "Wrong result value"
        def same_types(actual, expected):
            if type(actual) is not type(expected):
                return False
            if type(expected) in (list, tuple):
                return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected))
            if type(expected) is dict:
                return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items())
            return True
        assert same_types(result, expected), "Wrong nested result type"
        assert type(result[0]) is bool and type(result[1]) is dict, "Wrong transition component types"
        assert result[1] is not source, "Returned record aliases caller"
        result[1]["title"] = "caller edits result"
        assert source == before, "Returned record leaked ownership"
        
        Why is a version check not an idempotency key?

        A repeated successful request now has a stale version and is rejected, not recognised as the same logical operation. A real store must compare and write atomically. For this fixed flat record, copying and updating uses bounded work and storage.

        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

        Communicate trade-offs

        Keyset pagination uses a unique ordered cursor. Include a tie-breaker so equal scores do not make records disappear between pages.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Filtering only score > last_score drops unseen rows with the same score. A composite score-and-ID key gives a deterministic continuation boundary.

        Words you will see

        Cursor
        The ordered key of the last returned row.
        Tie-breaker
        A second key making equal primary values distinguishable.
        Snapshot
        A consistent view of data at one logical point in time.

        Compare the complete key

        The ascending cursor is (10, 'a'). Tuple comparison first considers score, then ID when scores match. Therefore (10, 'b') is after the cursor and remains on the next page, along with (11, 'c').

        A score-only comparison would omit b. Use a unique stable ID and state ascending versus descending order explicitly. The source in this fixture is already ordered; a general pure helper may sort a new list rather than mutate caller storage.

        State the consistency limit

        A cursor is not a snapshot. Later inserts or score updates can move rows across the boundary, causing misses or repeats relative to a changing feed. Define whether the API promises only forward traversal of a current order or a versioned snapshot.

        The fixture filter scans n rows in O(n) time and allocates its matches before slicing. A database with a matching composite index can seek and read a bounded page, but its costs and isolation depend on that system. Do not transfer a database performance guarantee to this list illustration.

        The original example, step by step

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

        1. rows = [(10, "a"), (10, "b"), (11, "c"), (12, "d")]

          Use unique composite keys in ascending order.

        2. cursor = (10, "a")

          Record both parts of the last returned key.

        3. page = [row for row in rows if row > cursor][:2]

          Keep keys strictly after the cursor, including the equal-score b row.

        4. print(page[-1])

          Provide the next boundary from the last returned key.

        For each answer, distinguish language guarantees from CPython implementation details and average-case complexity from worst-case behaviour. Explain what you would measure or test when the environment changes rather than asserting a universal performance rule.

        Predict before you run

        Which row starts the page?

        Keep equal-score rows after a composite cursorPYTHON 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 page size.

        Try: Replace [:2] with [:1].

        Only b is returned, and its complete key becomes the next cursor.

        Demonstrate a score-only bug.

        Try: Use row[0] > cursor[0] in the filter.

        The equal-score b row disappears, violating continuation by the complete ordering key.

        Before you move on

        If a new row (9, 'z') arrives after this cursor was issued, will the next ascending page include it?

        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. Its key is before the cursor. A cursor alone does not revisit earlier keys or preserve an earlier snapshot.

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

        Review after the mock

        Optimistic concurrency accepts an update only when its expected version still matches. It prevents a stale overwrite, not repeated execution of the same request.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Two writers can read version four. After one succeeds, the other's version-four update must be rejected rather than erasing the first change.

        Words you will see

        Expected version
        The version observed before constructing an update.
        Conditional update
        A write allowed only if its predicate remains true atomically.
        Lost update
        One writer overwriting another's change without recognising it.

        Trace sequential evidence of the invariant

        The model starts at version four. The first update matches, changes the title and increments to five. The second still expects four, so it returns False without changing the saved title or version.

        This program is sequential. A real store must combine comparison and mutation atomically in one transaction or conditional statement. A Python check followed by a separate remote write does not establish that guarantee.

        Separate competing protocols

        An idempotency key recognises a retry of one logical request, potentially returning its recorded result. A version precondition recognises a stale view and rejects it. A retry of the successful version-four request would now conflict unless a separate idempotency layer handles it.

        The in-memory example stores one flat record and performs bounded field operations. Real costs include transaction conflicts, indexes and retry policy. On conflict, re-read and reconcile under the application's rules instead of blindly overwriting with a new version.

        The original example, step by step

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

        1. record = {"version": 4, "title": "draft"}

          Start both conceptual writers from version four.

        2. if record["version"] != expected:

          Reject a stale precondition before touching fields.

        3. record["version"] += 1

          Advance the version after an accepted change.

        4. print(update(4, "second"))

          Observe the second writer's stale version being rejected.

        Write down one misconception, one missing edge case and one topic to revisit. Schedule a later independent attempt rather than reading the answer repeatedly. The course reading milestone records reflection, not an interviewer certification.

        Predict before you run

        What title survives the unchanged program?

        A stale writer is rejectedPYTHON 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.

        Use a fresh precondition.

        Try: Change the second call to update(5, 'second').

        It succeeds and the final version is six with title second.

        Start from another version.

        Try: Set record's initial version to 5 but leave both expected versions at 4.

        Both calls fail and the draft stays unchanged.

        Before you move on

        If the second caller re-reads version five and intentionally submits expected=5, can its update succeed?

        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

        Yes, in this model it succeeds and creates version six. Re-reading is necessary, but the application must still decide whether the new title correctly reconciles the first change.

        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.