[Cosmos] Queries intermittently fail with "RuntimeError: OrderedDict mutated during iteration" (regression in 4.16.0)

Ouverte
#49,949 2 commentaires 1 réaction 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 1 jour

Personne n'a encore pris cette issue.

Évaluation

Difficulté
4/5
Temps estimé
3-5 jours
Accessibilité débutants
45/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
azure, python
Domaine
backend, databases

Piste de recherche

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.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

Client Cosmos customer-reported needs-team-attention question Service Attention
  • 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 CosmosClient starts 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).

  1. Deterministic repro (repro.py below).
    It does not patch the SDK. sys.settrace / threading.settrace are 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 iterating last_response_headers, then allowed to finish.

    COSMOS_URL=... COSMOS_KEY=... COSMOS_DATABASE=... COSMOS_CONTAINER=... python repro.py
    

    Result: 4.16.2 and 4.17.1 raise the RuntimeError on every run (10 out of 10). 4.15.0 prints not 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
    
  2. Load test without any hooks (shared_client_stress.py below).
    One client is shared by 16 threads, each running SELECT * FROM c with 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 RuntimeError
    4.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_headers and response_headers.update(...)) before assigning them to self.last_response_headers.
      Then no other thread can reach the object while it is being iterated.
    • Do not mutate client.last_response_headers in place from Execute.
      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's last_response_headers at all.
Langage dominant
Python
Étoiles
5.6k
Forks
3.4k
Merge moyen
1 j 22 h
PR mergées (30 j)
189

Préparer son environnement

Ouvrir dans Codespaces

Lance le conteneur de développement du projet dans votre navigateur, avec votre propre compte GitHub.

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de Azure/azure-sdk-for-python

Toutes les issues de Azure/azure-sdk-for-python

Issues similaires

Plus d'issues Python

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.