dongjoon-hyun commented on code in PR #60555: URL: https://github.com/apache/spark/pull/60555#discussion_r4588700171
########## dev/agent_docs_lint.py: ########## @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +""" +Checks the repository's agent instruction files (AGENTS.md / CLAUDE.md, and the detail files +in .agents/ directories) for the properties that coding agents such as Claude Code and Codex +depend on: + + pairing Each directory with agent instructions has both names, one a symlink to the + other, as the root AGENTS.md asks. Codex reads AGENTS.md and ignores CLAUDE.md + by default. Claude Code reads AGENTS.md only when no CLAUDE.md exists in the + working directory or above it, so once the root has a CLAUDE.md, a nested + directory with only an AGENTS.md is skipped. Two real files let the two tools + follow different instructions. + codex-cap Codex concatenates AGENTS.md from the repo root down to its working directory + into one budget of project_doc_max_bytes (32768 by default), filled root first, + and silently truncates past it. Every root-to-directory chain must fit. + budget Soft size targets that keep always-loaded instructions small: the root file + and nested files. Detail belongs in a sibling .agents/ directory behind a + pointer. Warnings only. + pointers Every `.agents/...`, `AGENTS.md` or `CLAUDE.md` path quoted in an instruction + file, including the files under .agents/, resolves to an existing file. + +Known failures that cannot be fixed yet (e.g. vendored third-party docs) can be exempted in +an optional exceptions file, dev/agent_docs_lint_exceptions.txt by default. Each line is +`<check> <subject>`, where the subject is what the error names: the directory for pairing, +the file where truncation starts for codex-cap, and `<file> <target>` for pointers. `#` +starts a comment. Exempted errors are still reported but do not fail --strict. An entry that +no longer matches any error is itself an error, so the list only shrinks as files are fixed. + +Report-only by default; pass --strict to exit non-zero on errors (not on budget warnings). +CI runs it with --strict. + + $ dev/agent_docs_lint.py + $ dev/agent_docs_lint.py --strict --only codex-cap +""" + +import argparse +import os +import re +import subprocess +import sys +from collections import defaultdict + +CODEX_CAP = 32768 +ROOT_BUDGET = 8 * 1024 +NESTED_BUDGET = 4 * 1024 +CHECKS = ("pairing", "codex-cap", "budget", "pointers") +EXEMPTIBLE = ("pairing", "codex-cap", "pointers") +EXCEPTIONS_FILE = "dev/agent_docs_lint_exceptions.txt" +NAMES = ("AGENTS.md", "CLAUDE.md", "AGENTS.override.md") +POINTER_RE = re.compile(r"`((?:[\w.-]+/)*(?:\.agents/[\w./-]+\.md|AGENTS\.md|CLAUDE\.md))`") + + +def repo_root(): + return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip() + + +def tracked_files(): + # Tracked plus untracked-but-not-ignored files, so a new AGENTS.md is checked before it is + # staged. Skip tracked files deleted in the working tree. + out = subprocess.check_output( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], text=True + ) + return sorted({p for p in out.split("\0") if p and os.path.lexists(p)}) + + +def is_detail_file(path): + """A Markdown file under a .agents/ directory.""" + return path.endswith(".md") and ".agents" in path.split("/")[:-1] + + +def codex_selected(directory): + """The one file Codex loads in `directory`, if any (override > AGENTS.md).""" + for name in ("AGENTS.override.md", "AGENTS.md"): + path = os.path.join(directory, name) + if os.path.isfile(path): + return path + return None + + +def size(path): + with open(path, "rb") as f: + return len(f.read()) + + +# Each check returns (errors, warnings). An error is a (subject, message) pair; the subject is +# what an exceptions-file entry names to exempt it. + + +def check_pairing(dirs): + errors = [] + for d, names in sorted(dirs.items()): + shown = d or "." + agents = os.path.join(d, "AGENTS.md") + claude = os.path.join(d, "CLAUDE.md") + if "AGENTS.md" not in names: + msg = ( + f"no AGENTS.md (found {', '.join(sorted(names))}). Make AGENTS.md the real " + "file and CLAUDE.md a symlink to it" + ) + elif not os.path.isfile(agents): + msg = "AGENTS.md is a dangling symlink" + elif "CLAUDE.md" not in names: + msg = ( + "only AGENTS.md; add a CLAUDE.md symlink to it (ln -s AGENTS.md CLAUDE.md). " + "By default Claude Code skips it when a CLAUDE.md exists in or above its " + "working directory" + ) + elif os.path.realpath(claude) != os.path.realpath(agents): Review Comment: **[1] `pairing` passes when an `AGENTS.override.md` makes Codex and Claude Code read different files.** `codex_selected` already models that Codex prefers `AGENTS.override.md` over `AGENTS.md`, but `check_pairing` compares only `AGENTS.md` with `CLAUDE.md`. Take a directory with a real `AGENTS.md`, `CLAUDE.md -> AGENTS.md` and an `AGENTS.override.md`. Codex reads the override and Claude Code reads `AGENTS.md`, yet the two realpaths match, so the directory passes. That is the "two tools follow different instructions" case this check exists for. Since `tracked_files` also lists untracked files, a local override is picked up here too. Would it work to compare `CLAUDE.md` with the file Codex selects instead, e.g. `os.path.realpath(claude) != os.path.realpath(codex_selected(d))`, and report the override in the message when it is the one that differs? ########## dev/agent_docs_lint.py: ########## @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +""" +Checks the repository's agent instruction files (AGENTS.md / CLAUDE.md, and the detail files +in .agents/ directories) for the properties that coding agents such as Claude Code and Codex +depend on: + + pairing Each directory with agent instructions has both names, one a symlink to the + other, as the root AGENTS.md asks. Codex reads AGENTS.md and ignores CLAUDE.md + by default. Claude Code reads AGENTS.md only when no CLAUDE.md exists in the + working directory or above it, so once the root has a CLAUDE.md, a nested + directory with only an AGENTS.md is skipped. Two real files let the two tools + follow different instructions. + codex-cap Codex concatenates AGENTS.md from the repo root down to its working directory + into one budget of project_doc_max_bytes (32768 by default), filled root first, + and silently truncates past it. Every root-to-directory chain must fit. + budget Soft size targets that keep always-loaded instructions small: the root file + and nested files. Detail belongs in a sibling .agents/ directory behind a + pointer. Warnings only. + pointers Every `.agents/...`, `AGENTS.md` or `CLAUDE.md` path quoted in an instruction + file, including the files under .agents/, resolves to an existing file. + +Known failures that cannot be fixed yet (e.g. vendored third-party docs) can be exempted in +an optional exceptions file, dev/agent_docs_lint_exceptions.txt by default. Each line is +`<check> <subject>`, where the subject is what the error names: the directory for pairing, +the file where truncation starts for codex-cap, and `<file> <target>` for pointers. `#` +starts a comment. Exempted errors are still reported but do not fail --strict. An entry that +no longer matches any error is itself an error, so the list only shrinks as files are fixed. + +Report-only by default; pass --strict to exit non-zero on errors (not on budget warnings). +CI runs it with --strict. + + $ dev/agent_docs_lint.py + $ dev/agent_docs_lint.py --strict --only codex-cap +""" + +import argparse +import os +import re +import subprocess +import sys +from collections import defaultdict + +CODEX_CAP = 32768 +ROOT_BUDGET = 8 * 1024 +NESTED_BUDGET = 4 * 1024 +CHECKS = ("pairing", "codex-cap", "budget", "pointers") +EXEMPTIBLE = ("pairing", "codex-cap", "pointers") +EXCEPTIONS_FILE = "dev/agent_docs_lint_exceptions.txt" +NAMES = ("AGENTS.md", "CLAUDE.md", "AGENTS.override.md") +POINTER_RE = re.compile(r"`((?:[\w.-]+/)*(?:\.agents/[\w./-]+\.md|AGENTS\.md|CLAUDE\.md))`") + + +def repo_root(): + return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip() + + +def tracked_files(): + # Tracked plus untracked-but-not-ignored files, so a new AGENTS.md is checked before it is + # staged. Skip tracked files deleted in the working tree. + out = subprocess.check_output( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], text=True + ) + return sorted({p for p in out.split("\0") if p and os.path.lexists(p)}) + + +def is_detail_file(path): + """A Markdown file under a .agents/ directory.""" + return path.endswith(".md") and ".agents" in path.split("/")[:-1] + + +def codex_selected(directory): + """The one file Codex loads in `directory`, if any (override > AGENTS.md).""" + for name in ("AGENTS.override.md", "AGENTS.md"): + path = os.path.join(directory, name) + if os.path.isfile(path): + return path + return None + + +def size(path): + with open(path, "rb") as f: + return len(f.read()) + + +# Each check returns (errors, warnings). An error is a (subject, message) pair; the subject is +# what an exceptions-file entry names to exempt it. + + +def check_pairing(dirs): + errors = [] + for d, names in sorted(dirs.items()): + shown = d or "." + agents = os.path.join(d, "AGENTS.md") + claude = os.path.join(d, "CLAUDE.md") + if "AGENTS.md" not in names: + msg = ( + f"no AGENTS.md (found {', '.join(sorted(names))}). Make AGENTS.md the real " + "file and CLAUDE.md a symlink to it" + ) + elif not os.path.isfile(agents): + msg = "AGENTS.md is a dangling symlink" + elif "CLAUDE.md" not in names: + msg = ( + "only AGENTS.md; add a CLAUDE.md symlink to it (ln -s AGENTS.md CLAUDE.md). " + "By default Claude Code skips it when a CLAUDE.md exists in or above its " + "working directory" + ) + elif os.path.realpath(claude) != os.path.realpath(agents): + msg = ( + "AGENTS.md and CLAUDE.md are different files, so Claude Code and Codex can " + "follow different instructions. Keep one real file and make the other a " + "symlink to it" + ) + else: + continue + errors.append((shown, f"{shown}: {msg}")) + return errors, [] + + +def check_codex_cap(dirs): + # Group by the file where truncation starts: one oversized ancestor cuts every chain + # below it, and listing each of those chains separately hides the cause. + cuts = defaultdict(list) + for d in sorted(dirs): + parts = d.split("/") if d else [] + chain = [] + for i in range(len(parts) + 1): + f = codex_selected("/".join(parts[:i])) + if f: + chain.append(f) + total = sum(size(f) for f in chain) + if total > CODEX_CAP: + used, cut_in = 0, None + for f in chain: + if used + size(f) > CODEX_CAP: + cut_in = f + break + used += size(f) + cuts[cut_in].append((d or ".", total)) + errors = [] + for cut_in, chains in sorted(cuts.items()): + worst = max(chains, key=lambda c: c[1]) + msg = ( + f"{cut_in}: Codex truncates here in {len(chains)} chain(s); worst is " + f"{worst[0]} at {worst[1]} bytes, {worst[1] - CODEX_CAP} bytes never seen" + ) + errors.append((cut_in, msg)) + return errors, [] + + +def check_budget(files): + warnings = [] + for f in files: + if os.path.islink(f): + continue + budget = ROOT_BUDGET if os.path.dirname(f) == "" else NESTED_BUDGET + n = size(f) + if n > budget: + warnings.append( + f"{f}: {n} bytes > {budget} target; move branch-only detail into .agents/ " + "behind a pointer" + ) + return [], warnings + + +def check_pointers(files): + errors = [] + for f in files: + if os.path.islink(f): + continue + # Pointers may be written relative to the file or to any ancestor directory (e.g. a + # nested AGENTS.md naming `.agents/x.md` beside it, or a file under .agents/ naming + # a sibling as `.agents/y.md`). + parts = os.path.dirname(f).split("/") if os.path.dirname(f) else [] + bases = ["/".join(parts[:i]) for i in range(len(parts), -1, -1)] + with open(f, encoding="utf-8", errors="replace") as fh: + for lineno, line in enumerate(fh, 1): + for target in POINTER_RE.findall(line): + if "..." in target.split("/"): + continue # An elided path such as `a/.../AGENTS.md`, not a pointer. + candidates = [os.path.normpath(os.path.join(b, target)) for b in bases] Review Comment: **[2] A pointer resolves against any ancestor, so a nested pointer to the wrong `.agents/` still passes.** The root `AGENTS.md` says each index points to "a `.agents/` directory beside it", but `bases` tries the file's own directory and then every ancestor up to the root. Say `sql/core/AGENTS.md` names `.agents/build-and-test.md` and means `sql/core/.agents/build-and-test.md`, and that file is renamed or never added. The root `.agents/build-and-test.md` exists, so the pointer passes. An agent that follows the "beside it" rule looks in `sql/core/.agents/` and finds nothing, or reads the root file by accident. Today every pointer is at the root, so nothing is affected yet. The ancestor search seems to be needed only for a file under `.agents/` that names a sibling as `.agents/y.md`. Could `bases` be just the instruction file's own directory, plus the parent of `.agents/` for a detail file? ########## .agents/build-and-test.md: ########## @@ -0,0 +1,60 @@ +# Build and Test + +Build and tests can take a long time, so prefer the narrowest relevant build or test command. Review Comment: **[7] nit: the root and the detail files now carry the same text.** Most of L3-L25 here repeats what `AGENTS.md` L37-L40 now say inline: the narrowest command, SBT over Maven, where the module names are, `compile`, `Test/compile` and `testOnly ... -- -z`. The first paragraphs of `code-conventions.md` and `pr-merge-status.md` overlap with the root in the same way. Moving the text verbatim made the "no content lost" check easy. From now on, though, each command or rule has two copies to keep in sync, and an agent that follows the pointer reads both. Once this lands, consider trimming each detail file to what the root does not already say, which here is the optional-module profile, interactive SBT and the PySpark section. ########## AGENTS.md: ########## @@ -12,263 +32,63 @@ Before the first code edit or running test in a session, ensure a clean working - **New edits**: ask the user to choose: create a new git worktree from `<upstream>/master` with `--no-track` and work from there (recommended), or create and switch to a new branch from `<upstream>/master` with `--no-track`. - **Running tests**: use `<upstream>/master`. -## Development Notes - -SQL golden file tests are managed by `SQLQueryTestSuite` and its variants. Read the class documentation before running or updating these tests. DO NOT edit the generated golden files (`.sql.out`) directly. Always regenerate them when needed, and carefully review the diff to make sure it's expected. - -When adding new SQL syntax or a user-visible SQL feature, follow the streaming test coverage -guidance in the `SQLQueryTestSuite` class documentation. - -Spark Connect protocol is defined in proto files under `sql/connect/common/src/main/protobuf/`. Read the README there before modifying proto definitions. - -When adding a member to an existing class or object, follow the sectioning the file already uses and put the new member with the code it belongs with. The common failure mode is dropping it wherever it is first used without checking how the file is organized, splitting a section of unrelated code in the process. Beyond grouping related code there is no prescribed order -- the Databricks Scala guide, which Spark follows, asks only that a long class group its members into logical sections with comment headers. Do not reorganize existing members unless the change requires it. - -Avoid introducing non-ASCII characters in code or comments. String literals may contain non-ASCII when the content requires it (error messages, test data, etc.). Identifiers are ASCII by convention. The common failure mode is typographic characters (em-dash, smart quotes, ellipsis, non-breaking space) sneaking into comments; scalastyle flags some of these. Spot-check before committing: `grep -rn -P "[^\x00-\x7F]" <files>`. - -Keep source lines within 100 characters — the linters enforce this for Scala, Java, and Python, and LLMs commonly overrun it in comments and long expressions. A quick scan of just the changed files catches most cases in seconds, far cheaper than a CI round trip: - - { git diff --name-only --diff-filter=ACM HEAD; git ls-files --others --exclude-standard; } \ - | grep -E '\.(scala|java|py)$' | sort -u \ - | xargs -r awk 'length>100 && $0 !~ /^[[:space:]]*(import|package) / && $0 !~ /https?:\/\// \ - {print FILENAME":"FNR": "length" chars"}' - -This is only a hint: it approximates the linters' exemptions (imports, URLs) rather than matching them exactly, so it can over- or under-report. The linters remain the source of truth. - -## Scala Test Base Classes - -When writing a new Scala test suite, pick the lowest base class that provides what the test actually needs. Spark uses the `AnyFunSuite` ScalaTest style throughout, so the bases below are the chain to choose from. Each adds capability on top of the previous: - - SparkFunSuite (core) - <- PlanTest (sql/catalyst) - <- QueryTest (sql/core) - -| Test scope | Base | Notes | -|------------|------|-------| -| Plain JVM/Scala — no Spark SQL | `SparkFunSuite` | `core` utilities, RDD, network, util classes, etc. Adds per-test timeout, `testRetry`, `gridTest`, thread audit, fixed timezone/locale, `withTempDir`, `withLogAppender`, `checkError`. | -| Catalyst plan tests — no `SparkSession` | `PlanTest` | Adds `comparePlans`, `normalizePlan`, `normalizeExprIds`. For analyzer / optimizer / planner rule tests. | -| SQL/DataFrame tests — needs a `SparkSession` | `QueryTest` | Adds `checkAnswer`, codegen-on/off helpers. `spark: SparkSession` is abstract and must be supplied by a session-providing trait (see below). | - -### Providing a `SparkSession` for `QueryTest` - -`QueryTest` declares `spark: SparkSession` abstractly via `SparkSessionProvider`, so it cannot be instantiated on its own. A concrete suite mixes in one of the session-providing traits below: - - QueryTest (abstract `spark`) - + SharedSparkSession (sql/core) -> classic in-process `TestSparkSession` - + TestHiveSingleton (sql/hive) -> Hive-backed `TestHive` session - -| Session provider | Module / location | Typical usage | -|---|---|---| -| `SharedSparkSession` | `sql/core` | Already extends `QueryTest` for historical reasons, but still mix in `QueryTest` explicitly, e.g. `class X extends QueryTest with SharedSparkSession`. Default for tests under `sql/core`. | -| `TestHiveSingleton` | `sql/hive` | Mixed in alongside `QueryTest`, e.g. `class X extends QueryTest with TestHiveSingleton`. Used by tests under `sql/hive`. | - -## Python Test Base Classes - -PySpark tests use the stdlib `unittest` framework: every suite subclasses `unittest.TestCase` (run via `python/run-tests`, see below). As with Scala, pick the lowest base that provides what the test actually needs. The bases live under `python/pyspark/testing/` and each adds capability on top of the previous: - - unittest.TestCase (stdlib) - <- PySparkBaseTestCase (pyspark.testing.utils) - <- ReusedPySparkTestCase (pyspark.testing.utils) - <- ReusedSQLTestCase (pyspark.testing.sqlutils) - <- PandasOnSparkTestCase (pyspark.testing.pandasutils) - -| Test scope | Base | Notes | -|------------|------|-------| -| Plain Python — no Spark | `unittest.TestCase` | Use the stdlib base directly. `PySparkBaseTestCase` is the same thing plus a SIGTERM fault-handler dump enabled when `PYSPARK_TEST_TIMEOUT` is set; subclass it only when you want that. | -| RDD / `SparkContext` — no `SparkSession` | `PySparkTestCase` (fresh) or `ReusedPySparkTestCase` (shared) | Both create a `SparkContext("local[4]")`. `PySparkTestCase` makes a new one per test (isolation); `ReusedPySparkTestCase` shares one per class (faster, the usual choice) and adds `quiet()` and an overridable `conf()` / `master()`. | -| SQL / DataFrame — needs a `SparkSession` | `ReusedSQLTestCase` | The workhorse for classic tests under `python/pyspark/sql`. Adds a shared `cls.spark`, sample `cls.df` / `cls.testData`, and mixes in `SQLTestUtils` + `PySparkErrorTestUtils`. Classic (non-Connect) mode. | -| pandas API on Spark | `PandasOnSparkTestCase` | Extends `ReusedSQLTestCase` with Arrow enabled and pandas-on-Spark assertions (`PandasOnSparkTestUtils`); `ComparisonTestBase` builds on it. | - -### Spark Connect test bases - -Spark Connect suites live in `pyspark.testing.connectutils` and are auto-skipped (via `should_test_connect`) when Connect dependencies are missing: - - PySparkBaseTestCase (pyspark.testing.utils) - <- PlanOnlyTestFixture (pyspark.testing.connectutils) - <- ReusedConnectTestCase (pyspark.testing.connectutils) - <- ReusedMixedTestCase (pyspark.testing.connectutils) - -| Test scope | Base | Notes | -|------------|------|-------| -| Plan / proto construction — no server | `PlanOnlyTestFixture` | Uses a `MockRemoteSession`; builds and inspects plans without a running Connect server. For proto / plan-shape assertions. | -| Connect DataFrame — real session | `ReusedConnectTestCase` | The Connect analog of `ReusedSQLTestCase`; starts a session via `.remote(...)` (honoring `SPARK_CONNECT_TESTING_REMOTE`, default `local[4]`). Mixes in `SQLTestUtils` + `PySparkErrorTestUtils`. | -| Classic + Connect side by side | `ReusedMixedTestCase` | Extends `ReusedConnectTestCase`. For directly comparing classic vs Connect: it exposes a classic `self.spark` and a Connect `self.connect` so a test can run the same operation on each and assert they agree (`compare_by_show`, `both_conf`). Requires JVM access. | - -### Mixins and helpers - -These are combined with a base above rather than used on their own: - -- `SQLTestUtils` — context managers `sql_conf`, `table`, `temp_view`, `view`, `database`, `function`, `temp_func`, `temp_env`; assumes `self.spark`. Already mixed into `ReusedSQLTestCase` and `ReusedConnectTestCase`. -- `PySparkErrorTestUtils` — `check_error(...)` to assert on a `PySparkException`'s error class and message parameters. The Python counterpart of Scala's `checkError`. -- `assertDataFrameEqual` / `assertSchemaEqual` (public API, from `pyspark.testing`) — standalone assertion functions that work in any test, no particular base class required. -- Domain bases outside the main ladder: `SparkSessionTestCase` (`pyspark.testing.mlutils`, for `ml`), `MLlibTestCase` (`pyspark.testing.mllibutils`), and `PySparkStreamingTestCase` (`pyspark.testing.streamingutils`, DStreams). - ## Build and Test -Build and tests can take a long time, so prefer the narrowest relevant build or test command. - -For build and test setup, including how to run tests and troubleshoot common -local failures, see `docs/building-spark.md`. - -Prefer SBT over Maven for faster incremental compilation. Module names are defined in `project/SparkBuild.scala`. - -Compile a single module: - - build/sbt <module>/compile - -Compile test code for a single module: - - build/sbt <module>/Test/compile - -Run test suites by wildcard or full class name: - - build/sbt '<module>/testOnly *MySuite' - build/sbt '<module>/testOnly org.apache.spark.sql.MySuite' - -Run test cases matching a substring: - - build/sbt '<module>/testOnly *MySuite -- -z "test name"' - -Run test cases in an optional module: - - build/sbt -P<maven-profiles> '<module>/testOnly *MySuite' - -For faster iteration, keep SBT open in interactive mode: - - build/sbt - > project <module> - > testOnly *MySuite - -### PySpark Tests - -PySpark tests require building Spark with Hive support first: - - build/sbt -Phive package - -Activate the virtual environment specified by the user, or default to `.venv`: - - source <venv>/bin/activate - -If the default venv does not exist, create it: - - python3 -m venv .venv - source .venv/bin/activate - pip install --upgrade pip - pip install --group dev - -Run a single test suite: - - python/run-tests --testnames pyspark.sql.tests.arrow.test_arrow - -Run a single test case: - - python/run-tests --testnames "pyspark.sql.tests.test_catalog CatalogTests.test_current_database" - -## Investigating PR CI Failures - -Enumerate all failing check runs first, then drill into each by type. Do not assume a single failure: a PR can fail tests, linters, and the build at once, and these surface through different channels. - -Step 1 — Get the fork owner and the latest commit SHA of the PR: - - gh api repos/apache/spark/pulls/<PR_NUMBER> --jq '{owner: .head.repo.owner.login, sha: .head.sha}' - -Step 2 — List every failing check run on the fork's commit. This is the complete failure set: - - gh api repos/<OWNER>/spark/commits/<SHA>/check-runs --paginate \ - --jq '.check_runs[] | select(.conclusion == "failure") | {name, id: .id}' - -A passing (or absent) "Report test results" does NOT mean CI is green. That check aggregates only test-case failures; linter, license, dependency, MiMa, compile, and doc-build failures are separate check runs that produce no test annotations. Always work from the list in Step 2, not from any single check. - -Step 3 — Drill into each failure according to its kind: - -- **Test jobs** (e.g. "Report test results", "Build modules: ..."): fetch failure annotations. Each annotation contains the test class, test name, and failure message: - - gh api repos/<OWNER>/spark/check-runs/<CHECK_RUN_ID>/annotations - -- **Non-test jobs** (e.g. "Linters, licenses, and dependencies", "Build"): find the failed step, then read only that job's log: - - gh api repos/<OWNER>/spark/actions/jobs/<JOB_ID> \ - --jq '{name, steps: [.steps[] | select(.conclusion == "failure") | .name]}' - gh api repos/<OWNER>/spark/actions/jobs/<JOB_ID>/logs - -Avoid downloading the large per-shard *test* job logs — they are very large and slow; use the annotations for those. Lint, license, dependency, and build job logs are small and fine to read directly when a step fails. - -## Checking PR Merge Status - -Spark merges PRs with `dev/merge_spark_pr.py`, not the GitHub merge button, so a **merged PR shows up on GitHub as Closed, not Merged** — its `merged` / `mergedAt` are empty, and backports to maintenance branches are plain pushes. **Do not read a Closed PR as rejected**; most Closed PRs were in fact merged. - -To check whether, and to which branches, a PR was merged, run `dev/pr_merge_status.py <pr-number>`: - - $ dev/pr_merge_status.py 56356 - PR #56356 (base master): [SPARK-57295][SQL] Make database location validation ... - merged: yes - master 9357bc9ae05 - branch-4.x 72edddb358e - -It lists `master` and the latest major's release branches the commit reached (e.g. `branch-4.x`, `branch-4.2`) — or reports `open` or `closed without merging`. It needs `gh` authenticated and a non-shallow checkout, and exits non-zero with a clear message if the PR is unknown (404) or the environment isn't ready (no `gh`/auth, no apache/spark remote). Older majors' branches are omitted; pass `--all-branches` to list every branch the commit reached. - -## Pull Request Workflow - -PR title format is `[SPARK-xxxx][COMPONENT] Title`. Draft, WIP, MINOR, and TRIVIAL PRs may omit the JIRA ID. The component tag comes from the `COMPONENTS` registry in `dev/merge_spark_pr.py`, the source of truth: each entry pairs a PR-title tag with its canonical JIRA component name and accepted aliases (e.g. `Documentation` → `[DOC]`, `Pandas API on Spark` → `[PS]`, `SQL` → `[SQL]`). Read that registry to pick the right tag. - -Use `[FOLLOWUP]` only for small PRs that directly modify or correct unreleased earlier PRs. For separately planned work, non-trivial changes, or work outside the earlier JIRA's scope, create a separate JIRA ticket for each PR and use the normal title format without `[FOLLOWUP]`. - -Infer the PR title from the changes. If no ticket ID is given and the PR is not draft, WIP, MINOR, or TRIVIAL, create one using `dev/create_spark_jira.py`, using the PR title (without the JIRA ID and component tag) as the ticket title. - - python3 dev/create_spark_jira.py "<title>" -c <component> { -t <type> | -p <parent-jira-id> } - -- **Component** (`-c`): the exact JIRA component name (not the PR title shorthand), e.g. "SQL", "Spark Core", "PySpark", "Connect". Run `python3 dev/create_spark_jira.py --list-components` for the full list. -- **Issue type** (`-t`): "Bug", "Improvement", "New Feature", "Test", "Documentation", or "Dependency upgrade". -- **Parent** (`-p`): if the user mentions a parent JIRA ticket (e.g., "this is a subtask of SPARK-12345"), pass it instead of `-t`. The issue type is automatically "Sub-task". - -The script sets the latest unreleased version as the default affected version. - -After creating a JIRA ticket, print a prominent notice so the user does not miss it: - - ============================================================ - JIRA ticket created: SPARK-XXXXX - https://issues.apache.org/jira/browse/SPARK-XXXXX - - Title: <title> - Component(s): <component> - Issue type: <type> - Affected version(s): <version> - Priority: <priority> - - Please review and adjust these fields if needed. - ============================================================ - -Before writing the PR description, read `.github/PULL_REQUEST_TEMPLATE` and fill in every section from that file. - -DO NOT push to the upstream repo. Always push to the personal fork. Open PRs against `master` on the upstream repo. - -DO NOT force push or use `--amend` on pushed commits unless the user explicitly asks. If the remote branch has new commits, fetch and rebase before pushing. - -Always get user approval before external operations such as pushing commits, creating PRs, or posting comments. Use `gh pr create` to open PRs. If `gh` is not installed, generate the GitHub PR URL for the user and recommend installing the GitHub CLI. - -## Project Instructions Discovery - -When exploring or working in any directory, always check for nested `AGENTS.md` files in that -directory and its ancestors. Read and follow every applicable file; instructions in a more specific -directory take precedence for that directory's scope. - -A directory may carry these instructions as `CLAUDE.md` rather than `AGENTS.md`, so check **both** names — a directory with only a `CLAUDE.md` has project instructions you must read too. Where both files exist, one is typically the real file and the other is a symlink to it, although either name may be the real file. Reading either one is sufficient. When adding instructions to a directory that has neither file, create AGENTS.md as the real file and add a CLAUDE.md symlink beside it (ln -s AGENTS.md CLAUDE.md). This keeps a single source of truth accessible under both names. - -## Versioning and Branch Policy - -When a change needs a version — `@since` annotations, config `.version("...")` (`SQLConf` / `*Conf`), new `MimaExcludes` sections, etc. — use the version of the branch it first ships in, with `-SNAPSHOT` stripped. Determine that branch: - -- **PR opened against a non-`master` base branch** (e.g. a maintenance line like `branch-4.2`): use that base branch's version -- when you're checked out on it, that's just the working tree's `pom.xml`. The helper below covers only the common `master`-base case. -- **PR opened against `master`:** most PRs merge to **both** `master` and the latest `branch-<N>.x` (the branch for the next feature release, e.g. `branch-4.x`), so use the `branch-<N>.x` version. The exception is **master-only** changes — use `master`'s version — which are only: - - breaking / binary-incompatible changes that can't ship in a minor release; - - dependency upgrades that don't fix a critical issue worth backporting. - -Do **not** just read `master`'s version: a normally-backported PR ships first in `branch-<N>.x`, whose version is lower than `master`'s. If unsure whether a change is master-only, ask the user. - -`dev/next_version_candidates.py` (no arguments) prints both candidate versions, reading from the local `apache/spark` remote (the `upstream` configured during pre-flight). It reports the mechanical facts only -- choosing between them per the rules above is the judgement call (the numbers below are illustrative and advance over time): - - $ dev/next_version_candidates.py - master 5.0.0 - branch-4.x 4.3.0 +- Build and tests can take a long time, so prefer the narrowest relevant command. Prefer SBT over + Maven; module names are defined in `project/SparkBuild.scala`. Compile with + `build/sbt <module>/compile` (`<module>/Test/compile` for test code), and run a suite or test + case with `build/sbt '<module>/testOnly *MySuite -- -z "test name"'`. +- Before running tests in an optional module, using SBT interactively, or running PySpark tests: + read `.agents/build-and-test.md`. For setup and local troubleshooting: `docs/building-spark.md`. +- Before writing a new Scala or Python test suite: read `.agents/test-base-classes.md` and pick + the lowest base class that provides what the test actually needs. +- SQL golden file tests are managed by `SQLQueryTestSuite` and its variants. Read the class + documentation before running or updating these tests. DO NOT edit the generated golden files + (`.sql.out`) directly. Always regenerate them when needed, and carefully review the diff to make + sure it's expected. +- When adding new SQL syntax or a user-visible SQL feature, follow the streaming test coverage + guidance in the `SQLQueryTestSuite` class documentation. + +## Code Standards + +- Keep source lines within 100 characters; the linters enforce this for Scala, Java, and Python. + Avoid non-ASCII characters in code and comments (string literals may contain them when the + content requires it). When adding a member to an existing class or object, put it with the code + it belongs with, following the file's existing sectioning. Detail and spot-check commands: Review Comment: **[5] This is the one pointer without a trigger, and the "do not reorganize" rule moved behind it.** The PR body says each `.agents/` file sits behind a pointer that starts with its trigger, and the other pointers do, e.g. "Before writing a new Scala or Python test suite: ...". This one only says "Detail and spot-check commands:", so it does not tell an agent when to read the file. The inline summary also dropped "Do not reorganize existing members unless the change requires it", which now lives only in `.agents/code-conventions.md`. An agent breaks that rule while it is adding a member, without noticing it is in that situation, which is the criterion L15-L17 give for keeping a rule inline. Maybe keep that sentence here, and start the pointer with a trigger, e.g. "Before committing Scala, Java or Python changes: run the spot-checks in `.agents/code-conventions.md`." ########## dev/next_version_candidates.py: ########## @@ -19,8 +19,8 @@ """ Prints the two candidate first-release versions for a change, so the caller can pick -one per the "Versioning and Branch Policy" section of AGENTS.md (numbers below are -illustrative; the actual versions advance as branches are cut): +one per `.agents/versioning.md` (numbers below are illustrative; the actual versions Review Comment: **[6] nit: the lint does not see the new docstring pointers here and in `pr_merge_status.py`.** This docstring and `dev/pr_merge_status.py` L22 now point to `.agents/versioning.md` and `.agents/pr-merge-status.md`, but `check_pointers` reads only the instruction files and the files under `.agents/`. If one of those two files is renamed, the lint flags the `AGENTS.md` pointer but not these docstrings. Either the pointers check could also read these two scripts, or the docstrings could keep pointing at `AGENTS.md`, which the lint does cover. ########## dev/sparktestsupport/modules.py: ########## @@ -39,6 +39,8 @@ # standard library. ignored_file_patterns = ( # Contributor docs. + ".agents/*.md", Review Comment: **[8] `.agents/*.md` matches only files directly in a `.agents/` directory.** `PurePath.match` with a relative pattern matches from the right, one component per `*`. So `.agents/pr-workflow.md` and `sql/core/.agents/x.md` are ignored, but `.agents/sub/x.md` and `.agents/skills/foo/SKILL.md` are not. I checked that `PurePath("/.agents/sub/b.md").match(".agents/*.md")` is `False`. The lint's `is_detail_file` treats a Markdown file at any depth under `.agents/` as a detail file, so a doc-only change there falls through to the `root` module in `determine_modules_for_files` and runs every test job. If `.agents/` is meant to stay flat, the lint could say so, e.g. report a Markdown file below a direct child of `.agents/`. Otherwise `/.agents/` would cover the whole root subtree, since a trailing slash already means a subtree in this list. ########## .ignore: ########## @@ -0,0 +1,3 @@ +# rg skips hidden directories by default; let it search these tracked ones. +!.agents/ Review Comment: **[11] Would a non-hidden directory name avoid the need for `.ignore`?** `rg` skips `.agents/` only because the name starts with a dot. With a non-hidden name, `rg` would search it by default, and this file, its `dev/.rat-excludes` entry and the `/.ignore` entry in `modules.py` would not be needed. If `.agents/` is chosen because tools are expected to read it by that name, it would help to say so in the PR body. The `.github/` whitelist is a reasonable change on its own, but it changes what `rg`, `fd` and editor search show every contributor, which is a separate decision from splitting `AGENTS.md`. Would it be better as its own PR? ########## dev/agent_docs_lint.py: ########## @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +""" +Checks the repository's agent instruction files (AGENTS.md / CLAUDE.md, and the detail files +in .agents/ directories) for the properties that coding agents such as Claude Code and Codex +depend on: + + pairing Each directory with agent instructions has both names, one a symlink to the + other, as the root AGENTS.md asks. Codex reads AGENTS.md and ignores CLAUDE.md + by default. Claude Code reads AGENTS.md only when no CLAUDE.md exists in the + working directory or above it, so once the root has a CLAUDE.md, a nested + directory with only an AGENTS.md is skipped. Two real files let the two tools + follow different instructions. + codex-cap Codex concatenates AGENTS.md from the repo root down to its working directory + into one budget of project_doc_max_bytes (32768 by default), filled root first, + and silently truncates past it. Every root-to-directory chain must fit. + budget Soft size targets that keep always-loaded instructions small: the root file + and nested files. Detail belongs in a sibling .agents/ directory behind a + pointer. Warnings only. + pointers Every `.agents/...`, `AGENTS.md` or `CLAUDE.md` path quoted in an instruction + file, including the files under .agents/, resolves to an existing file. + +Known failures that cannot be fixed yet (e.g. vendored third-party docs) can be exempted in +an optional exceptions file, dev/agent_docs_lint_exceptions.txt by default. Each line is +`<check> <subject>`, where the subject is what the error names: the directory for pairing, +the file where truncation starts for codex-cap, and `<file> <target>` for pointers. `#` +starts a comment. Exempted errors are still reported but do not fail --strict. An entry that +no longer matches any error is itself an error, so the list only shrinks as files are fixed. + +Report-only by default; pass --strict to exit non-zero on errors (not on budget warnings). +CI runs it with --strict. + + $ dev/agent_docs_lint.py + $ dev/agent_docs_lint.py --strict --only codex-cap +""" + +import argparse +import os +import re +import subprocess +import sys +from collections import defaultdict + +CODEX_CAP = 32768 +ROOT_BUDGET = 8 * 1024 +NESTED_BUDGET = 4 * 1024 +CHECKS = ("pairing", "codex-cap", "budget", "pointers") +EXEMPTIBLE = ("pairing", "codex-cap", "pointers") +EXCEPTIONS_FILE = "dev/agent_docs_lint_exceptions.txt" +NAMES = ("AGENTS.md", "CLAUDE.md", "AGENTS.override.md") +POINTER_RE = re.compile(r"`((?:[\w.-]+/)*(?:\.agents/[\w./-]+\.md|AGENTS\.md|CLAUDE\.md))`") + + +def repo_root(): + return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip() + + +def tracked_files(): + # Tracked plus untracked-but-not-ignored files, so a new AGENTS.md is checked before it is + # staged. Skip tracked files deleted in the working tree. + out = subprocess.check_output( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], text=True + ) + return sorted({p for p in out.split("\0") if p and os.path.lexists(p)}) + + +def is_detail_file(path): + """A Markdown file under a .agents/ directory.""" + return path.endswith(".md") and ".agents" in path.split("/")[:-1] + + +def codex_selected(directory): + """The one file Codex loads in `directory`, if any (override > AGENTS.md).""" + for name in ("AGENTS.override.md", "AGENTS.md"): + path = os.path.join(directory, name) + if os.path.isfile(path): + return path + return None + + +def size(path): + with open(path, "rb") as f: + return len(f.read()) + + +# Each check returns (errors, warnings). An error is a (subject, message) pair; the subject is +# what an exceptions-file entry names to exempt it. + + +def check_pairing(dirs): + errors = [] + for d, names in sorted(dirs.items()): + shown = d or "." + agents = os.path.join(d, "AGENTS.md") + claude = os.path.join(d, "CLAUDE.md") + if "AGENTS.md" not in names: + msg = ( + f"no AGENTS.md (found {', '.join(sorted(names))}). Make AGENTS.md the real " + "file and CLAUDE.md a symlink to it" + ) + elif not os.path.isfile(agents): Review Comment: **[4] nit: a dangling `CLAUDE.md` is reported as two different files.** A dangling `AGENTS.md` gets its own message here, but a dangling `CLAUDE.md` falls through to the `realpath` comparison. `os.path.realpath` returns the missing target, which differs from `AGENTS.md`, so the error says the two are different files and asks to make one a symlink, although it already is a symlink, just a broken one. A branch such as `elif not os.path.exists(claude)` with "CLAUDE.md is a dangling symlink" would name the actual problem. ########## dev/agent_docs_lint.py: ########## @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +""" +Checks the repository's agent instruction files (AGENTS.md / CLAUDE.md, and the detail files +in .agents/ directories) for the properties that coding agents such as Claude Code and Codex +depend on: + + pairing Each directory with agent instructions has both names, one a symlink to the + other, as the root AGENTS.md asks. Codex reads AGENTS.md and ignores CLAUDE.md + by default. Claude Code reads AGENTS.md only when no CLAUDE.md exists in the + working directory or above it, so once the root has a CLAUDE.md, a nested + directory with only an AGENTS.md is skipped. Two real files let the two tools + follow different instructions. + codex-cap Codex concatenates AGENTS.md from the repo root down to its working directory + into one budget of project_doc_max_bytes (32768 by default), filled root first, + and silently truncates past it. Every root-to-directory chain must fit. + budget Soft size targets that keep always-loaded instructions small: the root file + and nested files. Detail belongs in a sibling .agents/ directory behind a + pointer. Warnings only. + pointers Every `.agents/...`, `AGENTS.md` or `CLAUDE.md` path quoted in an instruction + file, including the files under .agents/, resolves to an existing file. + +Known failures that cannot be fixed yet (e.g. vendored third-party docs) can be exempted in +an optional exceptions file, dev/agent_docs_lint_exceptions.txt by default. Each line is +`<check> <subject>`, where the subject is what the error names: the directory for pairing, +the file where truncation starts for codex-cap, and `<file> <target>` for pointers. `#` +starts a comment. Exempted errors are still reported but do not fail --strict. An entry that +no longer matches any error is itself an error, so the list only shrinks as files are fixed. + +Report-only by default; pass --strict to exit non-zero on errors (not on budget warnings). +CI runs it with --strict. + + $ dev/agent_docs_lint.py + $ dev/agent_docs_lint.py --strict --only codex-cap +""" + +import argparse +import os +import re +import subprocess +import sys +from collections import defaultdict + +CODEX_CAP = 32768 +ROOT_BUDGET = 8 * 1024 +NESTED_BUDGET = 4 * 1024 +CHECKS = ("pairing", "codex-cap", "budget", "pointers") +EXEMPTIBLE = ("pairing", "codex-cap", "pointers") +EXCEPTIONS_FILE = "dev/agent_docs_lint_exceptions.txt" +NAMES = ("AGENTS.md", "CLAUDE.md", "AGENTS.override.md") +POINTER_RE = re.compile(r"`((?:[\w.-]+/)*(?:\.agents/[\w./-]+\.md|AGENTS\.md|CLAUDE\.md))`") + + +def repo_root(): + return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip() + + +def tracked_files(): + # Tracked plus untracked-but-not-ignored files, so a new AGENTS.md is checked before it is + # staged. Skip tracked files deleted in the working tree. + out = subprocess.check_output( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], text=True + ) + return sorted({p for p in out.split("\0") if p and os.path.lexists(p)}) + + +def is_detail_file(path): + """A Markdown file under a .agents/ directory.""" + return path.endswith(".md") and ".agents" in path.split("/")[:-1] + + +def codex_selected(directory): + """The one file Codex loads in `directory`, if any (override > AGENTS.md).""" + for name in ("AGENTS.override.md", "AGENTS.md"): + path = os.path.join(directory, name) + if os.path.isfile(path): + return path + return None + + +def size(path): + with open(path, "rb") as f: + return len(f.read()) + + +# Each check returns (errors, warnings). An error is a (subject, message) pair; the subject is +# what an exceptions-file entry names to exempt it. + + +def check_pairing(dirs): + errors = [] + for d, names in sorted(dirs.items()): + shown = d or "." + agents = os.path.join(d, "AGENTS.md") + claude = os.path.join(d, "CLAUDE.md") + if "AGENTS.md" not in names: + msg = ( + f"no AGENTS.md (found {', '.join(sorted(names))}). Make AGENTS.md the real " + "file and CLAUDE.md a symlink to it" + ) + elif not os.path.isfile(agents): + msg = "AGENTS.md is a dangling symlink" + elif "CLAUDE.md" not in names: + msg = ( + "only AGENTS.md; add a CLAUDE.md symlink to it (ln -s AGENTS.md CLAUDE.md). " + "By default Claude Code skips it when a CLAUDE.md exists in or above its " + "working directory" + ) + elif os.path.realpath(claude) != os.path.realpath(agents): + msg = ( + "AGENTS.md and CLAUDE.md are different files, so Claude Code and Codex can " + "follow different instructions. Keep one real file and make the other a " + "symlink to it" + ) + else: + continue + errors.append((shown, f"{shown}: {msg}")) + return errors, [] + + +def check_codex_cap(dirs): + # Group by the file where truncation starts: one oversized ancestor cuts every chain + # below it, and listing each of those chains separately hides the cause. + cuts = defaultdict(list) + for d in sorted(dirs): + parts = d.split("/") if d else [] + chain = [] + for i in range(len(parts) + 1): + f = codex_selected("/".join(parts[:i])) + if f: + chain.append(f) + total = sum(size(f) for f in chain) + if total > CODEX_CAP: + used, cut_in = 0, None + for f in chain: + if used + size(f) > CODEX_CAP: + cut_in = f + break + used += size(f) + cuts[cut_in].append((d or ".", total)) + errors = [] + for cut_in, chains in sorted(cuts.items()): + worst = max(chains, key=lambda c: c[1]) + msg = ( + f"{cut_in}: Codex truncates here in {len(chains)} chain(s); worst is " + f"{worst[0]} at {worst[1]} bytes, {worst[1] - CODEX_CAP} bytes never seen" + ) + errors.append((cut_in, msg)) + return errors, [] + + +def check_budget(files): + warnings = [] + for f in files: + if os.path.islink(f): + continue + budget = ROOT_BUDGET if os.path.dirname(f) == "" else NESTED_BUDGET + n = size(f) + if n > budget: + warnings.append( + f"{f}: {n} bytes > {budget} target; move branch-only detail into .agents/ " + "behind a pointer" + ) + return [], warnings + + +def check_pointers(files): + errors = [] + for f in files: + if os.path.islink(f): + continue + # Pointers may be written relative to the file or to any ancestor directory (e.g. a + # nested AGENTS.md naming `.agents/x.md` beside it, or a file under .agents/ naming + # a sibling as `.agents/y.md`). + parts = os.path.dirname(f).split("/") if os.path.dirname(f) else [] + bases = ["/".join(parts[:i]) for i in range(len(parts), -1, -1)] + with open(f, encoding="utf-8", errors="replace") as fh: + for lineno, line in enumerate(fh, 1): + for target in POINTER_RE.findall(line): + if "..." in target.split("/"): + continue # An elided path such as `a/.../AGENTS.md`, not a pointer. + candidates = [os.path.normpath(os.path.join(b, target)) for b in bases] + if not any(os.path.exists(c) for c in candidates): + msg = f"{f}:{lineno}: pointer to missing file `{target}`" + errors.append((f"{f} {target}", msg)) + return errors, [] + + +def load_exceptions(path): + """Returns ({check: {subject: lineno}}, errors) for the exceptions file, if it exists.""" + exceptions = defaultdict(dict) + errors = [] + if not os.path.isfile(path): + return exceptions, errors + with open(path, encoding="utf-8") as f: + for lineno, raw in enumerate(f, 1): + line = raw.split("#", 1)[0].strip() + if not line: + continue + check, _, subject = line.partition(" ") + subject = " ".join(subject.split()) + if check not in EXEMPTIBLE or not subject: + errors.append( + f"{path}:{lineno}: expected `<check> <subject>` with <check> one of " + f"{', '.join(EXEMPTIBLE)}" + ) + continue + exceptions[check][subject] = lineno Review Comment: **[13] nit: a duplicate entry is accepted silently, and a tab separator is rejected.** `exceptions[check][subject] = lineno` keeps only the last of two identical entries. After the error is fixed, only that last line is reported as stale, and the earlier copy shows up only on the next run. Reporting a duplicate as a malformed line would keep the file clean in one pass. Also, `line.partition(" ")` splits only on a space, so an entry separated by a tab is reported as malformed; `line.split(None, 1)` would accept both. ########## dev/sparktestsupport/modules.py: ########## @@ -39,6 +39,8 @@ # standard library. ignored_file_patterns = ( # Contributor docs. + ".agents/*.md", + "/.ignore", # lets rg search .agents/ and .github/ Review Comment: **[9] nit: `/.ignore` sits in "Contributor docs" and is root-anchored, unlike `.gitignore`.** `.ignore` is search-tool config like `.gitignore`, which is listed under "Git and ASF metadata" as a bare pattern that matches at any depth, and `dev/.rat-excludes` puts `.ignore` right next to `.gitignore`. Here it is under "Contributor docs" and anchored at the root, so a later `python/.ignore` would not be ignored while `python/.gitignore` is. A bare `.ignore` next to `.gitignore` would keep the two consistent. ########## .github/workflows/build_and_test.yml: ########## @@ -939,6 +939,9 @@ jobs: shell: 'script -q -e -c "bash {0}"' run: | python3.12 ./dev/structured_logging_style.py + - name: Agent instruction files check Review Comment: **[10] nit: this sub-second check runs after MiMa and the Scala linter.** The step comes after the License, Dependencies, MiMa and Scala linter steps. A PR that only edits `AGENTS.md` waits for all of them before it sees a pointer error. If any of them fails, this step does not run at all, so an agent doc error shows up only on the next push. It needs only `git` and Python, so running it right after "Setup build environment" would report in seconds. The structured logging check has the same placement, so this is optional. ########## dev/agent_docs_lint.py: ########## @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +""" +Checks the repository's agent instruction files (AGENTS.md / CLAUDE.md, and the detail files +in .agents/ directories) for the properties that coding agents such as Claude Code and Codex +depend on: + + pairing Each directory with agent instructions has both names, one a symlink to the + other, as the root AGENTS.md asks. Codex reads AGENTS.md and ignores CLAUDE.md + by default. Claude Code reads AGENTS.md only when no CLAUDE.md exists in the + working directory or above it, so once the root has a CLAUDE.md, a nested + directory with only an AGENTS.md is skipped. Two real files let the two tools + follow different instructions. + codex-cap Codex concatenates AGENTS.md from the repo root down to its working directory + into one budget of project_doc_max_bytes (32768 by default), filled root first, + and silently truncates past it. Every root-to-directory chain must fit. + budget Soft size targets that keep always-loaded instructions small: the root file + and nested files. Detail belongs in a sibling .agents/ directory behind a + pointer. Warnings only. + pointers Every `.agents/...`, `AGENTS.md` or `CLAUDE.md` path quoted in an instruction + file, including the files under .agents/, resolves to an existing file. + +Known failures that cannot be fixed yet (e.g. vendored third-party docs) can be exempted in +an optional exceptions file, dev/agent_docs_lint_exceptions.txt by default. Each line is +`<check> <subject>`, where the subject is what the error names: the directory for pairing, +the file where truncation starts for codex-cap, and `<file> <target>` for pointers. `#` +starts a comment. Exempted errors are still reported but do not fail --strict. An entry that +no longer matches any error is itself an error, so the list only shrinks as files are fixed. + +Report-only by default; pass --strict to exit non-zero on errors (not on budget warnings). +CI runs it with --strict. + + $ dev/agent_docs_lint.py + $ dev/agent_docs_lint.py --strict --only codex-cap +""" + +import argparse +import os +import re +import subprocess +import sys +from collections import defaultdict + +CODEX_CAP = 32768 +ROOT_BUDGET = 8 * 1024 +NESTED_BUDGET = 4 * 1024 +CHECKS = ("pairing", "codex-cap", "budget", "pointers") +EXEMPTIBLE = ("pairing", "codex-cap", "pointers") +EXCEPTIONS_FILE = "dev/agent_docs_lint_exceptions.txt" +NAMES = ("AGENTS.md", "CLAUDE.md", "AGENTS.override.md") +POINTER_RE = re.compile(r"`((?:[\w.-]+/)*(?:\.agents/[\w./-]+\.md|AGENTS\.md|CLAUDE\.md))`") + + +def repo_root(): + return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip() + + +def tracked_files(): + # Tracked plus untracked-but-not-ignored files, so a new AGENTS.md is checked before it is + # staged. Skip tracked files deleted in the working tree. + out = subprocess.check_output( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], text=True + ) + return sorted({p for p in out.split("\0") if p and os.path.lexists(p)}) + + +def is_detail_file(path): + """A Markdown file under a .agents/ directory.""" + return path.endswith(".md") and ".agents" in path.split("/")[:-1] + + +def codex_selected(directory): + """The one file Codex loads in `directory`, if any (override > AGENTS.md).""" + for name in ("AGENTS.override.md", "AGENTS.md"): + path = os.path.join(directory, name) + if os.path.isfile(path): + return path + return None + + +def size(path): + with open(path, "rb") as f: + return len(f.read()) + + +# Each check returns (errors, warnings). An error is a (subject, message) pair; the subject is +# what an exceptions-file entry names to exempt it. + + +def check_pairing(dirs): + errors = [] + for d, names in sorted(dirs.items()): + shown = d or "." + agents = os.path.join(d, "AGENTS.md") + claude = os.path.join(d, "CLAUDE.md") + if "AGENTS.md" not in names: + msg = ( + f"no AGENTS.md (found {', '.join(sorted(names))}). Make AGENTS.md the real " + "file and CLAUDE.md a symlink to it" + ) + elif not os.path.isfile(agents): + msg = "AGENTS.md is a dangling symlink" + elif "CLAUDE.md" not in names: + msg = ( + "only AGENTS.md; add a CLAUDE.md symlink to it (ln -s AGENTS.md CLAUDE.md). " + "By default Claude Code skips it when a CLAUDE.md exists in or above its " + "working directory" + ) + elif os.path.realpath(claude) != os.path.realpath(agents): + msg = ( + "AGENTS.md and CLAUDE.md are different files, so Claude Code and Codex can " + "follow different instructions. Keep one real file and make the other a " + "symlink to it" + ) + else: + continue + errors.append((shown, f"{shown}: {msg}")) + return errors, [] + + +def check_codex_cap(dirs): + # Group by the file where truncation starts: one oversized ancestor cuts every chain + # below it, and listing each of those chains separately hides the cause. + cuts = defaultdict(list) + for d in sorted(dirs): + parts = d.split("/") if d else [] + chain = [] + for i in range(len(parts) + 1): + f = codex_selected("/".join(parts[:i])) + if f: + chain.append(f) + total = sum(size(f) for f in chain) + if total > CODEX_CAP: + used, cut_in = 0, None + for f in chain: + if used + size(f) > CODEX_CAP: + cut_in = f + break + used += size(f) + cuts[cut_in].append((d or ".", total)) + errors = [] + for cut_in, chains in sorted(cuts.items()): + worst = max(chains, key=lambda c: c[1]) + msg = ( + f"{cut_in}: Codex truncates here in {len(chains)} chain(s); worst is " + f"{worst[0]} at {worst[1]} bytes, {worst[1] - CODEX_CAP} bytes never seen" + ) + errors.append((cut_in, msg)) + return errors, [] + + +def check_budget(files): + warnings = [] + for f in files: + if os.path.islink(f): + continue + budget = ROOT_BUDGET if os.path.dirname(f) == "" else NESTED_BUDGET + n = size(f) + if n > budget: + warnings.append( + f"{f}: {n} bytes > {budget} target; move branch-only detail into .agents/ " + "behind a pointer" + ) + return [], warnings + + +def check_pointers(files): Review Comment: **[3] Nothing reports a detail file that no pointer names.** `check_pointers` catches a pointer whose file is gone, but not the reverse: a file under `.agents/` that no `AGENTS.md` and no other detail file points to. A detail file is read only through its pointer, so such a file is dead. Examples are a new `.agents/foo.md` added without its pointer, or a pointer reworded so that it no longer names the file. Collecting the resolved targets in `check_pointers` and reporting the `details` that none of them hit would cover this in a few lines, and the exceptions file could take it as another check. ########## dev/agent_docs_lint.py: ########## @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +""" +Checks the repository's agent instruction files (AGENTS.md / CLAUDE.md, and the detail files +in .agents/ directories) for the properties that coding agents such as Claude Code and Codex +depend on: + + pairing Each directory with agent instructions has both names, one a symlink to the + other, as the root AGENTS.md asks. Codex reads AGENTS.md and ignores CLAUDE.md + by default. Claude Code reads AGENTS.md only when no CLAUDE.md exists in the + working directory or above it, so once the root has a CLAUDE.md, a nested + directory with only an AGENTS.md is skipped. Two real files let the two tools + follow different instructions. + codex-cap Codex concatenates AGENTS.md from the repo root down to its working directory + into one budget of project_doc_max_bytes (32768 by default), filled root first, + and silently truncates past it. Every root-to-directory chain must fit. + budget Soft size targets that keep always-loaded instructions small: the root file + and nested files. Detail belongs in a sibling .agents/ directory behind a + pointer. Warnings only. + pointers Every `.agents/...`, `AGENTS.md` or `CLAUDE.md` path quoted in an instruction + file, including the files under .agents/, resolves to an existing file. + +Known failures that cannot be fixed yet (e.g. vendored third-party docs) can be exempted in +an optional exceptions file, dev/agent_docs_lint_exceptions.txt by default. Each line is +`<check> <subject>`, where the subject is what the error names: the directory for pairing, +the file where truncation starts for codex-cap, and `<file> <target>` for pointers. `#` +starts a comment. Exempted errors are still reported but do not fail --strict. An entry that +no longer matches any error is itself an error, so the list only shrinks as files are fixed. + +Report-only by default; pass --strict to exit non-zero on errors (not on budget warnings). +CI runs it with --strict. + + $ dev/agent_docs_lint.py + $ dev/agent_docs_lint.py --strict --only codex-cap +""" + +import argparse +import os +import re +import subprocess +import sys +from collections import defaultdict + +CODEX_CAP = 32768 +ROOT_BUDGET = 8 * 1024 +NESTED_BUDGET = 4 * 1024 +CHECKS = ("pairing", "codex-cap", "budget", "pointers") +EXEMPTIBLE = ("pairing", "codex-cap", "pointers") +EXCEPTIONS_FILE = "dev/agent_docs_lint_exceptions.txt" +NAMES = ("AGENTS.md", "CLAUDE.md", "AGENTS.override.md") +POINTER_RE = re.compile(r"`((?:[\w.-]+/)*(?:\.agents/[\w./-]+\.md|AGENTS\.md|CLAUDE\.md))`") + + +def repo_root(): + return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip() + + +def tracked_files(): + # Tracked plus untracked-but-not-ignored files, so a new AGENTS.md is checked before it is + # staged. Skip tracked files deleted in the working tree. + out = subprocess.check_output( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], text=True + ) + return sorted({p for p in out.split("\0") if p and os.path.lexists(p)}) + + +def is_detail_file(path): + """A Markdown file under a .agents/ directory.""" + return path.endswith(".md") and ".agents" in path.split("/")[:-1] + + +def codex_selected(directory): + """The one file Codex loads in `directory`, if any (override > AGENTS.md).""" + for name in ("AGENTS.override.md", "AGENTS.md"): + path = os.path.join(directory, name) + if os.path.isfile(path): + return path + return None + + +def size(path): + with open(path, "rb") as f: + return len(f.read()) + + +# Each check returns (errors, warnings). An error is a (subject, message) pair; the subject is +# what an exceptions-file entry names to exempt it. + + +def check_pairing(dirs): + errors = [] + for d, names in sorted(dirs.items()): + shown = d or "." + agents = os.path.join(d, "AGENTS.md") + claude = os.path.join(d, "CLAUDE.md") + if "AGENTS.md" not in names: + msg = ( + f"no AGENTS.md (found {', '.join(sorted(names))}). Make AGENTS.md the real " + "file and CLAUDE.md a symlink to it" + ) + elif not os.path.isfile(agents): + msg = "AGENTS.md is a dangling symlink" + elif "CLAUDE.md" not in names: + msg = ( + "only AGENTS.md; add a CLAUDE.md symlink to it (ln -s AGENTS.md CLAUDE.md). " + "By default Claude Code skips it when a CLAUDE.md exists in or above its " + "working directory" + ) + elif os.path.realpath(claude) != os.path.realpath(agents): + msg = ( + "AGENTS.md and CLAUDE.md are different files, so Claude Code and Codex can " + "follow different instructions. Keep one real file and make the other a " + "symlink to it" + ) + else: + continue + errors.append((shown, f"{shown}: {msg}")) + return errors, [] + + +def check_codex_cap(dirs): + # Group by the file where truncation starts: one oversized ancestor cuts every chain + # below it, and listing each of those chains separately hides the cause. + cuts = defaultdict(list) + for d in sorted(dirs): + parts = d.split("/") if d else [] + chain = [] + for i in range(len(parts) + 1): + f = codex_selected("/".join(parts[:i])) + if f: + chain.append(f) + total = sum(size(f) for f in chain) + if total > CODEX_CAP: + used, cut_in = 0, None + for f in chain: + if used + size(f) > CODEX_CAP: + cut_in = f + break + used += size(f) + cuts[cut_in].append((d or ".", total)) + errors = [] + for cut_in, chains in sorted(cuts.items()): + worst = max(chains, key=lambda c: c[1]) + msg = ( + f"{cut_in}: Codex truncates here in {len(chains)} chain(s); worst is " + f"{worst[0]} at {worst[1]} bytes, {worst[1] - CODEX_CAP} bytes never seen" + ) + errors.append((cut_in, msg)) + return errors, [] + + +def check_budget(files): + warnings = [] + for f in files: + if os.path.islink(f): + continue + budget = ROOT_BUDGET if os.path.dirname(f) == "" else NESTED_BUDGET + n = size(f) + if n > budget: + warnings.append( + f"{f}: {n} bytes > {budget} target; move branch-only detail into .agents/ " + "behind a pointer" + ) + return [], warnings + + +def check_pointers(files): + errors = [] + for f in files: + if os.path.islink(f): + continue + # Pointers may be written relative to the file or to any ancestor directory (e.g. a + # nested AGENTS.md naming `.agents/x.md` beside it, or a file under .agents/ naming + # a sibling as `.agents/y.md`). + parts = os.path.dirname(f).split("/") if os.path.dirname(f) else [] + bases = ["/".join(parts[:i]) for i in range(len(parts), -1, -1)] + with open(f, encoding="utf-8", errors="replace") as fh: + for lineno, line in enumerate(fh, 1): + for target in POINTER_RE.findall(line): + if "..." in target.split("/"): + continue # An elided path such as `a/.../AGENTS.md`, not a pointer. + candidates = [os.path.normpath(os.path.join(b, target)) for b in bases] + if not any(os.path.exists(c) for c in candidates): + msg = f"{f}:{lineno}: pointer to missing file `{target}`" + errors.append((f"{f} {target}", msg)) + return errors, [] + + +def load_exceptions(path): + """Returns ({check: {subject: lineno}}, errors) for the exceptions file, if it exists.""" + exceptions = defaultdict(dict) + errors = [] + if not os.path.isfile(path): Review Comment: **[12] An explicit `--exceptions` path that does not exist is ignored silently.** A missing default file is expected, but `load_exceptions` treats a path the user passed the same way. Because of the `os.chdir(repo_root())` at L243, a relative path is also resolved from the repo root, as the help text says, not from where the script runs. So `cd dev; ./agent_docs_lint.py --strict --exceptions agent_docs_lint_exceptions.txt` silently reads nothing and reports every exempted error as failing, with no hint why. Failing when `--exceptions` is given and the file is missing, e.g. with `default=None` and a fallback to `EXCEPTIONS_FILE`, would make that visible. ########## dev/agent_docs_lint.py: ########## @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +""" +Checks the repository's agent instruction files (AGENTS.md / CLAUDE.md, and the detail files +in .agents/ directories) for the properties that coding agents such as Claude Code and Codex +depend on: + + pairing Each directory with agent instructions has both names, one a symlink to the + other, as the root AGENTS.md asks. Codex reads AGENTS.md and ignores CLAUDE.md + by default. Claude Code reads AGENTS.md only when no CLAUDE.md exists in the + working directory or above it, so once the root has a CLAUDE.md, a nested + directory with only an AGENTS.md is skipped. Two real files let the two tools + follow different instructions. + codex-cap Codex concatenates AGENTS.md from the repo root down to its working directory + into one budget of project_doc_max_bytes (32768 by default), filled root first, + and silently truncates past it. Every root-to-directory chain must fit. + budget Soft size targets that keep always-loaded instructions small: the root file + and nested files. Detail belongs in a sibling .agents/ directory behind a + pointer. Warnings only. + pointers Every `.agents/...`, `AGENTS.md` or `CLAUDE.md` path quoted in an instruction + file, including the files under .agents/, resolves to an existing file. + +Known failures that cannot be fixed yet (e.g. vendored third-party docs) can be exempted in +an optional exceptions file, dev/agent_docs_lint_exceptions.txt by default. Each line is +`<check> <subject>`, where the subject is what the error names: the directory for pairing, +the file where truncation starts for codex-cap, and `<file> <target>` for pointers. `#` +starts a comment. Exempted errors are still reported but do not fail --strict. An entry that +no longer matches any error is itself an error, so the list only shrinks as files are fixed. + +Report-only by default; pass --strict to exit non-zero on errors (not on budget warnings). +CI runs it with --strict. + + $ dev/agent_docs_lint.py + $ dev/agent_docs_lint.py --strict --only codex-cap +""" + +import argparse +import os +import re +import subprocess +import sys +from collections import defaultdict + +CODEX_CAP = 32768 +ROOT_BUDGET = 8 * 1024 +NESTED_BUDGET = 4 * 1024 +CHECKS = ("pairing", "codex-cap", "budget", "pointers") +EXEMPTIBLE = ("pairing", "codex-cap", "pointers") +EXCEPTIONS_FILE = "dev/agent_docs_lint_exceptions.txt" +NAMES = ("AGENTS.md", "CLAUDE.md", "AGENTS.override.md") +POINTER_RE = re.compile(r"`((?:[\w.-]+/)*(?:\.agents/[\w./-]+\.md|AGENTS\.md|CLAUDE\.md))`") + + +def repo_root(): + return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip() + + +def tracked_files(): + # Tracked plus untracked-but-not-ignored files, so a new AGENTS.md is checked before it is + # staged. Skip tracked files deleted in the working tree. + out = subprocess.check_output( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], text=True + ) + return sorted({p for p in out.split("\0") if p and os.path.lexists(p)}) + + +def is_detail_file(path): + """A Markdown file under a .agents/ directory.""" + return path.endswith(".md") and ".agents" in path.split("/")[:-1] + + +def codex_selected(directory): + """The one file Codex loads in `directory`, if any (override > AGENTS.md).""" + for name in ("AGENTS.override.md", "AGENTS.md"): + path = os.path.join(directory, name) + if os.path.isfile(path): + return path + return None + + +def size(path): Review Comment: **[15] nit: `os.path.getsize` instead of reading the whole file.** `size` reads the file into memory just to take its length. `check_codex_cap` calls it on every file of every chain twice, once in the `sum` and once in the cut loop, so the root `AGENTS.md` is read twice per directory. `os.path.getsize(path)` follows symlinks the same way and needs no read. ########## dev/agent_docs_lint.py: ########## @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +""" +Checks the repository's agent instruction files (AGENTS.md / CLAUDE.md, and the detail files +in .agents/ directories) for the properties that coding agents such as Claude Code and Codex +depend on: + + pairing Each directory with agent instructions has both names, one a symlink to the + other, as the root AGENTS.md asks. Codex reads AGENTS.md and ignores CLAUDE.md + by default. Claude Code reads AGENTS.md only when no CLAUDE.md exists in the + working directory or above it, so once the root has a CLAUDE.md, a nested + directory with only an AGENTS.md is skipped. Two real files let the two tools + follow different instructions. + codex-cap Codex concatenates AGENTS.md from the repo root down to its working directory + into one budget of project_doc_max_bytes (32768 by default), filled root first, + and silently truncates past it. Every root-to-directory chain must fit. + budget Soft size targets that keep always-loaded instructions small: the root file + and nested files. Detail belongs in a sibling .agents/ directory behind a + pointer. Warnings only. + pointers Every `.agents/...`, `AGENTS.md` or `CLAUDE.md` path quoted in an instruction + file, including the files under .agents/, resolves to an existing file. + +Known failures that cannot be fixed yet (e.g. vendored third-party docs) can be exempted in +an optional exceptions file, dev/agent_docs_lint_exceptions.txt by default. Each line is +`<check> <subject>`, where the subject is what the error names: the directory for pairing, +the file where truncation starts for codex-cap, and `<file> <target>` for pointers. `#` +starts a comment. Exempted errors are still reported but do not fail --strict. An entry that +no longer matches any error is itself an error, so the list only shrinks as files are fixed. + +Report-only by default; pass --strict to exit non-zero on errors (not on budget warnings). +CI runs it with --strict. + + $ dev/agent_docs_lint.py + $ dev/agent_docs_lint.py --strict --only codex-cap +""" + +import argparse +import os +import re +import subprocess +import sys +from collections import defaultdict + +CODEX_CAP = 32768 +ROOT_BUDGET = 8 * 1024 +NESTED_BUDGET = 4 * 1024 +CHECKS = ("pairing", "codex-cap", "budget", "pointers") +EXEMPTIBLE = ("pairing", "codex-cap", "pointers") +EXCEPTIONS_FILE = "dev/agent_docs_lint_exceptions.txt" +NAMES = ("AGENTS.md", "CLAUDE.md", "AGENTS.override.md") +POINTER_RE = re.compile(r"`((?:[\w.-]+/)*(?:\.agents/[\w./-]+\.md|AGENTS\.md|CLAUDE\.md))`") + + +def repo_root(): + return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip() + + +def tracked_files(): + # Tracked plus untracked-but-not-ignored files, so a new AGENTS.md is checked before it is + # staged. Skip tracked files deleted in the working tree. + out = subprocess.check_output( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], text=True + ) + return sorted({p for p in out.split("\0") if p and os.path.lexists(p)}) + + +def is_detail_file(path): + """A Markdown file under a .agents/ directory.""" + return path.endswith(".md") and ".agents" in path.split("/")[:-1] + + +def codex_selected(directory): + """The one file Codex loads in `directory`, if any (override > AGENTS.md).""" + for name in ("AGENTS.override.md", "AGENTS.md"): + path = os.path.join(directory, name) + if os.path.isfile(path): + return path + return None + + +def size(path): + with open(path, "rb") as f: + return len(f.read()) + + +# Each check returns (errors, warnings). An error is a (subject, message) pair; the subject is +# what an exceptions-file entry names to exempt it. + + +def check_pairing(dirs): Review Comment: **[14] Could the lint and the new patterns get a few unit tests?** The negative cases in the PR body were checked by hand in a scratch repo: a `CLAUDE.md`-only or `AGENTS.md`-only directory, two real files, an over-cap chain, stale and malformed exceptions, and an elided path. In CI the lint runs only on this repo, which has no failures, so a later change to `POINTER_RE`, the truncation math in `check_codex_cap` or the stale logic would not be caught. The `check_*` functions read files relative to the working directory, so a `unittest` that writes a few files into a temp directory and calls them there would be enough. `dev/sparktestsupport/tests/test_modules.py` could also take the `is_ignored_file` cases from the PR body: `.agents/pr-workflow.md`, `.ignore` and `dev/agent_docs_lint.py` are ignored, and `x.agents/y.md` is not. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
