[Cosmos] Queries intermittently fail with "RuntimeError: OrderedDict mutated during iteration" (regression in 4.16.0)
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Idoneità per principianti
- 45/100
Direzione di ricerca
Start in azure/cosmos/_cosmos_client_connection.py at _capture_internal_headers and the query paths named in the report, then read the Execute writes to last_response_headers in _retry_utility.py. Reproduce with the supplied scripts and compare against 4.15.0. Done means concurrent queries no longer raise RuntimeError: OrderedDict mutated during iteration; verify with the shared client stress case.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
- Package Name: azure-cosmos
- Package Version: 4.16.0 and later (confirmed on 4.16.2 and 4.17.1; not reproducible on 4.15.0)
- Operating System: Linux (Azure Functions, Python worker); reproduced locally on Debian 12
- Python Version: 3.12 (azure-core 1.41.0, requests 2.34.2)
Describe the bug
Queries made with the sync client intermittently fail with RuntimeError: OrderedDict mutated during iteration.
We hit this in production on 4.16.2, in an Azure Functions app whose synchronous queue-triggered functions run on a thread pool:
File ".../azure/cosmos/_cosmos_client_connection.py", line 3276, in _capture_internal_headers
internal_headers_capture.update(headers)
File "<frozen _collections_abc>", line 869, in __iter__
File ".../requests/structures.py", line 71, in <genexpr>
return (casedkey for casedkey, _ in self._store.values())
RuntimeError: OrderedDict mutated during iteration
The cause appears to be unsynchronized in-place mutation of CosmosClientConnection.last_response_headers.
This attribute is shared by every thread that uses the client, including the SDK's own background threads.
The query thread publishes the response headers of the current request and then iterates them.
The _internal_response_headers_capture path that does this was added in 4.16.0:
# azure/cosmos/_cosmos_client_connection.py (4.17.1), lines 3703-3705
# (same pattern at 3332-3334 and 3605-3607)
self.last_response_headers = post_response_headers
if internal_headers_capture is not None:
_capture_internal_headers(post_response_headers) # -> internal_headers_capture.update(headers)
After every request, _retry_utility.Execute adds keys to whatever object client.last_response_headers points to at that moment:
# azure/cosmos/_retry_utility.py (4.17.1), lines 152-157 (and 265-270 on the error path)
client.last_response_headers[HttpHeaders.ThrottleRetryCount] = ...
client.last_response_headers[HttpHeaders.ThrottleRetryWaitTimeInMs] = ...
If Execute finishes on another thread while the query thread is inside _capture_internal_headers, two new keys are added to the
requests.structures.CaseInsensitiveDict (backed by an OrderedDict) that is being iterated, and the iteration fails.
These threads run Execute on the same client:
- The background endpoint health check that every
CosmosClientstarts in its constructor.
The call chain is_GlobalEndpointManager._endpoints_health_check→CosmosClientConnection.health_check→__Get→Execute.
Because of this, even a client used from a single thread is affected: its first queries race with the startup health check.
When we instrumented the SDK, the health check's two writes landed on the query thread's headers object for every client we created. - The periodic background refresh (
_refresh_database_account_and_health). We found this by reading the code and did not test it. - Application threads that share one client (the recommended singleton pattern).
This was the most exposed configuration in our tests (see below).
Execute already wrote to last_response_headers in 4.15.0, but nothing on the query path iterated the published object.
That is presumably why 4.15.0 is not affected.
To Reproduce
The race window is small, so we reproduced it in two ways.
Both need only an existing container (any partition key, no items required).
-
Deterministic repro (
repro.pybelow).
It does not patch the SDK.sys.settrace/threading.settraceare used only to force the interleaving that otherwise happens by chance.
The background health check is held at its entry until the query thread starts iteratinglast_response_headers, then allowed to finish.COSMOS_URL=... COSMOS_KEY=... COSMOS_DATABASE=... COSMOS_CONTAINER=... python repro.pyResult: 4.16.2 and 4.17.1 raise the
RuntimeErroron every run (10 out of 10). 4.15.0 printsnot reproduced(10 out of 10).Traceback (most recent call last): File "./repro.py", line 67, in <module> list(container.query_items("SELECT * FROM c", partition_key="repro")) # raises RuntimeError ... File ".../azure/cosmos/_cosmos_client_connection.py", line 3705, in __QueryFeed _capture_internal_headers(post_response_headers) File ".../azure/cosmos/_cosmos_client_connection.py", line 3281, in _capture_internal_headers internal_headers_capture.update(headers) File "<frozen _collections_abc>", line 869, in __iter__ File ".../requests/structures.py", line 71, in <genexpr> return (casedkey for casedkey, _ in self._store.values()) RuntimeError: OrderedDict mutated during iteration -
Load test without any hooks (
shared_client_stress.pybelow).
One client is shared by 16 threads, each runningSELECT * FROM cwith a partition key for 30 seconds.
sys.setswitchinterval(1e-5)makes thread switches more frequent, so the race shows up within seconds.azure-cosmos Succeeded RuntimeError4.15.0 10,111 0 4.16.2 9,436 493 4.17.1 9,412 650 With the default switch interval (5 ms), we saw no errors in 10,572 queries on 4.17.1.
In normal conditions the error is rare, which matches our production experience: a single occurrence.
The numbers above were measured against a minimal local HTTP stub of the gateway.
The race is entirely client-side, so the server does not affect it.
repro.py
"""Deterministic repro: RuntimeError: OrderedDict mutated during iteration (azure-cosmos >= 4.16.0).
The SDK itself is not modified. Trace hooks only force the thread interleaving that happens by chance
in production: the background health check finishes while a query is iterating
client.last_response_headers.
Usage: COSMOS_URL=... COSMOS_KEY=... COSMOS_DATABASE=... COSMOS_CONTAINER=... python repro.py
(any existing container; the query may return no items)
"""
import os
import sys
import threading
import requests.structures
from azure.cosmos import CosmosClient
URL = os.environ["COSMOS_URL"]
KEY = os.environ["COSMOS_KEY"]
DATABASE = os.environ["COSMOS_DATABASE"]
CONTAINER = os.environ["COSMOS_CONTAINER"]
main_is_iterating = threading.Event()
health_check_done = threading.Event()
def background_tracer(frame, event, arg):
"""Installed on threads started by the SDK: hold health_check() until the main thread is mid-iteration."""
if (event == "call" and frame.f_code.co_name == "health_check"
and frame.f_globals.get("__name__") == "azure.cosmos._cosmos_client_connection"):
main_is_iterating.wait(30)
def on_return(frame, event, arg):
if event == "return":
health_check_done.set()
return on_return
return on_return
return None
def main_thread_tracer(connection):
"""Pause the main thread as soon as the SDK starts iterating connection.last_response_headers."""
iter_code = requests.structures.CaseInsensitiveDict.__iter__.__code__
armed = False
def tracer(frame, event, arg):
nonlocal armed
if event != "call":
return None
if frame.f_code is iter_code and frame.f_locals.get("self") is connection.last_response_headers:
armed = True
elif armed and frame.f_code.co_name == "<genexpr>" and frame.f_code.co_filename == iter_code.co_filename:
sys.settrace(None)
main_is_iterating.set() # let the background health check run to completion
health_check_done.wait(30)
return None
return tracer
threading.settrace(background_tracer)
client = CosmosClient(URL, credential=KEY) # starts the background endpoint health check
container = client.get_database_client(DATABASE).get_container_client(CONTAINER)
sys.settrace(main_thread_tracer(client.client_connection))
try:
list(container.query_items("SELECT * FROM c", partition_key="repro")) # raises RuntimeError
finally:
sys.settrace(None)
threading.settrace(None)
main_is_iterating.set()
print("not reproduced")
shared_client_stress.py
"""Load test without any hooks: one CosmosClient shared by N threads, counting RuntimeErrors.
Usage: COSMOS_URL=... COSMOS_KEY=... COSMOS_DATABASE=... COSMOS_CONTAINER=... \
python shared_client_stress.py [threads=16] [seconds=30] [switch_interval]
A small switch_interval (e.g. 1e-5) makes thread switches more frequent, so the race shows up within seconds.
"""
import os
import sys
import threading
import time
import traceback
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from importlib.metadata import version
from azure.cosmos import CosmosClient
THREADS = int(sys.argv[1]) if len(sys.argv) > 1 else 16
SECONDS = float(sys.argv[2]) if len(sys.argv) > 2 else 30
if len(sys.argv) > 3:
sys.setswitchinterval(float(sys.argv[3]))
client = CosmosClient(os.environ["COSMOS_URL"], credential=os.environ["COSMOS_KEY"])
container = client.get_database_client(os.environ["COSMOS_DATABASE"]).get_container_client(
os.environ["COSMOS_CONTAINER"]
)
succeeded, errors, first_error = Counter(), Counter(), []
lock = threading.Lock()
deadline = time.monotonic() + SECONDS
def worker():
while time.monotonic() < deadline:
try:
list(container.query_items("SELECT * FROM c", partition_key="repro"))
with lock:
succeeded["queries"] += 1
except Exception as e: # noqa: BLE001
with lock:
errors[f"{type(e).__name__}: {e}"[:100]] += 1
if not first_error:
first_error.append(traceback.format_exc())
with ThreadPoolExecutor(THREADS) as pool:
for _ in range(THREADS):
pool.submit(worker)
print(
f"azure-cosmos {version('azure-cosmos')}, switchinterval={sys.getswitchinterval()}, threads={THREADS}, "
f"seconds={SECONDS}: succeeded={succeeded['queries']}, failed={sum(errors.values())}"
)
for message, count in errors.most_common(3):
print(f" {count} {message}")
if first_error:
print(first_error[0])
Expected behavior
A query should not fail because another thread, including the SDK's own background health check, completed a request on the same client at the same time.
Additional context
- Workaround: we pinned azure-cosmos to 4.15.0.
- Possible fixes (suggestions only; we have not tested them):
- In
__QueryFeed, finish using the per-request headers (_capture_internal_headersandresponse_headers.update(...)) before assigning them toself.last_response_headers.
Then no other thread can reach the object while it is being iterated. - Do not mutate
client.last_response_headersin place fromExecute.
For example, write the throttle headers into the per-request headers before they are published, or assign a new mapping.
Background health checks probably should not touch the client'slast_response_headersat all.
- In
- Lingua principale
- Python
- Stelle
- 5.6k
- Fork
- 3.4k
- Merge medio
- 1g 22h
- PR unite (30g)
- 189
Preparare l'ambiente
Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di Azure/azure-sdk-for-python
-
needs-triage
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 85/100
Azure/azure-sdk-for-python#50155 · 1 reazione ·
I maintainer di solito rispondono entro 1 giorno
-
[Teams Chatbot]: next-mypy install 404s should point to CFS auth or --pypi workaroundForse già presa @jianingwang123 l’ha presa 17 giorni fa. Apertaneeds-triage
Difficoltà 1/5 1-3 ore Idoneità per principianti 72/100
Azure/azure-sdk-for-python#49886 · 1 commento · 2 reazioni · 2 assegnatari ·
I maintainer di solito rispondono entro 1 giorno
-
[AI Projects] AIProjectInstrumentor: non-streamed responses.create raises AttributeError ('NonRecordingSpan' object has no attribute 'attributes') when the span is not sampledForse già presa @14H034160212 l’ha presa 19 giorni fa. ApertaAI Projects Client customer-reported question
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
Azure/azure-sdk-for-python#49854 · 2 commenti · 1 reazione ·
I maintainer di solito rispondono entro 1 giorno
-
azure-eventhub migration guide: legacy checkpoint sample writes "None" metadata for partitions that were never checkpointedForse già presa @hidingmyname l’ha presa 27 giorni fa. ApertaClient customer-reported Event Hubs needs-team-attention question Service Attention
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
Azure/azure-sdk-for-python#49723 · 2 commenti · 1 reazione ·
I maintainer di solito rispondono entro 1 giorno
-
Scheduled test pipelines fail at the Analyze_Test stage due to date formattingForse già presa Una pull request collegata a questa issue è aperta o già unita. ApertaEngSys
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
Azure/azure-sdk-for-python#49614 · 1 commento · 1 reazione ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di Azure/azure-sdk-for-python
Issue simili
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
vllm-project/vllm#70030 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
TigreGotico/tugaphone#408 ·
I maintainer di solito rispondono entro 1 giorno
-
needs-triage
Difficoltà 2/5 1-3 ore Idoneità per principianti 74/100
gke-labs/kube-agents#7308 ·
I maintainer di solito rispondono entro 1 giorno
-
t: bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 3 giorni
-
chore
Difficoltà 1/5 1-3 ore Idoneità per principianti 88/100
lugassawan/swe-workbench#841 ·