Repository navigation
[ci/doc] Apply the direct-annotation rule to the doc-side resolve check - #65208
dstrodtman merged 1 commit into
Conversation
Follow-up to ray-project#65196, which stopped the API walk and the subpackage guard from treating inherited annotations as owned ones. The third reader of that marker family was left on a plain getattr: annotated_type = getattr(obj, "_annotated_type", None) `_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, so a documented, undecorated subclass of a @deprecated class fails as "documented API resolves to a deprecated object" -- on a doc entry that is correct, for a class nobody deprecated. Same inheritance bug as ray-project#65196, opposite direction, latent until someone documents such a subclass. Route the read through `_is_directly_annotated`. Safe in both directions: an inherited @deprecated resolves to UNKNOWN and is accepted, and 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, because functions do not inherit class attributes. Move `_is_directly_annotated` 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. The docstring now points at `ray.util.annotations._is_annotated` as the definition this deliberately mirrors, so the name-equality edge case is not later "fixed" into divergence from what Ray's runtime considers annotated. Also refresh the `_import_status` docstring, which still described the old hasattr rule that ray-project#65196 replaced. Tests: a deprecated class and an undecorated subclass in the mock fixture, unit coverage on `introspect_annotation_type` in both directions, and a regression test through `split_resolvable_and_broken_doc_apis` for the failure above. Both new tests fail without the api.py change. test_walk is rekeyed by name instead of list index, since it silently depended on dir() ordering of the fixture, and test_walk_ignores_inherited_api_annotations gains a positive control so it cannot pass by the walk finding nothing. Signed-off-by: Douglas Strodtman <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request refactors the API annotation checking logic by moving the _is_directly_annotated helper function to ci/ray_ci/doc/api.py and using it to ensure that inherited annotations (such as @Deprecated or @PublicAPI on base classes) are ignored when evaluating subclasses. It also adds corresponding unit tests to verify this behavior. The review feedback suggests wrapping the attribute accesses in _is_directly_annotated with a try-except block to defensively handle arbitrary objects that might raise exceptions during attribute lookup.
| annotation_owner = getattr(obj, "_annotated", None) | ||
| return annotation_owner is not None and annotation_owner == getattr( | ||
| obj, "__name__", None | ||
| ) |
There was a problem hiding this comment.
When resolving documented APIs, obj can be any arbitrary object (including third-party objects, custom descriptors, or proxy objects) that might have custom __getattr__ implementations or properties. Accessing _annotated or __name__ on such objects can raise unexpected exceptions (e.g., TypeError, ValueError, or custom exceptions), which would crash the entire API discrepancy check script.
Wrapping the attribute access in a try-except block ensures that any such exceptions are safely caught and treated as not directly annotated, preventing unexpected CI failures.
| annotation_owner = getattr(obj, "_annotated", None) | |
| return annotation_owner is not None and annotation_owner == getattr( | |
| obj, "__name__", None | |
| ) | |
| try: | |
| annotation_owner = getattr(obj, "_annotated", None) | |
| return annotation_owner is not None and annotation_owner == getattr( | |
| obj, "__name__", None | |
| ) | |
| except Exception: | |
| return False |
References
- Defensive programming: ensure appropriate guards or exception handling exist before accessing properties on arbitrary or potentially nullable/untrusted objects to prevent unexpected runtime crashes.
There was a problem hiding this comment.
Checked this rather than taking it at face value, and it's half right in a way worth writing down.
The exposure is real. getattr(obj, "_annotated", None) only swallows AttributeError — the default doesn't catch anything else — so a module or metaclass with a PEP 562 __getattr__ that raises ValueError / ImportError propagates and takes the whole check down:
>>> getattr(hostile, "_annotated", None)
ValueError: lazy import blew up on _annotated
The placement is right about coverage. I assumed the walk would crash earlier, at getattr(module, child) in _walk, which would have made a guard here useless on that path. That's wrong: dir() doesn't consult __getattr__, so the walk gets past that line and lands in this helper.
module.py:58 if self._is_api(attribute):
module.py:93 return self._is_valid_child(module) and _is_directly_annotated(module)
api.py:35 annotation_owner = getattr(obj, "_annotated", None)
_import_status is the one caller already protected, and its except Exception: continue carries a comment noting lazy attribute access blew up in practice — so this failure mode isn't hypothetical in this repo.
Two reasons I'm still leaving it out of this PR.
First, it's pre-existing rather than introduced here. Master's introspect_annotation_type did getattr(obj, "_annotated_type", None) and crashes identically, and pre-#65196 _is_api used hasattr, which also only swallows AttributeError. This PR relocates the exposure; it doesn't create it. Fixing it here would bury an unrelated behavior change in a follow-up whose point is the inheritance rule.
Second, and more substantively, except Exception: return False means different things at the two call sites. In introspect_annotation_type it's clean — "couldn't introspect" maps onto the existing UNKNOWN case, which is already accepted. In the walk it isn't: a class whose attribute access raises would silently stop being a required-to-be-documented API. That's a quiet enforcement hole, which is the exact failure _check_unwalked_annotated_subpackages was built to catch. Swapping a loud crash for a silent coverage gap is the wrong trade on that path, and a blanket except in the shared helper applies it to both. _import_status gets away with the same swallow because it's an explicitly best-effort probe with the fallback reasoned about at the site — a scoped decision, not a default.
The version I'd argue for guards the doc-side resolve path, where UNKNOWN is already a valid answer, and lets the walk keep failing loudly. That's a different change from this one and applies to master today, so I'd rather file it than bolt it on here.
There was a problem hiding this comment.
Filed as #65209 with the repro, the traceback, and the split fix (guard the docs-to-code path where UNKNOWN is already a valid answer; leave the walk loud so it cannot silently drop a required-to-be-documented symbol). It also records the interim escape hatches, since the two paths differ: a documented name can be parked in a team white_list_apis / doc_only_whitelist, which short-circuits before resolve(), but the walk has no per-name lever.
Keeping this PR scoped to the inheritance rule.
…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]>
## 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]>
…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]>
…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]>
…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]>
…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]>
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 plaingetattr:_annotated_typeis 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@Deprecatedclass 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_typethrough_is_directly_annotated. This is safe in both directions:@Deprecatedresolves toUNKNOWNand is accepted, removing the false failure@PublicAPIresolves toUNKNOWNand is still accepted, sinceUNKNOWNis already the accepted case for a documented method of an annotated classMethods are unaffected either way — functions don't inherit class attributes, so
Dataset.map_batchesalready resolved toUNKNOWN._is_directly_annotatedmoves frommodule.pytoapi.pyso both sides share one definition.module.pyalready imports fromapi.py, so leaving it in place would have made the dependency circular. Its docstring now namesray.util.annotations._is_annotatedas 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_statusdocstring, which still described thehasattrrule #65196 replaced.Tests
@Deprecatedclass 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 readsDEPRECATEDso 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.pychange (verified locally by reverting it).Two hardening changes to the existing tests while the fixture grew:
test_walkis rekeyed by name instead of list index. It silently depended ondir()ordering of the mock module, so any annotated symbol added to the fixture renumbered its assertions.test_walk_ignores_inherited_api_annotationsgains 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/, excludingtest_update_cache_env.py, which needs Sphinx installed).Related
Follow-up to #65196. Consistent with the AST-based
@PublicAPIdetection 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.