Python Debugging and Observability
Collect SQL evidence only on a trusted, server-created UserContext. The
generated Debug Assist supplies a safe_sql_evidence(...) projection that
omits params and debug_sql.
context.enable_select_sql_log()
rows = await (
Q.schools().limit(20)
.comment("Diagnose the school search")
.purpose("Verify filters, facets, and relation loading")
.execute_for_list(context)
)
safe = safe_sql_evidence(context.sql_logs())
Use enable_all_sql_log(), enable_select_sql_log(),
enable_mutation_sql_log(), and disable_sql_log(); mode changes clear old
entries. Select and mutation output can also be disabled independently. Use
with_diagnostic_sql_log_sink(TextDiagnosticSqlLogSink()) only for trusted
operator output.
Run the Facet, aggregate, deep relation, Top-N, and audited save examples from
Python advanced data operations. Correlate
trace_path, aliases, duration, result count, and affected rows. Preserve
native not-found, checker, conflict, and provider exceptions.
Install OpenTelemetry with context.with_runtime_telemetry(telemetry). Raw row
audit remains separate from the masked application audit sink. Python request
policy currently prepares queries; mutation tenant authorization must also be
enforced and tested at the application/provider/TFP boundary.
Finish with the shared checklist.
Order troubleshooting
For the full operation and recovery sequence, use the Python mutation recipes: deletion, state changes and version conflicts.
Start with the Python Order tutorial and API usage guide. Diagnose the first native error before changing a dependency or rerunning a suite. Compare the failing runtime, model and fixture against the authority for that operation.
| Symptom | What to inspect | Next action |
|---|---|---|
ORDER_OK is printed but the wrong Order is visible | Absolute database path, model revision and selected fixture. | The first-edit fixture has three Orders; pagination and insights use separate nine-/ten-order fixtures. Keep each in its own database and use business keys, not copied numeric IDs. |
| Empty result or duplicate business identity | Query cardinality and scoped predicates. | Keep the expected-one check. An empty result is distinct from a provider exception. A buyer filter alone does not authorize a tenant. |
| Wrong total or omitted item after edit | Full scalar/relation loading, item bounds and money validation. | Reload the complete bounded collection before calculating totals; a preview is not a full edit graph and omission is not deletion. |
| Program refuses to start with assertions disabled | The acceptance console requires __debug__; optimized Python removes fixture checks. | Run the prepared virtual environment without -O or PYTHONOPTIMIZE. Do not remove the guard to obtain a success exit. |
| Boolean input is accepted as a quantity | bool is a subclass of int in Python. | Keep the explicit boolean, finite-number and integral-range checks from the edit function. |
| Missing authoritative persisted state after a stale update | The retained runtime reports a rejected revision through this error path. | Compare the full authoritative Order/item state and preserve the native exception. It does not imply a normal empty query. |
| Background aiosqlite thread or task survives cancellation | A request or native connection may not have completed cleanup. | Await the request’s cancellation/completion and inspect actual open handles, thread counts and independent writer admission as in the soak example. |
| Async call appears to do nothing | A query/save coroutine was not awaited or the wrong virtual environment supplied imports. | Run the complete module entry point and await both query and audited save. Keep module/provider installation before execution. |
Order query troubleshooting
Use Python Order Queries with the matching export/insights fixture and recorded workspace. Diagnose the native plan and result carrier before changing an optimizer, cache or numeric conversion.
| Symptom | What to inspect | Next action |
|---|---|---|
| Export count is 9 instead of 8 | Export uses a buyer-only predicate; the ten-order fixture adds an export-buyer EUR control. | Use the nine-order export database. Retained-ID and summary recipes deliberately use the ten-order database and a currency predicate. |
| Empty export tail looks like failure | The ascending export's final offset 9 reports CACHE_MISS, zero rows and exact total 8. | Stop on the empty tail normally. For retained IDs an empty tail can instead be an ID_SET_HIT. |
| ID overflow shows 5 while total is 8 | Capacity 4, lower-bound scan and exact provider COUNT. | Keep observedCount separate from the matching total; do not retain a partial set or present 5 as the exact count. |
| Grand total equals a page/preview sum | Parent page size, child preview size and predicates on every aggregate/Facet request. | Aggregate the whole filtered set in the provider. In the all-USD fixture it is 8/35350, even though only three parents are visible. |
| Empty sum or zero buckets are unexpected | Empty groups, the one-row overall aggregate, and include-all versus matched-only Facets. | Preserve overall count 0/sum null; keep zero status buckets only for the requested all-status variant. |
| Expiry never rebuilds or every page rebuilds | Check store lifetime, same key, one-second expiry branch and actual awaited elapsed time. | Keep one context/store inside the sequence; a new process is a fresh store, while the expiry control waits about 1.3 seconds on the same query. |
| Aggregate result is confused with a nullable entity field | Rows are dictionaries with native order_status, count and totalMinor keys. | Preserve overall None; do not use an E-expression default or require the empty sum to be numeric. |
| ID count is unpacked incorrectly | Inspect the result of id_set_count() rather than assuming its shape matches another runtime. | id_set_count() returns (count, accuracy); the report takes index 0. Keep the accuracy and distinguish this observation from page.total_count. |
Read the plan immediately after its request; a namespace string or stale observation from another request is not proof of reuse. The existing query cases record actual provider SQL, keys, builds/hits, elapsed expiry/invalidation events and unchanged database snapshots. Use that evidence first. Fixed-data reads do not supply a concurrent-write snapshot or a distributed-cache guarantee. All original runtime pending-release and generator-deployment qualifications remain.
Order isolation troubleshooting
Use Python Order Isolation with the v1.1 model/library and fresh eight-order database. Inspect the facade boundary and actual provider predicates before broadening access or changing a cache namespace.
| Symptom / code | What to inspect | Next action |
|---|---|---|
| Wrong model or missing tenant-key API | v1.0 core/query workspace versus the v1.1 isolation library, manifest and database. | Use the retained regenerated isolation set; this is a fresh-database tutorial, not a live migration. Do not hand-edit generated files. |
UNAUTHENTICATED / FORGED_SCOPE | Server-owned session resolution and identity/policy fields in business JSON. | Keep client fields out of the session tuple; the fixture key is not a production credential. |
INVALID_TRUSTED_SCOPE | Zero/multiple tenant roots for the resolved key. | Fail closed and repair provisioning; never choose an arbitrary root. |
Foreign ID gives NOT_FOUND | Root + buyer predicates and parent-owned item resolution. | Preserve the common missing/foreign response; do not make a public unscoped lookup to distinguish them. |
INVALID_BOUNDS, FORBIDDEN_FIELD, FORBIDDEN_OPERATION | Native numeric type, exact patch keys and read-only actor. | Use integer 1–2 and the exact note/label patch. Do not coerce identity, strip extra fields or partially save. |
| List is scoped but summary/cache is not | Same trusted predicates on every aggregate and retained request. | Expect count 2/7700 cents; cache a,b,c,a must BUILD,BUILD,BUILD,HIT on one context with distinct scope identities. |
| Child edit reads a partial graph or changes unrelated versions | Three-child sentinel, two-child supported bound and native save path. | Detail/edit overflow returns ITEM_LIMIT; preserve scoped complete-state loading and compare unrelated rows. |
| Boolean limits are accepted or note edits change items | type(limit) is int excludes bool; the note edit reloads scalar state without the child relation graph. | Keep the strict validator and awaited scoped reload/save. isinstance(..., int) would weaken this boundary. |
| Audit actor or HTTP authorization is assumed from response metadata | The example tuple is separate from native context principal and transport authentication. | Wire real authenticated membership/principal mapping at the service boundary. JSON actor metadata and an audit reason do not prove that integration. |
The isolation receipt checks the named console requests with SQL and SQLite snapshots. It does not certify arbitrary raw Q/database access, exhaustive hostile JSON, production migration or authorization revocation during a save. Keep runtime and generator release marks from the API scope guide.
Read the evidence in order
| Question | Existing authority |
|---|---|
| Query shape, null state, edit, page or analytic result | Core Order receipt, this language’s native source, and the selected fixture. |
| Stale winner or atomic child failure | Concurrent writes and the stored unchanged/authoritative database snapshots. Busy/locked and timeout errors do not qualify as version conflicts. |
| Request cancellation, provider statement failure or real COMMIT failure | Lifecycle evidence. Preserve the native error and verify rollback before retry. |
| Transaction, connection or task ownership after drain/close | Finite soak evidence. Separate active leases from idle owned connections and verify the final native close/lifetime end. |
| Published package differs from a recorded workspace PASS | Release qualifications. Keep the pending-release marker and exact runtime source/package identity. |
Collect the failing phase, native error type/message, model and fixture revision, resolved runtime/package identity, and parameterized SQL shape/affected rows. Keep raw parameters and rendered SQL in the trusted operator boundary. Runtime telemetry sampling is not proof that an audit event was delivered or a transaction committed.
Reuse the existing failure and successful recovery evidence first. If a specific claim still has no authority, isolate that one operation on a disposable database and record the minimal result. Keep that reproduction scoped to the failing operation. Preserve School, every historical Order receipt, all six lifecycle/soak workspace pending-release qualifications, and the generator repairs pending deployment.
This language’s recorded advanced Order result remains WORKSPACE PASS — RELEASE PENDING.