Fix the tenant context model for concurrent requests
Your task
An AI set up a FastAPI dependency that writes the current tenant into one module-level context object. Under concurrency, requests sometimes read or write another tenant's data: after an await, a different request may have overwritten the shared object. Your team models a trace of interleaved requests to show what each read sees, with the shared object and with a per-request context.
An assistant wrote resolve_tenant_reads(trace, use_request_scope). It is in the editor. It has a bug. Find it and fix it.
Input and output:
trace: the steps of several requests, in the order they ran.set:<request>:<tenant>means a request sets its tenant.read:<request>means a request reads its tenant. Other steps, such asawait:r1ortick, do not touch the context.use_request_scope: false for one shared context in the process, true for a separate context per request.- Return one string per read, in order:
"<request>=<tenant>".
Rules the tests check:
- Split each step on
:. A step is a set only when it has exactly 3 parts and the first isset. A step is a read only when it has exactly 2 parts and the first isread. Every other step changes nothing and records nothing. - With
use_request_scopefalse: a set writes the shared context. A read sees the tenant most recently set by any request, or""if no request has set one yet. - With
use_request_scopetrue: each request has its own context. A read sees the tenant most recently set by that same request, or""if that request never set one.
Examples
resolve_tenant_reads(trace: list[str], use_request_scope: bool) -> list[str]Example 1
Input
resolve_tenant_reads(["set:r1:acme", "await:r1", "set:r2:globex", "read:r1", "read:r2"], False)Output
["r1=globex", "r2=globex"]Example 2
Input
resolve_tenant_reads(["set:r1:acme", "await:r1", "set:r2:globex", "read:r1", "read:r2"], True)Output
["r1=acme", "r2=globex"]Example 3
Input
resolve_tenant_reads(["set:r1:acme", "read:r1"], False)Output
["r1=acme"]