Skip to content

ci(tests): add PR concurrency cancellation, AST selective pytest runs, and clean up conftest - #11468

Merged
mantoujun12 merged 3 commits into
AstrBotDevs:masterfrom
whatevertogo:ci/tests-ops-and-guidelines
Dec 4, 2026
Merged

mantoujun12 merged 3 commits into
AstrBotDevs:masterfrom
whatevertogo:ci/tests-ops-and-guidelines

Conversation

@whatevertogo

@whatevertogo whatevertogo commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Speed up Python PR CI with PR concurrency cancellation and conservative AST-based selective pytest execution, while removing unused test-tiering dead code from tests/conftest.py.

Update after review:

  • Split out the independent Dashboard CI rename, concurrency, and path-filtering changes into ci(dashboard): rename workflow, cancel stale PR runs, and skip non-dashboard PRs #11640 (merged).
  • Rebased onto latest master (incorporating remove test_install_script.py #11573 which removed tests/test_install_script.py) and dropped the tests/ops/ directory migration to keep this PR smaller and conflict-free.
  • Removed tests/test_select_tests.py per review feedback.
  • Fixed all 12 Pyright static type-checking errors in scripts/select_tests.py (0 errors, 0 warnings).
  • Hardened .github/workflows/tests.yml fail-open gating (002ebf9c): selector crashes/empty outputs fall back to run_tests=true / test_mode=full with a warning, and smoke-test / unit-tests still fail open to full 3-OS runs even if the changes job itself fails (e.g., actions/checkout failure).

Background

Previously on pull_request:

  • Tests ran smoke-test and the full 3-OS (ubuntu-latest, macos-latest, windows-latest) pytest suite (~11–12 min wall-clock dominated by Windows) even for docs-only, changelog-only, README-only, dashboard-only, or isolated single-adapter/provider PRs.
  • Tests had no PR concurrency configuration, so rapid follow-up pushes stacked multiple full 3-OS runs concurrently.
  • Standalone project-sync tests (tests/test_sync_github_project.py and tests/test_project_events.py, already executed by project-sync-tests.yml) ran redundantly on every PR in Tests.
  • tests/conftest.py carried ~95 lines of unused manual tiering hooks (--test-profile, tier_c/tier_d, 8 unreferenced custom markers, TEST_PROVIDER_API_KEY / TEST_*_ENABLED). Verified against master: tests/ has no integration directory/paths (so pytest_collection_modifyitems did not reorder any tests) and zero test files reference those 8 markers.

Modifications

File Change Summary
scripts/select_tests.py Added Stdlib-only static AST reverse-import test selector (~0.8s runtime) with SelectionResult TypedDict and narrowed AST branches (Pyright clean). Supports skip / selective / full modes, cross-layer mappings (openapi-scopes.md, openapi.json, use/command.md, tested dashboard locale JSONs), per-module fail-open checks, conftest.py/tests/fixtures/ guards, GitHub Actions outputs, and $GITHUB_STEP_SUMMARY reporting.
.github/workflows/tests.yml Modified Add PR-only concurrency cancellation; add fail-open job-level changes step running scripts/select_tests.py (preserving smoke-test and unit-tests job names for required checks and failing open even if select_tests.py or changes fails); run selected targets in unit-tests when selective or ./tests --ignore=tests/test_sync_github_project.py --ignore=tests/test_project_events.py when full; remove unused OPENAI_API_KEY env.
scripts/run_pytests_ci.sh Modified Remove dead OPENAI_API_KEY -> ZHIPU_API_KEY compatibility shim and forward CLI arguments cleanly.
tests/conftest.py Modified Remove ~95 lines of unused manual tiering/profile hooks and unreferenced marker registrations while keeping isolated ASTRBOT_ROOT cleanup intact.
AGENTS.md & CONTRIBUTING.md Modified Document how to force a full 3-OS PR test run (run-full-tests label or [full-test] in PR title + push/re-run Tests).

PR Test-Selection Flow

flowchart TD
    PR["Pull Request (fetch-depth=2, --no-renames)"] --> TC["tests.yml: changes -> scripts/select_tests.py (~0.8s)"]
    TC -->|"Non-PR / [full-test] / run-full-tests / changes or script failure"| Full["mode=full (./tests excluding project-sync scripts on 3 OS)"]
    TC -->|"All files ignored (docs/README/AGENTS/dashboard/ops tests)"| Skip["mode=skip (skip smoke-test & unit-tests)"]
    TC -->|"Shared infra / conftest / fixtures / non-.py / deleted / unmapped / fanout >= 50%"| Full
    TC -->|"Mapped astrbot/tests or cross-layer docs/locales"| Sel["mode=selective (impacted tests + test_smoke.py on 3 OS)"]
Loading

Safety Guarantees

  • Required Status Checks compatibility: Job-level if: gating keeps smoke-test and unit-tests job names unchanged so skipped PRs never hang in pending state.

  • Two-layer fail-open:

    • Within changes: selector failures or missing outputs emit a warning and fall back to run_tests=true / test_mode=full / test_targets=./tests; missing merge parents, shared fixtures/conftest.py, non-Python assets under astrbot/, deleted source files, unmapped changed astrbot/ modules, missing cross-layer target tests, or fan-out >= 50% also fall back to full.
    • Across jobs: smoke-test (!cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.run_tests != 'false')) and unit-tests (!cancelled() && needs.smoke-test.result == 'success') still execute the full 3-OS suite even if changes itself fails before writing outputs (e.g., checkout error).
  • Full 3-OS safety net preserved: Selective runs always include tests/test_smoke.py across Ubuntu, macOS, and Windows; every push to master, workflow_dispatch, or PR with run-full-tests label / [full-test] title (on push or manual re-run) runs the complete 3-OS suite.

  • This is NOT a breaking change.

Screenshots or Test Results

  • PR CI (GitHub Actions): changes (mode=full, expected since this PR modifies tests.yml, scripts/select_tests.py, and tests/conftest.py), smoke-test, and 3-OS unit-tests (ubuntu-latest, macos-latest, windows-latest) all passed (run #47259123285).
  • pyright scripts/select_tests.py tests/conftest.py -> 0 errors, 0 warnings, 0 informations
  • ruff format --check . & ruff check . -> All checks passed
  • pytest tests/test_smoke.py -v -> 6 passed
  • pytest --collect-only -q ./tests --ignore=tests/test_sync_github_project.py --ignore=tests/test_project_events.py -> 5,918 tests collected, 0 unknown-marker warnings
  • CLI verification of scripts/select_tests.py across real repo scenarios:
    • Docs/README/AGENTS/dashboard/ops-only changes -> mode=skip (0/265)
    • docs/zh/dev/openapi-scopes.md -> mode=selective (2/265: test_smoke.py, tests/unit/test_openapi_scope_docs.py)
    • dashboard/src/i18n/locales/zh-CN/features/command.json -> mode=selective (2/265: test_smoke.py, tests/unit/test_conversation_restart.py)
    • astrbot/core/provider/sources/anthropic_source.py -> mode=selective (5/265)
    • tests/conftest.py & --force-full -> mode=full (265/265)
  • Historical backtest on 200 recent master commits (from initial evaluation): 86 / 86 (100.0%) strict recall.

Checklist

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc. (CI & test workflow optimization; no new user-facing feature)

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.

  • 📚 I checked the affected WebUI instructions and screenshots in docs/zh and docs/en against the changed navigation, page structure, and labels, and updated them in this PR (or explained why no documentation update is needed). (CI/test infra only; no WebUI changes)

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml. (Stdlib only; no new dependencies)

  • 😮 My changes do not introduce malicious code.

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-28T15:24:36.925274Z
We couldn’t complete this review. Comment @codex review to try again.
0bfff93 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="scripts/select_tests.py" line_range="325" />
<code_context>
+        refs = _extract_module_refs(
+            repo_root / rel,
+            path_to_mod.get(rel, ""),
+            top_level_only=not is_test,
+        )
+        for ref in refs:
</code_context>
<issue_to_address>
**Affected tests are skipped**

When a changed application module is imported only inside production functions or classes, including through lazy dispatch, and at least one other test is statically mapped to the change, `top_level_only=not is_test` makes `_extract_module_refs` omit those imports, so the reverse graph has no edge to tests exercising that path; because another test is mapped, the empty-selection fallback does not run, and PR CI passes without running the affected tests.

Include function- and class-local imports from application modules when building the reverse graph so tests exercising those paths are selected.

Also at `scripts/select_tests.py:137-138`.
</issue_to_address>

### Comment 2
<location path=".github/workflows/tests.yml" line_range="40" />
<code_context>
+        shell: bash
+        env:
+          EVENT_NAME: ${{ github.event_name }}
+          FORCE_FULL: ${{ contains(github.event.pull_request.labels.*.name, 'run-full-tests') || contains(github.event.pull_request.title, '[full-test]') }}
+        run: |
+          if [ "$EVENT_NAME" != "pull_request" ]; then
</code_context>
<issue_to_address>
**Override changes do not rerun tests**

When a contributor adds the override label or edits the PR title after the workflow has already run, the workflow does not subscribe to `labeled` or `edited` pull-request activity types, so adding the `run-full-tests` label or changing the title to include `[full-test]` does not start a run that evaluates `FORCE_FULL`. The documented full-suite override therefore has no effect until another triggering event occurs.

Subscribe to the `labeled` and `edited` pull-request activity types, or remove the claim that these changes trigger a full run and provide another way to rerun the workflow.
</issue_to_address>

### Comment 3
<location path="tests/test_select_tests.py" line_range="22" />
<code_context>
+
+
+def _make_sample_repo(tmp_path: Path) -> Path:
+    """Create a minimal synthetic AstrBot-like package and test tree."""
+    _write(tmp_path, "astrbot/__init__.py", "")
+    _write(tmp_path, "astrbot/core/__init__.py", "")
</code_context>
<issue_to_address>
**Helper docstring omits required sections**

`_make_sample_repo` documents a `tmp_path` parameter and `Path` return value without Google-style `Args:` and `Returns:` sections, violating the repository’s docstring format rule.

Add Google-style `Args:` and `Returns:` sections to the docstring.
</issue_to_address>

### Comment 4
<location path="tests/test_select_tests.py" line_range="1" />
<code_context>
+"""Unit tests for AST-based selective pytest target selection."""
+
+from __future__ import annotations
</code_context>
<issue_to_address>
**Tests are added without request**

The review task does not ask for tests, but the PR adds `tests/test_select_tests.py`; this violates the default rule against adding tests unless the task explicitly requests them.

Remove the newly added test file.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: scripts/select_tests.py:325, .github/workflows/tests.yml:40


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread scripts/select_tests.py Resolved
Comment thread .github/workflows/tests.yml Resolved
Comment thread tests/test_select_tests.py Resolved
Comment thread tests/test_select_tests.py Resolved
@whatevertogo
whatevertogo force-pushed the ci/tests-ops-and-guidelines branch from 0bfff93 to bf81841 Compare November 28, 2026 15:39
@whatevertogo whatevertogo changed the title chore(tests): group standalone ops tests under tests/ops and document test guidelines ci: optimize PR CI with concurrency cancellation, AST selective tests, and tests/ops grouping Nov 28, 2026

@whatevertogo whatevertogo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@mantoujun12 pls have a look
(看一看喵)

@whatevertogo

whatevertogo commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

@Soulter 牢大有空帮忙看下这个 PR~核心目标是加速 PR CI、减少重复跑测并清理遗留测试基建(零新依赖,不改 Required Checks 名称,不影响 master 全量回归和发版):

1. PR 并发取消 + 按路径分流

  • 并发取消(concurrency):以前连着推多次 commit 会把多轮三端 CI 叠在一起跑完。现在 4 个测试工作流(tests.yml、dashboard-ci.yml、install-script-test.yml、project-sync-tests.yml)都加了仅对 PR 生效的并发取消(push 到 master 不会取消)。
  • 前后端互不拖累:纯改文档 / README / Changelog / 前端的 PR 不再跑 10+ 分钟的三端 Python 单测;纯改后端 Python 的 PR 不再跑 dashboard-ci.yml 的 pnpm install + vue-tsc + vite build(合并到 master 时依然必跑,不影响 astrbot-release-harbour 发版)。
  • 不破坏 Required Checks:分流做在 job 级(前置 changes job + 下游 if:),smoke-test、unit-tests、build 原名字不变,跳过时不会被分支保护卡在 Pending。

2. 新增静态 AST 增量选测(scripts/select_tests.py)

  • 零依赖快速分析:纯 Python 标准库实现,扫描全仓约 ~0.8s,分析 astrbot/ 和 tests/ 的 import 关系(含 patch("astrbot...") 字符串引用、__init__.py、类体 / match 导入等),反向选出本次改动影响到的测试文件。
  • 隔离懒加载分发器:刻意不追踪应用侧函数体内的懒导入(如 ProviderManager / PlatformManager 在分发函数里按需导入各 provider / platform),避免改单个 provider 扇出到几乎全仓测试导致选测失效。
  • 跨层精确映射:改了 openapi-scopes.md、openapi.json、use/command.md 或被 Python 单测校验的前端 locale JSON 时,不会误跳过,而是精准跑对应的 Python 单测。
  • 保守兜底(宁可多跑、绝不漏测):
    • 改动共享基建(pyproject.toml、conftest.py、tests/fixtures/、scripts/、tests.yml 等)、非 .py 资源、删除源码、任意改动模块静态找不到测试、或受影响测试 ≥ 50% 时,一律自动回退跑全量。
    • 增量模式下默认带上 tests/test_smoke.py,三端(Ubuntu / macOS / Windows)照常跑;合进 master 时永远跑完整三端全量;需要手动在 PR 上强制全量时,打 run-full-tests 标签或在标题加 [full-test] 后 push / 重跑即可。
  • 回测与自测:用 master 最近 200 次提交回测,仅看源码改动预测测试的召回率 86 / 86(100%);约 1/3 直接跳过,1/3 走增量(中位数只跑 11 / 262 个文件),1/3 自动回退全量。并配了 tests/test_select_tests.py 防止后续改坏选测逻辑。

3. 归类运维测试 + 清理死代码 + 统一工作流命名

  • 把 4 个安装脚本 / GitHub Project 同步脚本测试迁到 tests/ops/,由 install-script-test.yml 和 project-sync-tests.yml 各自独立跑(顺手补齐了原先 install-script-test.yml 只做 bash -n 却没实际执行 test_install_script.py 的空缺),主测试流通过 --ignore=tests/ops 排除重复执行。
  • 删掉 tests/conftest.py 里约 95 行全仓 0 引用的旧分级钩子(--test-profile / tier_c / tier_d 等),以及 scripts/run_pytests_ci.sh 里废弃的 OPENAI_API_KEY → ZHIPU_API_KEY 透传。
  • 按 @Sha1rholder 建议,把仅剩的两个下划线命名工作流统一成 kebab-case:dashboard-ci.yml 和 install-script-test.yml。

4. 补齐测试放置规范文档

  • 在 AGENTS.md 和 CONTRIBUTING.md 中补充了新测试放置规范(tests/ops/ 与按领域目录)、避免一 PR 一文件碎片化 / .__new__() / 硬编码 parents[N],以及 PR 强制触发全量测试的方法。
image

@Sha1rholder Sha1rholder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Might as well rename dashboard_ci.yml to dashboard-ci.yml and install_script_test.yml to install-script-test.yml to make CI filenames more consistent

@whatevertogo

Copy link
Copy Markdown
Contributor Author

@Sha1rholder Done in 787b6e5 — renamed .github/workflows/dashboard_ci.yml\ to .github/workflows/dashboard-ci.yml\ and .github/workflows/install_script_test.yml\ to .github/workflows/install-script-test.yml\ (along with internal path filters and test references). Please take another look when convenient!

@Sha1rholder

Copy link
Copy Markdown
Contributor

I'll review this later

@Sha1rholder Sha1rholder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This PR includes multiple changes, resulting in a rather large diff. Following the principle of keeping each PR as atomic as possible, could you please split it into the following PRs?

  1. Move files like tests/install_script.Tests.ps1 to tests/ops/install_script.Tests.ps1 and update the corresponding relative paths accordingly.
  2. Rename dashboard_ci.yml to dashboard-ci.yml and install_script_test.yml to install-script-test.yml. This is purely a naming convention issue, but since these files are already touched by this PR, we might as well fix it.
  3. Add concurrency configurations to the four workflows individually to cancel outdated CI runs triggered by previous commits within the same PR. This essentially saves GitHub some money rather than speeding up CI, but there's no harm in adding it.
  4. Regarding test_install_script.py, I personally prefer removing it altogether rather than adapting it. I'll open a separate PR proposing its removal.
  5. Clean up conftest.py.
  6. Put AST-based selective testing and incremental testing into a separate PR.

Otherwise it's unlikely that a human would be able to thoroughly review all these changes.

Additionally, select_tests.py introduced some static type-checking errors. Please make Pyright happy before submitting.

中文 该PR涉及多个改动,diff量过大。根据尽可能使每个PR保持原子化的原则,麻烦您把它分成以下PR: 1. move things like `tests/install_script.Tests.ps1` to `tests/ops/install_script.Tests.ps1`,然后把那堆相对路径同步一下 2. rename `dashboard_ci.yml` to `dashboard-ci.yml` and `install_script_test.yml` to `install-script-test.yml`。仅代码风格问题,这个PR既然涉及到了就是顺手的事 3. 取消同一PR连续commit的旧CI,单独给4个工作流加concurrency,这个其实就是给GitHub省点钱,不会加速,不过加了也没什么问题 4. `test_install_script.py`,这个我个人倾向于直接删了,不要去适配。我会开个PR suggest deletion 5. 清理`conftest.py` 6. AST selective tests和增量测试单独放一个PR

不然一个人类不太可能完整认真review这些改动

另外,select_tests.py引入了一些静态类型检查报错。麻烦提交前先过一遍Pyright尽可能不新增报错以顾代码质量

Comment thread tests/test_select_tests.py Resolved
@Sha1rholder Sha1rholder mentioned this pull request Dec 1, 2026
5 of 6 tasks
@mantoujun6

Copy link
Copy Markdown

起来了起来了你的pr又有合并冲突了

@whatevertogo

Copy link
Copy Markdown
Contributor Author

起来了起来了你的pr又有合并冲突了

好困

@whatevertogo
whatevertogo force-pushed the ci/tests-ops-and-guidelines branch from 787b6e5 to aa1dc2d Compare December 4, 2026 02:58
@whatevertogo whatevertogo changed the title ci: optimize PR CI with concurrency cancellation, AST selective tests, and tests/ops grouping ci(tests): add PR concurrency cancellation, AST selective pytest runs, and clean up conftest Dec 4, 2026
@whatevertogo

Copy link
Copy Markdown
Contributor Author

#11468 (review)

就这几个文件我觉得没必要拆了

@whatevertogo whatevertogo reopened this Dec 4, 2026

@mantoujun12 mantoujun12 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

有一个问题:.github/workflows/tests.yml 的 fail-open 逻辑是反的。changes job 只有在 scripts/select_tests.py 成功执行时才会写出 run_tests / test_mode / test_targets;一旦脚本抛异常、语法错误或环境缺失,job 失败、outputs 为空,smoke-test 的 if: needs.changes.outputs.run_tests == 'true' 判为假,smoke-test 和 unit-tests 会全部 skipped ,一条测试都不跑。

修法:在调用脚本前先往 $GITHUB_OUTPUT 预写 run_tests=true、test_mode=full、test_targets=./tests,让脚本成功后覆盖;或给调用加 || { ... } 兜底。

@mantoujun12

Copy link
Copy Markdown
Collaborator

两个建议:

  1. 增量选测未在 CI 真实跑过:本 PR 改了 scripts/select_tests.py 和 tests.yml,日志确认本次是 run_tests=true mode=full selected=265/265,selective 分支目前只有本地验证和自述的 86/86 回测。
  2. PR 粒度过大:四件事一个 PR(并发取消、AST 选测、conftest 清理、文档)。

小点:

  • 删除 pytest_collection_modifyitems 后失去了 unit 先于 integration 的顺序,理论上会暴露顺序依赖的 flaky 测试。

@whatevertogo

Copy link
Copy Markdown
Contributor Author

@mantoujun12 感谢细看,刚在 002ebf9c 修掉了 tests.yml 的 fail-open 问题,同时补充说明一下其余两点:

  1. 已修复 tests.yml fail-open 兜底(两层防护):
    • changes 内部:先把 scripts/select_tests.py 的输出写到 $RUNNER_TEMP/select_output.txt 并校验退出码与 grep -q '^run_tests=';一旦脚本抛异常、环境缺失或输出为空,打 ::warning:: 并显式写入 run_tests=true / test_mode=full / test_targets=./tests。
    • 下游 job 级兜底:smoke-test 改为 if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.run_tests != 'false') }},unit-tests 显式加 if: ${{ !cancelled() && needs.smoke-test.result == 'success' }}。这样即使 actions/checkout 等步骤失败导致 changes 整个 job 挂掉、未产出 outputs,也不会被 GitHub Actions 默认的隐式 success() 静默跳过,而是照常跑完 smoke-test 和全量三端 unit-tests(同时在 run_tests=false 或 concurrency 取消时仍正常跳过)。
  2. 关于 conftest.py 删掉 pytest_collection_modifyitems 后的顺序:
    • 核查了当前 master,tests/ 下仅有 agent、fixtures、test_kook、unit 四个子目录,完全没有 integration 目录或路径段,且全仓 0 处使用那 8 个自定义 marker,因此原 pytest_collection_modifyitems 的排序逻辑一直是纯空操作(integration_tests 恒为空),删除后不会改变任何测试的执行顺序。
  3. 关于本次 PR 走 mode=full:
    • 因为本 PR 本身改动了 .github/workflows/tests.yml、scripts/select_tests.py 和 tests/conftest.py,按保守 fail-open 规则必然走全量三端(之前跑过三端全绿);selective 路径已在本地按实仓文件(单 provider、跨层 docs/locales、忽略路径等)验证通过。

请有空再看一眼~

@mantoujun12
mantoujun12 merged commit 632f684 into AstrBotDevs:master Dec 4, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants