Skip to content

[ci/doc] Ignore inherited API annotations in documentation checks - #65196

Merged
elliot-barn merged 1 commit into
masterfrom
fix-serve-api
Aug 4, 2026
Merged

elliot-barn merged 1 commit into
masterfrom
fix-serve-api

Conversation

@jeffreywang88

Copy link
Copy Markdown
Contributor

Why

The API-doc checker used hasattr, so it treated subclasses as independently annotated. RoundRobinRouter inherits markers from public router base classes, causing the expanded Serve walk to report it as undocumented and fail premerge.

What

Require annotations to be owned by the inspected object, matching ray.util.annotations, in both the API walk and subpackage guard. Add regression tests. Alternative: add RoundRobinRouter to the API index, but that incorrectly promotes an experimental implementation.

Related issues

https://buildkite.com/ray-project/premerge/builds/71313#019fcae0-04dc-4fe2-a9dc-d7ba2ecd39e1

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

@jeffreywang88
jeffreywang88 requested a review from a team as a code owner August 4, 2026 06:28
@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Aug 4, 2026

@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 introduces changes to ignore inherited API annotations when scanning modules for public APIs. It implements a helper function _is_directly_annotated and updates mock decorators to store the object's name, along with adding corresponding tests. Feedback suggests a more robust and Pythonic way to check if an attribute is defined directly on an object by checking its __dict__ directly, which avoids potential name collision issues when a subclass shares the same name as its annotated base class.

Comment thread ci/ray_ci/doc/module.py
Comment on lines +9 to +15
def _is_directly_annotated(obj: object) -> bool:
"""Return whether an object owns an API annotation, rather than
inheriting one from a base class."""
annotation_owner = getattr(obj, "_annotated", None)
return annotation_owner is not None and annotation_owner == getattr(
obj, "__name__", None
)

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.

high

Comparing _annotated with __name__ can lead to false positives when a subclass has the same name as its annotated base class (for example, when subclassing a class imported from another module or package, or with nested classes).

A more robust and Pythonic way to check if an attribute is defined directly on an object (and not inherited via the MRO) is to check the object's __dict__ directly using "_annotated" in getattr(obj, "__dict__", {}). This avoids any name collision issues and simplifies the logic.

Suggested change
def _is_directly_annotated(obj: object) -> bool:
"""Return whether an object owns an API annotation, rather than
inheriting one from a base class."""
annotation_owner = getattr(obj, "_annotated", None)
return annotation_owner is not None and annotation_owner == getattr(
obj, "__name__", None
)
def _is_directly_annotated(obj: object) -> bool:
"""Return whether an object owns an API annotation, rather than
inheriting one from a base class."""
return "_annotated" in getattr(obj, "__dict__", {})

@ray-gardener ray-gardener Bot added the devprod label Aug 4, 2026
@elliot-barn
elliot-barn merged commit 5236fd0 into master Aug 4, 2026
7 checks passed
@elliot-barn
elliot-barn deleted the fix-serve-api branch August 4, 2026 17:46

@dstrodtman dstrodtman 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.

Approving. I verified the semantics against the source of truth: _mark_annotated sets obj._annotated = obj.__name__ and _is_annotated checks obj._annotated == obj.__name__ (python/ray/util/annotations.py:332, :337), so _is_directly_annotated is a faithful reimplementation. The mock change from obj._annotated = None to obj._annotated = obj.__name__ is the real unlock here — the fixture had been diverging from Ray's actual decorator and hiding the bug. Tests pass locally, and because InheritedAnnotation sorts before MockClass in dir(), the existing index-based test_walk also acts as a positive control if the fix ever regresses.

Comments below are all non-blocking.

api.py:189 is the same bug in the other direction

This PR fixes two of the three places that read the _annotated family. The third is API.introspect_annotation_type:

annotated_type = getattr(obj, "_annotated_type", None)   # ci/ray_ci/doc/api.py:189

Plain getattr, so it inherits. That value is the only input to the "documented APIs resolve to public code" check (split_resolvable_and_broken_doc_apis, api.py:332). The concrete failure: an undecorated subclass of a @Deprecated class, if documented, gets classified non_public and fails as "documented API resolves to a deprecated object" — even though nothing deprecated it. Same inheritance bug, opposite direction, currently latent.

Routing that read through _is_directly_annotated is safe both ways:

  • inherited @Deprecated resolves to UNKNOWN and is accepted, which removes the false failure
  • inherited @PublicAPI resolves to UNKNOWN and is still accepted, since UNKNOWN is already the accepted case for methods

Methods are unaffected either way — functions don't inherit class attributes, so Dataset.map_batches already resolves to UNKNOWN today.

Fine as a follow-up rather than a change here. The thing I'd want to avoid long-term is the checker carrying two different definitions of "annotated" on the two sides of the same discrepancy check.

On the __dict__ suggestion, I'd keep what you have

The review bot is technically right that "_annotated" in obj.__dict__ is more robust, since name equality false-positives when a subclass shares its base's __name__. But ray.util.annotations._is_annotated uses name equality, and a CI checker that disagrees with the runtime definition of "annotated" seems worse than one that inherits its edge case. Parity looks like the right call.

Worth a line in the _is_directly_annotated docstring pointing at ray.util.annotations._is_annotated as the canonical implementation, so the next person doesn't "fix" this into divergence.

Two prose nits

  • ci/ray_ci/doc/cmd_check_api_discrepancy.py:343 still reads "is @PublicAPI-annotated (has _annotated)". That sentence describes exactly what this PR changed. Something like "directly annotated (owns _annotated, doesn't inherit it)" would keep it accurate.
  • The _is_directly_annotated docstring says what it returns but not why the rule exists. One clause naming inherited-from-a-base as the case it excludes would carry the intent for the next reader.

For context on why I'm in this file: I have open work on the adjacent API-annotation surface, including a diff-scoped @PublicAPI parameter-coverage check (#64788). That one is AST-based, so it reads decorators directly and never had this bug. Good to have the runtime walk agree with it now.

dstrodtman added a commit that referenced this pull request Aug 5, 2026
…ck (#65208)

## Why

Follow-up to #65196, which stopped the API walk (`Module._is_api`) and
the subpackage guard (`_import_status`) from treating an inherited
annotation as an owned one. A third reader of that marker family was
left on a plain `getattr`:

```python
annotated_type = getattr(obj, "_annotated_type", None)   # ci/ray_ci/doc/api.py
```

`_annotated_type` is a plain class attribute, so an undecorated subclass
reads its base's value. That value is the only input to the "documented
APIs resolve to public code" check
(`split_resolvable_and_broken_doc_apis`), which means a documented,
undecorated subclass of a `@Deprecated` class fails as "documented API
resolves to a deprecated object" — on a doc entry that's correct, for a
class nobody deprecated.

Same inheritance bug as #65196, opposite direction. It's latent today
and stays latent until someone documents such a subclass, at which point
it presents as an unexplained premerge failure on a correct doc change.
Leaving it also means the checker carries two different definitions of
"annotated" on the two sides of the same discrepancy check.

## What

Route `introspect_annotation_type` through `_is_directly_annotated`.
This is safe in both directions:

- an inherited `@Deprecated` resolves to `UNKNOWN` and is accepted,
removing the false failure
- an inherited `@PublicAPI` resolves to `UNKNOWN` and is still accepted,
since `UNKNOWN` is already the accepted case for a documented method of
an annotated class

Methods are unaffected either way — functions don't inherit class
attributes, so `Dataset.map_batches` already resolved to `UNKNOWN`.

`_is_directly_annotated` moves from `module.py` to `api.py` so both
sides share one definition. `module.py` already imports from `api.py`,
so leaving it in place would have made the dependency circular. Its
docstring now names `ray.util.annotations._is_annotated` as the
definition it deliberately mirrors, so the name-equality edge case
doesn't later get "fixed" into disagreeing with what Ray's runtime
considers annotated.

Also refreshes the `_import_status` docstring, which still described the
`hasattr` rule #65196 replaced.

## Tests

- A `@Deprecated` class and an undecorated subclass added to the mock
fixture.
- `test_introspect_annotation_type_ignores_inherited_annotations` —
covers both directions, and asserts the directly-annotated base still
reads `DEPRECATED` so the rule keeps its teeth.
- `test_split_resolvable_accepts_subclass_of_deprecated_class` —
end-to-end regression through the check that would actually have failed.

Both new tests fail without the `api.py` change (verified locally by
reverting it).

Two hardening changes to the existing tests while the fixture grew:

- `test_walk` is rekeyed by name instead of list index. It silently
depended on `dir()` ordering of the mock module, so any annotated symbol
added to the fixture renumbered its assertions.
- `test_walk_ignores_inherited_api_annotations` gains a positive
control. As written it asserts only absence, so it would pass if the
walk found nothing at all.

Full suite: 44 passed (`ci/ray_ci/doc/`, excluding
`test_update_cache_env.py`, which needs Sphinx installed).

## Related

Follow-up to #65196. Consistent with the AST-based `@PublicAPI`
detection in #64788, which reads decorator nodes directly and so never
had this bug — after this the runtime walk and the static check agree on
what "annotated" means.

Signed-off-by: Douglas Strodtman <[email protected]>
Artimislyy pushed a commit to Artimislyy/ray that referenced this pull request Aug 11, 2026
…y-project#65196)

## Why
The API-doc checker used `hasattr`, so it treated subclasses as
independently annotated. `RoundRobinRouter` inherits markers from public
router base classes, causing the expanded Serve walk to report it as
undocumented and fail premerge.

## What
Require annotations to be owned by the inspected object, matching
`ray.util.annotations`, in both the API walk and subpackage guard. Add
regression tests. Alternative: add `RoundRobinRouter` to the API index,
but that incorrectly promotes an experimental implementation.

## Related issues

https://buildkite.com/ray-project/premerge/builds/71313#019fcae0-04dc-4fe2-a9dc-d7ba2ecd39e1

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

Signed-off-by: Jeffrey Wang <[email protected]>
Artimislyy pushed a commit to Artimislyy/ray that referenced this pull request Aug 11, 2026
…ck (ray-project#65208)

## Why

Follow-up to ray-project#65196, which stopped the API walk (`Module._is_api`) and
the subpackage guard (`_import_status`) from treating an inherited
annotation as an owned one. A third reader of that marker family was
left on a plain `getattr`:

```python
annotated_type = getattr(obj, "_annotated_type", None)   # ci/ray_ci/doc/api.py
```

`_annotated_type` is a plain class attribute, so an undecorated subclass
reads its base's value. That value is the only input to the "documented
APIs resolve to public code" check
(`split_resolvable_and_broken_doc_apis`), which means a documented,
undecorated subclass of a `@Deprecated` class fails as "documented API
resolves to a deprecated object" — on a doc entry that's correct, for a
class nobody deprecated.

Same inheritance bug as ray-project#65196, opposite direction. It's latent today
and stays latent until someone documents such a subclass, at which point
it presents as an unexplained premerge failure on a correct doc change.
Leaving it also means the checker carries two different definitions of
"annotated" on the two sides of the same discrepancy check.

## What

Route `introspect_annotation_type` through `_is_directly_annotated`.
This is safe in both directions:

- an inherited `@Deprecated` resolves to `UNKNOWN` and is accepted,
removing the false failure
- an inherited `@PublicAPI` resolves to `UNKNOWN` and is still accepted,
since `UNKNOWN` is already the accepted case for a documented method of
an annotated class

Methods are unaffected either way — functions don't inherit class
attributes, so `Dataset.map_batches` already resolved to `UNKNOWN`.

`_is_directly_annotated` moves from `module.py` to `api.py` so both
sides share one definition. `module.py` already imports from `api.py`,
so leaving it in place would have made the dependency circular. Its
docstring now names `ray.util.annotations._is_annotated` as the
definition it deliberately mirrors, so the name-equality edge case
doesn't later get "fixed" into disagreeing with what Ray's runtime
considers annotated.

Also refreshes the `_import_status` docstring, which still described the
`hasattr` rule ray-project#65196 replaced.

## Tests

- A `@Deprecated` class and an undecorated subclass added to the mock
fixture.
- `test_introspect_annotation_type_ignores_inherited_annotations` —
covers both directions, and asserts the directly-annotated base still
reads `DEPRECATED` so the rule keeps its teeth.
- `test_split_resolvable_accepts_subclass_of_deprecated_class` —
end-to-end regression through the check that would actually have failed.

Both new tests fail without the `api.py` change (verified locally by
reverting it).

Two hardening changes to the existing tests while the fixture grew:

- `test_walk` is rekeyed by name instead of list index. It silently
depended on `dir()` ordering of the mock module, so any annotated symbol
added to the fixture renumbered its assertions.
- `test_walk_ignores_inherited_api_annotations` gains a positive
control. As written it asserts only absence, so it would pass if the
walk found nothing at all.

Full suite: 44 passed (`ci/ray_ci/doc/`, excluding
`test_update_cache_env.py`, which needs Sphinx installed).

## Related

Follow-up to ray-project#65196. Consistent with the AST-based `@PublicAPI`
detection in ray-project#64788, which reads decorator nodes directly and so never
had this bug — after this the runtime walk and the static check agree on
what "annotated" means.

Signed-off-by: Douglas Strodtman <[email protected]>
dstrodtman added a commit that referenced this pull request Aug 11, 2026
## Why

Ray's public API reference accretes undocumented parameters over time: a
new
`@PublicAPI` callable, or a new parameter on an existing one, can ship
without a
docstring `Args:` entry, and nothing fails. This adds a **static,
diff-scoped**
check that blocks *new* debt on the `@PublicAPI` surface while
grandfathering the
standing backlog.

### What pydoclint already covers, and the gap it leaves

pydoclint (pinned at `0.8.3` in `.pre-commit-config.yaml`) already runs
its
argument-completeness checks `DOC101`/`DOC103` repo-wide across
`python/ray`,
against an **empty** `ci/lint/pydoclint-baseline.txt`. So that class of
violation
is already fully enforced with zero grandfathering, and the tree is
essentially
clean: a repo-wide run under the exact pre-commit config flags exactly
**one**
callable, `_find_imported_submodules` in vendored
`python/ray/cloudpickle/cloudpickle.py`, which is private. The
per-module
cleanups (#63500, #63509,
#63518, #63541, #63571, #63632, #63633, #63634, #63639) are what got it
there.

The gap is `--skip-checking-short-docstrings`, which defaults to `True`
and is not
overridden. It makes pydoclint skip any callable whose docstring is
absent or is a
bare one-line summary with no sections. Those callables can gain
parameters
indefinitely without any check firing.

Flipping that one flag is not a viable fix. Repo-wide with
`--skip-checking-short-docstrings=False`, `DOC101`/`DOC103` fire on
**8,285**
callables across `python/ray` (public and private alike; 16,570
violations, since
each callable trips both codes) -- precisely the "baseline the size of
the
codebase" that the config comment on master already says the team
doesn't want,
and it has no `@PublicAPI` awareness to narrow it.

Measured on the `@PublicAPI` surface, the same unit for comparison: of
815 public
callables that take parameters, **230** have at least one undocumented
parameter,
totalling **505** undocumented parameters. So the public surface is
roughly 3% of
what a repo-wide flag flip would drag in.

**All 230 of them sit in pydoclint's blind spot** -- zero overlap with
what
`DOC101`/`DOC103` catch today. That falls out of the numbers above
without relying
on any modelling of pydoclint's "short docstring" rule: if any
`@PublicAPI`
callable had a section-bearing docstring missing a param, pydoclint
would already
report `DOC101` on it, and the only such callable in the tree is a
private
cloudpickle function. The two checks partition the problem rather than
duplicating
it.

This check therefore scopes exactly to the `@PublicAPI` surface with
**no baseline
file**: it parses the base-branch and working-tree versions of the
changed files
and diffs their undocumented-parameter sets, so it needs **no Ray build
or import
environment**.

## What it does

- Enumerates the `@PublicAPI` callables changed by the PR (module-level
`@PublicAPI` functions and methods of `@PublicAPI` classes). A method
that
carries its own `@DeveloperAPI` or `@Deprecated` is out of scope even on
a
  public class, since it isn't part of the rendered surface; an explicit
  `@PublicAPI` on the method wins over both.
- For each, computes the signature parameters missing from the docstring
`Args:`/`Arguments:` block (for `__init__`, also the class docstring,
matching
the default `autoclass_content="class"`), resolving docstring
inheritance so an
override with no own docstring isn't flagged when a base documents the
param.
- Fails only on parameters that are **newly** undocumented versus the
base
branch. Pre-existing gaps are grandfathered; the gate fires on new
public
callables, newly-added params, and doc entries removed from an existing
param.

**Scope and limits (intentional):** all signature params, not only
annotated
ones. Presence only -- a param counts as documented if its name appears
in
`Args:`; description prose is not inspected (empty-description detection
would
need `numpydoc.validate` and is out of scope). Static source analysis,
so it does
not confirm what the reference actually renders.

## Where it lives / rollout

Sits in the `ci/ray_ci/doc` guard family next to
`cmd_check_api_discrepancy.py`,
and runs in the **lint group** (static, no docbuild). It starts as a
`soft_fail: true` step -- **visible but non-blocking** -- so the
measured
false-positive rate above can be confirmed against live traffic before
the check
gates anything. Flipping it to a required check is a one-line removal of
`soft_fail`.

One caveat for reviewers on the warn phase: the pipeline passes
`--blocking` and
relies on `soft_fail` to absorb the exit code, so an environment failure
(an
unfetched base branch, a shallow clone deeper than `--depth=500`)
surfaces the
same way a finding does. Happy to drop `--blocking` from the pipeline
command
instead, so the script's own warn mode carries the phase and
infrastructure
errors stay distinguishable from real findings.

Because the check is AST-based, it matches only *directly* applied
`@PublicAPI`
decorators, which lines up with the direct-annotation policy established
in
#65196 and #65208.

## Testing

- `python -m pytest ci/ray_ci/doc/test_api_param_coverage.py` -- **28
passed**.
Covers new API, new param, grandfathered gap, removed doc entry,
non-public /
private skips, `@PublicAPI(...)` call form,
`__init__`-on-class-docstring,
`Args:` block termination on dedent, docstring-inheritance recovery, and
the
  `@DeveloperAPI`/`@Deprecated`-method scoping rule.
- End-to-end on the pydoclint blind spot, which is the case this check
exists
  for: adding an undocumented `strict` param to `RayError.from_bytes` (a
`@PublicAPI` method with no docstring) fired on exactly `strict`, while
pydoclint under the pre-commit config reported no violations on the same
file.
  `--blocking` exits 1; documenting the param cleared it.
- End-to-end on a case pydoclint *does* cover, to confirm agreement
rather than
contradiction: adding an undocumented `seed` param to `tune.loguniform`
fired
on exactly `seed` and correctly grandfathered the pre-existing gaps in
the same
  file. pydoclint independently blocks this one at pre-commit.
- `shellcheck ci/lint/lint.sh` clean; `.buildkite/lint.rayci.yml`
parses.
- Renaming `python/ray/exceptions.py` with no content change reported 22
violations across 11 callables before rename detection was added, and
reports
none after. A rename that also adds an undocumented param still fires on
  exactly that param.

### False-positive rate, measured against real history

Replayed the check over the **200** most recent merged commits touching
`python/ray/**/*.py`, each evaluated against its own parent. **Two**
fired (1%):

- #64963 flagged `Dataset.map_batches_internal` with 15 parameters. A
genuine
false positive: the method is `@DeveloperAPI`, but the check was pulling
in
every non-underscore method of an `@PublicAPI` class regardless of the
method's
own annotation. Fixed in this PR, with regression tests; the commit is
clean on
  the replay now.
- #64519 flagged `mode`, a newly added and undocumented parameter on
`Catalog.resolve` (`@PublicAPI(stability="alpha")`, one-line docstring).
A true
positive, and squarely the blind-spot class this check exists for. It
correctly
grandfathered the pre-existing `table` and `reader` gaps on the same
callable.

Post-fix that is **one firing across 200 commits, and it is a real
finding**.

### False-negative probe

Coverage was probed independently of the replay: for every `@PublicAPI`
callable
on the surface, inject a new undocumented keyword parameter and assert
the check
reports it. **815 callables probed, 0 misses** -- 585 that are currently
fully
documented, plus the 230 that already carry gaps, which verifies that
grandfathering an existing gap doesn't mask a newly added parameter.
Broken out
by shape: 176 module-level functions, 470 methods, 157 `__init__`, and
12 async
methods, with no misses in any group.

## Alternatives considered

- **Flip `--skip-checking-short-docstrings=False` repo-wide.** 8,285
callables, no
  `@PublicAPI` scoping. Rejected above.
- **A second pydoclint invocation with that flag plus its own
baseline.**
pre-commit is already diff-scoped, so this is closer than it looks, but
it
requires committing a baseline on the order of 8,000 entries and still
gates all
  of `python/ray` rather than the rendered public surface.

## Relationship to other open work

No open PR builds a parameter-coverage gate. #64779 changes how type
hints render
into the Parameters list, which is a separate deliverable and does not
gate new
undocumented params.

## AI assistance

This change was developed with AI assistance. The submitter has reviewed
every
changed line and run the tests above locally.

---------

Signed-off-by: Douglas Strodtman <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…y-project#65196)

## Why
The API-doc checker used `hasattr`, so it treated subclasses as
independently annotated. `RoundRobinRouter` inherits markers from public
router base classes, causing the expanded Serve walk to report it as
undocumented and fail premerge.

## What
Require annotations to be owned by the inspected object, matching
`ray.util.annotations`, in both the API walk and subpackage guard. Add
regression tests. Alternative: add `RoundRobinRouter` to the API index,
but that incorrectly promotes an experimental implementation.

## Related issues

https://buildkite.com/ray-project/premerge/builds/71313#019fcae0-04dc-4fe2-a9dc-d7ba2ecd39e1

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…ck (ray-project#65208)

## Why

Follow-up to ray-project#65196, which stopped the API walk (`Module._is_api`) and
the subpackage guard (`_import_status`) from treating an inherited
annotation as an owned one. A third reader of that marker family was
left on a plain `getattr`:

```python
annotated_type = getattr(obj, "_annotated_type", None)   # ci/ray_ci/doc/api.py
```

`_annotated_type` is a plain class attribute, so an undecorated subclass
reads its base's value. That value is the only input to the "documented
APIs resolve to public code" check
(`split_resolvable_and_broken_doc_apis`), which means a documented,
undecorated subclass of a `@Deprecated` class fails as "documented API
resolves to a deprecated object" — on a doc entry that's correct, for a
class nobody deprecated.

Same inheritance bug as ray-project#65196, opposite direction. It's latent today
and stays latent until someone documents such a subclass, at which point
it presents as an unexplained premerge failure on a correct doc change.
Leaving it also means the checker carries two different definitions of
"annotated" on the two sides of the same discrepancy check.

## What

Route `introspect_annotation_type` through `_is_directly_annotated`.
This is safe in both directions:

- an inherited `@Deprecated` resolves to `UNKNOWN` and is accepted,
removing the false failure
- an inherited `@PublicAPI` resolves to `UNKNOWN` and is still accepted,
since `UNKNOWN` is already the accepted case for a documented method of
an annotated class

Methods are unaffected either way — functions don't inherit class
attributes, so `Dataset.map_batches` already resolved to `UNKNOWN`.

`_is_directly_annotated` moves from `module.py` to `api.py` so both
sides share one definition. `module.py` already imports from `api.py`,
so leaving it in place would have made the dependency circular. Its
docstring now names `ray.util.annotations._is_annotated` as the
definition it deliberately mirrors, so the name-equality edge case
doesn't later get "fixed" into disagreeing with what Ray's runtime
considers annotated.

Also refreshes the `_import_status` docstring, which still described the
`hasattr` rule ray-project#65196 replaced.

## Tests

- A `@Deprecated` class and an undecorated subclass added to the mock
fixture.
- `test_introspect_annotation_type_ignores_inherited_annotations` —
covers both directions, and asserts the directly-annotated base still
reads `DEPRECATED` so the rule keeps its teeth.
- `test_split_resolvable_accepts_subclass_of_deprecated_class` —
end-to-end regression through the check that would actually have failed.

Both new tests fail without the `api.py` change (verified locally by
reverting it).

Two hardening changes to the existing tests while the fixture grew:

- `test_walk` is rekeyed by name instead of list index. It silently
depended on `dir()` ordering of the mock module, so any annotated symbol
added to the fixture renumbered its assertions.
- `test_walk_ignores_inherited_api_annotations` gains a positive
control. As written it asserts only absence, so it would pass if the
walk found nothing at all.

Full suite: 44 passed (`ci/ray_ci/doc/`, excluding
`test_update_cache_env.py`, which needs Sphinx installed).

## Related

Follow-up to ray-project#65196. Consistent with the AST-based `@PublicAPI`
detection in ray-project#64788, which reads decorator nodes directly and so never
had this bug — after this the runtime walk and the static check agree on
what "annotated" means.

Signed-off-by: Douglas Strodtman <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…ject#64788)

## Why

Ray's public API reference accretes undocumented parameters over time: a
new
`@PublicAPI` callable, or a new parameter on an existing one, can ship
without a
docstring `Args:` entry, and nothing fails. This adds a **static,
diff-scoped**
check that blocks *new* debt on the `@PublicAPI` surface while
grandfathering the
standing backlog.

### What pydoclint already covers, and the gap it leaves

pydoclint (pinned at `0.8.3` in `.pre-commit-config.yaml`) already runs
its
argument-completeness checks `DOC101`/`DOC103` repo-wide across
`python/ray`,
against an **empty** `ci/lint/pydoclint-baseline.txt`. So that class of
violation
is already fully enforced with zero grandfathering, and the tree is
essentially
clean: a repo-wide run under the exact pre-commit config flags exactly
**one**
callable, `_find_imported_submodules` in vendored
`python/ray/cloudpickle/cloudpickle.py`, which is private. The
per-module
cleanups (ray-project#63500, ray-project#63509,
ray-project#63518, ray-project#63541, ray-project#63571, ray-project#63632, ray-project#63633, ray-project#63634, ray-project#63639) are what got it
there.

The gap is `--skip-checking-short-docstrings`, which defaults to `True`
and is not
overridden. It makes pydoclint skip any callable whose docstring is
absent or is a
bare one-line summary with no sections. Those callables can gain
parameters
indefinitely without any check firing.

Flipping that one flag is not a viable fix. Repo-wide with
`--skip-checking-short-docstrings=False`, `DOC101`/`DOC103` fire on
**8,285**
callables across `python/ray` (public and private alike; 16,570
violations, since
each callable trips both codes) -- precisely the "baseline the size of
the
codebase" that the config comment on master already says the team
doesn't want,
and it has no `@PublicAPI` awareness to narrow it.

Measured on the `@PublicAPI` surface, the same unit for comparison: of
815 public
callables that take parameters, **230** have at least one undocumented
parameter,
totalling **505** undocumented parameters. So the public surface is
roughly 3% of
what a repo-wide flag flip would drag in.

**All 230 of them sit in pydoclint's blind spot** -- zero overlap with
what
`DOC101`/`DOC103` catch today. That falls out of the numbers above
without relying
on any modelling of pydoclint's "short docstring" rule: if any
`@PublicAPI`
callable had a section-bearing docstring missing a param, pydoclint
would already
report `DOC101` on it, and the only such callable in the tree is a
private
cloudpickle function. The two checks partition the problem rather than
duplicating
it.

This check therefore scopes exactly to the `@PublicAPI` surface with
**no baseline
file**: it parses the base-branch and working-tree versions of the
changed files
and diffs their undocumented-parameter sets, so it needs **no Ray build
or import
environment**.

## What it does

- Enumerates the `@PublicAPI` callables changed by the PR (module-level
`@PublicAPI` functions and methods of `@PublicAPI` classes). A method
that
carries its own `@DeveloperAPI` or `@Deprecated` is out of scope even on
a
  public class, since it isn't part of the rendered surface; an explicit
  `@PublicAPI` on the method wins over both.
- For each, computes the signature parameters missing from the docstring
`Args:`/`Arguments:` block (for `__init__`, also the class docstring,
matching
the default `autoclass_content="class"`), resolving docstring
inheritance so an
override with no own docstring isn't flagged when a base documents the
param.
- Fails only on parameters that are **newly** undocumented versus the
base
branch. Pre-existing gaps are grandfathered; the gate fires on new
public
callables, newly-added params, and doc entries removed from an existing
param.

**Scope and limits (intentional):** all signature params, not only
annotated
ones. Presence only -- a param counts as documented if its name appears
in
`Args:`; description prose is not inspected (empty-description detection
would
need `numpydoc.validate` and is out of scope). Static source analysis,
so it does
not confirm what the reference actually renders.

## Where it lives / rollout

Sits in the `ci/ray_ci/doc` guard family next to
`cmd_check_api_discrepancy.py`,
and runs in the **lint group** (static, no docbuild). It starts as a
`soft_fail: true` step -- **visible but non-blocking** -- so the
measured
false-positive rate above can be confirmed against live traffic before
the check
gates anything. Flipping it to a required check is a one-line removal of
`soft_fail`.

One caveat for reviewers on the warn phase: the pipeline passes
`--blocking` and
relies on `soft_fail` to absorb the exit code, so an environment failure
(an
unfetched base branch, a shallow clone deeper than `--depth=500`)
surfaces the
same way a finding does. Happy to drop `--blocking` from the pipeline
command
instead, so the script's own warn mode carries the phase and
infrastructure
errors stay distinguishable from real findings.

Because the check is AST-based, it matches only *directly* applied
`@PublicAPI`
decorators, which lines up with the direct-annotation policy established
in
ray-project#65196 and ray-project#65208.

## Testing

- `python -m pytest ci/ray_ci/doc/test_api_param_coverage.py` -- **28
passed**.
Covers new API, new param, grandfathered gap, removed doc entry,
non-public /
private skips, `@PublicAPI(...)` call form,
`__init__`-on-class-docstring,
`Args:` block termination on dedent, docstring-inheritance recovery, and
the
  `@DeveloperAPI`/`@Deprecated`-method scoping rule.
- End-to-end on the pydoclint blind spot, which is the case this check
exists
  for: adding an undocumented `strict` param to `RayError.from_bytes` (a
`@PublicAPI` method with no docstring) fired on exactly `strict`, while
pydoclint under the pre-commit config reported no violations on the same
file.
  `--blocking` exits 1; documenting the param cleared it.
- End-to-end on a case pydoclint *does* cover, to confirm agreement
rather than
contradiction: adding an undocumented `seed` param to `tune.loguniform`
fired
on exactly `seed` and correctly grandfathered the pre-existing gaps in
the same
  file. pydoclint independently blocks this one at pre-commit.
- `shellcheck ci/lint/lint.sh` clean; `.buildkite/lint.rayci.yml`
parses.
- Renaming `python/ray/exceptions.py` with no content change reported 22
violations across 11 callables before rename detection was added, and
reports
none after. A rename that also adds an undocumented param still fires on
  exactly that param.

### False-positive rate, measured against real history

Replayed the check over the **200** most recent merged commits touching
`python/ray/**/*.py`, each evaluated against its own parent. **Two**
fired (1%):

- ray-project#64963 flagged `Dataset.map_batches_internal` with 15 parameters. A
genuine
false positive: the method is `@DeveloperAPI`, but the check was pulling
in
every non-underscore method of an `@PublicAPI` class regardless of the
method's
own annotation. Fixed in this PR, with regression tests; the commit is
clean on
  the replay now.
- ray-project#64519 flagged `mode`, a newly added and undocumented parameter on
`Catalog.resolve` (`@PublicAPI(stability="alpha")`, one-line docstring).
A true
positive, and squarely the blind-spot class this check exists for. It
correctly
grandfathered the pre-existing `table` and `reader` gaps on the same
callable.

Post-fix that is **one firing across 200 commits, and it is a real
finding**.

### False-negative probe

Coverage was probed independently of the replay: for every `@PublicAPI`
callable
on the surface, inject a new undocumented keyword parameter and assert
the check
reports it. **815 callables probed, 0 misses** -- 585 that are currently
fully
documented, plus the 230 that already carry gaps, which verifies that
grandfathering an existing gap doesn't mask a newly added parameter.
Broken out
by shape: 176 module-level functions, 470 methods, 157 `__init__`, and
12 async
methods, with no misses in any group.

## Alternatives considered

- **Flip `--skip-checking-short-docstrings=False` repo-wide.** 8,285
callables, no
  `@PublicAPI` scoping. Rejected above.
- **A second pydoclint invocation with that flag plus its own
baseline.**
pre-commit is already diff-scoped, so this is closer than it looks, but
it
requires committing a baseline on the order of 8,000 entries and still
gates all
  of `python/ray` rather than the rendered public surface.

## Relationship to other open work

No open PR builds a parameter-coverage gate. ray-project#64779 changes how type
hints render
into the Parameters list, which is a separate deliverable and does not
gate new
undocumented params.

## AI assistance

This change was developed with AI assistance. The submitter has reviewed
every
changed line and run the tests above locally.

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Signed-off-by: 400Ping <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…y-project#65196)

## Why
The API-doc checker used `hasattr`, so it treated subclasses as
independently annotated. `RoundRobinRouter` inherits markers from public
router base classes, causing the expanded Serve walk to report it as
undocumented and fail premerge.

## What
Require annotations to be owned by the inspected object, matching
`ray.util.annotations`, in both the API walk and subpackage guard. Add
regression tests. Alternative: add `RoundRobinRouter` to the API index,
but that incorrectly promotes an experimental implementation.

## Related issues

https://buildkite.com/ray-project/premerge/builds/71313#019fcae0-04dc-4fe2-a9dc-d7ba2ecd39e1

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

Signed-off-by: Jeffrey Wang <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ck (ray-project#65208)

## Why

Follow-up to ray-project#65196, which stopped the API walk (`Module._is_api`) and
the subpackage guard (`_import_status`) from treating an inherited
annotation as an owned one. A third reader of that marker family was
left on a plain `getattr`:

```python
annotated_type = getattr(obj, "_annotated_type", None)   # ci/ray_ci/doc/api.py
```

`_annotated_type` is a plain class attribute, so an undecorated subclass
reads its base's value. That value is the only input to the "documented
APIs resolve to public code" check
(`split_resolvable_and_broken_doc_apis`), which means a documented,
undecorated subclass of a `@Deprecated` class fails as "documented API
resolves to a deprecated object" — on a doc entry that's correct, for a
class nobody deprecated.

Same inheritance bug as ray-project#65196, opposite direction. It's latent today
and stays latent until someone documents such a subclass, at which point
it presents as an unexplained premerge failure on a correct doc change.
Leaving it also means the checker carries two different definitions of
"annotated" on the two sides of the same discrepancy check.

## What

Route `introspect_annotation_type` through `_is_directly_annotated`.
This is safe in both directions:

- an inherited `@Deprecated` resolves to `UNKNOWN` and is accepted,
removing the false failure
- an inherited `@PublicAPI` resolves to `UNKNOWN` and is still accepted,
since `UNKNOWN` is already the accepted case for a documented method of
an annotated class

Methods are unaffected either way — functions don't inherit class
attributes, so `Dataset.map_batches` already resolved to `UNKNOWN`.

`_is_directly_annotated` moves from `module.py` to `api.py` so both
sides share one definition. `module.py` already imports from `api.py`,
so leaving it in place would have made the dependency circular. Its
docstring now names `ray.util.annotations._is_annotated` as the
definition it deliberately mirrors, so the name-equality edge case
doesn't later get "fixed" into disagreeing with what Ray's runtime
considers annotated.

Also refreshes the `_import_status` docstring, which still described the
`hasattr` rule ray-project#65196 replaced.

## Tests

- A `@Deprecated` class and an undecorated subclass added to the mock
fixture.
- `test_introspect_annotation_type_ignores_inherited_annotations` —
covers both directions, and asserts the directly-annotated base still
reads `DEPRECATED` so the rule keeps its teeth.
- `test_split_resolvable_accepts_subclass_of_deprecated_class` —
end-to-end regression through the check that would actually have failed.

Both new tests fail without the `api.py` change (verified locally by
reverting it).

Two hardening changes to the existing tests while the fixture grew:

- `test_walk` is rekeyed by name instead of list index. It silently
depended on `dir()` ordering of the mock module, so any annotated symbol
added to the fixture renumbered its assertions.
- `test_walk_ignores_inherited_api_annotations` gains a positive
control. As written it asserts only absence, so it would pass if the
walk found nothing at all.

Full suite: 44 passed (`ci/ray_ci/doc/`, excluding
`test_update_cache_env.py`, which needs Sphinx installed).

## Related

Follow-up to ray-project#65196. Consistent with the AST-based `@PublicAPI`
detection in ray-project#64788, which reads decorator nodes directly and so never
had this bug — after this the runtime walk and the static check agree on
what "annotated" means.

Signed-off-by: Douglas Strodtman <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ject#64788)

## Why

Ray's public API reference accretes undocumented parameters over time: a
new
`@PublicAPI` callable, or a new parameter on an existing one, can ship
without a
docstring `Args:` entry, and nothing fails. This adds a **static,
diff-scoped**
check that blocks *new* debt on the `@PublicAPI` surface while
grandfathering the
standing backlog.

### What pydoclint already covers, and the gap it leaves

pydoclint (pinned at `0.8.3` in `.pre-commit-config.yaml`) already runs
its
argument-completeness checks `DOC101`/`DOC103` repo-wide across
`python/ray`,
against an **empty** `ci/lint/pydoclint-baseline.txt`. So that class of
violation
is already fully enforced with zero grandfathering, and the tree is
essentially
clean: a repo-wide run under the exact pre-commit config flags exactly
**one**
callable, `_find_imported_submodules` in vendored
`python/ray/cloudpickle/cloudpickle.py`, which is private. The
per-module
cleanups (ray-project#63500, ray-project#63509,
ray-project#63518, ray-project#63541, ray-project#63571, ray-project#63632, ray-project#63633, ray-project#63634, ray-project#63639) are what got it
there.

The gap is `--skip-checking-short-docstrings`, which defaults to `True`
and is not
overridden. It makes pydoclint skip any callable whose docstring is
absent or is a
bare one-line summary with no sections. Those callables can gain
parameters
indefinitely without any check firing.

Flipping that one flag is not a viable fix. Repo-wide with
`--skip-checking-short-docstrings=False`, `DOC101`/`DOC103` fire on
**8,285**
callables across `python/ray` (public and private alike; 16,570
violations, since
each callable trips both codes) -- precisely the "baseline the size of
the
codebase" that the config comment on master already says the team
doesn't want,
and it has no `@PublicAPI` awareness to narrow it.

Measured on the `@PublicAPI` surface, the same unit for comparison: of
815 public
callables that take parameters, **230** have at least one undocumented
parameter,
totalling **505** undocumented parameters. So the public surface is
roughly 3% of
what a repo-wide flag flip would drag in.

**All 230 of them sit in pydoclint's blind spot** -- zero overlap with
what
`DOC101`/`DOC103` catch today. That falls out of the numbers above
without relying
on any modelling of pydoclint's "short docstring" rule: if any
`@PublicAPI`
callable had a section-bearing docstring missing a param, pydoclint
would already
report `DOC101` on it, and the only such callable in the tree is a
private
cloudpickle function. The two checks partition the problem rather than
duplicating
it.

This check therefore scopes exactly to the `@PublicAPI` surface with
**no baseline
file**: it parses the base-branch and working-tree versions of the
changed files
and diffs their undocumented-parameter sets, so it needs **no Ray build
or import
environment**.

## What it does

- Enumerates the `@PublicAPI` callables changed by the PR (module-level
`@PublicAPI` functions and methods of `@PublicAPI` classes). A method
that
carries its own `@DeveloperAPI` or `@Deprecated` is out of scope even on
a
  public class, since it isn't part of the rendered surface; an explicit
  `@PublicAPI` on the method wins over both.
- For each, computes the signature parameters missing from the docstring
`Args:`/`Arguments:` block (for `__init__`, also the class docstring,
matching
the default `autoclass_content="class"`), resolving docstring
inheritance so an
override with no own docstring isn't flagged when a base documents the
param.
- Fails only on parameters that are **newly** undocumented versus the
base
branch. Pre-existing gaps are grandfathered; the gate fires on new
public
callables, newly-added params, and doc entries removed from an existing
param.

**Scope and limits (intentional):** all signature params, not only
annotated
ones. Presence only -- a param counts as documented if its name appears
in
`Args:`; description prose is not inspected (empty-description detection
would
need `numpydoc.validate` and is out of scope). Static source analysis,
so it does
not confirm what the reference actually renders.

## Where it lives / rollout

Sits in the `ci/ray_ci/doc` guard family next to
`cmd_check_api_discrepancy.py`,
and runs in the **lint group** (static, no docbuild). It starts as a
`soft_fail: true` step -- **visible but non-blocking** -- so the
measured
false-positive rate above can be confirmed against live traffic before
the check
gates anything. Flipping it to a required check is a one-line removal of
`soft_fail`.

One caveat for reviewers on the warn phase: the pipeline passes
`--blocking` and
relies on `soft_fail` to absorb the exit code, so an environment failure
(an
unfetched base branch, a shallow clone deeper than `--depth=500`)
surfaces the
same way a finding does. Happy to drop `--blocking` from the pipeline
command
instead, so the script's own warn mode carries the phase and
infrastructure
errors stay distinguishable from real findings.

Because the check is AST-based, it matches only *directly* applied
`@PublicAPI`
decorators, which lines up with the direct-annotation policy established
in
ray-project#65196 and ray-project#65208.

## Testing

- `python -m pytest ci/ray_ci/doc/test_api_param_coverage.py` -- **28
passed**.
Covers new API, new param, grandfathered gap, removed doc entry,
non-public /
private skips, `@PublicAPI(...)` call form,
`__init__`-on-class-docstring,
`Args:` block termination on dedent, docstring-inheritance recovery, and
the
  `@DeveloperAPI`/`@Deprecated`-method scoping rule.
- End-to-end on the pydoclint blind spot, which is the case this check
exists
  for: adding an undocumented `strict` param to `RayError.from_bytes` (a
`@PublicAPI` method with no docstring) fired on exactly `strict`, while
pydoclint under the pre-commit config reported no violations on the same
file.
  `--blocking` exits 1; documenting the param cleared it.
- End-to-end on a case pydoclint *does* cover, to confirm agreement
rather than
contradiction: adding an undocumented `seed` param to `tune.loguniform`
fired
on exactly `seed` and correctly grandfathered the pre-existing gaps in
the same
  file. pydoclint independently blocks this one at pre-commit.
- `shellcheck ci/lint/lint.sh` clean; `.buildkite/lint.rayci.yml`
parses.
- Renaming `python/ray/exceptions.py` with no content change reported 22
violations across 11 callables before rename detection was added, and
reports
none after. A rename that also adds an undocumented param still fires on
  exactly that param.

### False-positive rate, measured against real history

Replayed the check over the **200** most recent merged commits touching
`python/ray/**/*.py`, each evaluated against its own parent. **Two**
fired (1%):

- ray-project#64963 flagged `Dataset.map_batches_internal` with 15 parameters. A
genuine
false positive: the method is `@DeveloperAPI`, but the check was pulling
in
every non-underscore method of an `@PublicAPI` class regardless of the
method's
own annotation. Fixed in this PR, with regression tests; the commit is
clean on
  the replay now.
- ray-project#64519 flagged `mode`, a newly added and undocumented parameter on
`Catalog.resolve` (`@PublicAPI(stability="alpha")`, one-line docstring).
A true
positive, and squarely the blind-spot class this check exists for. It
correctly
grandfathered the pre-existing `table` and `reader` gaps on the same
callable.

Post-fix that is **one firing across 200 commits, and it is a real
finding**.

### False-negative probe

Coverage was probed independently of the replay: for every `@PublicAPI`
callable
on the surface, inject a new undocumented keyword parameter and assert
the check
reports it. **815 callables probed, 0 misses** -- 585 that are currently
fully
documented, plus the 230 that already carry gaps, which verifies that
grandfathering an existing gap doesn't mask a newly added parameter.
Broken out
by shape: 176 module-level functions, 470 methods, 157 `__init__`, and
12 async
methods, with no misses in any group.

## Alternatives considered

- **Flip `--skip-checking-short-docstrings=False` repo-wide.** 8,285
callables, no
  `@PublicAPI` scoping. Rejected above.
- **A second pydoclint invocation with that flag plus its own
baseline.**
pre-commit is already diff-scoped, so this is closer than it looks, but
it
requires committing a baseline on the order of 8,000 entries and still
gates all
  of `python/ray` rather than the rendered public surface.

## Relationship to other open work

No open PR builds a parameter-coverage gate. ray-project#64779 changes how type
hints render
into the Parameters list, which is a separate deliverable and does not
gate new
undocumented params.

## AI assistance

This change was developed with AI assistance. The submitter has reviewed
every
changed line and run the tests above locally.

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

devprod go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants