Skip to content

[serve] Fix TypeError when recording a custom metric with a route tag - #66616

Merged
abrarsheikh merged 3 commits into
ray-project:masterfrom
GNITOAHC:serve/fix-metrics-typeerror-on-route-tag
Oct 3, 2026
Merged

abrarsheikh merged 3 commits into
ray-project:masterfrom
GNITOAHC:serve/fix-metrics-typeerror-on-route-tag

Conversation

@GNITOAHC

Copy link
Copy Markdown
Contributor

Description

ray.serve.metrics.{Counter,Gauge,Histogram} raise TypeError: argument of type 'NoneType' is not iterable when a metric declares "route" in tag_keys and is recorded without an explicit tags argument:

from ray.serve.metrics import Counter

Counter("my_counter", tag_keys=("route",)).inc()
# TypeError: argument of type 'NoneType' is not iterable

inc(), set() and observe() all default tags to None and pass it straight to _add_serve_context_tag_values(), which evaluates ROUTE_TAG not in tags against that None.

Related issues

No existing issue

@GNITOAHC
GNITOAHC requested a review from a team as a code owner September 30, 2026 23:36

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request updates Ray Serve metrics (Counter, Gauge, and Histogram) to correctly handle cases where no explicit tags are provided during recording, preventing a potential TypeError when filling in the route tag. It also updates the documentation and adds a test to verify this behavior. The reviewer suggests copying the user-provided tags dictionary instead of mutating it in place to avoid unexpected side-effects.

Comment thread python/ray/serve/metrics.py Resolved
@abrarsheikh

Copy link
Copy Markdown
Contributor

can you please provide a repro script for this issue?

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Oct 1, 2026
@GNITOAHC

GNITOAHC commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

can you please provide a repro script for this issue?

Sure! Below is the repro script, it exits 1 when the bug is present, 0 when it's fixed, so it can be run against master and against this branch to compare:

repro_issue.py
"""Repro: ray.serve.metrics.{Counter,Gauge,Histogram} raise TypeError when a
metric declares "route" in tag_keys and is recorded with tags left as None.

    pip install "ray[serve]"
    python repro_issue.py

Exit code 1 if the bug is present, 0 if it is fixed.
"""
import sys
import traceback

import ray
from ray import serve
from ray.serve.metrics import Counter, Gauge, Histogram

BUG = "argument of type 'NoneType' is not iterable"


def check(label, fn):
    """Run fn; return "ok", "bug", or "other" and print what happened."""
    try:
        fn()
    except TypeError as e:
        if BUG in str(e):
            print(f"  [BUG ] {label}")
            print(f"         TypeError: {e}")
            return "bug"
        print(f"  [????] {label}: unexpected TypeError: {e}")
        return "other"
    except Exception as e:  # noqa: BLE001 - repro script, report anything
        print(f"  [????] {label}: unexpected {type(e).__name__}: {e}")
        return "other"
    print(f"  [ ok ] {label}")
    return "ok"


def part1_no_cluster():
    """The crash needs no cluster: it happens before anything is recorded."""
    print("\n=== 1. Plain Python, no Serve deployment ===")
    results = {}

    # "route" is the only Serve tag a user has to declare themselves:
    # _add_serve_metric_tags() injects deployment/replica/application, never route.
    results["counter"] = check(
        'Counter(tag_keys=("route",)).inc()',
        lambda: Counter("repro_counter", tag_keys=("route",)).inc(),
    )
    results["gauge"] = check(
        'Gauge(tag_keys=("route",)).set(1)',
        lambda: Gauge("repro_gauge", tag_keys=("route",)).set(1),
    )
    results["histogram"] = check(
        'Histogram(tag_keys=("route",)).observe(1)',
        lambda: Histogram(
            "repro_histogram", boundaries=[1.0, 2.0], tag_keys=("route",)
        ).observe(1),
    )

    print("\n  Controls (these are expected to pass either way):")
    # Same metric, empty dict instead of the None default -> works. This is the
    # only workaround today, and shows the failure is purely about tags being None.
    check(
        'Counter(tag_keys=("route",)).inc(tags={})  <- workaround',
        lambda: Counter("repro_counter_2", tag_keys=("route",)).inc(tags={}),
    )
    # No "route" in tag_keys -> the broken branch is never entered.
    check(
        "Counter().inc()  <- no route tag declared",
        lambda: Counter("repro_counter_3").inc(),
    )

    return "bug" in results.values()


def part2_in_a_deployment():
    """The same metric inside a replica: the request fails with a 500."""
    print("\n=== 2. Inside a Serve deployment ===")

    @serve.deployment
    class Model:
        def __init__(self):
            self.counter = Counter(
                "repro_deployment_counter",
                description="requests handled",
                tag_keys=("route",),
            )

        def __call__(self):
            self.counter.inc()  # no tags= -> boom
            return "ok"

    serve.run(Model.bind(), name="repro", route_prefix="/repro")

    import requests

    resp = requests.get("http://127.0.0.1:8000/repro", timeout=30)
    print(f"\n  HTTP {resp.status_code} - {resp.text.strip()}")
    if resp.status_code == 200:
        print("  [ ok ] request succeeded")
        return False

    # Serve returns a bare "Internal Server Error" body; the TypeError itself is
    # logged by the replica, which log_to_driver surfaces above this line.
    print("  [BUG ] request failed - see the replica traceback logged above")
    return True


def main():
    print(f"ray {ray.__version__}  ({ray.__file__})")
    # log_to_driver=True so the replica's TypeError traceback reaches the console.
    ray.init(num_cpus=2, include_dashboard=False)
    try:
        bug_standalone = part1_no_cluster()
        try:
            bug_deployment = part2_in_a_deployment()
        finally:
            serve.shutdown()
    finally:
        ray.shutdown()

    print("\n=== verdict ===")
    if bug_standalone or bug_deployment:
        print("BUG REPRODUCED")
        return 1
    print("No bug: route tag filled in from the request context as documented.")
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception:
        traceback.print_exc()
        sys.exit(2)

@GNITOAHC

GNITOAHC commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Hey @abrarsheikh, just checking in, I've posted the repro above, and CI is green. Let me know if you’d like me to take a different approach.

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Signed-off-by: Chao-Ting, Chen <[email protected]>
@abrarsheikh
abrarsheikh enabled auto-merge (squash) October 3, 2026 04:51
@github-actions github-actions Bot added the go add ONLY when ready to merge, run all tests label Oct 3, 2026
@abrarsheikh
abrarsheikh merged commit 43b706d into ray-project:master Oct 3, 2026
8 checks passed
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ray-project#66616)

## Description

`ray.serve.metrics.{Counter,Gauge,Histogram}` raise `TypeError: argument
of type 'NoneType' is not iterable` when a metric declares `"route"` in
`tag_keys` and is recorded without an explicit `tags` argument:

```python
from ray.serve.metrics import Counter

Counter("my_counter", tag_keys=("route",)).inc()
# TypeError: argument of type 'NoneType' is not iterable
```

`inc()`, `set()` and `observe()` all default `tags` to `None` and pass
it straight to `_add_serve_context_tag_values()`, which evaluates
`ROUTE_TAG not in tags` against that `None`.

## Related issues
No existing issue

---------

Signed-off-by: GNITOAHC <[email protected]>
Signed-off-by: Chao-Ting, Chen <[email protected]>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
chia7712 pushed a commit to opensource4you/readme that referenced this pull request Nov 25, 2026
fellowship: 提名 GNITOAHC (ray, 2026-11)

建議等級 2 萬

- [x] 關係人宣告:提名人與被提名者無親屬、僱傭、財務、業務合作或其他可能影響公正判斷之利害關係
- 在兩個月內自己從 Ray Serve 原始碼找到 9 個 bug 並開了 PR,其中 6 個 PR 被 Merged ([Merged PRs](https://github.com/ray-project/ray/pulls?q=is%3Apr+author%3AGNITOAHC+is%3Amerged+merged%3A%3C%3D2026-11-24))
- 開了 Gang Scheduling + Autoscaling 的 Issue 並附上 Repro Script,社群後續依此開 PR 修復,提名人則變成該 PR 的 Reviewer ([#67494](ray-project/ray#67494))
- PR Description 簡潔清楚,讓 Reviewer 清楚理解 PR 解決了什麼問題 ([#66358](ray-project/ray#66358), [#66438](ray-project/ray#66438), [#66616](ray-project/ray#66616), [#66910](ray-project/ray#66910))
- 對於 Maintainer 的 Review 會清楚了解之後回覆 ([#67923 comment](ray-project/ray#67923 (comment)), [#67210 comment](ray-project/ray#67210 (comment)), [#66438 comment](ray-project/ray#66438 (comment)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants