[Cosmos] Queries intermittently fail with "RuntimeError: OrderedDict mutated during iteration" (regression in 4.16.0)
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 初心者へのやさしさ
- 45/100
調査の方向性
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.
索引モデルが issue の本文から書いたものです。
説明
- 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
- 主要言語
- Python
- スター
- 5.6k
- フォーク
- 3.4k
- 平均マージ
- 1日 22時間
- マージ済み PR(30日)
- 189
環境構築
このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
Azure/azure-sdk-for-python のほかの issue
-
needs-triage
難易度 1/5 1時間未満 初心者へのやさしさ 85/100
Azure/azure-sdk-for-python#50155 · リアクション 1 件 ·
メンテナーはふだん 1 日以内に返信
-
[Teams Chatbot]: next-mypy install 404s should point to CFS auth or --pypi workaround対応中かも @jianingwang123 が 17 日前に担当しました。 オープンneeds-triage
難易度 1/5 1〜3時間 初心者へのやさしさ 72/100
Azure/azure-sdk-for-python#49886 · コメント 1 件 · リアクション 2 件 · 担当者 2 名 ·
メンテナーはふだん 1 日以内に返信
-
[AI Projects] AIProjectInstrumentor: non-streamed responses.create raises AttributeError ('NonRecordingSpan' object has no attribute 'attributes') when the span is not sampled対応中かも @14H034160212 が 19 日前に担当しました。 オープンAI Projects Client customer-reported question
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
Azure/azure-sdk-for-python#49854 · コメント 2 件 · リアクション 1 件 ·
メンテナーはふだん 1 日以内に返信
-
azure-eventhub migration guide: legacy checkpoint sample writes "None" metadata for partitions that were never checkpointed対応中かも @hidingmyname が 27 日前に担当しました。 オープンClient customer-reported Event Hubs needs-team-attention question Service Attention
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
Azure/azure-sdk-for-python#49723 · コメント 2 件 · リアクション 1 件 ·
メンテナーはふだん 1 日以内に返信
-
Scheduled test pipelines fail at the Analyze_Test stage due to date formatting対応中かも このイシューにリンクされたプルリクエストがオープン中、またはマージ済みです。 オープンEngSys
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
Azure/azure-sdk-for-python#49614 · コメント 1 件 · リアクション 1 件 ·
メンテナーはふだん 1 日以内に返信
Azure/azure-sdk-for-python の issue をすべて見る
似ている issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
vllm-project/vllm#70030 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
TigreGotico/tugaphone#408 ·
メンテナーはふだん 1 日以内に返信
-
needs-triage
難易度 2/5 1〜3時間 初心者へのやさしさ 74/100
gke-labs/kube-agents#7308 ·
メンテナーはふだん 1 日以内に返信
-
t: bug
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 3 日以内に返信
-
chore
難易度 1/5 1〜3時間 初心者へのやさしさ 88/100
lugassawan/swe-workbench#841 ·