From fa6b79b9874866aa09914e185fa66ab612551f73 Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Wed, 25 Nov 2026 09:52:00 +0800 Subject: [PATCH 1/3] Group test support by module and consolidate overlapping coverage Move the remaining root test, checkout probes and process helpers to their owners. Update the installed-wheel and host checks to run them in the same environments. Keep explicit coverage for each writer and shell case, share common setup and fold the PR diagnostic suite into the existing diagnostics module. Agent-assisted-by: Codex / unknown [effort=unknown] (coordination, repository and Skill Eval implementation) Agent-assisted-by: Codex / unknown [effort=unknown] (Apps and Campaigns audit and implementation) Agent-assisted-by: Codex / unknown [effort=unknown] (Knowledge and Skill Eval audit and implementation) Agent-assisted-by: Codex / unknown [effort=unknown] (Harness, Benchmark, Contracts and Skill Eval audit and implementation) Signed-off-by: dongxinwen --- .github/workflows/ci-ready.yml | 12 +-- .github/workflows/release.yml | 4 +- CHANGELOG.md | 6 +- docs/apps-module-migrations.json | 46 +++++----- docs/contributing.md | 2 +- docs/legacy-knowledge-manifest.json | 2 +- docs/module-layout.md | 10 +- docs/workswarm-plugin.md | 2 +- plugins/inferrsi-dsh/vendor/README.md | 2 +- tests/README.md | 8 +- tests/{ => apps}/check_dsh_bridge.cjs | 0 tests/{ => apps}/check_dsh_form.cjs | 0 tests/{ => apps}/check_dsh_remote.cjs | 4 +- tests/{ => apps}/check_profile_review.cjs | 0 tests/{ => apps}/check_workswarm_installed.py | 0 tests/{ => apps}/check_workswarm_rendered.py | 0 tests/apps/conftest.py | 10 +- tests/apps/test_apps_artifact_reader.py | 2 +- tests/apps/test_apps_module_migrations.py | 2 +- tests/apps/test_campaign_record_injection.py | 2 +- tests/apps/test_codex_search_shell_forms.py | 27 +----- tests/apps/test_dashboard_experiments.py | 91 +++++++++---------- .../test_dashboard_experiments_browser.py | 82 ++++++++--------- tests/apps/test_dsh_plugin.py | 6 +- .../test_engineering_benchmark_plugins.py | 2 +- tests/apps/test_legacy_run_split.py | 22 +---- tests/apps/test_optimization_session.py | 2 +- tests/apps/test_optimization_story.py | 29 +++--- tests/apps/test_profile_story_checks.py | 2 +- tests/apps/test_project_explanation.py | 2 +- tests/apps/test_project_optimization.py | 2 +- tests/apps/test_result_delivery.py | 2 +- .../engineering_task_support.py | 0 tests/benchmark/test_benchmark_preparation.py | 38 +++----- tests/benchmark/test_evaluator_loaders.py | 2 +- tests/benchmark/test_moe_benchmark.py | 2 +- .../test_qwen_optimization_protocol.py | 2 +- tests/benchmark/test_tts_benchmark.py | 2 +- tests/benchmark/test_tts_standalone.py | 2 +- tests/contracts/test_evidence_paths.py | 12 +-- .../diagnosis.py} | 0 tests/fixtures/optimization-session/README.md | 2 +- tests/fixtures/service_reuse.py | 2 +- tests/fixtures/skill_eval_pr_support.py | 19 ++++ tests/fixtures/task-input/README.md | 2 +- .../run_store_child.py} | 2 +- tests/{ => harness}/session_lock_probe.py | 4 +- tests/harness/test_confinement.py | 34 ++----- tests/harness/test_harness_execute.py | 27 +++--- tests/harness/test_harness_run_store.py | 2 +- .../harness/test_moe_optimization_protocol.py | 2 +- .../test_session_lock_across_processes.py | 6 +- tests/knowledge/_repo_to_skill_support.py | 18 ++++ .../test_knowledge_compatibility_shells.py | 24 +---- .../knowledge/test_knowledge_fresh_install.py | 2 +- .../knowledge/test_knowledge_model_policy.py | 48 ++++------ tests/knowledge/test_knowledge_policy_http.py | 34 +++---- .../test_mistral_rs_repo_to_skill.py | 14 +-- .../test_mlx_swift_lm_repo_to_skill.py | 15 +-- tests/knowledge/test_resource_migration.py | 4 +- .../{ => repository}/_gate_policy_support.py | 2 +- .../architecture_closed_loop.py | 0 .../architecture_real_ports.py | 2 +- tests/{ => repository}/check_installed.py | 2 +- .../test_architecture_closed_loop.py | 8 +- .../test_artifact_helper_copies.py | 27 +++++- .../repository/test_campaign_plan_template.py | 12 --- .../test_first_wave_isolation_policy.py | 4 +- .../test_legacy_run_forwarder_gate.py | 4 +- .../test_target_module_import_gate.py | 4 +- tests/repository/test_template_layout.py | 1 + tests/skill_eval/_budget_git_support.py | 37 ++++++-- .../skill_eval/test_skill_eval_budget_git.py | 47 +++------- .../test_skill_eval_daily_budget.py | 35 ++----- .../skill_eval/test_skill_eval_diagnostic.py | 53 +++++++++++ .../test_skill_eval_optional_dependencies.py | 3 - .../test_skill_eval_planned_guidance.py | 3 +- .../test_skill_eval_planning_boundaries.py | 3 +- tests/skill_eval/test_skill_eval_pr.py | 14 +-- .../test_skill_eval_pr_diagnostic.py | 67 -------------- .../skill_eval/test_skill_eval_pr_summary.py | 5 +- tests/skill_eval/test_skill_eval_retention.py | 3 +- tests/skill_eval/test_skill_evaluation.py | 13 +-- 83 files changed, 452 insertions(+), 601 deletions(-) rename tests/{ => apps}/check_dsh_bridge.cjs (100%) rename tests/{ => apps}/check_dsh_form.cjs (100%) rename tests/{ => apps}/check_dsh_remote.cjs (99%) rename tests/{ => apps}/check_profile_review.cjs (100%) rename tests/{ => apps}/check_workswarm_installed.py (100%) rename tests/{ => apps}/check_workswarm_rendered.py (100%) rename tests/{ => benchmark}/engineering_task_support.py (100%) rename tests/{diagnosis_support.py => fixtures/diagnosis.py} (100%) rename tests/{h01_run_store_child.py => harness/run_store_child.py} (99%) rename tests/{ => harness}/session_lock_probe.py (98%) create mode 100644 tests/knowledge/_repo_to_skill_support.py rename tests/{ => repository}/_gate_policy_support.py (99%) rename tests/{ => repository}/architecture_closed_loop.py (100%) rename tests/{ => repository}/architecture_real_ports.py (98%) rename tests/{ => repository}/check_installed.py (99%) rename tests/{ => repository}/test_artifact_helper_copies.py (86%) delete mode 100644 tests/skill_eval/test_skill_eval_pr_diagnostic.py diff --git a/.github/workflows/ci-ready.yml b/.github/workflows/ci-ready.yml index 886e4bc31..41467a2eb 100644 --- a/.github/workflows/ci-ready.yml +++ b/.github/workflows/ci-ready.yml @@ -37,9 +37,9 @@ jobs: python -m venv "$RUNNER_TEMP/wheel-env" wheels=("$RUNNER_TEMP"/dist/*.whl) "$RUNNER_TEMP/wheel-env/bin/python" -m pip install "${wheels[0]}" - cp tests/check_installed.py "$RUNNER_TEMP/check_installed.py" + cp tests/repository/check_installed.py "$RUNNER_TEMP/check_installed.py" cd "$RUNNER_TEMP" - env -u PYTHONPATH INFERRSI_CHECKOUT_RESOURCES="$GITHUB_WORKSPACE/src/inferrsi" INFERRSI_SESSION_LOCK_PROBE="$GITHUB_WORKSPACE/tests/session_lock_probe.py" INFERRSI_PRE_CHANGE_SESSIONS="$GITHUB_WORKSPACE/tests/fixtures/optimization-session" "$RUNNER_TEMP/wheel-env/bin/python" -I check_installed.py + env -u PYTHONPATH INFERRSI_CHECKOUT_RESOURCES="$GITHUB_WORKSPACE/src/inferrsi" INFERRSI_SESSION_LOCK_PROBE="$GITHUB_WORKSPACE/tests/harness/session_lock_probe.py" INFERRSI_PRE_CHANGE_SESSIONS="$GITHUB_WORKSPACE/tests/fixtures/optimization-session" "$RUNNER_TEMP/wheel-env/bin/python" -I check_installed.py full-check: permissions: @@ -220,8 +220,8 @@ jobs: nodes = [ "tests/skill_eval/test_skill_evaluation.py::test_harness_artifact_primitives_match_apps_bytes_and_semantics", "tests/skill_eval/test_skill_evaluation.py::test_harness_owned_writes_and_digests_match_apps_bytes", - "tests/apps/test_legacy_run_split.py::test_harness_writer_bytes_equal_the_apps_writer", - "tests/apps/test_legacy_run_split.py::test_harness_writer_rejects_nan_and_leaves_no_file", + "tests/repository/test_artifact_helper_copies.py::test_harness_writer_bytes_equal_the_apps_writer", + "tests/repository/test_artifact_helper_copies.py::test_every_writer_writes_the_same_bytes[atomic_write_json]", "tests/apps/test_legacy_run_split.py::test_sampling_sha256_matches_the_apps_hasher", "tests/apps/test_optimization_session.py::test_runtime_identity_covers_migrated_process_domain_and_not_removed_executor", "tests/harness/test_session_lock_across_processes.py", @@ -266,7 +266,7 @@ jobs: # #498: the installed-wheel check drives a real session lock from this probe, on # Windows and macOS as well as Linux. environment["INFERRSI_SESSION_LOCK_PROBE"] = str( - workspace / "tests" / "session_lock_probe.py" + workspace / "tests" / "harness" / "session_lock_probe.py" ) # #498 slice 5: a session that main planned before infra/artifacts.py left the # runtime identity must be refused by the installed wheel without any change. @@ -301,7 +301,7 @@ jobs: console = scripts / ("inferrsi.exe" if os.name == "nt" else "inferrsi") run(python, "-m", "pip", "install", f"{wheels[0]}[skills]") assert console.is_file(), console - shutil.copyfile(workspace / "tests" / "check_installed.py", work / "check_installed.py") + shutil.copyfile(workspace / "tests" / "repository" / "check_installed.py", work / "check_installed.py") run(python, "-I", "check_installed.py") # The package under test is the installed wheel, never the source checkout. location = Path( diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 79a3507df..1adc1dc67 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -126,9 +126,9 @@ jobs: python -m venv "$RUNNER_TEMP/wheel-env" wheels=("$RUNNER_TEMP"/release-dist/*.whl) "$RUNNER_TEMP/wheel-env/bin/python" -m pip install "${wheels[0]}[skills]" - cp tests/check_installed.py tools/check_release.py "$RUNNER_TEMP/" + cp tests/repository/check_installed.py tools/check_release.py "$RUNNER_TEMP/" cd "$RUNNER_TEMP" - env -u PYTHONPATH INFERRSI_CHECKOUT_RESOURCES="$GITHUB_WORKSPACE/src/inferrsi" INFERRSI_SESSION_LOCK_PROBE="$GITHUB_WORKSPACE/tests/session_lock_probe.py" INFERRSI_PRE_CHANGE_SESSIONS="$GITHUB_WORKSPACE/tests/fixtures/optimization-session" "$RUNNER_TEMP/wheel-env/bin/python" -I check_installed.py + env -u PYTHONPATH INFERRSI_CHECKOUT_RESOURCES="$GITHUB_WORKSPACE/src/inferrsi" INFERRSI_SESSION_LOCK_PROBE="$GITHUB_WORKSPACE/tests/harness/session_lock_probe.py" INFERRSI_PRE_CHANGE_SESSIONS="$GITHUB_WORKSPACE/tests/fixtures/optimization-session" "$RUNNER_TEMP/wheel-env/bin/python" -I check_installed.py env -u PYTHONPATH "$RUNNER_TEMP/wheel-env/bin/python" -I check_release.py \ installed --tag "$RELEASE_TAG" - name: Build and validate the installable host plugin ZIPs diff --git a/CHANGELOG.md b/CHANGELOG.md index c888875ad..5133c120c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,7 +71,7 @@ either package name, with or without a file behind it. - `inferrsi.infra.artifacts` is now `inferrsi.apps.artifacts`. Apps owns this copy with the same function source as the Harness and Benchmark copies, and - `tests/test_artifact_helper_copies.py` keeps the three equal. `apps/delivery/`, the + `tests/repository/test_artifact_helper_copies.py` keeps the three equal. `apps/delivery/`, the tools, the examples and the tests import it. The Apps copy and `harness/artifact_primitives.py` use the same `.session.lock` file lock, so a Harness writer and an Apps export exclude each other across processes. @@ -183,7 +183,7 @@ - New `inferrsi.benchmark.artifacts` holds Benchmark's own `sha256`, `write_json` and `atomic_write_json`. Their code equals the copies in `inferrsi.infra.artifacts` and Harness, and - `tests/test_artifact_helper_copies.py` keeps the copies equal. + `tests/repository/test_artifact_helper_copies.py` keeps the copies equal. `inferrsi.infra.artifacts` stays for its other users. - A new Flare receipt keeps its schema and keys. Its `adapter` digests are those of `benchmark/validators/flare.py` and `benchmark/artifacts.py`. Existing @@ -417,7 +417,7 @@ ninth pair, `infra.inspection` → `inferrsi.resources.repository_packs`, is a live import that no deletion removes. It is now a permanent exact rule outside the allowlist: `technical_leaf.permanent_importers` in the manifest - and `LEAF_IMPORTERS` in `tests/_gate_policy_support.py`. That one module + and `LEAF_IMPORTERS` in `tests/repository/_gate_policy_support.py`. That one module binds only `repository_pack`, with one plain module-level `from` import. Any other importer, name, alias, import of the leaf as a module object, nested import, `sys.modules` use or dynamic import fails, and an diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index c407f967d..bcf82d43f 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -31,7 +31,7 @@ "src/inferrsi/apps/views/attempt.py", "src/inferrsi/apps/workflows/benchmark_compare.py", "src/inferrsi/apps/workflows/evaluation.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_assess.py", "tests/apps/test_apps_evaluate_cli.py", "tests/apps/test_apps_evidence_capture.py", @@ -69,7 +69,7 @@ "src/inferrsi/apps/handoff/production_capture.py", "src/inferrsi/apps/views/attempt.py", "src/inferrsi/apps/workflows/evaluation.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_artifact_reader.py", "tests/apps/test_apps_assess.py", "tests/apps/test_apps_evidence_capture.py", @@ -107,7 +107,7 @@ "src/inferrsi/apps/storage/artifact_reader.py", "src/inferrsi/apps/views/attempt.py", "src/inferrsi/apps/workflows/evaluation.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/apps/test_result_delivery.py" ] @@ -126,8 +126,8 @@ "docs/operations.md", "src/inferrsi/apps/evidence_layout.py", "src/inferrsi/contracts/evidence.py", - "tests/_gate_policy_support.py", - "tests/check_installed.py", + "tests/repository/_gate_policy_support.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/contracts/test_evidence_paths.py", "tests/repository/test_first_wave_isolation_policy.py", @@ -153,7 +153,7 @@ "src/inferrsi/apps/handoff/candidate_provider.py", "src/inferrsi/apps/views/attempt.py", "src/inferrsi/apps/workflows/evaluation.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_evidence.py", "tests/apps/test_apps_execution_binding.py", "tests/apps/test_apps_generation_plan.py", @@ -178,7 +178,7 @@ "docs/module-layout.md", "docs/operations.md", "src/inferrsi/apps/context_provider.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_context_provider.py", "tests/apps/test_apps_module_migrations.py", "tests/harness/test_harness_generation_seal.py" @@ -197,7 +197,7 @@ "docs/operations.md", "src/inferrsi/apps/api.py", "src/inferrsi/apps/candidate_provider.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py" ] }, @@ -220,7 +220,7 @@ "src/inferrsi/apps/views/capture_delivery.py", "src/inferrsi/apps/views/optimization_story.py", "src/inferrsi/harness/optimization_session.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/fixtures/dashboard_profile_review.py", "tests/fixtures/knowledge_retrieval.py", "tests/apps/test_apps_module_migrations.py", @@ -245,8 +245,8 @@ "docs/architecture.md", "docs/module-layout.md", "src/inferrsi/apps/cli/__init__.py", - "tests/_gate_policy_support.py", - "tests/check_installed.py", + "tests/repository/_gate_policy_support.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/benchmark/test_benchmark_operations.py", "tests/apps/test_optimization_session.py", @@ -268,7 +268,7 @@ "docs/contracts/function-owners.md", "docs/harness-improvement.md", "docs/module-layout.md", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/harness/test_harness_improvement.py", "tools/skill_eval_improve.py" @@ -286,7 +286,7 @@ "docs/contracts/function-owners.md", "docs/module-layout.md", "docs/skill-evaluation.md", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_anthropic_agent.py", "tests/apps/test_apps_module_migrations.py", "tests/skill_eval/test_skill_eval_compare.py", @@ -309,7 +309,7 @@ "docs/local-skill-evaluation.md", "docs/module-layout.md", "src/inferrsi/apps/workflows/skill_evaluation.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/skill_eval/test_skill_eval_compare.py", "tests/skill_eval/test_skill_eval_engineering.py", @@ -341,7 +341,7 @@ "docs/architecture.md", "docs/module-layout.md", "src/inferrsi/apps/cli/__init__.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/benchmark/test_benchmark_compare.py" ] @@ -357,7 +357,7 @@ "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/integrations/cannbot/round_knowledge.py", "src/inferrsi/apps/integrations/external_channels.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/knowledge/test_knowledge_channels.py" ], @@ -389,7 +389,7 @@ "src/inferrsi/apps/integrations/cannbot/__init__.py", "src/inferrsi/apps/integrations/cannbot/round_knowledge.py", "src/inferrsi/apps/integrations/external_channels.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/apps/test_cannbot_boundaries.py", "tests/apps/test_mindie_runtime.py", @@ -410,7 +410,7 @@ "consumers": [ "src/inferrsi/apps/integrations/cannbot/project.py", "src/inferrsi/apps/integrations/cannbot/round_knowledge.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/apps/test_cannbot_boundaries.py", "tests/apps/test_project_optimization.py" @@ -424,7 +424,7 @@ "docs/architecture.md", "docs/external-channels.md", "docs/module-layout.md", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py" ], "package": true @@ -442,7 +442,7 @@ "src/inferrsi/apps/integrations/mindie/mcp.py", "src/inferrsi/apps/integrations/mindie/navigation.py", "src/inferrsi/apps/integrations/mindie/project.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/apps/test_mindie_context.py", "tests/apps/test_mindie_runtime.py" @@ -465,7 +465,7 @@ "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/integrations/mindie/mcp.py", "src/inferrsi/apps/integrations/mindie/navigation.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/apps/test_mindie_project.py", "tests/apps/test_mindie_runtime.py" @@ -480,7 +480,7 @@ "consumers": [ "docs/module-layout.md", "src/inferrsi/apps/integrations/mindie/project.py", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/apps/test_mindie_project.py" ] @@ -493,7 +493,7 @@ ], "consumers": [ "docs/module-layout.md", - "tests/check_installed.py", + "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py" ] } diff --git a/docs/contributing.md b/docs/contributing.md index 1f079eb79..76514079e 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -261,7 +261,7 @@ Keep the existing four lanes: Ready CI also builds the source distribution and wheel, installs the wheel with the optional `skills` parser in a fresh virtual environment, and runs -`tests/check_installed.py` outside the checkout with `PYTHONPATH` unset and Python +`tests/repository/check_installed.py` outside the checkout with `PYTHONPATH` unset and Python isolated mode enabled. This checks packaged knowledge, skill bodies, licenses, helpers and CLI reads without installing any inference engine. The ready test and installed-package jobs cover the declared minimum Python diff --git a/docs/legacy-knowledge-manifest.json b/docs/legacy-knowledge-manifest.json index 3ff7ce015..0e076c57e 100644 --- a/docs/legacy-knowledge-manifest.json +++ b/docs/legacy-knowledge-manifest.json @@ -384,7 +384,7 @@ } ], "not_a_compatibility_pair": "The entry is not in compatibility_pairs and is never counted by the allowlist blocker. It does not retire with a shell, because the importer is not a shell.", - "gate": "tests/_gate_policy_support.py LEAF_IMPORTERS holds the same importer and name. tests/knowledge/test_knowledge_compatibility_shells.py requires the two to match exactly.", + "gate": "tests/repository/_gate_policy_support.py LEAF_IMPORTERS holds the same importer and name. tests/knowledge/test_knowledge_compatibility_shells.py requires the two to match exactly.", "review": "This rule requires formal architecture review. The implementer does not self-approve it, and passing tests are not that review.", "relocated": { "stage": "#498 slice 3a", diff --git a/docs/module-layout.md b/docs/module-layout.md index b5f5e4d4e..7c40fe86e 100644 --- a/docs/module-layout.md +++ b/docs/module-layout.md @@ -119,13 +119,13 @@ move must update packaging in that same slice), and `.agents/` (review skill). ## CPU/offline connection -`tests/architecture_closed_loop.py` is the handoff exercised by +`tests/repository/architecture_closed_loop.py` is the handoff exercised by `tests/repository/test_architecture_closed_loop.py`. The coordinator does not import Knowledge, Harness, or Benchmark. Refusal cases still inject outcomes. That file is not the Apps implementation owned by #371. It does not change Bundle revision. -`tests/architecture_real_ports.py` is the CPU/offline connection injected for +`tests/repository/architecture_real_ports.py` is the CPU/offline connection injected for the success path. It calls `KnowledgeReader.read` on one installed package card, `execute_trial` for one local process record, and `evaluate` for one offline assessment. It does not call `collect` or `search_knowledge`. It does @@ -153,7 +153,7 @@ Application assembly is the `inferrsi.apps` package, identified by its first pat segment. No root file is application assembly: A1 (#408) moved `cli.py` and `arguments.py` into `apps/cli/`, A2 (#408) moved `benchmark_operations.py` into `apps/`, and with that last move the exact-file `APPLICATION_ENTRIES` listing in -`tests/_gate_policy_support.py` is removed. A root file that returns under any of +`tests/repository/_gate_policy_support.py` is removed. A root file that returns under any of those names is not admitted. Other flat modules retain the same restrictions. The gate checks Benchmark task scripts as well as module code. @@ -233,7 +233,7 @@ bundle program that loads by path, so the static `isolation_complete` result nev reads as runtime isolation. R1 (#412) deleted the three root forwarders of the old run chain and removed -their `LEGACY_RUN_FORWARDERS` registration from `tests/_gate_policy_support.py`. +their `LEGACY_RUN_FORWARDERS` registration from `tests/repository/_gate_policy_support.py`. With the seven Knowledge shells and root `inspection`, their names are now `RETIRED_ROOT_MODULES` in that file. Nothing is registered for them: @@ -434,7 +434,7 @@ without reaching Knowledge or Harness. #498 slice 3a moved the importer from `inferrsi.infra.inspection` with its file, in one change: the old name is retired and is never admitted beside the new one, and the move needs the same formal architecture review as the rule. The rule is `LEAF_IMPORTERS` in -`tests/_gate_policy_support.py`, restated as +`tests/repository/_gate_policy_support.py`, restated as `technical_leaf.permanent_importers` in the manifest. `tests/knowledge/test_knowledge_compatibility_shells.py` requires the two to match, and requires that line to be the file's only import under `inferrsi.resources`. diff --git a/docs/workswarm-plugin.md b/docs/workswarm-plugin.md index 0e144a5df..8a8535a78 100644 --- a/docs/workswarm-plugin.md +++ b/docs/workswarm-plugin.md @@ -167,7 +167,7 @@ For the native backend lifecycle, use the host's prepared interpreter from a scratch directory outside either checkout: ```text -python -X utf8 "/tests/check_workswarm_installed.py" --host-source "" --archive "" +python -X utf8 "/tests/apps/check_workswarm_installed.py" --host-source "" --archive "" ``` This check creates its own temporary profile, imports and installs the archive, diff --git a/plugins/inferrsi-dsh/vendor/README.md b/plugins/inferrsi-dsh/vendor/README.md index 2d93cd4d0..d414126f4 100644 --- a/plugins/inferrsi-dsh/vendor/README.md +++ b/plugins/inferrsi-dsh/vendor/README.md @@ -19,7 +19,7 @@ node node_modules/esbuild/bin/esbuild node_modules/ssh2/lib/index.js --bundle -- Reconcile the included `ssh2`, `asn1`, `safer-buffer`, `bcrypt-pbkdf` and `tweetnacl` license files and versions when refreshing the bundle. Run -`node tests/check_dsh_remote.cjs` and the native DSH installation check before +`node tests/apps/check_dsh_remote.cjs` and the native DSH installation check before shipping a regenerated bundle. The checked-in output removes trailing spaces from one empty line in an diff --git a/tests/README.md b/tests/README.md index 66b86aa72..b123a17ee 100644 --- a/tests/README.md +++ b/tests/README.md @@ -18,5 +18,9 @@ Parallel-round execution tests that need POSIX directory descriptors run on Linu Place a new test with the module that owns the behavior. Keep related cases together, using named parameters when inputs exercise the same contract. Shared test data, synthetic campaigns, and frozen snapshots live in [fixtures](fixtures/). -The root holds shared helpers, installed-package probes, and the -[cross-component artifact byte-equivalence test](test_artifact_helper_copies.py). +Keep probes and support code beside the tests that use them. The repository-wide +[installed-wheel check](repository/check_installed.py) also runs the Harness +[session-lock probe](harness/session_lock_probe.py) against the installed package. +The [artifact-copy contract](repository/test_artifact_helper_copies.py) is the test +called `tests/test_artifact_helper_copies.py` in the byte-pinned runtime sources. +Only this guide and the Python package marker live at the root. diff --git a/tests/check_dsh_bridge.cjs b/tests/apps/check_dsh_bridge.cjs similarity index 100% rename from tests/check_dsh_bridge.cjs rename to tests/apps/check_dsh_bridge.cjs diff --git a/tests/check_dsh_form.cjs b/tests/apps/check_dsh_form.cjs similarity index 100% rename from tests/check_dsh_form.cjs rename to tests/apps/check_dsh_form.cjs diff --git a/tests/check_dsh_remote.cjs b/tests/apps/check_dsh_remote.cjs similarity index 99% rename from tests/check_dsh_remote.cjs rename to tests/apps/check_dsh_remote.cjs index a7e8eecb4..1da88ff3b 100644 --- a/tests/check_dsh_remote.cjs +++ b/tests/apps/check_dsh_remote.cjs @@ -6,8 +6,8 @@ const { spawnSync } = require('node:child_process'); const net = require('node:net'); const os = require('node:os'); const path = require('node:path'); -const { createRemoteManager } = require('../plugins/inferrsi-dsh/remote.cjs'); -const { Client, Server, utils } = require('../plugins/inferrsi-dsh/vendor/ssh2.cjs'); +const { createRemoteManager } = require('../../plugins/inferrsi-dsh/remote.cjs'); +const { Client, Server, utils } = require('../../plugins/inferrsi-dsh/vendor/ssh2.cjs'); const fakePassword = 'fake-password-with-no-service-access'; const hostKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey diff --git a/tests/check_profile_review.cjs b/tests/apps/check_profile_review.cjs similarity index 100% rename from tests/check_profile_review.cjs rename to tests/apps/check_profile_review.cjs diff --git a/tests/check_workswarm_installed.py b/tests/apps/check_workswarm_installed.py similarity index 100% rename from tests/check_workswarm_installed.py rename to tests/apps/check_workswarm_installed.py diff --git a/tests/check_workswarm_rendered.py b/tests/apps/check_workswarm_rendered.py similarity index 100% rename from tests/check_workswarm_rendered.py rename to tests/apps/check_workswarm_rendered.py diff --git a/tests/apps/conftest.py b/tests/apps/conftest.py index 5026918d5..04f639b7d 100644 --- a/tests/apps/conftest.py +++ b/tests/apps/conftest.py @@ -1,10 +1,18 @@ -"""Browser setup shared by Apps UI tests.""" +"""Shared fixtures for Apps tests.""" from contextlib import contextmanager import pytest +@pytest.fixture +def dashboard_campaign(tmp_path): + from tests.fixtures.dashboard_experiments import build + + build(tmp_path) + return tmp_path + + @contextmanager def _chromium(**launch_options): playwright = pytest.importorskip("playwright.sync_api") diff --git a/tests/apps/test_apps_artifact_reader.py b/tests/apps/test_apps_artifact_reader.py index a8f110082..3452030b5 100644 --- a/tests/apps/test_apps_artifact_reader.py +++ b/tests/apps/test_apps_artifact_reader.py @@ -7,7 +7,7 @@ from inferrsi.apps.storage.artifact_reader import ArtifactReader from inferrsi.harness.errors import PublicError from inferrsi.harness.run_store import RunStore, artifact_ref -from tests.h01_run_store_child import make_attempt, make_digest, make_payload +from tests.harness.run_store_child import make_attempt, make_digest, make_payload def _config(tmp_path): diff --git a/tests/apps/test_apps_module_migrations.py b/tests/apps/test_apps_module_migrations.py index 9b2bd56ba..1d691d0e9 100644 --- a/tests/apps/test_apps_module_migrations.py +++ b/tests/apps/test_apps_module_migrations.py @@ -12,8 +12,8 @@ import pytest -from tests import _gate_policy_support as support from tests.contracts.test_contracts_package import IO_CONTROL, IO_PROBE, _fresh +from tests.repository import _gate_policy_support as support REPO = Path(__file__).resolve().parents[2] ROOT = REPO / "src/inferrsi" diff --git a/tests/apps/test_campaign_record_injection.py b/tests/apps/test_campaign_record_injection.py index ce205e803..ba0bba358 100644 --- a/tests/apps/test_campaign_record_injection.py +++ b/tests/apps/test_campaign_record_injection.py @@ -15,7 +15,7 @@ from inferrsi.knowledge._skill_selection import FIND_RELEVANCE from inferrsi.knowledge.context_projection import context_item from inferrsi.knowledge.knowledge_operations import KnowledgeReader -from tests._gate_policy_support import ( +from tests.repository._gate_policy_support import ( NEW_H_ENTRIES, REPO, RETIRED_BY_A1, diff --git a/tests/apps/test_codex_search_shell_forms.py b/tests/apps/test_codex_search_shell_forms.py index 35f3efa05..0ae748c14 100644 --- a/tests/apps/test_codex_search_shell_forms.py +++ b/tests/apps/test_codex_search_shell_forms.py @@ -1,4 +1,3 @@ -import shlex from pathlib import Path import pytest @@ -61,19 +60,7 @@ def test_wrapped_shell_forms_decode_like_the_plain_form(wrapped): def test_unreadable_shell_forms_stay_incomplete(tmp_path, command): # A search this reader cannot decode must not count as complete coverage. item = {"command": command, "exit_code": 0, "aggregated_output": ""} - assert _command(item, tmp_path) == (None, False, None) - - -@pytest.mark.parametrize("direct", [ - ["bash", "search.sh"], - ["bash", "--", "-c", "rg -n needle docs"], - ["pwsh", "-Command", "rg -n needle docs"], -]) -def test_a_wrapped_shell_reads_like_the_same_shell_run_directly(tmp_path, direct): - wrapped = ["bash", "-lc", shlex.join(direct)] - for command in (direct, wrapped): - item = {"command": command, "exit_code": 0, "aggregated_output": ""} - assert _command(item, tmp_path) == (None, False, None), command + assert _command(item, tmp_path) == (None, False, None), command @pytest.mark.parametrize("tool", ["rg", "C:/tools/rg.exe", "C:\\tools\\rg.exe"]) @@ -114,6 +101,9 @@ def test_dash_c_after_double_dash_names_a_script_file(): @pytest.mark.parametrize("script, argv", [ ("rg -n if docs", ["rg", "-n", "if", "docs"]), ("rg -n '$(bash x)' docs", ["rg", "-n", "$(bash x)", "docs"]), + ("rg -n '&>' docs", ["rg", "-n", "&>", "docs"]), + ("rg -n '2>&1' docs", ["rg", "-n", "2>&1", "docs"]), + ("rg -n '|&' docs", ["rg", "-n", "|&", "docs"]), ]) def test_shell_syntax_inside_a_quoted_or_tool_argument_still_decodes(script, argv): assert _recorded_argv({"command": ["bash", "-lc", script]}) == (argv, False) @@ -148,15 +138,6 @@ def test_an_unquoted_redirection_becomes_one_plain_operator(script, argv): assert _recorded_argv({"command": ["bash", "-lc", script]}) == (argv, True) -@pytest.mark.parametrize("script, argv", [ - ("rg -n '&>' docs", ["rg", "-n", "&>", "docs"]), - ("rg -n '2>&1' docs", ["rg", "-n", "2>&1", "docs"]), - ("rg -n '|&' docs", ["rg", "-n", "|&", "docs"]), -]) -def test_a_quoted_redirection_is_an_argument(script, argv): - assert _recorded_argv({"command": ["bash", "-lc", script]}) == (argv, False) - - def test_a_background_ampersand_between_commands_is_a_command_boundary(): assert _recorded_argv({"command": ["bash", "-lc", "rg -n needle docs & cd ."]}) == ( ["rg", "-n", "needle", "docs", ";", "cd", "."], True) diff --git a/tests/apps/test_dashboard_experiments.py b/tests/apps/test_dashboard_experiments.py index 436958f6d..5e177ce18 100644 --- a/tests/apps/test_dashboard_experiments.py +++ b/tests/apps/test_dashboard_experiments.py @@ -2,8 +2,6 @@ import copy import json -import runpy -from pathlib import Path import pytest @@ -15,22 +13,15 @@ references_for, timestamp, ) - -FIXTURE = runpy.run_path(str(Path(__file__).parents[1] / "fixtures/dashboard_experiments.py")) - - -@pytest.fixture -def campaign(tmp_path): - FIXTURE["build"](tmp_path) - return tmp_path +from tests.fixtures import dashboard_experiments as experiment_data def points(root): return load_dashboard(root)["experiments"]["points"] -def test_multi_workload_axes_and_configurations_are_explicit(campaign): - data = load_dashboard(campaign) +def test_multi_workload_axes_and_configurations_are_explicit(dashboard_campaign): + data = load_dashboard(dashboard_campaign) plot = data["experiments"] baseline = [p for p in plot["points"] if p["candidate_id"] == "native-control"] assert {p["workload"] for p in baseline} == {"W1", "W2", "W3"} @@ -50,8 +41,8 @@ def test_multi_workload_axes_and_configurations_are_explicit(campaign): assert "synthetic-device" not in json.dumps(data) -def test_unknown_does_not_equal_unknown_and_numbers_never_come_from_text(campaign): - data = load_dashboard(campaign)["experiments"] +def test_unknown_does_not_equal_unknown_and_numbers_never_come_from_text(dashboard_campaign): + data = load_dashboard(dashboard_campaign)["experiments"] unknown = [p for p in data["points"] if p["candidate_id"] in ("unknown-a", "unknown-b")] assert len(unknown) == 2 assert all(p["series_id"] is None for p in unknown) @@ -66,8 +57,8 @@ def test_unknown_does_not_equal_unknown_and_numbers_never_come_from_text(campaig assert timestamp("2026-01-01T12:00:00Z") is not None -def test_failure_keeps_measurement_and_missing_artifacts_never_become_zero(campaign): - data = load_dashboard(campaign)["experiments"] +def test_failure_keeps_measurement_and_missing_artifacts_never_become_zero(dashboard_campaign): + data = load_dashboard(dashboard_campaign)["experiments"] failed = next(p for p in data["points"] if p["candidate_id"] == "quality-rejected") assert failed["value"] == 7.5 and failed["quality"] == failed["verdict"] == "FAIL" assert failed["target_gaps"][0]["gap"] == -0.5 @@ -84,8 +75,8 @@ def test_failure_keeps_measurement_and_missing_artifacts_never_become_zero(campa assert legacy["round"] is None and not legacy["experiment_ids"] -def test_same_candidate_same_round_runs_and_measurements_have_stable_ids(campaign): - before = points(campaign) +def test_same_candidate_same_round_runs_and_measurements_have_stable_ids(dashboard_campaign): + before = points(dashboard_campaign) native = [p for p in before if p["candidate_id"] == "native-repeat"] external = [p for p in before if p["candidate_id"] == "repeated-candidate"] assert len(native) == len(external) == 2 @@ -94,15 +85,16 @@ def test_same_candidate_same_round_runs_and_measurements_have_stable_ids(campaig assert all(p["run_id"] is None and p["source_record"] for p in external) assert {p["round"] for p in native} == {3} # Candidate directory sorting and metric values do not define identity. - (campaign / "candidates/native-run-a").rename(campaign / "candidates/zzz-native-a") - path = campaign / "runs/native-run-a/evaluation.json" + candidate = dashboard_campaign / "candidates/native-run-a" + candidate.rename(dashboard_campaign / "candidates/zzz-native-a") + path = dashboard_campaign / "runs/native-run-a/evaluation.json" data = json.loads(path.read_text()) data["candidate"]["median"] = 108 path.write_text(json.dumps(data)) - after = points(campaign) + after = points(dashboard_campaign) assert {p["id"] for p in after if p["candidate_id"] == "native-repeat"} == { p["id"] for p in native} - event = next(e for e in load_dashboard(campaign)["experiments"]["events"] + event = next(e for e in load_dashboard(dashboard_campaign)["experiments"]["events"] if e["narrative_category"] and "native runs" in e["description"]) assert set(event["experiment_ids"]) == {p["experiment_id"] for p in native} @@ -114,14 +106,16 @@ def test_same_candidate_same_round_runs_and_measurements_have_stable_ids(campaig ("repositories.lock.json", lambda d: d["baseline"].update(snapshot_hash="b" * 64)), ("environment.json", lambda d: d["target_python"]["environment"].update(python="changed")), ]) -def test_native_join_preserves_all_existing_comparison_boundaries(campaign, artifact, mutate): - native = [p for p in points(campaign) if p["candidate_id"] == "native-repeat"] +def test_native_join_preserves_all_existing_comparison_boundaries( + dashboard_campaign, artifact, mutate, +): + native = [p for p in points(dashboard_campaign) if p["candidate_id"] == "native-repeat"] assert native[0]["series_id"] == native[1]["series_id"] is not None - path = campaign / "runs/native-run-a" / artifact + path = dashboard_campaign / "runs/native-run-a" / artifact data = json.loads(path.read_text()) mutate(data) path.write_text(json.dumps(data)) - native = [p for p in points(campaign) if p["candidate_id"] == "native-repeat"] + native = [p for p in points(dashboard_campaign) if p["candidate_id"] == "native-repeat"] assert native[0]["series_id"] != native[1]["series_id"] @@ -136,7 +130,7 @@ def test_native_join_preserves_all_existing_comparison_boundaries(campaign, arti (None, "improvement_pct", 20, None), ]) def test_reference_roles_and_target_conversions(direction, definition, value, expected): - m = FIXTURE["metric"]() + m = experiment_data.metric() m["references"][0]["value"] = 100 m["references"][2].update(relative_to="local", definition=definition, value=value) specs = external_dimensions(m)["references"] @@ -149,7 +143,7 @@ def test_reference_roles_and_target_conversions(direction, definition, value, ex def test_invalid_and_unfrozen_targets_are_retained_with_reasons(): - specs = external_dimensions(FIXTURE["metric"]())["references"] + specs = external_dimensions(experiment_data.metric())["references"] point = {**dict.fromkeys(DIMENSIONS), "direction": "minimize", "unit": "s", "refs": []} for change in [{"frozen": False}, {"unit": "ms"}, {"relative_to": "absent"}, {"provenance": ""}, {"value": float("inf")}]: @@ -162,8 +156,8 @@ def test_invalid_and_unfrozen_targets_are_retained_with_reasons(): assert result["value"] is None and result["reason"] -def test_static_and_live_embed_the_same_self_contained_renderer(campaign): - snapshot = dashboard_snapshot(campaign) +def test_static_and_live_embed_the_same_self_contained_renderer(dashboard_campaign): + snapshot = dashboard_snapshot(dashboard_campaign) offline = render_dashboard(snapshot) live = render_dashboard(snapshot, live=True) assert "__DASHBOARD_EXPERIMENTS__" not in offline @@ -175,48 +169,49 @@ def test_static_and_live_embed_the_same_self_contained_renderer(campaign): assert renderer in render_dashboard(snapshot) -def test_metric_identity_survives_reordering_and_order_is_not_round(campaign): - before = [p for p in points(campaign) if p["candidate_id"] == "native-control"] - path = campaign / "native-control.json" +def test_metric_identity_survives_reordering_and_order_is_not_round(dashboard_campaign): + before = [p for p in points(dashboard_campaign) if p["candidate_id"] == "native-control"] + path = dashboard_campaign / "native-control.json" data = json.loads(path.read_text()) data["metrics"].reverse() for metric in data["metrics"]: metric["order"] = 50 - ref = FIXTURE["write"](path, data) - candidate = campaign / "candidates/native-control/candidate.json" + ref = experiment_data.write(path, data) + candidate = dashboard_campaign / "candidates/native-control/candidate.json" data = json.loads(candidate.read_text()) data["external_record_ref"] = ref candidate.write_text(json.dumps(data)) - after = [p for p in points(campaign) if p["candidate_id"] == "native-control"] + after = [p for p in points(dashboard_campaign) if p["candidate_id"] == "native-control"] assert {p["id"] for p in before} == {p["id"] for p in after} assert all(p["round"] == 1 and p["order"] == 50 for p in after) -def test_redacted_dimensions_and_legacy_reference_roles_are_not_inferred(campaign): - raw = FIXTURE["metric"](workload="/private/workload") +def test_redacted_dimensions_and_legacy_reference_roles_are_not_inferred(dashboard_campaign): + raw = experiment_data.metric(workload="/private/workload") mapped = external_dimensions(raw) assert mapped["workload"] is None for value in [None, [], {}, True, 0, -1]: raw["configuration"]["batch"] = value assert external_dimensions(raw)["comparison_reasons"] - raw = FIXTURE["metric"](baseline=10, target=8, references=[]) - FIXTURE["external"](campaign, "legacy-references", 11, [raw]) - p = next(p for p in points(campaign) if p["candidate_id"] == "legacy-references") + raw = experiment_data.metric(baseline=10, target=8, references=[]) + experiment_data.external(dashboard_campaign, "legacy-references", 11, [raw]) + p = next(p for p in points(dashboard_campaign) if p["candidate_id"] == "legacy-references") assert len(p["references"]) == 2 assert all(r["value"] is None and r["reason"] == "unknown reference role" for r in p["references"]) assert [r["original_value"] for r in p["references"]] == [10, 8] -def test_external_event_ids_survive_reorder_only_when_explicit(campaign): +def test_external_event_ids_survive_reorder_only_when_explicit(dashboard_campaign): event_a = {"id": "stable-event", "stage": "execution", "summary": "First"} event_b = {"stage": "validation", "summary": "Second"} - FIXTURE["external"](campaign, "events", 12, [], events=[event_a, event_b]) + experiment_data.external(dashboard_campaign, "events", 12, [], events=[event_a, event_b]) def ids(): - return {e["description"]: e["id"] for e in load_dashboard(campaign)["experiments"]["events"] + events = load_dashboard(dashboard_campaign)["experiments"]["events"] + return {e["description"]: e["id"] for e in events if e.get("candidate_id") == "events"} before = ids() - FIXTURE["external"](campaign, "events", 12, [], events=[event_b, event_a]) + experiment_data.external(dashboard_campaign, "events", 12, [], events=[event_b, event_a]) after = ids() assert before["First"] == after["First"] assert before["Second"] != after["Second"] @@ -228,11 +223,11 @@ def ids(): ]) @pytest.mark.parametrize("blank", ["", " ", "\t\r\n", "\u00a0\u2003"]) def test_blank_external_configuration_keeps_points_without_joining(tmp_path, field, blank): - FIXTURE["write"](tmp_path / "campaign.json", {"campaign_id": "synthetic-blank-config"}) + experiment_data.write(tmp_path / "campaign.json", {"campaign_id": "synthetic-blank-config"}) for round_number in (1, 2): - metric = FIXTURE["metric"](value=8 + round_number) + metric = experiment_data.metric(value=8 + round_number) metric["configuration"][field] = blank - FIXTURE["external"](tmp_path, f"blank-{round_number}", round_number, [metric]) + experiment_data.external(tmp_path, f"blank-{round_number}", round_number, [metric]) projected = points(tmp_path) assert len(projected) == 2 assert [p["value"] for p in projected] == [9, 10] diff --git a/tests/apps/test_dashboard_experiments_browser.py b/tests/apps/test_dashboard_experiments_browser.py index cf7221d8e..37cefedf5 100644 --- a/tests/apps/test_dashboard_experiments_browser.py +++ b/tests/apps/test_dashboard_experiments_browser.py @@ -1,10 +1,8 @@ """Optional real-browser regressions: pip install playwright; playwright install chromium.""" import json -import runpy import shutil import threading -from pathlib import Path import pytest @@ -13,23 +11,16 @@ from tests.apps.test_optimization_session import session as session from tests.apps.test_optimization_session import submit from tests.apps.test_optimization_session import task as task +from tests.fixtures import dashboard_experiments as experiment_data playwright = pytest.importorskip("playwright.sync_api") -FIXTURE = runpy.run_path(str(Path(__file__).parents[1] / "fixtures/dashboard_experiments.py")) - -@pytest.fixture -def campaign(tmp_path): - FIXTURE["build"](tmp_path) - return tmp_path - - -def test_offline_axes_keyboard_exact_run_and_shared_selection(browser, campaign): +def test_offline_axes_keyboard_exact_run_and_shared_selection(browser, dashboard_campaign): page = browser.new_page(viewport={"width": 1440, "height": 1000}) errors, requests = [], [] page.on("pageerror", lambda e: errors.append(str(e))) page.on("request", lambda r: requests.append(r.url)) - page.goto((campaign / "dashboard.html").as_uri()) + page.goto((dashboard_campaign / "dashboard.html").as_uri()) assert page.locator("#verdict-total").inner_text() == "16" legend = page.locator("#verdict-legend") assert dict(zip(legend.locator("dt").all_text_contents(), @@ -93,11 +84,11 @@ def test_offline_axes_keyboard_exact_run_and_shared_selection(browser, campaign) page.close() -def test_time_axis_chinese_narrow_screen_and_accessible_table(browser, campaign): +def test_time_axis_chinese_narrow_screen_and_accessible_table(browser, dashboard_campaign): page = browser.new_page(viewport={"width": 390, "height": 844}) errors = [] page.on("pageerror", lambda e: errors.append(str(e))) - page.goto((campaign / "dashboard.html").as_uri()) + page.goto((dashboard_campaign / "dashboard.html").as_uri()) page.locator("#language-zh").click() root = page.locator("#summary-experiments") root.get_by_label("工作负载", exact=True).select_option("W1") @@ -117,9 +108,9 @@ def test_time_axis_chinese_narrow_screen_and_accessible_table(browser, campaign) page.close() -def test_story_tabs_keep_keyboard_focus_and_label_the_active_panel(browser, campaign): +def test_story_tabs_keep_keyboard_focus_and_label_the_active_panel(browser, dashboard_campaign): page = browser.new_page() - page.goto((campaign / "dashboard.html").as_uri()) + page.goto((dashboard_campaign / "dashboard.html").as_uri()) story = page.locator("#story") tabs = story.get_by_role("tablist").get_by_role("tab") story.get_by_role("tab", selected=True).focus() @@ -143,10 +134,12 @@ def test_story_tabs_keep_keyboard_focus_and_label_the_active_panel(browser, camp @pytest.mark.parametrize("profile_first", [False, True]) -def test_narrow_viewport_contains_data_in_both_languages(browser, campaign, profile_first): - path = campaign / "dashboard.html" +def test_narrow_viewport_contains_data_in_both_languages( + browser, dashboard_campaign, profile_first, +): + path = dashboard_campaign / "dashboard.html" if profile_first: - snapshot = dashboard_snapshot(campaign) + snapshot = dashboard_snapshot(dashboard_campaign) snapshot["data"]["review_layout"] = "profile_first" path.write_text(render_dashboard(snapshot), encoding="utf-8") page = browser.new_page(viewport={"width": 320, "height": 740}) @@ -173,14 +166,14 @@ def test_narrow_viewport_contains_data_in_both_languages(browser, campaign, prof @pytest.mark.parametrize("profile_first", [False, True]) def test_real_live_refresh_keeps_filters_and_measurement_then_marks_disappearance( - browser, campaign, profile_first, + browser, dashboard_campaign, profile_first, ): if profile_first: - path = campaign / "campaign.json" + path = dashboard_campaign / "campaign.json" data = json.loads(path.read_text()) data["review_layout"] = "profile_first" path.write_text(json.dumps(data)) - server = DashboardServer(campaign, None, 0) + server = DashboardServer(dashboard_campaign, None, 0) worker = threading.Thread(target=server.serve_forever, daemon=True) worker.start() page = browser.new_page() @@ -197,8 +190,9 @@ def test_real_live_refresh_keeps_filters_and_measurement_then_marks_disappearanc point.focus() identity = point.get_attribute("data-xp-id") # Reorder directories and update the selected run's value while keeping its identity. - (campaign / "candidates/native-run-b").rename(campaign / "candidates/aaa-reordered") - path = campaign / "runs/native-run-b/evaluation.json" + candidate = dashboard_campaign / "candidates/native-run-b" + candidate.rename(dashboard_campaign / "candidates/aaa-reordered") + path = dashboard_campaign / "runs/native-run-b/evaluation.json" data = json.loads(path.read_text()) data["candidate"]["median"] = 107 path.write_text(json.dumps(data)) @@ -207,7 +201,7 @@ def test_real_live_refresh_keeps_filters_and_measurement_then_marks_disappearanc assert root.locator('[data-xp-control="workload"]').input_value() == "W-throughput" assert root.locator(f'.xp-point[data-xp-id="{identity}"]').get_attribute( "aria-pressed") == "true" - shutil.rmtree(campaign / "candidates/aaa-reordered") + shutil.rmtree(dashboard_campaign / "candidates/aaa-reordered") playwright.expect(root.locator(".xp-detail")).to_contain_text( "Selection no longer available", timeout=15000) assert root.locator('.xp-point[aria-pressed="true"]').count() == 0 @@ -219,10 +213,12 @@ def test_real_live_refresh_keeps_filters_and_measurement_then_marks_disappearanc server.server_close() -def test_profile_layout_preserves_partial_summary_and_keyboard_drilldown(browser, campaign): - snapshot = dashboard_snapshot(campaign) +def test_profile_layout_preserves_partial_summary_and_keyboard_drilldown( + browser, dashboard_campaign, +): + snapshot = dashboard_snapshot(dashboard_campaign) snapshot["data"]["review_layout"] = "profile_first" - path = campaign / "profile.html" + path = dashboard_campaign / "profile.html" path.write_text(render_dashboard(snapshot)) page = browser.new_page() errors = [] @@ -287,7 +283,7 @@ def test_mixed_profile_keeps_native_paired_reference(browser, tmp_path): run(tmp_path, "native", 15, quality="completed", verified=True) candidate(tmp_path, "native", "native", round=1) native_chart = dashboard_snapshot(tmp_path)["chart"] - FIXTURE["external"](tmp_path, "external-latency", 2, [FIXTURE["metric"]()]) + experiment_data.external(tmp_path, "external-latency", 2, [experiment_data.metric()]) snapshot = dashboard_snapshot(tmp_path) path = tmp_path / "dashboard.html" path.write_text(render_dashboard(snapshot), encoding="utf-8") @@ -308,16 +304,16 @@ def test_mixed_profile_keeps_native_paired_reference(browser, tmp_path): def test_blank_configuration_renders_isolated_points_and_reason( browser, tmp_path, field, profile_first, ): - FIXTURE["write"](tmp_path / "campaign.json", { + experiment_data.write(tmp_path / "campaign.json", { "campaign_id": "synthetic-blank-config", "synthetic": True, **({"review_layout": "profile_first"} if profile_first else {}), }) for round_number in (1, 2): - metric = FIXTURE["metric"](value=8 + round_number) + metric = experiment_data.metric(value=8 + round_number) metric["configuration"][field] = " " - FIXTURE["external"](tmp_path, f"blank-{round_number}", round_number, [metric]) - control = FIXTURE["metric"]("W2", value=8 + round_number) - FIXTURE["external"](tmp_path, f"control-{round_number}", round_number, [control]) + experiment_data.external(tmp_path, f"blank-{round_number}", round_number, [metric]) + control = experiment_data.metric("W2", value=8 + round_number) + experiment_data.external(tmp_path, f"control-{round_number}", round_number, [control]) path = tmp_path / "dashboard.html" path.write_text(render_dashboard(dashboard_snapshot(tmp_path))) page = browser.new_page() @@ -403,9 +399,9 @@ def test_managed_session_preserves_objective_and_token_chart(browser, session, c "panel_key,root_id", [("summary", "summary-experiments"), ("trend", "chart")], ) def test_profile_opens_with_trend_and_keeps_reader_panel_state( - browser, campaign, live, panel_key, root_id, + browser, dashboard_campaign, live, panel_key, root_id, ): - path = campaign / "campaign.json" + path = dashboard_campaign / "campaign.json" data = json.loads(path.read_text()) data["review_layout"] = "profile_first" path.write_text(json.dumps(data)) @@ -413,13 +409,13 @@ def test_profile_opens_with_trend_and_keeps_reader_panel_state( page = browser.new_page() try: if live: - server = DashboardServer(campaign, None, 0) + server = DashboardServer(dashboard_campaign, None, 0) worker = threading.Thread(target=server.serve_forever, daemon=True) worker.start() page.goto(f"http://127.0.0.1:{server.server_port}") else: - path = campaign / "profile.html" - path.write_text(render_dashboard(dashboard_snapshot(campaign))) + path = dashboard_campaign / "profile.html" + path.write_text(render_dashboard(dashboard_snapshot(dashboard_campaign))) page.goto(path.as_uri()) assert page.locator("#chart .xp-chart").first.is_visible() assert page.locator("main > section").evaluate_all( @@ -437,7 +433,7 @@ def test_profile_opens_with_trend_and_keeps_reader_panel_state( root.locator('[data-xp-control="workload"]').select_option("W-throughput") root.locator('.xp-point[aria-label^="native-run-b"]').focus() if live: - path = campaign / "runs/native-run-b/evaluation.json" + path = dashboard_campaign / "runs/native-run-b/evaluation.json" data = json.loads(path.read_text()) data["candidate"]["median"] = 107 path.write_text(json.dumps(data)) @@ -464,7 +460,7 @@ def test_profile_opens_with_trend_and_keeps_reader_panel_state( @pytest.mark.parametrize("profile_first", [False, True]) @pytest.mark.parametrize("width", [1440, 390]) def test_dense_round_titles_do_not_overlap(browser, tmp_path, profile_first, width): - FIXTURE["write"](tmp_path / "campaign.json", { + experiment_data.write(tmp_path / "campaign.json", { "campaign_id": "synthetic-dense-rounds", "synthetic": True, **({"review_layout": "profile_first"} if profile_first else {}), }) @@ -474,8 +470,8 @@ def test_dense_round_titles_do_not_overlap(browser, tmp_path, profile_first, wid name = f"candidate-{index}" events = [{"stage": "validation", "category": "quality", "workload": "W1", "summary": f"Synthetic event {n}"} for n in range(8)] if index == 7 else [] - FIXTURE["external"](tmp_path, name, round_number, - [FIXTURE["metric"](value=20-index/2)], events=events) + experiment_data.external(tmp_path, name, round_number, + [experiment_data.metric(value=20-index/2)], events=events) path = tmp_path / "candidates" / name / "candidate.json" data = json.loads(path.read_text()) title = f"方案{index:02d}中文长名称并行计算内存优化" diff --git a/tests/apps/test_dsh_plugin.py b/tests/apps/test_dsh_plugin.py index c72aa2dfa..cd6627567 100644 --- a/tests/apps/test_dsh_plugin.py +++ b/tests/apps/test_dsh_plugin.py @@ -45,11 +45,11 @@ def test_manual_bundle_runs_from_an_external_workspace(tmp_path): assert client.is_file() if shutil.which("node"): subprocess.run([ - "node", str(PROJECT / "tests/check_dsh_form.cjs"), + "node", str(PROJECT / "tests/apps/check_dsh_form.cjs"), str(PROJECT / "plugins/inferrsi-dsh/form.cjs"), str(client), ], check=True, capture_output=True, text=True, timeout=30) subprocess.run([ - "node", str(PROJECT / "tests/check_dsh_bridge.cjs"), + "node", str(PROJECT / "tests/apps/check_dsh_bridge.cjs"), str(package / "remote-host.cjs"), ], check=True, capture_output=True, text=True, timeout=30) assert (package / "LICENSE").read_bytes() == (PROJECT / "LICENSE").read_bytes() @@ -142,5 +142,5 @@ def invoke_remote(*args): @pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for native SSH checks") def test_remote_ssh_connection_and_scoped_operations(): - subprocess.run(["node", str(PROJECT / "tests/check_dsh_remote.cjs")], + subprocess.run(["node", str(PROJECT / "tests/apps/check_dsh_remote.cjs")], cwd=PROJECT, check=True, capture_output=True, text=True, timeout=60) diff --git a/tests/apps/test_engineering_benchmark_plugins.py b/tests/apps/test_engineering_benchmark_plugins.py index 1a80411c3..b1eadd835 100644 --- a/tests/apps/test_engineering_benchmark_plugins.py +++ b/tests/apps/test_engineering_benchmark_plugins.py @@ -5,7 +5,7 @@ from tests.apps.test_codex_plugin import distribution as distribution from tests.apps.test_codex_plugin import invoke from tests.apps.test_project_optimization import project as project -from tests.diagnosis_support import diagnosis_args +from tests.fixtures.diagnosis import diagnosis_args def test_isolated_benchmark_child_uses_its_bundled_runtime(distribution, tmp_path, monkeypatch): diff --git a/tests/apps/test_legacy_run_split.py b/tests/apps/test_legacy_run_split.py index d3dbd7466..40baa815d 100644 --- a/tests/apps/test_legacy_run_split.py +++ b/tests/apps/test_legacy_run_split.py @@ -20,10 +20,9 @@ from inferrsi.apps.legacy import run as legacy_run from inferrsi.benchmark import legacy_run_v0, metrics, sampling from inferrsi.contracts import RunSpec, claim -from inferrsi.harness import atomic_json from inferrsi.harness.runner import run_experiment from inferrsi.harness.trials.external import execute_trial -from tests._gate_policy_support import ROOT, _scan, _walk +from tests.repository._gate_policy_support import ROOT, _scan, _walk GRAPH = _scan(ROOT, frozenset()) # Harness reaches no Infra or Model module any more: #498 removed both packages. @@ -147,31 +146,12 @@ def reject(document, key): assert json.loads((tmp_path / name / "execution.json").read_text("utf-8")) == record -@pytest.mark.parametrize("value", [ - {}, [], {"verdict": "PASS", "values": [1.0, 2, None, True]}, - {"文本": "未转义 ✓", "nested": {"path": "C:\\runs\\a", "quote": "\"", "line": "a\nb"}}, - {"float": 1e-308, "large": 1e308, "negative": -0.0}, -]) -def test_harness_writer_bytes_equal_the_apps_writer(tmp_path, value): - atomic_json.atomic_write_json(tmp_path / "harness.json", value) - artifacts.atomic_write_json(tmp_path / "infra.json", value) - assert (tmp_path / "harness.json").read_bytes() == (tmp_path / "infra.json").read_bytes() - assert sorted(path.name for path in tmp_path.iterdir()) == ["harness.json", "infra.json"] - - def test_sampling_sha256_matches_the_apps_hasher(tmp_path): path = tmp_path / "artifact.bin" path.write_bytes(b"inferrsi-b01-sampling-pin") assert sampling._sha256(path) == artifacts.sha256(path) -def test_harness_writer_rejects_nan_and_leaves_no_file(tmp_path): - for writer in (atomic_json.atomic_write_json, artifacts.atomic_write_json): - with pytest.raises(ValueError): - writer(tmp_path / "value.json", {"metric": float("nan")}) - assert list(tmp_path.iterdir()) == [] - - def _trials(value: float) -> list[dict]: return [{"status": "completed", "metric": value}] diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index 968985b6a..bfca1696d 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -14,7 +14,7 @@ from inferrsi.benchmark import registry from inferrsi.harness import optimization_session from inferrsi.harness.optimization import _locked -from tests.diagnosis_support import diagnosis_args +from tests.fixtures.diagnosis import diagnosis_args @pytest.fixture diff --git a/tests/apps/test_optimization_story.py b/tests/apps/test_optimization_story.py index 91c72f4ce..01a00c50c 100644 --- a/tests/apps/test_optimization_story.py +++ b/tests/apps/test_optimization_story.py @@ -590,19 +590,27 @@ def test_unavailable_named_capture_does_not_fall_back_to_another_capture(tmp_pat for check in checks) -def test_capture_identity_must_match_campaign_and_context_id(tmp_path): +@pytest.mark.parametrize(("updates", "state"), [ + pytest.param( + {"campaign_id": "another-campaign", "context_id": "another-context"}, + "identity_mismatch", + id="identity-mismatch", + ), + pytest.param({"items": [None]}, "invalid_format", id="invalid-format"), +]) +def test_capture_envelope_errors_withhold_text(tmp_path, updates, state): digest = campaign(tmp_path) document = log_document(digest) path = tmp_path / "knowledge/r1.json" capture = json.loads(path.read_text(encoding="utf-8")) - capture.update(campaign_id="another-campaign", context_id="another-context") + capture.update(updates) raw = json.dumps(capture).encode() path.write_bytes(raw) document["knowledge"][0]["sha256"] = hashlib.sha256(raw).hexdigest() write_log(tmp_path, document) retrieval = load_dashboard(tmp_path)["story"]["retrievals"][0] - assert retrieval["state"] == "identity_mismatch" + assert retrieval["state"] == state assert "assembled_text" not in retrieval @@ -680,21 +688,6 @@ def test_dashboard_withholds_log_from_another_campaign(tmp_path): assert load_dashboard(tmp_path)["story"]["state"] == "identity_mismatch" -def test_malformed_capture_envelope_is_withheld(tmp_path): - digest = campaign(tmp_path) - document = log_document(digest) - path = tmp_path / "knowledge/r1.json" - capture = json.loads(path.read_text(encoding="utf-8")) - capture["items"] = [None] - raw = json.dumps(capture).encode() - path.write_bytes(raw) - document["knowledge"][0]["sha256"] = hashlib.sha256(raw).hexdigest() - write_log(tmp_path, document) - retrieval = load_dashboard(tmp_path)["story"]["retrievals"][0] - assert retrieval["state"] == "invalid_format" - assert "assembled_text" not in retrieval - - def test_search_import_joins_capture_use_with_failed_run(tmp_path): from inferrsi.apps.views.search_attribution import import_search diff --git a/tests/apps/test_profile_story_checks.py b/tests/apps/test_profile_story_checks.py index 37b9fa848..f01ea5b19 100644 --- a/tests/apps/test_profile_story_checks.py +++ b/tests/apps/test_profile_story_checks.py @@ -39,7 +39,7 @@ def test_profile_review_displays_narrative_evidence_conflicts(tmp_path, conflict def _check_page(html, mode): - script = Path(__file__).parents[1] / "check_profile_review.cjs" + script = Path(__file__).with_name("check_profile_review.cjs") subprocess.run([shutil.which("node"), str(script), str(html), mode], check=True) diff --git a/tests/apps/test_project_explanation.py b/tests/apps/test_project_explanation.py index 9ca04b74b..75604c055 100644 --- a/tests/apps/test_project_explanation.py +++ b/tests/apps/test_project_explanation.py @@ -11,7 +11,7 @@ from inferrsi.apps.views.optimization_chart import render_result from inferrsi.harness.artifact_primitives import digest from inferrsi.harness.optimization import read_records -from tests.diagnosis_support import diagnosis_args +from tests.fixtures.diagnosis import diagnosis_args # Device-wide factor applied to every timed value of one measurement call, cycling per # call. It scales all regions together, as clocks or temperature would. diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index 056ac777c..4d6476615 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -11,7 +11,7 @@ from inferrsi.apps.cli import main from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard from inferrsi.harness.optimization import read_records -from tests.diagnosis_support import diagnosis_args +from tests.fixtures.diagnosis import diagnosis_args @pytest.fixture diff --git a/tests/apps/test_result_delivery.py b/tests/apps/test_result_delivery.py index 40450c3e7..5fcea0941 100644 --- a/tests/apps/test_result_delivery.py +++ b/tests/apps/test_result_delivery.py @@ -14,7 +14,7 @@ from inferrsi.apps.storage import archive from inferrsi.apps.storage.result import preparation_result from inferrsi.harness import optimization -from tests.diagnosis_support import diagnosis_evidence +from tests.fixtures.diagnosis import diagnosis_evidence def make_campaign(tmp_path, *, scores=(5,), final=True, final_verdict="PASS", usage=False, diff --git a/tests/engineering_task_support.py b/tests/benchmark/engineering_task_support.py similarity index 100% rename from tests/engineering_task_support.py rename to tests/benchmark/engineering_task_support.py diff --git a/tests/benchmark/test_benchmark_preparation.py b/tests/benchmark/test_benchmark_preparation.py index f115e0de4..26a3a4ff5 100644 --- a/tests/benchmark/test_benchmark_preparation.py +++ b/tests/benchmark/test_benchmark_preparation.py @@ -83,6 +83,14 @@ def resources(role): return service, request, sources, protocol, opened, config, archive +def _prepare_with_apps(request, workspace, config, producer): + return apps_prepare( + {"schema_version": 1, "request": request}, workspace=workspace, + storage_config=config, prepare_benchmark=producer, + encode_prepared=benchmark.encode, validate_prepared=benchmark.validate_prepared, + ) + + def test_real_prepare_freezes_exact_supplied_bytes_and_isolates_caller_mutations(preparation): service, request, sources, protocol, opened, _, _ = preparation protocol["task_parameters"]["label"] = "changed after configuration" @@ -175,11 +183,7 @@ def test_t36_resource_loss_at_each_boundary(preparation, tmp_path, stage): sources["input-data"].unlink() def producer(value): return response - result = apps_prepare( - {"schema_version": 1, "request": request}, workspace=tmp_path, - storage_config=config, prepare_benchmark=producer, - encode_prepared=benchmark.encode, validate_prepared=benchmark.validate_prepared, - ) + result = _prepare_with_apps(request, tmp_path, config, producer) assert result.result["reason_code"] == "ArtifactUnavailable", result.result assert result.result["error"]["stage"] == ("prepare" if stage == "prepare" else "prepared_archive") @@ -217,11 +221,7 @@ def close(self): resources=lambda role: stream if role == "input-data" else sources[role].read_bytes(), worker_role="worker-code", ) - result = apps_prepare( - {"schema_version": 1, "request": request}, workspace=tmp_path, - storage_config=config, prepare_benchmark=service.prepare, - encode_prepared=benchmark.encode, validate_prepared=benchmark.validate_prepared, - ) + result = _prepare_with_apps(request, tmp_path, config, service.prepare) assert result.result["reason_code"] == "ArtifactIntegrityError" assert result.result["error"]["stage"] == "prepare" assert result.result["prepared_ref"] is None @@ -263,11 +263,7 @@ def test_source_change_after_preparation_is_rejected_by_independent_apps_verific service, request, sources, _, _, config, archive = preparation response = service.prepare(request) sources["input-data"].write_bytes(b"changed input") - result = apps_prepare( - {"schema_version": 1, "request": request}, workspace=tmp_path, - storage_config=config, prepare_benchmark=lambda value: response, - encode_prepared=benchmark.encode, validate_prepared=benchmark.validate_prepared, - ) + result = _prepare_with_apps(request, tmp_path, config, lambda value: response) assert result.result["reason_code"] == "ArtifactIntegrityError" assert result.result["prepared_ref"] is None and list(archive.iterdir()) == [] @@ -314,11 +310,7 @@ def test_provisional_locations_do_not_replace_role_authority_or_archive_paths( assert pin["role"] == "input-data" pin["artifact"]["location"] = protocol["resources"][1]["artifact"]["location"] request["input_pins"] = [pin] - result = apps_prepare( - {"schema_version": 1, "request": request}, workspace=tmp_path, - storage_config=config, prepare_benchmark=service.prepare, - encode_prepared=benchmark.encode, validate_prepared=benchmark.validate_prepared, - ) + result = _prepare_with_apps(request, tmp_path, config, service.prepare) assert result.result["exit_code"] == 0, result.result prepared = read_prepared(config, result.result["prepared_ref"]) assert len({item["artifact"]["location"] for item in prepared["resources"]}) == 2 @@ -333,11 +325,7 @@ def test_provisional_locations_do_not_replace_role_authority_or_archive_paths( def test_t36_real_port_archive_and_cross_process_fixed_readback(preparation, tmp_path): service, request, sources, _, _, config, _ = preparation expected, protocol, _ = service.prepare(request) - result = apps_prepare( - {"schema_version": 1, "request": request}, workspace=tmp_path, - storage_config=config, prepare_benchmark=service.prepare, - encode_prepared=benchmark.encode, validate_prepared=benchmark.validate_prepared, - ) + result = _prepare_with_apps(request, tmp_path, config, service.prepare) assert result.result["exit_code"] == 0, result.result ref = result.result["prepared_ref"] assert ref["prepared_id"] == expected["prepared_id"] diff --git a/tests/benchmark/test_evaluator_loaders.py b/tests/benchmark/test_evaluator_loaders.py index 1bce6e2ac..0f1198789 100644 --- a/tests/benchmark/test_evaluator_loaders.py +++ b/tests/benchmark/test_evaluator_loaders.py @@ -8,7 +8,7 @@ import pytest -from tests.engineering_task_support import load_task_module +from tests.benchmark.engineering_task_support import load_task_module grader = load_task_module("moe-forward-npu", "grader") qwen = load_task_module("qwen21-denoise-npu", "benchmark") diff --git a/tests/benchmark/test_moe_benchmark.py b/tests/benchmark/test_moe_benchmark.py index 16a9ee4d7..82495e285 100644 --- a/tests/benchmark/test_moe_benchmark.py +++ b/tests/benchmark/test_moe_benchmark.py @@ -14,7 +14,7 @@ from inferrsi.benchmark.metrics import read_metric from inferrsi.harness.trials.external import execute_trial -from tests.engineering_task_support import load_task_module +from tests.benchmark.engineering_task_support import load_task_module moe = load_task_module("moe-forward-npu", "benchmark") # #412 R3: worker cleanup moved from the sibling processes.py into benchmark.py. diff --git a/tests/benchmark/test_qwen_optimization_protocol.py b/tests/benchmark/test_qwen_optimization_protocol.py index 6bfdc386f..0f42e10ae 100644 --- a/tests/benchmark/test_qwen_optimization_protocol.py +++ b/tests/benchmark/test_qwen_optimization_protocol.py @@ -9,7 +9,7 @@ import pytest from inferrsi.benchmark.registry import task_resources -from tests.engineering_task_support import load_task_module +from tests.benchmark.engineering_task_support import load_task_module protocol = load_task_module("qwen21-denoise-npu", "optimization") diff --git a/tests/benchmark/test_tts_benchmark.py b/tests/benchmark/test_tts_benchmark.py index fbdc8a4f8..082bb6a66 100644 --- a/tests/benchmark/test_tts_benchmark.py +++ b/tests/benchmark/test_tts_benchmark.py @@ -11,7 +11,7 @@ import pytest -from tests.engineering_task_support import load_task_module +from tests.benchmark.engineering_task_support import load_task_module tts = load_task_module("qwen3-tts-npu", "benchmark") main = tts.main diff --git a/tests/benchmark/test_tts_standalone.py b/tests/benchmark/test_tts_standalone.py index 114fed0d1..474cadc01 100644 --- a/tests/benchmark/test_tts_standalone.py +++ b/tests/benchmark/test_tts_standalone.py @@ -16,7 +16,7 @@ import pytest -from tests.engineering_task_support import load_task_module +from tests.benchmark.engineering_task_support import load_task_module tts = load_task_module("qwen3-tts-npu", "benchmark") diff --git a/tests/contracts/test_evidence_paths.py b/tests/contracts/test_evidence_paths.py index ff7493b81..cf8ba942a 100644 --- a/tests/contracts/test_evidence_paths.py +++ b/tests/contracts/test_evidence_paths.py @@ -75,21 +75,11 @@ def _tree(base: Path) -> list[str]: ) -def test_campaign_root_under_evidence(tmp_path: Path) -> None: - root = campaign_evidence_root(tmp_path, "demo-campaign") - assert root == tmp_path / "evidence" / "demo-campaign" - - -def test_ensure_layout_creates_dirs(tmp_path: Path) -> None: - root = tmp_path / "evidence" / "x" - paths = ensure_evidence_layout(root) - assert all(p.is_dir() for p in paths.values()) - - def test_segments_and_subpaths_are_unchanged(tmp_path: Path) -> None: assert EVIDENCE_SEGMENTS == ("plan", "results", "patch", "validator") assert type(EVIDENCE_SEGMENTS) is tuple root = campaign_evidence_root(tmp_path, "demo-campaign") + assert root == tmp_path / "evidence" / "demo-campaign" paths = evidence_subpaths(root) assert type(paths) is dict assert list(paths) == list(EVIDENCE_SEGMENTS) diff --git a/tests/diagnosis_support.py b/tests/fixtures/diagnosis.py similarity index 100% rename from tests/diagnosis_support.py rename to tests/fixtures/diagnosis.py diff --git a/tests/fixtures/optimization-session/README.md b/tests/fixtures/optimization-session/README.md index 795ce12f0..898682c9c 100644 --- a/tests/fixtures/optimization-session/README.md +++ b/tests/fixtures/optimization-session/README.md @@ -18,7 +18,7 @@ that is not settled: The current runtime refuses every one of them for `status` and `recover` before any operation runs and leaves every file unchanged. `tests/apps/test_optimization_session.py` checks this against the -checkout, and `tests/check_installed.py` checks it against the installed wheel through +checkout, and `tests/repository/check_installed.py` checks it against the installed wheel through `INFERRSI_PRE_CHANGE_SESSIONS`, which names this directory. Neither can run the old runtime: that needs the old commit installed in its own environment. diff --git a/tests/fixtures/service_reuse.py b/tests/fixtures/service_reuse.py index 3257d6adf..06878954c 100644 --- a/tests/fixtures/service_reuse.py +++ b/tests/fixtures/service_reuse.py @@ -13,7 +13,7 @@ from inferrsi.harness import artifact_primitives from inferrsi.harness.records import evidence, knowledge_capture from inferrsi.knowledge import knowledge_operations -from tests.diagnosis_support import diagnosis_args +from tests.fixtures.diagnosis import diagnosis_args @pytest.fixture(autouse=True) diff --git a/tests/fixtures/skill_eval_pr_support.py b/tests/fixtures/skill_eval_pr_support.py index f6572ae70..4f5cf2877 100644 --- a/tests/fixtures/skill_eval_pr_support.py +++ b/tests/fixtures/skill_eval_pr_support.py @@ -1,5 +1,7 @@ import io +import re import shutil +import sys import zipfile from urllib.parse import parse_qs, urlsplit @@ -9,6 +11,23 @@ from tools import skill_eval_pr as integration +def dispatch_event(monkeypatch, root, output, inputs, mode, run_id=11): + write_json(root / "event.json", {"inputs": inputs}) + environment = {"GITHUB_EVENT_PATH": str(root / "event.json"), + "GITHUB_EVENT_NAME": "workflow_dispatch", + "GITHUB_REPOSITORY": "example/fixture", "GITHUB_RUN_ID": str(run_id), + "GITHUB_RUN_ATTEMPT": "1", "GITHUB_ACTOR": "fixture-operator", + "GITHUB_TOKEN": "offline-not-a-credential", + "GITHUB_OUTPUT": str(root / "github-output")} + for key, value in environment.items(): + monkeypatch.setenv(key, value) + monkeypatch.setattr(sys, "argv", ["skill_eval_pr", mode, "--output", str(output)]) + + +def visible(text): + return re.sub(r"
.*?
", "", text, flags=re.S) + + def setup(root, mode="update", ids=("fix", "regression", "same", "wrong", "error", "missing"), **limits): config_path, repo = configuration(root, ids=ids, **limits) diff --git a/tests/fixtures/task-input/README.md b/tests/fixtures/task-input/README.md index 9f7dfcacb..0fe49089e 100644 --- a/tests/fixtures/task-input/README.md +++ b/tests/fixtures/task-input/README.md @@ -12,7 +12,7 @@ template under `src/inferrsi/apps/cli/task-input/v1/`). See | `invalid-cases.json` | Rejected inputs: `yaml` text and the exact error `fields`; `schema_detects: false` marks cases that JSON Schema alone accepts or that never load as YAML: duplicate or merge keys, several documents, values the loader cannot build, NaN, integral floats such as `3.0`, numbers beyond float range, quoted-command parsing, malformed URLs (unparsable, without a host, or with an invalid port, whitespace or control characters), NUL characters in paths, the Python selector and argv items, and lone surrogates | `tests/apps/test_task_input.py` checks the Python contract and the packaged JSON Schema -against these files, and `tests/check_installed.py` reuses `complete.yaml` from an +against these files, and `tests/repository/check_installed.py` reuses `complete.yaml` from an installed wheel outside the checkout. `tests/apps/test_task_plan_run.py` uses `complete.yaml` and `partial.yaml` with `inferrsi plan --task` and `inferrsi run --task`. It checks the expected RunSpec, the `task` block against `task preview --json`, overrides, conflicting diff --git a/tests/h01_run_store_child.py b/tests/harness/run_store_child.py similarity index 99% rename from tests/h01_run_store_child.py rename to tests/harness/run_store_child.py index 0a1a47ec3..e5a5c8dce 100644 --- a/tests/h01_run_store_child.py +++ b/tests/harness/run_store_child.py @@ -15,7 +15,7 @@ # Child process for the H01 RunStore tests: it claims, commits, reads, or dies at one # injected crash point. Crash points replace module helpers inside this child only. -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] FIXTURES = REPO / "docs" / "contracts" / "fixtures" / "t108-v4" CHILD = Path(__file__) # Exit status that proves the child reached its injected crash point. diff --git a/tests/session_lock_probe.py b/tests/harness/session_lock_probe.py similarity index 98% rename from tests/session_lock_probe.py rename to tests/harness/session_lock_probe.py index c6271da8b..9e33c5670 100644 --- a/tests/session_lock_probe.py +++ b/tests/harness/session_lock_probe.py @@ -1,7 +1,7 @@ """Hold a real optimization session's lock from a separate Harness process, then export it. Run by tests/harness/test_session_lock_across_processes.py once per interpreter: against the -checkout in the test run, and against an installed wheel in tests/check_installed.py. It +checkout in the test run, and against an installed wheel in tests/repository/check_installed.py. It builds a valid managed session that is not final, starts a child process that holds ``/.session.lock`` through ``harness.optimization``'s own lock, and exports the session through the Apps ``export_bundle`` from this process. While the child holds the lock @@ -57,7 +57,7 @@ def make_session(root: Path) -> None: } optimization.initialize(root, plan) # A round needs recorded bottleneck evidence first. The file sits beside the session - # root, as in tests/diagnosis_support.py, which an installed wheel does not ship. + # root, as in tests/fixtures/diagnosis.py, which an installed wheel does not ship. evidence = root.with_name(root.name + "-measurement.txt") evidence.write_text("Synthetic workload: reference operation took 4 ms.", encoding="utf-8") optimization.record_diagnosis(root, "Reference operation", evidence) diff --git a/tests/harness/test_confinement.py b/tests/harness/test_confinement.py index 0c4d656c4..b600eab05 100644 --- a/tests/harness/test_confinement.py +++ b/tests/harness/test_confinement.py @@ -115,13 +115,14 @@ def fake_popen(argv, **kwargs): """ -def test_unshare_timeout_kills_the_whole_process_group(tmp_path, monkeypatch): +def _assert_unshare_timeout_kills_child(tmp_path, monkeypatch, *, start_new_session): real_popen = subprocess.Popen (tmp_path / "child.py").write_text(_LATE_CHILD, encoding="utf-8") child = [str(tmp_path / "child.py"), str(tmp_path), "1.5"] + popen_options = ", start_new_session=True" if start_new_session else "" payload = ( "import subprocess, sys, time\n" - f"subprocess.Popen([sys.executable, *{child!r}])\n" + f"subprocess.Popen([sys.executable, *{child!r}]{popen_options})\n" "time.sleep(30)\n" ) @@ -144,33 +145,12 @@ def fake_popen(argv, **kwargs): assert not (tmp_path / "late").exists() -def test_unshare_timeout_kills_a_direct_child_that_left_the_session(tmp_path, monkeypatch): - real_popen = subprocess.Popen - (tmp_path / "child.py").write_text(_LATE_CHILD, encoding="utf-8") - child = [str(tmp_path / "child.py"), str(tmp_path), "1.5"] - payload = ( - "import subprocess, sys, time\n" - f"subprocess.Popen([sys.executable, *{child!r}], start_new_session=True)\n" - "time.sleep(30)\n" - ) +def test_unshare_timeout_kills_the_whole_process_group(tmp_path, monkeypatch): + _assert_unshare_timeout_kills_child(tmp_path, monkeypatch, start_new_session=False) - def fake_popen(argv, **kwargs): - if argv and argv[0] == "unshare": - argv = [sys.executable, "-c", payload] - return real_popen(argv, **kwargs) - monkeypatch.setattr("inferrsi.harness.confinement.subprocess.Popen", fake_popen) - with pytest.raises(ConfinementUnavailable, match="timed out"): - UnshareBackend().run( - (sys.executable, "-c", "print('unused')"), - tmp_path, - (tmp_path,), - (), - time.monotonic() + 1, - ) - time.sleep(2) - assert (tmp_path / "started").exists() - assert not (tmp_path / "late").exists() +def test_unshare_timeout_kills_a_direct_child_that_left_the_session(tmp_path, monkeypatch): + _assert_unshare_timeout_kills_child(tmp_path, monkeypatch, start_new_session=True) def test_a_group_that_never_empties_is_reported_unreaped(monkeypatch): diff --git a/tests/harness/test_harness_execute.py b/tests/harness/test_harness_execute.py index 0473d6452..795e7064e 100644 --- a/tests/harness/test_harness_execute.py +++ b/tests/harness/test_harness_execute.py @@ -19,8 +19,8 @@ from inferrsi.harness.api import Harness, LocalCpuTarget from inferrsi.harness.errors import PublicError from inferrsi.harness.run_store import RunStore, RunStoreReader -from tests._gate_policy_support import ROOT, _scan, _walk, exact_pairs, load_manifest -from tests.h01_run_store_child import REPO, child_env +from tests.harness.run_store_child import REPO, child_env +from tests.repository._gate_policy_support import ROOT, _scan, _walk, exact_pairs, load_manifest NAMESPACE = "h02-test" TARGET = {"target_id": "cpu-h02", "executor_kind": "local_cpu", "config_revision": "1"} @@ -713,12 +713,7 @@ def _tree_record(tmp_path: Path, seconds: float) -> tuple[dict, int]: return record, int((tmp_path / "trial" / "stdout.log").read_text().strip()) -@pytest.mark.skipif(os.name != "nt", reason="Windows Job Object domain") -def test_windows_job_owns_and_empties_the_command_tree(tmp_path: Path) -> None: - record, grandchild = _tree_record(tmp_path, 8) - assert record["status"] == "timeout" and record["process_group_id"] is None - # The Job is drained before the call returns; no asynchronous kill remains. - assert not alive(grandchild) +def _assert_supervised_tree_emptied_after_timeout(tmp_path: Path) -> None: run = local_process._supervise( [sys.executable, "-c", TREE], tmp_path, dict(os.environ), tmp_path / "out.log", tmp_path / "err.log", time.monotonic() + 8, @@ -727,18 +722,22 @@ def test_windows_job_owns_and_empties_the_command_tree(tmp_path: Path) -> None: assert not alive(int((tmp_path / "out.log").read_text().strip())) +@pytest.mark.skipif(os.name != "nt", reason="Windows Job Object domain") +def test_windows_job_owns_and_empties_the_command_tree(tmp_path: Path) -> None: + record, grandchild = _tree_record(tmp_path, 8) + assert record["status"] == "timeout" and record["process_group_id"] is None + # The Job is drained before the call returns; no asynchronous kill remains. + assert not alive(grandchild) + _assert_supervised_tree_emptied_after_timeout(tmp_path) + + @pytest.mark.skipif(os.name == "nt", reason="POSIX process-group domain") def test_posix_process_group_owns_and_empties_the_command_tree(tmp_path: Path) -> None: record, grandchild = _tree_record(tmp_path, 8) assert record["status"] == "timeout" assert record["process_group_id"] == record["pid"] assert not alive(grandchild) - run = local_process._supervise( - [sys.executable, "-c", TREE], tmp_path, dict(os.environ), - tmp_path / "out.log", tmp_path / "err.log", time.monotonic() + 8, - ) - assert (run["status"], run["domain_empty"]) == ("timeout", True) - assert not alive(int((tmp_path / "out.log").read_text().strip())) + _assert_supervised_tree_emptied_after_timeout(tmp_path) def test_normal_exit_still_empties_a_lingering_descendant(tmp_path: Path) -> None: diff --git a/tests/harness/test_harness_run_store.py b/tests/harness/test_harness_run_store.py index 754077b4d..3523d1702 100644 --- a/tests/harness/test_harness_run_store.py +++ b/tests/harness/test_harness_run_store.py @@ -22,7 +22,7 @@ from inferrsi.harness import run_store from inferrsi.harness.errors import PublicError from inferrsi.harness.run_store import Claim, CommittedRecord, RunStore, RunStoreReader -from tests.h01_run_store_child import ( +from tests.harness.run_store_child import ( ARTIFACT, ARTIFACT_MEDIA_TYPE, CRASH, diff --git a/tests/harness/test_moe_optimization_protocol.py b/tests/harness/test_moe_optimization_protocol.py index 4f8b7a784..9eb527f32 100644 --- a/tests/harness/test_moe_optimization_protocol.py +++ b/tests/harness/test_moe_optimization_protocol.py @@ -9,7 +9,7 @@ import pytest from inferrsi.harness import task_protocol -from tests.engineering_task_support import load_task_module +from tests.benchmark.engineering_task_support import load_task_module moe = load_task_module("moe-forward-npu", "benchmark") protocol = load_task_module("moe-forward-npu", "optimization") diff --git a/tests/harness/test_session_lock_across_processes.py b/tests/harness/test_session_lock_across_processes.py index 73e5fa77f..f20be5d30 100644 --- a/tests/harness/test_session_lock_across_processes.py +++ b/tests/harness/test_session_lock_across_processes.py @@ -6,10 +6,10 @@ separate process for each holder, so they cover the actual writer and reader on Windows (msvcrt byte range) and POSIX (flock) alike. #498 slice 3b. -``tests/session_lock_probe.py`` drives the real pair with a valid managed session: a Harness +``tests/harness/session_lock_probe.py`` drives the real pair with a valid managed session: a Harness process holds the lock and the Apps ``export_bundle`` of that session is refused, then the same export publishes after release. The probe runs here against the checkout and in -``tests/check_installed.py`` against the installed wheel. +``tests/repository/check_installed.py`` against the installed wheel. """ import json @@ -22,7 +22,7 @@ import pytest SRC = str(Path(__file__).resolve().parents[2] / "src") -PROBE_SCRIPT = Path(__file__).parents[1] / "session_lock_probe.py" +PROBE_SCRIPT = Path(__file__).with_name("session_lock_probe.py") # A child process takes the named lock, reports it, then waits for a release file. HOLDER = """ diff --git a/tests/knowledge/_repo_to_skill_support.py b/tests/knowledge/_repo_to_skill_support.py new file mode 100644 index 000000000..c58c6f36f --- /dev/null +++ b/tests/knowledge/_repo_to_skill_support.py @@ -0,0 +1,18 @@ +"""Common CLI inputs and subprocess setup for repo-to-skill helpers.""" + +import os +import subprocess +import sys + +MALFORMED_HELPER_INPUTS = ( + b"", b"null", b"[]", b"{}", b"not-json-private-payload", b"\xff", + b'{"schema_version":1,"schema_version":2}', b'{"schema_version":NaN}', + b'{"schema_version":Infinity}', b"[" * 1500 + b"0" + b"]" * 1500, +) + + +def run_helper_cli(script, *args, data=None, cwd=None): + return subprocess.run( + [sys.executable, str(script), *args], input=data, capture_output=True, + timeout=10, cwd=cwd, env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}, + ) diff --git a/tests/knowledge/test_knowledge_compatibility_shells.py b/tests/knowledge/test_knowledge_compatibility_shells.py index 747959672..a854b7336 100644 --- a/tests/knowledge/test_knowledge_compatibility_shells.py +++ b/tests/knowledge/test_knowledge_compatibility_shells.py @@ -15,8 +15,8 @@ import pytest -from tests import _gate_policy_support as support -from tests._gate_policy_support import ( +from tests.repository import _gate_policy_support as support +from tests.repository._gate_policy_support import ( LEAF_IMPORTERS, REPO, RETIRED_ROOT_MODULES, @@ -34,7 +34,6 @@ # #408 A1 appended the R1 record, which holds the temporary parser entry it removed. # #498 slice 3a appended the A1 record after it. R1_RECORD = next(item for item in HISTORY if item["stage"] == "R1") -LEAF_NAMES = RETIRED["retired_catalog_two_routes"]["neutral_leaf_export"]["symbols"] MOVED = [item for item in RETIRED["retired_compatibility_pairs"] if "exports" in item] @@ -81,6 +80,8 @@ def test_retired_record_is_the_seven_shells_and_the_manifest_stages_nothing(): assert len(RETIRED["retired_compatibility_pairs"]) == 9 assert len(MOVED) == 7 assert {f"inferrsi.{item['importer']}" for item in MOVED} < RETIRED_ROOT_MODULES + retired_leaf = RETIRED["retired_catalog_two_routes"]["neutral_leaf_export"] + assert retired_leaf["symbols"] == ["REPO_TYPES", "repository_pack"] # Every retired shell record still carries the old root file hash it was audited at. for item in MOVED: assert item["file"] == f"src/inferrsi/{item['importer']}.py" @@ -88,23 +89,6 @@ def test_retired_record_is_the_seven_shells_and_the_manifest_stages_nothing(): assert not (REPO / item["file"]).exists() -def test_one_repo_types_tuple_reaches_knowledge_and_the_parser_directly(): - from inferrsi.apps.cli import arguments - from inferrsi.knowledge import catalog as knowledge_catalog - from inferrsi.resources import repository_packs - - assert knowledge_catalog.REPO_TYPES is repository_packs.REPO_TYPES - # #408 A1: the Apps parser reads the tuple through the Knowledge catalog, which - # binds it from the leaf: still one object on every route, never a copy. - assert arguments.REPO_TYPES is repository_packs.REPO_TYPES - assert LEAF_NAMES == ["REPO_TYPES", "repository_pack"] - assert not hasattr(arguments, "repository_pack") - assert not hasattr(knowledge_catalog, "repository_pack") - assert knowledge_catalog.KNOWLEDGE_SCOPES["contribution"] == ( - *repository_packs.REPO_TYPES, "vllm_ascend", "inferrsi" - ) - - def test_data_leaf_holds_the_recorded_fragment_and_locked_hash(): assert LEAF["module"] == "inferrsi.resources.repository_packs" assert LEAF["file"] == "src/inferrsi/resources/repository_packs.py" diff --git a/tests/knowledge/test_knowledge_fresh_install.py b/tests/knowledge/test_knowledge_fresh_install.py index 89d1b5131..77b4ca01c 100644 --- a/tests/knowledge/test_knowledge_fresh_install.py +++ b/tests/knowledge/test_knowledge_fresh_install.py @@ -11,7 +11,7 @@ RUN_FRESH_VENV=1 pytest tests/knowledge/test_knowledge_fresh_install.py The installed-package and release CI jobs enforce the same checkout-versus-wheel -byte inventory through tests/check_installed.py when INFERRSI_CHECKOUT_RESOURCES +byte inventory through tests/repository/check_installed.py when INFERRSI_CHECKOUT_RESOURCES points at the checkout (no second venv). This module remains the opt-in full fresh-venv path for local or extra isolation. """ diff --git a/tests/knowledge/test_knowledge_model_policy.py b/tests/knowledge/test_knowledge_model_policy.py index fe813bfc8..a69b5265b 100644 --- a/tests/knowledge/test_knowledge_model_policy.py +++ b/tests/knowledge/test_knowledge_model_policy.py @@ -525,6 +525,18 @@ def latest_status(state, head=HEAD): and str(s["context"]).casefold() == DECLARATION.casefold()) +def track_peer_reads(api, state): + state["peer_read"] = False + original = api.get + + def tracking_get(path): + if path == "pulls/123": + state["peer_read"] = True + return original(path) + + api.get = tracking_get + + @pytest.mark.parametrize("order", [(123, 124), (124, 123)]) def test_api_shared_head_cannot_be_overwritten_by_compliant_pr(api_fixture, policy, order): api, state = api_fixture @@ -813,18 +825,10 @@ def test_api_peer_closing_during_the_same_sweep_reassesses_the_survivor(api_fixt def close_peer(route): # The peer leaves after it was seen sharing the head in the evaluation pass and before # the publication-pass collection read completes. - if route == "pulls" and state["read"]: + if route == "pulls" and state["peer_read"]: state["prs"][123]["state"] = "closed" - state["read"] = [] - original = api.get - - def tracking_get(path): - if path == "pulls/123": - state["read"].append(path) - return original(path) - - api.get = tracking_get + track_peer_reads(api, state) state["before_request"] = close_peer results = check_prs(api, policy, BASE, False, [123, 124]) kinds = {r["pull_request"]: r["kind"] for r in results} @@ -932,20 +936,12 @@ def test_api_survivor_closing_during_reassessment_publishes_nothing(api_fixture, def close_peer_and_survivor(route): # A closes after the shared head was staged; B then closes while it is re-evaluated. - if route == "pulls" and state["read"]: + if route == "pulls" and state["peer_read"]: state["prs"][123]["state"] = "closed" if route == "pulls/124/files": state["prs"][124]["state"] = "closed" - state["read"] = [] - original = api.get - - def tracking_get(path): - if path == "pulls/123": - state["read"].append(path) - return original(path) - - api.get = tracking_get + track_peer_reads(api, state) state["before_request"] = close_peer_and_survivor results = check_prs(api, policy, BASE, False, [123, 124]) kinds = {r["pull_request"]: r["kind"] for r in results} @@ -960,20 +956,12 @@ def test_api_head_change_during_reassessment_publishes_nothing(api_fixture, poli state["prs"][124] = {**pr(), "number": 124} def advance_survivor(route): - if route == "pulls" and state["read"]: + if route == "pulls" and state["peer_read"]: state["prs"][123]["state"] = "closed" if route == "pulls/124/files": state["prs"][124]["head"] = {"sha": "d" * 40} - state["read"] = [] - original = api.get - - def tracking_get(path): - if path == "pulls/123": - state["read"].append(path) - return original(path) - - api.get = tracking_get + track_peer_reads(api, state) state["before_request"] = advance_survivor results = check_prs(api, policy, BASE, False, [123, 124]) kinds = {r["pull_request"]: r["kind"] for r in results} diff --git a/tests/knowledge/test_knowledge_policy_http.py b/tests/knowledge/test_knowledge_policy_http.py index 58e75d148..b2f2265b2 100644 --- a/tests/knowledge/test_knowledge_policy_http.py +++ b/tests/knowledge/test_knowledge_policy_http.py @@ -17,6 +17,19 @@ def failure(code, message="", headers=None): class DiagnosticsTests(unittest.TestCase): + def assert_terminal_capacity(self, error, message): + self.assertEqual(error.reason, "status-capacity") + self.assertNotIn(message, str(error)) + result = policy.status_write_failure(error, {"description": "fixture"}) + result.update(pull_request=1, rerun=result["kind"] in policy.RERUN_KINDS) + self.assertEqual(result["kind"], "budget-saturated") + self.assertEqual(result["state"], "failure") + self.assertFalse(result["rerun"]) + self.assertEqual(policy.exit_code([result]), policy.EXIT_NONCOMPLIANT) + summary = policy.summarize([result]) + self.assertEqual(summary["execution"], "failed") + self.assertEqual(summary["noncompliant_pull_requests"], []) + def test_permission_is_not_rate_limit(self): error = policy.GitHubHTTPError(failure(403, "Resource not accessible by integration")) self.assertEqual(error.category, "permission") @@ -52,16 +65,7 @@ def test_exact_string_capacity_is_recognized_but_remains_execution_failure(self) "This SHA and context has reached the maximum number of statuses."} error = policy.GitHubHTTPError(HTTPError("https://example.invalid", 422, "", {}, io.BytesIO(json.dumps(body).encode()))) - self.assertEqual(error.reason, "status-capacity") - self.assertNotIn(body["errors"], str(error)) - result = policy.status_write_failure(error, {"description": "fixture"}) - result.update(pull_request=1, rerun=result["kind"] in policy.RERUN_KINDS) - self.assertEqual(result["kind"], "budget-saturated") - self.assertEqual(result["state"], "failure") - self.assertFalse(result["rerun"]) - self.assertEqual(policy.exit_code([result]), policy.EXIT_NONCOMPLIANT) - self.assertEqual(policy.summarize([result])["execution"], "failed") - self.assertEqual(policy.summarize([result])["noncompliant_pull_requests"], []) + self.assert_terminal_capacity(error, body["errors"]) def test_verified_prefixed_capacity_string_is_terminal_not_compliance(self): message = ("Validation failed: This SHA and context has reached the maximum " @@ -69,15 +73,7 @@ def test_verified_prefixed_capacity_string_is_terminal_not_compliance(self): body = {"message": "Validation Failed", "errors": message} failure = policy.GitHubHTTPError(HTTPError("https://example.invalid", 422, "", {}, io.BytesIO(json.dumps(body).encode()))) - self.assertEqual(failure.reason, "status-capacity") - self.assertNotIn(message, str(failure)) - result = policy.status_write_failure(failure, {"description": "fixture"}) - result.update(pull_request=1, rerun=result["kind"] in policy.RERUN_KINDS) - self.assertEqual(result["kind"], "budget-saturated") - self.assertEqual(result["state"], "failure") - self.assertFalse(result["rerun"]) - self.assertEqual(policy.exit_code([result]), policy.EXIT_NONCOMPLIANT) - self.assertEqual(policy.summarize([result])["noncompliant_pull_requests"], []) + self.assert_terminal_capacity(failure, message) for changed in (message + " FAKE_SECRET", "FAKE_SECRET " + message, message.replace("Validation failed:", "Validation error:"), message[:-1]): diff --git a/tests/knowledge/test_mistral_rs_repo_to_skill.py b/tests/knowledge/test_mistral_rs_repo_to_skill.py index 144c79c00..8b56020d6 100644 --- a/tests/knowledge/test_mistral_rs_repo_to_skill.py +++ b/tests/knowledge/test_mistral_rs_repo_to_skill.py @@ -8,8 +8,6 @@ import os import re import runpy -import subprocess -import sys from pathlib import Path from urllib.parse import unquote, urlsplit @@ -17,6 +15,7 @@ import yaml from inferrsi.knowledge.skill_catalog import skill_metadata +from tests.knowledge._repo_to_skill_support import MALFORMED_HELPER_INPUTS, run_helper_cli PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/mistral-rs" @@ -34,10 +33,7 @@ def helper(area): def call_cli(area, *args, data=None, cwd=None): script = ROOT / "sub-skills" / area / "scripts" / SCRIPTS[area] - return subprocess.run( - [sys.executable, str(script), *args], input=data, capture_output=True, - timeout=10, cwd=cwd, env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}, - ) + return run_helper_cli(script, *args, data=data, cwd=cwd) def test_mistral_rs_graph_is_contained_candidate_with_exact_source_scope(): @@ -370,11 +366,7 @@ def test_helper_cli_help_example_and_valid_stdin_file_are_offline(tmp_path, area @pytest.mark.parametrize("area", SCRIPTS) -@pytest.mark.parametrize("raw", [ - b"", b"null", b"[]", b"{}", b"not-json-private-payload", b"\xff", - b'{"schema_version":1,"schema_version":2}', b'{"schema_version":NaN}', - b'{"schema_version":Infinity}', b"[" * 1500 + b"0" + b"]" * 1500, -]) +@pytest.mark.parametrize("raw", MALFORMED_HELPER_INPUTS) def test_all_helper_cli_malformed_input_fails_without_echo_or_traceback(tmp_path, area, raw): result = call_cli(area, "-", data=raw, cwd=tmp_path) assert result.returncode == 2 and not result.stdout diff --git a/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py b/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py index 33ab20aea..1a4ba2e37 100644 --- a/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py +++ b/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py @@ -9,8 +9,6 @@ import os import re import runpy -import subprocess -import sys from pathlib import Path from urllib.parse import unquote, urlsplit @@ -18,6 +16,7 @@ import yaml from inferrsi.knowledge.skill_catalog import skill_metadata +from tests.knowledge._repo_to_skill_support import MALFORMED_HELPER_INPUTS, run_helper_cli PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/mlx-swift-lm" @@ -37,10 +36,7 @@ def helper(area): def call_cli(area, *args, data=None, cwd=None): script = ROOT / "sub-skills" / area / "scripts" / SCRIPTS[area] - return subprocess.run( - [sys.executable, str(script), *args], input=data, capture_output=True, - timeout=10, cwd=cwd, env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}, - ) + return run_helper_cli(script, *args, data=data, cwd=cwd) @pytest.fixture(scope="module") @@ -370,12 +366,7 @@ def test_mlx_swift_helpers_cli_help_examples_stdin_and_regular_file_are_offline( @pytest.mark.parametrize("area", SCRIPTS) -@pytest.mark.parametrize("raw", [ - b"", b"null", b"[]", b"{}", b"not-json-private-payload", b"\xff", - b'{"schema_version":1,"schema_version":2}', b'{"schema_version":NaN}', - b'{"schema_version":Infinity}', b"[" * 1500 + b"0" + b"]" * 1500, - b" " * 65537, -]) +@pytest.mark.parametrize("raw", (*MALFORMED_HELPER_INPUTS, b" " * 65537)) def test_mlx_swift_helpers_cli_bad_json_is_bounded_without_echo_or_traceback(tmp_path, area, raw): result = call_cli(area, "-", data=raw, cwd=tmp_path) assert result.returncode == 2 and not result.stdout diff --git a/tests/knowledge/test_resource_migration.py b/tests/knowledge/test_resource_migration.py index 12de7fa40..9e2e2ce79 100644 --- a/tests/knowledge/test_resource_migration.py +++ b/tests/knowledge/test_resource_migration.py @@ -6,8 +6,8 @@ unchanged by the move. An installed wheel outside the checkout is covered by -``tests/knowledge/test_knowledge_fresh_install.py`` and ``tests/check_installed.py``; under -``pythonpath = ["src"]`` the importlib anchor here resolves to the same checkout +``tests/knowledge/test_knowledge_fresh_install.py`` and ``tests/repository/check_installed.py``. +Under ``pythonpath = ["src"]`` the importlib anchor here resolves to the same checkout directory, so this module proves the resolved paths and the packaging contract rather than a separate installation. """ diff --git a/tests/_gate_policy_support.py b/tests/repository/_gate_policy_support.py similarity index 99% rename from tests/_gate_policy_support.py rename to tests/repository/_gate_policy_support.py index 045048ba6..5f746704e 100644 --- a/tests/_gate_policy_support.py +++ b/tests/repository/_gate_policy_support.py @@ -12,7 +12,7 @@ from pathlib import Path from typing import Any, Callable -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] ROOT = REPO / "src" / "inferrsi" MANIFEST = REPO / "docs" / "legacy-knowledge-manifest.json" NEW_CORES = ("knowledge", "benchmark", "apps") diff --git a/tests/architecture_closed_loop.py b/tests/repository/architecture_closed_loop.py similarity index 100% rename from tests/architecture_closed_loop.py rename to tests/repository/architecture_closed_loop.py diff --git a/tests/architecture_real_ports.py b/tests/repository/architecture_real_ports.py similarity index 98% rename from tests/architecture_real_ports.py rename to tests/repository/architecture_real_ports.py index 4ba84115f..4cb492d6f 100644 --- a/tests/architecture_real_ports.py +++ b/tests/repository/architecture_real_ports.py @@ -20,7 +20,7 @@ from inferrsi.contracts import RunSpec from inferrsi.harness.trials.external import execute_trial from inferrsi.knowledge.knowledge_operations import KnowledgeReader -from tests.architecture_closed_loop import _canonical, _digest +from tests.repository.architecture_closed_loop import _canonical, _digest # Installed package card. Its bundle is record.json only, so this read does # not pull the skill library. The id is a catalog key, not a revision pin. diff --git a/tests/check_installed.py b/tests/repository/check_installed.py similarity index 99% rename from tests/check_installed.py rename to tests/repository/check_installed.py index 78eda6163..e57958306 100644 --- a/tests/check_installed.py +++ b/tests/repository/check_installed.py @@ -1005,7 +1005,7 @@ def assert_not_importable(name): # #498 slice 3b: a Harness process holds a real session's lock while the Apps export of that # session runs from the installed wheel. The export must be refused, and the same export must # publish after the holder releases. The probe source is the one the test suite runs against -# the checkout (tests/session_lock_probe.py); the wheel check receives it through the +# the checkout (tests/harness/session_lock_probe.py); the wheel check receives it through the # environment so this file still copies on its own. # #498: every caller passes the checkout probe, so a missing variable fails here. lock_probe = os.environ["INFERRSI_SESSION_LOCK_PROBE"] diff --git a/tests/repository/test_architecture_closed_loop.py b/tests/repository/test_architecture_closed_loop.py index 2a567a4ee..0e103b089 100644 --- a/tests/repository/test_architecture_closed_loop.py +++ b/tests/repository/test_architecture_closed_loop.py @@ -12,16 +12,16 @@ from unittest.mock import patch from inferrsi.knowledge.knowledge_operations import KnowledgeReader -from tests.architecture_closed_loop import MemoryArchive, _canonical, _digest, run_loop -from tests.architecture_real_ports import ( +from tests.repository.architecture_closed_loop import MemoryArchive, _canonical, _digest, run_loop +from tests.repository.architecture_real_ports import ( PACKAGE_READ, CpuOfflineHarnessRecord, OfflineBenchmarkAssessment, PackageKnowledgeRead, ) -LOOP = Path(__file__).parents[1] / "architecture_closed_loop.py" -PORTS = Path(__file__).parents[1] / "architecture_real_ports.py" +LOOP = Path(__file__).with_name("architecture_closed_loop.py") +PORTS = Path(__file__).with_name("architecture_real_ports.py") LAYOUT = Path(__file__).resolve().parents[2] / "docs" / "module-layout.md" ROOT = Path(__file__).resolve().parents[2] # Families the CPU/offline assembler must not couple to: the CLI, its parser, the diff --git a/tests/test_artifact_helper_copies.py b/tests/repository/test_artifact_helper_copies.py similarity index 86% rename from tests/test_artifact_helper_copies.py rename to tests/repository/test_artifact_helper_copies.py index c8841f06a..35cb1ee10 100644 --- a/tests/test_artifact_helper_copies.py +++ b/tests/repository/test_artifact_helper_copies.py @@ -57,19 +57,38 @@ def test_the_benchmark_copy_imports_no_other_inferrsi_module(): and any(alias.name.split(".")[0] == "inferrsi" for alias in node.names)] -@pytest.mark.parametrize("name", ["write_json", "atomic_write_json"]) -def test_every_writer_writes_the_same_bytes(tmp_path, name): +def _assert_writer_copies(tmp_path, name, value): written = set() + filenames = [] for index, module in enumerate(COPIES[name]): path = tmp_path / f"{index}.json" - getattr(importlib.import_module(module), name)(path, VALUE) + filenames.append(path.name) + getattr(importlib.import_module(module), name)(path, value) written.add(path.read_bytes()) assert len(written) == 1 - assert json.loads(written.pop()) == VALUE + assert json.loads(written.pop()) == value + assert sorted(path.name for path in tmp_path.iterdir()) == filenames + + +@pytest.mark.parametrize("name", ["write_json", "atomic_write_json"]) +def test_every_writer_writes_the_same_bytes(tmp_path, name): + output = tmp_path / "output" + output.mkdir() + _assert_writer_copies(output, name, VALUE) for module in COPIES[name]: with pytest.raises(ValueError): getattr(importlib.import_module(module), name)(tmp_path / "nan.json", {"value": float("nan")}) + assert list(tmp_path.iterdir()) == [output] + + +@pytest.mark.parametrize("value", [ + {}, [], {"verdict": "PASS", "values": [1.0, 2, None, True]}, + {"文本": "未转义 ✓", "nested": {"path": "C:\\runs\\a", "quote": "\"", "line": "a\nb"}}, + {"float": 1e-308, "large": 1e308, "negative": -0.0}, +]) +def test_harness_writer_bytes_equal_the_apps_writer(tmp_path, value): + _assert_writer_copies(tmp_path, "atomic_write_json", value) def test_every_digest_copy_reads_the_same_bytes(tmp_path): diff --git a/tests/repository/test_campaign_plan_template.py b/tests/repository/test_campaign_plan_template.py index df64c1ca1..ccf6221d4 100644 --- a/tests/repository/test_campaign_plan_template.py +++ b/tests/repository/test_campaign_plan_template.py @@ -8,7 +8,6 @@ import re from pathlib import Path -from urllib.parse import unquote, urlsplit import pytest @@ -99,7 +98,6 @@ REVISION = re.compile(r"\b[0-9a-f]{40}\b") DATE = re.compile(r"\b20\d\d-\d\d-\d\d\b") -MARKDOWN_LINK = re.compile(r"\[[^\]]*\]\(([^\s)]+)\)") def _load_machine_readable() -> dict: @@ -212,13 +210,3 @@ def test_template_holds_placeholders_not_campaign_values() -> None: plan = _load_machine_readable() non_string = [leaf for leaf in _leaves(plan) if not isinstance(leaf, str)] assert not non_string, f"campaign-plan.yaml carries a non-string value: {non_string}" - - -def test_plan_segment_documentation_links_resolve() -> None: - for document in sorted(PLAN_DIR.glob("*.md")): - for target in MARKDOWN_LINK.findall(document.read_text(encoding="utf-8")): - parsed = urlsplit(target) - if parsed.scheme or not parsed.path: - continue - path = (document.parent / unquote(parsed.path)).resolve() - assert path.exists(), f"{document.name}: broken link {target}" diff --git a/tests/repository/test_first_wave_isolation_policy.py b/tests/repository/test_first_wave_isolation_policy.py index f22a710f0..e23495145 100644 --- a/tests/repository/test_first_wave_isolation_policy.py +++ b/tests/repository/test_first_wave_isolation_policy.py @@ -7,8 +7,8 @@ from typing import Any from unittest import mock -from tests import _gate_policy_support as support -from tests._gate_policy_support import ( +from tests.repository import _gate_policy_support as support +from tests.repository._gate_policy_support import ( IsolationReport, blocker_kinds, exact_pairs, diff --git a/tests/repository/test_legacy_run_forwarder_gate.py b/tests/repository/test_legacy_run_forwarder_gate.py index 38fb11b66..07967d7c5 100644 --- a/tests/repository/test_legacy_run_forwarder_gate.py +++ b/tests/repository/test_legacy_run_forwarder_gate.py @@ -4,8 +4,8 @@ import pytest -from tests import _gate_policy_support as support -from tests._gate_policy_support import first_wave_report +from tests.repository import _gate_policy_support as support +from tests.repository._gate_policy_support import first_wave_report from tests.repository.test_first_wave_isolation_policy import CLEARED_TREE, EMPTY_ALLOWLIST, _report # The exact targets that were registered before R1. diff --git a/tests/repository/test_target_module_import_gate.py b/tests/repository/test_target_module_import_gate.py index d60d897b4..0ce32d829 100644 --- a/tests/repository/test_target_module_import_gate.py +++ b/tests/repository/test_target_module_import_gate.py @@ -14,8 +14,8 @@ import pytest -from tests import _gate_policy_support as support -from tests._gate_policy_support import ( +from tests.repository import _gate_policy_support as support +from tests.repository._gate_policy_support import ( NEW_CORES, ROOT, blocker_kinds, diff --git a/tests/repository/test_template_layout.py b/tests/repository/test_template_layout.py index 4579d8c25..beed529af 100644 --- a/tests/repository/test_template_layout.py +++ b/tests/repository/test_template_layout.py @@ -23,6 +23,7 @@ def test_maintained_documentation_links_resolve() -> None: documents += list((REPO_ROOT / "docs").rglob("*.md")) documents += list((REPO_ROOT / "src/inferrsi/knowledge/data/skill_library").rglob("*.md")) documents += [REPO_ROOT / "evidence/README.md", REPO_ROOT / "tests/README.md"] + documents.extend(sorted((REPO_ROOT / "evidence/_template/plan").glob("*.md"))) for document in documents: for target in re.findall( r"\[[^\]]*\]\(([^\s)]+)\)", document.read_text(encoding="utf-8") diff --git a/tests/skill_eval/_budget_git_support.py b/tests/skill_eval/_budget_git_support.py index 9ae00ba2e..3b3822ca9 100644 --- a/tests/skill_eval/_budget_git_support.py +++ b/tests/skill_eval/_budget_git_support.py @@ -1,4 +1,4 @@ -"""Git data objects shared by the PR and daily budget store fakes.""" +"""In-memory Git data API shared by the PR and daily budget store fakes.""" import base64 import copy @@ -6,18 +6,19 @@ import json -class GitObjects: - def __init__(self): +class GitDataAPI: + def __init__(self, repository_id, ref_name): + self.repository_id = repository_id + self.ref_name = ref_name self.objects = {} + self.tip = None + self.before_patch = None def put(self, value): sha = hashlib.sha1(json.dumps(value, sort_keys=True).encode()).hexdigest() self.objects[sha] = {**value, "sha": sha} return sha - def read_object(self, path): - return copy.deepcopy(self.objects[path.rsplit("/", 1)[1]]) - def tree(self, content): raw = content.encode() blob = self.put({ @@ -30,3 +31,27 @@ def tree(self, content): def commit(self, tree, parents, **fields): return self.put({"tree": {"sha": tree}, "parents": [{"sha": p} for p in parents], **fields}) + + def ref(self): + if self.tip is None: + raise OSError("404") + return {"ref": self.ref_name, "object": {"type": "commit", "sha": self.tip}} + + def request(self, method, path, data=None): + if method == "GET": + if path == "": + return {"id": self.repository_id} + if path.startswith("/git/ref/"): + return self.ref() + return copy.deepcopy(self.objects[path.rsplit("/", 1)[1]]) + if path == "/git/trees": + return {"sha": self.tree(data["tree"][0]["content"])} + if path == "/git/commits": + return {"sha": self.commit(data["tree"], data["parents"], message=data["message"])} + assert method == "PATCH" and path == f"/git/{self.ref_name}" + assert data["force"] is False + if self.before_patch: + callback, self.before_patch = self.before_patch, None + callback() + self.update_ref(data["sha"]) + return self.ref() diff --git a/tests/skill_eval/test_skill_eval_budget_git.py b/tests/skill_eval/test_skill_eval_budget_git.py index 5389a1bdb..2cf4521fb 100644 --- a/tests/skill_eval/test_skill_eval_budget_git.py +++ b/tests/skill_eval/test_skill_eval_budget_git.py @@ -5,7 +5,7 @@ import pytest -from tests.skill_eval._budget_git_support import GitObjects +from tests.skill_eval._budget_git_support import GitDataAPI from tools import skill_eval_budget as budget from tools.skill_eval_budget_git import GitHubGitStore, LedgerAnchor @@ -17,17 +17,14 @@ def binding(number=1, amount=50_000_000): return budget.Binding(f"{number:064x}", f"run-{number}:attempt-1", amount) -class GitAPI(GitObjects): +class GitAPI(GitDataAPI): """Immutable objects plus non-force fast-forward reference updates.""" def __init__(self): - super().__init__() + super().__init__(KEY.repository_id, REF) self.calls = [] - self.tip = None - self.before_patch = None self.lose_response = False self.reject_write = False - self.repository_id = KEY.repository_id ledger = budget.Ledger(KEY, budget.Genesis("audited legacy fixture", 0)) self.genesis = self.append(ledger, parents=[]) self.anchor = LedgerAnchor(KEY, REF, self.genesis, self.genesis) @@ -38,40 +35,24 @@ def append(self, ledger, parents=None): self.tip = self.commit(tree, parents) return self.tip - def ref(self): - if self.tip is None: - raise OSError("404") - return {"ref": REF, "object": {"type": "commit", "sha": self.tip}} - def request(self, method, path, data=None): self.calls.append((method, path, copy.deepcopy(data))) - if method == "GET": - if path == "": - return {"id": self.repository_id} - if path.startswith("/git/ref/"): - return self.ref() - return self.read_object(path) - if self.reject_write: - raise OSError("rules reject writes") - if path == "/git/trees": - assert set(data) == {"tree"} - return {"sha": self.tree(data["tree"][0]["content"])} - if path == "/git/commits": - return {"sha": self.commit(data["tree"], data["parents"], message=data["message"])} - assert method == "PATCH" and path == "/git/refs/heads/skill-eval-budget/123/7" - assert data["force"] is False - if self.before_patch: - callback, self.before_patch = self.before_patch, None - callback() + if method != "GET": + if self.reject_write: + raise OSError("rules reject writes") + if path == "/git/trees": + assert set(data) == {"tree"} + return super().request(method, path, data) + + def update_ref(self, sha): if self.tip is None: raise OSError("404") - parents = self.objects[data["sha"]]["parents"] - if self.tip != data["sha"] and parents != [{"sha": self.tip}]: + parents = self.objects[sha]["parents"] + if self.tip != sha and parents != [{"sha": self.tip}]: raise OSError("422 non fast-forward") - self.tip = data["sha"] + self.tip = sha if self.lose_response: raise TimeoutError("lost response after commit") - return self.ref() def test_real_adapter_read_reserve_claim_and_permanent_charge(): diff --git a/tests/skill_eval/test_skill_eval_daily_budget.py b/tests/skill_eval/test_skill_eval_daily_budget.py index 5d70c7aeb..b903870f2 100644 --- a/tests/skill_eval/test_skill_eval_daily_budget.py +++ b/tests/skill_eval/test_skill_eval_daily_budget.py @@ -4,7 +4,7 @@ from dataclasses import replace from datetime import datetime, timezone -from tests.skill_eval._budget_git_support import GitObjects +from tests.skill_eval._budget_git_support import GitDataAPI from tools import skill_eval_budget as b from tools.skill_eval_budget_git import DailyLedgerAnchor, GitHubDailyStore @@ -19,11 +19,9 @@ def binding(n, amount=200_000_000): return b.Binding(f"{n:064x}", f"{n}.1", amount) -class API(GitObjects): +class API(GitDataAPI): def __init__(self, ledger=None): - super().__init__() - self.tip = None - self.before_patch = None + super().__init__(KEY.repository_id, REF) self.lose_response = False self.genesis = self.append(ledger or b.DailyLedger(KEY, "reviewed legacy audit"), []) self.anchor = DailyLedgerAnchor(KEY, REF, self.genesis, self.genesis) @@ -32,33 +30,12 @@ def append(self, ledger, parents): self.tip = self.commit(self.tree(b.encode_daily(ledger)), parents) return self.tip - def ref(self): - if self.tip is None: - raise OSError("404") - return {"ref": REF, "object": {"type": "commit", "sha": self.tip}} - - def request(self, method, path, data=None): - if method == "GET": - if path == "": - return {"id": 123} - if path.startswith("/git/ref/"): - return self.ref() - return self.read_object(path) - if path == "/git/trees": - return {"sha": self.tree(data["tree"][0]["content"])} - if path == "/git/commits": - return {"sha": self.commit(data["tree"], data["parents"], message=data["message"])} - assert method == "PATCH" and path == "/git/refs/heads/skill-eval-budget/123/daily" - assert data["force"] is False - if self.before_patch: - callback, self.before_patch = self.before_patch, None - callback() - if self.objects[data["sha"]]["parents"] != [{"sha": self.tip}]: + def update_ref(self, sha): + if self.objects[sha]["parents"] != [{"sha": self.tip}]: raise OSError("422") - self.tip = data["sha"] + self.tip = sha if self.lose_response: raise TimeoutError("lost successful response") - return self.ref() class DailyBudgetTests(unittest.TestCase): diff --git a/tests/skill_eval/test_skill_eval_diagnostic.py b/tests/skill_eval/test_skill_eval_diagnostic.py index ef14b0279..d1de98608 100644 --- a/tests/skill_eval/test_skill_eval_diagnostic.py +++ b/tests/skill_eval/test_skill_eval_diagnostic.py @@ -10,7 +10,9 @@ from inferrsi.apps.artifacts import sha256, write_json from inferrsi.benchmark import skill_eval_diagnostic as diagnostic from tests.fixtures.skill_eval_compare_support import FixedOutputClient, configuration, git +from tests.fixtures.skill_eval_pr_support import setup from tools import skill_eval_compare as compare +from tools import skill_eval_pr as integration CASES = json.loads( (Path(__file__).parents[1] / 'fixtures/skill_eval_diagnostic_cases.json').read_text()) @@ -210,5 +212,56 @@ def test_retained_answer_reverified_not_trusted(self): compare.verify_retained_grader(plan, [trial], {task['id']: task}) +class PRDiagnosticTests(unittest.TestCase): + def prepare(self, root, mode='update', adapter=diagnostic.ADAPTER): + repo, path, identity = setup(root, mode, ids=('one',)) + mapping = compare.read_json(path) + mapping['skills'][0]['adapter'] = adapter + write_json(path, mapping) + write_json(root / 'cases.json', CASES[:1]) + output = root / 'planned' + plan = integration.prepare(repo, path, identity, output) + return plan, output, identity + + def test_explicit_diagnostic_mapping_preserves_exact_pair_and_gaps(self): + with tempfile.TemporaryDirectory() as directory: + plan, output, identity = self.prepare(Path(directory)) + self.assertEqual(plan['estimated_calls'], 2) + frozen = compare.load_plan(output / 'selected') + self.assertEqual(frozen['adapter'], diagnostic.ADAPTER) + self.assertEqual(frozen['mode'], 'update') + for role, revision in [('baseline', identity['base']), ('candidate', identity['head'])]: + self.assertEqual(frozen['arms'][role]['git_revision'], revision) + self.assertIsNotNone(frozen['arms'][role]['bundle']) + self.assertEqual([e for e in plan['coverage'] if e['coverage'] != 'covered'], + [{'path': 'exam.txt', 'status': 'M', 'coverage': 'uncovered'}]) + self.assertEqual(list((output / 'selected/results').iterdir()), []) + + def test_pr_report_rechecks_diagnostic_not_audit_schema(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + plan, output, _ = self.prepare(root) + client = FixedOutputClient(root) + write_json(client.answer, answer(0)) + item = plan['comparisons'][0] + compare.execute(output / 'selected', item['plan_sha256'], client=client) + result = integration.reports(output)[0] + self.assertEqual(result['pairs'][0]['outcome'], 'unchanged_correct') + + def test_unknown_adapter_cannot_fall_back_to_audit(self): + with tempfile.TemporaryDirectory() as directory: + plan, _, _ = self.prepare(Path(directory), adapter='untrusted-kind') + self.assertEqual(plan['estimated_calls'], 0) + self.assertIn('Unknown experiment adapter', plan['comparisons'][0]['unsupported']) + self.assertTrue(any(e['coverage'] == 'unsupported' for e in plan['coverage'])) + + def test_addition_cannot_claim_incremental_old_new_diagnosis(self): + with tempfile.TemporaryDirectory() as directory: + plan, _, _ = self.prepare(Path(directory), mode='addition') + self.assertEqual(plan['estimated_calls'], 0) + self.assertIn('paired old/new bundles', plan['comparisons'][0]['unsupported']) + self.assertTrue(any(e['coverage'] == 'unsupported' for e in plan['coverage'])) + + if __name__ == '__main__': unittest.main() diff --git a/tests/skill_eval/test_skill_eval_optional_dependencies.py b/tests/skill_eval/test_skill_eval_optional_dependencies.py index abc429bcf..660ddfd75 100644 --- a/tests/skill_eval/test_skill_eval_optional_dependencies.py +++ b/tests/skill_eval/test_skill_eval_optional_dependencies.py @@ -30,7 +30,6 @@ def test_comparison_reporting_without_yaml(self): assert all(item['input_tokens'] is None for item in summary.values()) assert callable(read_report) assert 'inferrsi.knowledge.skill_catalog' not in sys.modules - assert 'inferrsi.knowledge.skill_catalog' not in sys.modules """) def test_checkpoint_without_yaml(self): @@ -42,7 +41,6 @@ def test_checkpoint_without_yaml(self): assert result.action == 'repair_evidence' assert result.reasons == ('missing_evidence',) assert 'inferrsi.knowledge.skill_catalog' not in sys.modules - assert 'inferrsi.knowledge.skill_catalog' not in sys.modules """) def test_daily_controller_without_yaml(self): @@ -57,7 +55,6 @@ def test_daily_controller_without_yaml(self): else: raise AssertionError('Daily controller accepted missing budget configuration') assert 'inferrsi.knowledge.skill_catalog' not in sys.modules - assert 'inferrsi.knowledge.skill_catalog' not in sys.modules """) def test_selected_snapshot_still_requires_yaml_before_side_effects(self): diff --git a/tests/skill_eval/test_skill_eval_planned_guidance.py b/tests/skill_eval/test_skill_eval_planned_guidance.py index 2e9061e97..3f733858f 100644 --- a/tests/skill_eval/test_skill_eval_planned_guidance.py +++ b/tests/skill_eval/test_skill_eval_planned_guidance.py @@ -10,8 +10,7 @@ from inferrsi.apps.artifacts import write_json from tests.fixtures.skill_eval_compare_support import git -from tests.fixtures.skill_eval_pr_support import setup -from tests.skill_eval.test_skill_eval_pr_summary import visible +from tests.fixtures.skill_eval_pr_support import setup, visible from tools import skill_eval_pr as pr diff --git a/tests/skill_eval/test_skill_eval_planning_boundaries.py b/tests/skill_eval/test_skill_eval_planning_boundaries.py index c08325a60..01654b923 100644 --- a/tests/skill_eval/test_skill_eval_planning_boundaries.py +++ b/tests/skill_eval/test_skill_eval_planning_boundaries.py @@ -9,8 +9,7 @@ from inferrsi.apps.artifacts import write_json from tests.fixtures.skill_eval_compare_support import git -from tests.fixtures.skill_eval_pr_support import SimulatedGitHub, setup -from tests.skill_eval.test_skill_eval_pr import dispatch_event +from tests.fixtures.skill_eval_pr_support import SimulatedGitHub, dispatch_event, setup from tools import skill_eval_auto as auto from tools import skill_eval_pr as pr diff --git a/tests/skill_eval/test_skill_eval_pr.py b/tests/skill_eval/test_skill_eval_pr.py index a9a6b8c98..18a68b6f8 100644 --- a/tests/skill_eval/test_skill_eval_pr.py +++ b/tests/skill_eval/test_skill_eval_pr.py @@ -17,6 +17,7 @@ SimulatedGitHub, SimulatedWorkflowHistory, approval, + dispatch_event, envelope, setup, ) @@ -511,19 +512,6 @@ def test_download_redirect_drops_the_github_token(): assert not redirected.has_header("Authorization") -def dispatch_event(monkeypatch, root, output, inputs, mode, run_id=11): - write_json(root / "event.json", {"inputs": inputs}) - environment = {"GITHUB_EVENT_PATH": str(root / "event.json"), - "GITHUB_EVENT_NAME": "workflow_dispatch", - "GITHUB_REPOSITORY": "example/fixture", "GITHUB_RUN_ID": str(run_id), - "GITHUB_RUN_ATTEMPT": "1", "GITHUB_ACTOR": "fixture-operator", - "GITHUB_TOKEN": "offline-not-a-credential", - "GITHUB_OUTPUT": str(root / "github-output")} - for key, value in environment.items(): - monkeypatch.setenv(key, value) - monkeypatch.setattr(sys, "argv", ["skill_eval_pr", mode, "--output", str(output)]) - - @pytest.mark.parametrize("mode", ["addition", "update"]) @pytest.mark.parametrize("extra_inputs", [{}, {"source_run": "10", "budget": "not approval", "plan_sha256": "not approval"}]) diff --git a/tests/skill_eval/test_skill_eval_pr_diagnostic.py b/tests/skill_eval/test_skill_eval_pr_diagnostic.py deleted file mode 100644 index a118a658b..000000000 --- a/tests/skill_eval/test_skill_eval_pr_diagnostic.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Offline PR mapping plumbing; no provider or maintained mapping changes.""" -import tempfile -import unittest -from pathlib import Path - -from inferrsi.apps.artifacts import write_json -from inferrsi.benchmark import skill_eval_diagnostic as diagnostic -from tests.fixtures.skill_eval_compare_support import FixedOutputClient -from tests.fixtures.skill_eval_pr_support import setup -from tests.skill_eval.test_skill_eval_diagnostic import CASES, answer -from tools import skill_eval_compare as compare -from tools import skill_eval_pr as integration - - -class PRDiagnosticTests(unittest.TestCase): - def prepare(self, root, mode='update', adapter=diagnostic.ADAPTER): - repo, path, identity = setup(root, mode, ids=('one',)) - mapping = compare.read_json(path) - mapping['skills'][0]['adapter'] = adapter - write_json(path, mapping) - write_json(root / 'cases.json', CASES[:1]) - output = root / 'planned' - plan = integration.prepare(repo, path, identity, output) - return plan, output, identity - - def test_explicit_diagnostic_mapping_preserves_exact_pair_and_gaps(self): - with tempfile.TemporaryDirectory() as directory: - plan, output, identity = self.prepare(Path(directory)) - self.assertEqual(plan['estimated_calls'], 2) - frozen = compare.load_plan(output / 'selected') - self.assertEqual(frozen['adapter'], diagnostic.ADAPTER) - self.assertEqual(frozen['mode'], 'update') - for role, revision in [('baseline', identity['base']), ('candidate', identity['head'])]: - self.assertEqual(frozen['arms'][role]['git_revision'], revision) - self.assertIsNotNone(frozen['arms'][role]['bundle']) - self.assertEqual([e for e in plan['coverage'] if e['coverage'] != 'covered'], - [{'path': 'exam.txt', 'status': 'M', 'coverage': 'uncovered'}]) - self.assertEqual(list((output / 'selected/results').iterdir()), []) - - def test_pr_report_rechecks_diagnostic_not_audit_schema(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - plan, output, _ = self.prepare(root) - client = FixedOutputClient(root) - write_json(client.answer, answer(0)) - item = plan['comparisons'][0] - compare.execute(output / 'selected', item['plan_sha256'], client=client) - result = integration.reports(output)[0] - self.assertEqual(result['pairs'][0]['outcome'], 'unchanged_correct') - - def test_unknown_adapter_cannot_fall_back_to_audit(self): - with tempfile.TemporaryDirectory() as directory: - plan, _, _ = self.prepare(Path(directory), adapter='untrusted-kind') - self.assertEqual(plan['estimated_calls'], 0) - self.assertIn('Unknown experiment adapter', plan['comparisons'][0]['unsupported']) - self.assertTrue(any(e['coverage'] == 'unsupported' for e in plan['coverage'])) - - def test_addition_cannot_claim_incremental_old_new_diagnosis(self): - with tempfile.TemporaryDirectory() as directory: - plan, _, _ = self.prepare(Path(directory), mode='addition') - self.assertEqual(plan['estimated_calls'], 0) - self.assertIn('paired old/new bundles', plan['comparisons'][0]['unsupported']) - self.assertTrue(any(e['coverage'] == 'unsupported' for e in plan['coverage'])) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/skill_eval/test_skill_eval_pr_summary.py b/tests/skill_eval/test_skill_eval_pr_summary.py index eaf07e4ec..f879a353e 100644 --- a/tests/skill_eval/test_skill_eval_pr_summary.py +++ b/tests/skill_eval/test_skill_eval_pr_summary.py @@ -4,6 +4,7 @@ import pytest +from tests.fixtures.skill_eval_pr_support import visible from tools import skill_eval_pr as integration KEYS = ("fix", "regression", "unchanged_correct", "unchanged_incorrect", @@ -30,10 +31,6 @@ def render(plan, results=None, *, now=10, expires=100): plan, results or [], "https://example.invalid/evidence", expires, now) -def visible(text): - return re.sub(r"
.*?
", "", text, flags=re.S) - - def details(text): return re.findall(r"
(.*?)
", text, flags=re.S) diff --git a/tests/skill_eval/test_skill_eval_retention.py b/tests/skill_eval/test_skill_eval_retention.py index 40dd887d5..5d6563c5f 100644 --- a/tests/skill_eval/test_skill_eval_retention.py +++ b/tests/skill_eval/test_skill_eval_retention.py @@ -7,9 +7,8 @@ from inferrsi.apps.artifacts import write_json from tests.fixtures.skill_eval_compare_support import FixedOutputClient -from tests.fixtures.skill_eval_pr_support import SimulatedGitHub, approval, setup +from tests.fixtures.skill_eval_pr_support import SimulatedGitHub, approval, dispatch_event, setup from tests.skill_eval import test_skill_eval_auto as auto_tests -from tests.skill_eval.test_skill_eval_pr import dispatch_event from tools import skill_eval_auto as auto from tools import skill_eval_pr as pr from tools.skill_eval_budget import Binding, BudgetError, Entry diff --git a/tests/skill_eval/test_skill_evaluation.py b/tests/skill_eval/test_skill_evaluation.py index 66ce942ec..ac011bf6e 100644 --- a/tests/skill_eval/test_skill_evaluation.py +++ b/tests/skill_eval/test_skill_evaluation.py @@ -303,16 +303,9 @@ def test_harness_owned_writes_and_digests_match_apps_bytes(tmp_path): from inferrsi.harness import atomic_json, input_binding value = {"b": [1.5, None, True, 1e-07, 1e16], "a": "非 ASCII", "nested": {"z": 0.1 + 0.2}} - atomic_json.atomic_write_json(tmp_path / "harness.json", value) - artifacts.atomic_write_json(tmp_path / "infra.json", value) - written = (tmp_path / "harness.json").read_bytes() - assert written == (tmp_path / "infra.json").read_bytes() - assert input_binding.file_sha256(tmp_path / "harness.json") == ( - artifacts.sha256(tmp_path / "infra.json"), len(written)) - assert sorted(path.name for path in tmp_path.iterdir()) == ["harness.json", "infra.json"] - with pytest.raises(ValueError): - atomic_json.atomic_write_json(tmp_path / "nan.json", {"value": float("nan")}) - assert not (tmp_path / "nan.json").exists() + path = tmp_path / "harness.json" + atomic_json.atomic_write_json(path, value) + assert input_binding.file_sha256(path) == (artifacts.sha256(path), len(path.read_bytes())) def test_harness_artifact_primitives_match_apps_bytes_and_semantics(tmp_path): From c1cdb680e1bae58827165a1210c994825433248d Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Wed, 25 Nov 2026 11:24:10 +0800 Subject: [PATCH 2/3] Exercise helper CLI byte limits with valid JSON Feed each helper its valid example on stdin and in a regular file at its byte limit and one byte beyond it. Preserve the suite-specific cases and existing pytest selectors. Agent-assisted-by: Codex / unknown [effort=unknown] (test implementation) Agent-assisted-by: Codex / unknown [effort=unknown] (coverage audit and validation) Signed-off-by: dongxinwen --- tests/knowledge/_repo_to_skill_support.py | 16 ++++++++++++++++ tests/knowledge/test_mistral_rs_repo_to_skill.py | 10 +++++++--- .../knowledge/test_mlx_swift_lm_repo_to_skill.py | 7 ++++++- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/tests/knowledge/_repo_to_skill_support.py b/tests/knowledge/_repo_to_skill_support.py index c58c6f36f..4fce93b7f 100644 --- a/tests/knowledge/_repo_to_skill_support.py +++ b/tests/knowledge/_repo_to_skill_support.py @@ -16,3 +16,19 @@ def run_helper_cli(script, *args, data=None, cwd=None): [sys.executable, str(script), *args], input=data, capture_output=True, timeout=10, cwd=cwd, env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}, ) + + +def assert_cli_size_limit(call_cli, area, valid_json, limit, tmp_path): + # Trailing JSON whitespace changes the byte count without changing the document. + at_limit = valid_json.ljust(limit, b" ") + assert len(at_limit) == limit + input_file = tmp_path / "size-boundary.json" + for data, expected_code in ((at_limit, 0), (at_limit + b" ", 2)): + input_file.write_bytes(data) + for result in ( + call_cli(area, "-", data=data, cwd=tmp_path), + call_cli(area, str(input_file), cwd=tmp_path), + ): + assert result.returncode == expected_code, (result.args, len(data), result.stderr) + if expected_code == 2: + assert not result.stdout and b"Traceback" not in result.stderr diff --git a/tests/knowledge/test_mistral_rs_repo_to_skill.py b/tests/knowledge/test_mistral_rs_repo_to_skill.py index 8b56020d6..365ccb886 100644 --- a/tests/knowledge/test_mistral_rs_repo_to_skill.py +++ b/tests/knowledge/test_mistral_rs_repo_to_skill.py @@ -15,7 +15,11 @@ import yaml from inferrsi.knowledge.skill_catalog import skill_metadata -from tests.knowledge._repo_to_skill_support import MALFORMED_HELPER_INPUTS, run_helper_cli +from tests.knowledge._repo_to_skill_support import ( + MALFORMED_HELPER_INPUTS, + assert_cli_size_limit, + run_helper_cli, +) PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/mistral-rs" @@ -377,8 +381,8 @@ def test_all_helper_cli_malformed_input_fails_without_echo_or_traceback(tmp_path ("decode-contract", 65536), ("prefill-contract", 1 << 20), ("qualification", 16384), ]) def test_all_helper_cli_size_limits_are_enforced(tmp_path, area, limit): - result = call_cli(area, "-", data=b" " * (limit + 1), cwd=tmp_path) - assert result.returncode == 2 and not result.stdout and b"Traceback" not in result.stderr + raw = json.dumps(helper(area)["example"]()).encode() + assert_cli_size_limit(call_cli, area, raw, limit, tmp_path) def test_decode_cli_exit_one_is_declared_conflict_not_native_failure(tmp_path): diff --git a/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py b/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py index 1a4ba2e37..6af980cd1 100644 --- a/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py +++ b/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py @@ -16,7 +16,11 @@ import yaml from inferrsi.knowledge.skill_catalog import skill_metadata -from tests.knowledge._repo_to_skill_support import MALFORMED_HELPER_INPUTS, run_helper_cli +from tests.knowledge._repo_to_skill_support import ( + MALFORMED_HELPER_INPUTS, + assert_cli_size_limit, + run_helper_cli, +) PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/mlx-swift-lm" @@ -363,6 +367,7 @@ def test_mlx_swift_helpers_cli_help_examples_stdin_and_regular_file_are_offline( fixture.write_bytes(raw) result = call_cli(area, str(fixture), cwd=tmp_path) assert result.returncode == 0 and json.loads(result.stdout) == expected + assert_cli_size_limit(call_cli, area, raw, 65536, tmp_path) @pytest.mark.parametrize("area", SCRIPTS) From fbc87b4658888b1832a51947a10160048c214dc6 Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Wed, 25 Nov 2026 12:09:14 +0800 Subject: [PATCH 3/3] Isolate the Qwen protocol identity test from benchmark updates Freeze the clean task copy for this regression before corrupting the protocol. Assert the exact failure and that the loader is never invoked. Keep the published run specification and its historical input hashes intact. Agent-assisted-by: Codex / unknown [effort=unknown] (test fixture and verification) Signed-off-by: dongxinwen --- tests/campaigns/test_qwen_gvo_diagnostic.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/tests/campaigns/test_qwen_gvo_diagnostic.py b/tests/campaigns/test_qwen_gvo_diagnostic.py index d7765305d..3665e3884 100644 --- a/tests/campaigns/test_qwen_gvo_diagnostic.py +++ b/tests/campaigns/test_qwen_gvo_diagnostic.py @@ -1,5 +1,6 @@ """Control-level finals and protocol identity for the Qwen pilot, without device access.""" +import hashlib import importlib.util import json import shutil @@ -58,9 +59,25 @@ def test_protocol_identity_checked_before_loading(tmp_path, monkeypatch): checker = module("validator/check.py") task = tmp_path / "task" shutil.copytree(task_resources("qwen21-denoise-npu"), task) - (task / "optimization.py").write_text("this is deliberately invalid Python source.") + # Freeze the clean test copy before corrupting the protocol. The packaged + # benchmark can advance independently of the published experiment. + plan = tmp_path / "plan" + plan.mkdir() + shutil.copyfile(checker.PLAN / "plan.json", plan / "plan.json") + pinned_files = json.loads((checker.PLAN / "runspec.json").read_bytes())["packaged_task_sha256"] + hashes = {name: hashlib.sha256((task / name).read_bytes()).hexdigest() for name in pinned_files} + (plan / "runspec.json").write_text( + json.dumps({"packaged_task_sha256": hashes}), encoding="utf-8" + ) + monkeypatch.setattr(checker, "PLAN", plan) monkeypatch.setattr(checker, "task_resources", lambda _: task) - with pytest.raises(ValueError, match="optimization.py"): + + def unexpected_load(*args, **kwargs): + pytest.fail("the checker loaded the corrupted protocol") + + monkeypatch.setattr(checker.task_protocol, "run", unexpected_load) + (task / "optimization.py").write_text("this is deliberately invalid Python source.") + with pytest.raises(ValueError, match=r"^optimization\.py$"): checker.main(tmp_path / "trial", tmp_path / "failed")