diff --git a/.github/workflows/ci-draft.yml b/.github/workflows/ci-draft.yml index 8ef3408f9..62b6383a9 100644 --- a/.github/workflows/ci-draft.yml +++ b/.github/workflows/ci-draft.yml @@ -22,4 +22,4 @@ jobs: - name: Ruff run: ruff check src tests tools - name: Smoke tests - run: pytest tests/test_smoke.py tests/test_claim.py + run: pytest tests/repository/test_smoke.py tests/contracts/test_claim.py diff --git a/.github/workflows/ci-merge.yml b/.github/workflows/ci-merge.yml index 833eef3a4..9391710d1 100644 --- a/.github/workflows/ci-merge.yml +++ b/.github/workflows/ci-merge.yml @@ -29,4 +29,4 @@ jobs: - name: Install CPU smoke dependencies run: python -m pip install . pytest - name: CPU smoke on every main push - run: python -m pytest tests/test_smoke.py tests/test_claim.py + run: python -m pytest tests/repository/test_smoke.py tests/contracts/test_claim.py diff --git a/.github/workflows/ci-nightly.yml b/.github/workflows/ci-nightly.yml index e0c8603d8..1003ef50e 100644 --- a/.github/workflows/ci-nightly.yml +++ b/.github/workflows/ci-nightly.yml @@ -22,7 +22,7 @@ jobs: python-version: "3.11" - run: python -m pip install pytest - name: Frozen Git bytes across checkout policies - run: python -m pytest tests/test_frozen_bytes.py + run: python -m pytest tests/repository/test_frozen_bytes.py safety-net: runs-on: ubuntu-latest diff --git a/.github/workflows/ci-ready.yml b/.github/workflows/ci-ready.yml index da7f20b40..886e4bc31 100644 --- a/.github/workflows/ci-ready.yml +++ b/.github/workflows/ci-ready.yml @@ -62,11 +62,11 @@ jobs: run: ruff check src tests tools - name: Architecture anchor drift (advisory) continue-on-error: true - run: python -m pytest -q tests/test_architecture_anchors.py::test_architecture_anchors_resolve_to_existing_sources_and_checks + run: python -m pytest -q tests/repository/test_architecture_anchors.py::test_architecture_anchors_resolve_to_existing_sources_and_checks - name: Tests (smoke + unit) run: >- pytest -rs --deselect - tests/test_architecture_anchors.py::test_architecture_anchors_resolve_to_existing_sources_and_checks + tests/repository/test_architecture_anchors.py::test_architecture_anchors_resolve_to_existing_sources_and_checks dashboard-browser: if: ${{ github.event_name == 'pull_request' && !github.event.pull_request.draft }} @@ -88,11 +88,11 @@ jobs: - name: Test dashboards and offline delivery reports in Chromium run: | python -m pytest -vv -o addopts='' \ - tests/test_profile_story_checks.py::test_profile_and_trace_shortcuts_open_recorded_evidence \ - tests/test_knowledge_navigation_browser.py \ - tests/test_round_decisions_browser.py \ - tests/test_dashboard_experiments_browser.py \ - tests/test_result_delivery.py::test_offline_html_remains_readable_without_scripts_or_network \ + tests/apps/test_profile_story_checks.py::test_profile_and_trace_shortcuts_open_recorded_evidence \ + tests/apps/test_knowledge_navigation_browser.py \ + tests/apps/test_round_decisions_browser.py \ + tests/apps/test_dashboard_experiments_browser.py \ + tests/apps/test_result_delivery.py::test_offline_html_remains_readable_without_scripts_or_network \ --junitxml="$RUNNER_TEMP/dashboard-browser-results.xml" - name: Retain browser test results if: always() @@ -130,7 +130,7 @@ jobs: # GitHub-hosted Windows and macOS CPU evidence, separate from the Ubuntu jobs above: # a pass on Linux is not a pass on these hosts. It runs the eight plugin and DSH nodes # that an earlier Windows run recorded as failing (63 passed, 8 failed), on Windows the - # Harness artifact-primitive and writer nodes, then an installed-wheel check. A pass + # Harness artifact, writer and device lease nodes, then an installed-wheel check. A pass # here does not rewrite that record. No GPU, remote service or credential is used; the # DSH node talks to the fake SSH server that its own check starts. One host at a time, # one pytest process per step, no full suite. @@ -169,14 +169,14 @@ jobs: import xml.etree.ElementTree as ET nodes = [ - "tests/test_codex_plugin.py::test_comparison_preview_execution_status_and_report[codex-fail-1-FAIL]", - "tests/test_codex_plugin.py::test_isolated_runtime_can_export_dashboard[workswarm]", - "tests/test_codex_plugin.py::test_comparison_preview_execution_status_and_report[workswarm-pass-0-PASS]", - "tests/test_codex_plugin.py::test_comparison_preview_execution_status_and_report[workswarm-fail-1-FAIL]", - "tests/test_codex_plugin.py::test_comparison_preview_execution_status_and_report[workswarm-missing-2-INCONCLUSIVE]", - "tests/test_codex_plugin.py::test_release_archive_is_installable_and_all_versions_match[codex]", - "tests/test_codex_plugin.py::test_release_archive_is_installable_and_all_versions_match[workswarm]", - "tests/test_dsh_plugin.py::test_remote_ssh_connection_and_scoped_operations", + "tests/apps/test_codex_plugin.py::test_comparison_preview_execution_status_and_report[codex-fail-1-FAIL]", + "tests/apps/test_codex_plugin.py::test_isolated_runtime_can_export_dashboard[workswarm]", + "tests/apps/test_codex_plugin.py::test_comparison_preview_execution_status_and_report[workswarm-pass-0-PASS]", + "tests/apps/test_codex_plugin.py::test_comparison_preview_execution_status_and_report[workswarm-fail-1-FAIL]", + "tests/apps/test_codex_plugin.py::test_comparison_preview_execution_status_and_report[workswarm-missing-2-INCONCLUSIVE]", + "tests/apps/test_codex_plugin.py::test_release_archive_is_installable_and_all_versions_match[codex]", + "tests/apps/test_codex_plugin.py::test_release_archive_is_installable_and_all_versions_match[workswarm]", + "tests/apps/test_dsh_plugin.py::test_remote_ssh_connection_and_scoped_operations", ] # The DSH node skips without Node.js, and every node needs Git or Python. for tool in ("node", "git"): @@ -199,7 +199,7 @@ jobs: print(counts, flush=True) if counts != {"tests": len(nodes), "errors": 0, "failures": 0, "skipped": 0}: raise SystemExit("every selected host node must run and pass") - - name: Test the Harness artifact-primitive and writer nodes on Windows + - name: Test the Harness artifact, writer and device lease nodes on Windows # #412 R2: Harness owns copies of the digest, hash, file lock and atomic writer. # #498 slices 3b and 5 gave Apps and Benchmark their own copies and removed Infra, # so these nodes now compare the Harness copy with the Apps copy. On Windows the @@ -218,14 +218,15 @@ jobs: import xml.etree.ElementTree as ET nodes = [ - "tests/test_skill_evaluation.py::test_harness_artifact_primitives_match_apps_bytes_and_semantics", - "tests/test_skill_evaluation.py::test_harness_owned_writes_and_digests_match_apps_bytes", - "tests/test_legacy_run_split.py::test_harness_writer_bytes_equal_the_apps_writer", - "tests/test_legacy_run_split.py::test_harness_writer_rejects_nan_and_leaves_no_file", - "tests/test_legacy_run_split.py::test_sampling_sha256_matches_the_apps_hasher", - "tests/test_optimization_session.py::test_runtime_identity_covers_migrated_process_domain_and_not_removed_executor", - "tests/test_session_lock_across_processes.py", - "tests/test_agent_sessions.py", + "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/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", + "tests/harness/test_parallel_round.py::TestPortableParallelRound", + "tests/apps/test_agent_sessions.py", ] results = os.environ["RESULTS"] command = [sys.executable, "-m", "pytest", "-vv", "-rs", "-o", "addopts=", diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 67bff4877..a60494022 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -31,22 +31,22 @@ "src/inferrsi/apps/views/attempt.py", "src/inferrsi/apps/workflows/benchmark_compare.py", "tests/check_installed.py", - "tests/test_apps_assess.py", - "tests/test_apps_evaluate_cli.py", - "tests/test_apps_evidence_capture.py", - "tests/test_apps_module_migrations.py", - "tests/test_apps_output.py", - "tests/test_apps_port_validation.py", - "tests/test_apps_prepare.py", - "tests/test_apps_production_cli.py", - "tests/test_apps_publication.py", - "tests/test_apps_replay.py", - "tests/test_benchmark_assessment.py", - "tests/test_benchmark_cpu_smoke.py", - "tests/test_benchmark_preparation.py", - "tests/test_harness_entry_verification.py", - "tests/test_harness_generation_lineage.py", - "tests/test_result_delivery.py" + "tests/apps/test_apps_assess.py", + "tests/apps/test_apps_evaluate_cli.py", + "tests/apps/test_apps_evidence_capture.py", + "tests/apps/test_apps_module_migrations.py", + "tests/apps/test_apps_output.py", + "tests/apps/test_apps_port_validation.py", + "tests/apps/test_apps_prepare.py", + "tests/apps/test_apps_production_cli.py", + "tests/apps/test_apps_publication.py", + "tests/apps/test_apps_replay.py", + "tests/benchmark/test_benchmark_assessment.py", + "tests/benchmark/test_benchmark_cpu_smoke.py", + "tests/benchmark/test_benchmark_preparation.py", + "tests/harness/test_harness_entry_verification.py", + "tests/harness/test_harness_generation_lineage.py", + "tests/apps/test_result_delivery.py" ] }, { @@ -68,15 +68,15 @@ "src/inferrsi/apps/handoff/production_capture.py", "src/inferrsi/apps/views/attempt.py", "tests/check_installed.py", - "tests/test_apps_artifact_reader.py", - "tests/test_apps_assess.py", - "tests/test_apps_evidence_capture.py", - "tests/test_apps_generation_plan.py", - "tests/test_apps_module_migrations.py", - "tests/test_benchmark_assessment.py", - "tests/test_benchmark_cpu_smoke.py", - "tests/test_harness_entry_verification.py", - "tests/test_harness_generation_lineage.py" + "tests/apps/test_apps_artifact_reader.py", + "tests/apps/test_apps_assess.py", + "tests/apps/test_apps_evidence_capture.py", + "tests/apps/test_apps_generation_plan.py", + "tests/apps/test_apps_module_migrations.py", + "tests/benchmark/test_benchmark_assessment.py", + "tests/benchmark/test_benchmark_cpu_smoke.py", + "tests/harness/test_harness_entry_verification.py", + "tests/harness/test_harness_generation_lineage.py" ] }, { @@ -106,8 +106,8 @@ "src/inferrsi/apps/storage/artifact_reader.py", "src/inferrsi/apps/views/attempt.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_result_delivery.py" + "tests/apps/test_apps_module_migrations.py", + "tests/apps/test_result_delivery.py" ] }, { @@ -126,10 +126,10 @@ "src/inferrsi/contracts/evidence.py", "tests/_gate_policy_support.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_evidence_paths.py", - "tests/test_first_wave_isolation_policy.py", - "tests/test_repository_packs_facade.py" + "tests/apps/test_apps_module_migrations.py", + "tests/contracts/test_evidence_paths.py", + "tests/repository/test_first_wave_isolation_policy.py", + "tests/knowledge/test_repository_packs_facade.py" ] }, { @@ -152,15 +152,15 @@ "src/inferrsi/apps/handoff/candidate_provider.py", "src/inferrsi/apps/views/attempt.py", "tests/check_installed.py", - "tests/test_apps_evidence.py", - "tests/test_apps_execution_binding.py", - "tests/test_apps_generation_plan.py", - "tests/test_apps_module_migrations.py", - "tests/test_apps_production_cli.py", - "tests/test_benchmark_assessment.py", - "tests/test_benchmark_preparation.py", - "tests/test_harness_entry_verification.py", - "tests/test_harness_prepared_binding.py" + "tests/apps/test_apps_evidence.py", + "tests/apps/test_apps_execution_binding.py", + "tests/apps/test_apps_generation_plan.py", + "tests/apps/test_apps_module_migrations.py", + "tests/apps/test_apps_production_cli.py", + "tests/benchmark/test_benchmark_assessment.py", + "tests/benchmark/test_benchmark_preparation.py", + "tests/harness/test_harness_entry_verification.py", + "tests/harness/test_harness_prepared_binding.py" ] }, { @@ -177,9 +177,9 @@ "docs/operations.md", "src/inferrsi/apps/context_provider.py", "tests/check_installed.py", - "tests/test_apps_context_provider.py", - "tests/test_apps_module_migrations.py", - "tests/test_harness_generation_seal.py" + "tests/apps/test_apps_context_provider.py", + "tests/apps/test_apps_module_migrations.py", + "tests/harness/test_harness_generation_seal.py" ] }, { @@ -196,7 +196,7 @@ "src/inferrsi/apps/api.py", "src/inferrsi/apps/candidate_provider.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py" + "tests/apps/test_apps_module_migrations.py" ] }, { @@ -221,16 +221,16 @@ "tests/check_installed.py", "tests/fixtures/dashboard_profile_review.py", "tests/fixtures/knowledge_retrieval.py", - "tests/test_apps_module_migrations.py", - "tests/test_campaign_record_injection.py", - "tests/test_campaign_task_selection.py", - "tests/test_knowledge_navigation_browser.py", - "tests/test_optimization_session.py", - "tests/test_optimization_story.py", - "tests/test_round_citations.py", - "tests/test_search_archive.py", - "tests/test_search_attribution.py", - "tests/test_search_capture_delivery.py" + "tests/apps/test_apps_module_migrations.py", + "tests/apps/test_campaign_record_injection.py", + "tests/apps/test_campaign_task_selection.py", + "tests/apps/test_knowledge_navigation_browser.py", + "tests/apps/test_optimization_session.py", + "tests/apps/test_optimization_story.py", + "tests/apps/test_round_citations.py", + "tests/apps/test_search_archive.py", + "tests/apps/test_search_attribution.py", + "tests/apps/test_search_capture_delivery.py" ] }, { @@ -245,12 +245,12 @@ "src/inferrsi/apps/cli/__init__.py", "tests/_gate_policy_support.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_benchmark_operations.py", - "tests/test_optimization_session.py", - "tests/test_package_root_inventory.py", - "tests/test_project_optimization.py", - "tests/test_target_module_import_gate.py" + "tests/apps/test_apps_module_migrations.py", + "tests/benchmark/test_benchmark_operations.py", + "tests/apps/test_optimization_session.py", + "tests/repository/test_package_root_inventory.py", + "tests/apps/test_project_optimization.py", + "tests/repository/test_target_module_import_gate.py" ] }, { @@ -267,8 +267,8 @@ "docs/harness-improvement.md", "docs/module-layout.md", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_harness_improvement.py", + "tests/apps/test_apps_module_migrations.py", + "tests/harness/test_harness_improvement.py", "tools/skill_eval_improve.py" ] }, @@ -285,12 +285,12 @@ "docs/module-layout.md", "docs/skill-evaluation.md", "tests/check_installed.py", - "tests/test_anthropic_agent.py", - "tests/test_apps_module_migrations.py", - "tests/test_skill_eval_compare.py", - "tests/test_skill_eval_generation.py", - "tests/test_skill_eval_pipeline.py", - "tests/test_skill_evaluation.py", + "tests/apps/test_anthropic_agent.py", + "tests/apps/test_apps_module_migrations.py", + "tests/skill_eval/test_skill_eval_compare.py", + "tests/skill_eval/test_skill_eval_generation.py", + "tests/skill_eval/test_skill_eval_pipeline.py", + "tests/skill_eval/test_skill_evaluation.py", "tools/skill_eval_compare.py", "tools/skill_eval_pilot.py" ] @@ -308,12 +308,11 @@ "docs/module-layout.md", "src/inferrsi/apps/workflows/skill_evaluation.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_skill_eval_compare.py", - "tests/test_skill_eval_engineering.py", - "tests/test_skill_eval_generation.py", - "tests/test_skill_eval_local.py", - "tests/test_skill_eval_local_cli.py", + "tests/apps/test_apps_module_migrations.py", + "tests/skill_eval/test_skill_eval_compare.py", + "tests/skill_eval/test_skill_eval_engineering.py", + "tests/skill_eval/test_skill_eval_generation.py", + "tests/skill_eval/test_skill_eval_local.py", "tools/skill_eval_cloud_replay.py", "tools/skill_eval_compare.py", "tools/skill_eval_local.py", @@ -341,8 +340,8 @@ "docs/module-layout.md", "src/inferrsi/apps/cli/__init__.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_benchmark_compare.py" + "tests/apps/test_apps_module_migrations.py", + "tests/benchmark/test_benchmark_compare.py" ] }, { @@ -356,7 +355,7 @@ "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/integrations/cannbot/round_knowledge.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py" + "tests/apps/test_apps_module_migrations.py" ], "package": true, "module_exports": { @@ -386,10 +385,10 @@ "src/inferrsi/apps/integrations/cannbot/__init__.py", "src/inferrsi/apps/integrations/cannbot/round_knowledge.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_cannbot_boundaries.py", - "tests/test_optimization_session.py", - "tests/test_project_optimization.py" + "tests/apps/test_apps_module_migrations.py", + "tests/apps/test_cannbot_boundaries.py", + "tests/apps/test_optimization_session.py", + "tests/apps/test_project_optimization.py" ] }, { @@ -406,9 +405,9 @@ "src/inferrsi/apps/integrations/cannbot/project.py", "src/inferrsi/apps/integrations/cannbot/round_knowledge.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_cannbot_boundaries.py", - "tests/test_project_optimization.py" + "tests/apps/test_apps_module_migrations.py", + "tests/apps/test_cannbot_boundaries.py", + "tests/apps/test_project_optimization.py" ] }, { @@ -420,7 +419,7 @@ "docs/external-channels.md", "docs/module-layout.md", "tests/check_installed.py", - "tests/test_apps_module_migrations.py" + "tests/apps/test_apps_module_migrations.py" ], "package": true }, @@ -437,9 +436,9 @@ "src/inferrsi/apps/integrations/mindie/mcp.py", "src/inferrsi/apps/integrations/mindie/project.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_mindie_context.py", - "tests/test_mindie_runtime.py" + "tests/apps/test_apps_module_migrations.py", + "tests/apps/test_mindie_context.py", + "tests/apps/test_mindie_runtime.py" ] }, { @@ -459,9 +458,9 @@ "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/integrations/mindie/mcp.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_mindie_project.py", - "tests/test_mindie_runtime.py" + "tests/apps/test_apps_module_migrations.py", + "tests/apps/test_mindie_project.py", + "tests/apps/test_mindie_runtime.py" ] }, { @@ -474,8 +473,8 @@ "docs/module-layout.md", "src/inferrsi/apps/integrations/mindie/project.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py", - "tests/test_mindie_project.py" + "tests/apps/test_apps_module_migrations.py", + "tests/apps/test_mindie_project.py" ] }, { @@ -487,7 +486,7 @@ "consumers": [ "docs/module-layout.md", "tests/check_installed.py", - "tests/test_apps_module_migrations.py" + "tests/apps/test_apps_module_migrations.py" ] } ] diff --git a/docs/architecture.md b/docs/architecture.md index 9f52a1484..86b25752d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -64,8 +64,8 @@ cross-core imports and admits the exact `python -m inferrsi` CLI delegation, while [shared layers](#module-responsibilities-and-dependencies) stay independent of campaigns in `examples/`. -**Checked by** `tests/test_target_module_import_gate.py` and -`tests/test_module_boundaries.py::test_shared_layers_do_not_import_campaigns_or_reverse_dependencies`. +**Checked by** `tests/repository/test_target_module_import_gate.py` and +`tests/repository/test_module_boundaries.py::test_shared_layers_do_not_import_campaigns_or_reverse_dependencies`. ### A2 — Versioned envelopes and technical leaves @@ -74,7 +74,7 @@ core-owned business types, with shared technical leaves limited to the exact [D001 list](contracts/current-design.md#d001--one-distribution-three-cores-plus-apps-document-contracts-rather-than-shared-business-dtos) and its [neutral-leaf importer rule](module-layout.md#permanent-neutral-leaf-importer-rule-proposed). -**Checked by** `tests/test_first_wave_isolation_policy.py`. +**Checked by** `tests/repository/test_first_wave_isolation_policy.py`. ### A3 — Retired paths @@ -82,8 +82,8 @@ and its [neutral-leaf importer rule](module-layout.md#permanent-neutral-leaf-imp without forwarders or aliases, and the [tracked package root](contracts/current-design.md#d018--first-wave-gate-policy-detail) holds only `__init__.py` and `__main__.py`. -**Checked by** `tests/test_package_root_inventory.py` and -`tests/test_target_module_import_gate.py`. +**Checked by** `tests/repository/test_package_root_inventory.py` and +`tests/repository/test_target_module_import_gate.py`. ### A4 — Benchmark judgment @@ -122,7 +122,7 @@ and [old `run` exit codes](module-layout.md#old-run-exit-codes), while original bytes and a new campaign with a changed implementation requires fresh frozen references. -**Checked by** `tests/test_legacy_run_v0_frozen.py` for the legacy `run` exit codes +**Checked by** `tests/apps/test_legacy_run_v0_frozen.py` for the legacy `run` exit codes and `evaluation.json` bytes. Review covers the remaining clauses. ### A8 — Shared scenario and adapter lifecycle @@ -131,7 +131,7 @@ and `evaluation.json` bytes. Review covers the remaining clauses. process cleanup and performance adjudication. **Checked by** -`tests/test_module_boundaries.py::test_new_scenario_target_and_backend_share_abba_and_verdict`. +`tests/repository/test_module_boundaries.py::test_new_scenario_target_and_backend_share_abba_and_verdict`. ### A9 — Governing approval for contract changes diff --git a/docs/contracts/fixtures/README.md b/docs/contracts/fixtures/README.md index 60c3abc9d..aa695f75a 100644 --- a/docs/contracts/fixtures/README.md +++ b/docs/contracts/fixtures/README.md @@ -9,7 +9,7 @@ This directory holds two different things and they must not be conflated: | `fixtures/t108-v4/` | **Historic BASELINE / HISTORICAL golden byte vectors**, copied unchanged from the reviewed t108-v4 handoff | Validated against the **baseline** 106-definition library. **Not** D023-current examples; several of them no longer validate as-is. | | `fixtures/execution-spec-d023.json` | Current D023 `ExecutionSpec` example | Written for the D023 library (`CommandStep.expected_code_sha256` required). | | `fixtures/d023-conformance-cases.json` | Document vectors for T36–T40 plus V32/SCHEMA spec-time cases | Current; fixed example digests, not computed values. | -| `fixtures/pattern-boundary-cases.json` | Current paired vectors for every schema `pattern`: a valid value, then the same value with LF (trailing, leading, embedded), CRLF or CR inside | Validated against the current schema's named definitions by `tests/test_contract_schema_patterns.py`. | +| `fixtures/pattern-boundary-cases.json` | Current paired vectors for every schema `pattern`: a valid value, then the same value with LF (trailing, leading, embedded), CRLF or CR inside | Validated against the current schema's named definitions by `tests/contracts/test_contract_schema_patterns.py`. | ## Why the baseline bytes are preserved, not rewritten diff --git a/docs/contracts/function-owners.md b/docs/contracts/function-owners.md index dbf010194..5d81756a9 100644 --- a/docs/contracts/function-owners.md +++ b/docs/contracts/function-owners.md @@ -22,7 +22,7 @@ Status: **Proposed baseline**; individually **adopted** entries are identified b | `apps/views/dashboard_workflow` `command_state`/`run_workflow`/`validation_progress` (added with the OBS dissolve; **adopted owner: Apps views; RSI-master architecture decision 2026-11-14 Asia/Shanghai, recorded in the [D008 wave-2 ownership decision](d008-wave2-ownership-decision.md#dashboard-workflow); independent PR review remains separate**) | Apps views: read-only presentation projection of workflow and command state | The module imports only the standard library and reads records the caller already loaded; it has no H, K or Benchmark edge. A group `state` such as `completed` is a display state for the run workflow, not a verdict, and must not be read as the legacy `Verdict`. `validation_progress` only validates counters from a snapshot `dashboard_data` has already read; it opens no file. | | `harness/records/profile_timeline` `attach_profile`, `_compile` (builds the bounded dashboard overview stored with the record), fixed-byte verification, and digest reads (`read_profiles`/`profile_event_table`) (added with the OBS dissolve; **adopted owner: H records; RSI-master architecture decision 2026-11-14 Asia/Shanghai, recorded in the [D008 wave-2 ownership decision](d008-wave2-ownership-decision.md#profile-records-and-overview); independent PR review remains separate**) | H records: attach a reviewed profile, compile the stored overview from those bytes, and verify stored bytes | Record, overview-compile and byte-integrity paths stay in H because the overview is record content: it is computed once at attach from a bounded trace and published content-addressed, so the stored bytes cannot depend on who renders them. Its top-lane, longest-event and top-kernel selection reduces one trace for a bounded record; it ranks no candidate, run or claim and produces no verdict. UI route decoration, including `events_url`, belongs to Apps views, not H. Issue #413's broad timeline-to-Apps placement is refined here: persisted factual records and bounded overview encoding stay in H; UI projections and route decoration belong to Apps. The route decoration is removed from H in this PR, preserving stored bytes, digest verification and the external view response. | | `apps/views/profile_searches` `pre_profile_searches` (added with the OBS dissolve; **adopted owner: Apps views; RSI-master architecture decision 2026-11-14 Asia/Shanghai, recorded in the [D008 wave-2 ownership decision](d008-wave2-ownership-decision.md#pre-profile-searches); independent PR review remains separate**) | Apps views: Dashboard-consumed presentation list relating a profile capture to named searches completed before it | It joins an H record with ledger read models, which only Apps may assemble. Its `verified`/`not_before`/`unknown_time` values are display annotations over an existing search state; they are not evidence for a claim, and using them that way needs a new owner decision. | -| `benchmark/sampling` `collect_samples` (moved out of `harness/scenarios/media` by the old-run split; **ownership disposition: B sampling; RSI-master [adopted decision, 2026-11-14 Asia/Shanghai](d008-wave2-ownership-decision.md#benchmark-sampling); independent PR review remains separate**) | B sampling: seed ordering, timing records and artifact hashes | Request transport stays with the caller's injected `request(item, path)` callback; Benchmark hashes artifacts with its own `_sha256`, pinned to `apps.artifacts.sha256` by `tests/test_legacy_run_split.py::test_sampling_sha256_matches_the_apps_hasher` (the Infra hasher and its test name were retired by #498), and imports no H or Apps module. The per-group progress line on stdout is the old `run` protocol output kept for D022 and is a protocol constraint, not a presentation owner. | +| `benchmark/sampling` `collect_samples` (moved out of `harness/scenarios/media` by the old-run split; **ownership disposition: B sampling; RSI-master [adopted decision, 2026-11-14 Asia/Shanghai](d008-wave2-ownership-decision.md#benchmark-sampling); independent PR review remains separate**) | B sampling: seed ordering, timing records and artifact hashes | Request transport stays with the caller's injected `request(item, path)` callback; Benchmark hashes artifacts with its own `_sha256`, pinned to `apps.artifacts.sha256` by `tests/apps/test_legacy_run_split.py::test_sampling_sha256_matches_the_apps_hasher` (the Infra hasher and its test name were retired by #498), and imports no H or Apps module. The per-group progress line on stdout is the old `run` protocol output kept for D022 and is a protocol constraint, not a presentation owner. | | `harness/runner` `snapshot` port `(repo, exclude) -> dict` (separated from the runner by the old-run split; **ownership disposition: H port contract, Apps legacy binding, `apps/host/targets` implementation (moved from `infra/targets` by #498); RSI-master [adopted decision, 2026-11-14 Asia/Shanghai](d008-wave2-ownership-decision.md#snapshot-port); independent PR review remains separate**) | H owns the port and its contract; the Apps legacy composition owns the binding; `apps/host/targets` owns the Git identity implementation | H keeps the port required and keyword-only with no default and holds no copy of the implementation. `apps/legacy/run.py` binds `snapshot=repository_identity` for the old run; the root `execution.py` forwarder was deleted by #412 R1, and the CLI imports `apps/legacy/` itself. A change of the binding owner needs its own review. Out-of-tree callers that used the removed H defaults are not covered by this row. | D008 rows are architecture decisions under the delegation recorded at the top of this file. An independent reviewer verifies the cited code, tests and dependency direction and may block on a missing adoption record; a reviewer does not choose the owner, and a PR approval is not the D008 adoption record. The architecture owner records adoption in the governed contract or decision record; the rows cite that decision record, independently of PR approval. diff --git a/docs/contracts/gate-policy-runstore-and-first-prs.md b/docs/contracts/gate-policy-runstore-and-first-prs.md index 30b304420..53f8e7b65 100644 --- a/docs/contracts/gate-policy-runstore-and-first-prs.md +++ b/docs/contracts/gate-policy-runstore-and-first-prs.md @@ -47,7 +47,7 @@ The symbol inventory is AST-derived and does not claim to have found every third Synthetic negative controls run item by item per D020; an empty graph pass is not allowed on the grounds that target H files do not exist yet. Repository policy review is a process prerequisite, not another user choice. Without formal acceptance, these shells cannot be written and the gate cannot be changed. -P0b review package (Proposed): the exact pairs, shape rules, and staged isolation model are in [`../module-layout.md`](../module-layout.md#first-wave-compatibility-exceptions-proposed), [`../legacy-knowledge-manifest.json`](../legacy-knowledge-manifest.json), and `tests/test_target_module_import_gate.py`. +P0b review package (Proposed): the exact pairs, shape rules, and staged isolation model are in [`../module-layout.md`](../module-layout.md#first-wave-compatibility-exceptions-proposed), [`../legacy-knowledge-manifest.json`](../legacy-knowledge-manifest.json), and `tests/repository/test_target_module_import_gate.py`. ### B3. Later legacy evaluation entry (not mixed into the first wave) diff --git a/docs/dashboard-experiments.md b/docs/dashboard-experiments.md index 9424d4aa3..4c3864719 100644 --- a/docs/dashboard-experiments.md +++ b/docs/dashboard-experiments.md @@ -159,11 +159,11 @@ three reference roles, a maximize metric, and a partial story. ```bash python tests/fixtures/dashboard_experiments.py /tmp/dashboard-experiment-example # Open /tmp/dashboard-experiment-example/dashboard.html locally. -pytest tests/test_dashboard_experiments.py tests/test_dashboard_external.py +pytest tests/apps/test_dashboard_experiments.py tests/apps/test_dashboard_external.py # Optional real Chromium tests, including both layouts' actual loopback refresh: python -m pip install playwright python -m playwright install chromium -pytest tests/test_dashboard_experiments_browser.py +pytest tests/apps/test_dashboard_experiments_browser.py ``` [English screenshot](assets/dashboard-experiments-en.png) · diff --git a/docs/drama3-npu-readiness.md b/docs/drama3-npu-readiness.md index d06fca21a..7919736e5 100644 --- a/docs/drama3-npu-readiness.md +++ b/docs/drama3-npu-readiness.md @@ -122,7 +122,7 @@ Grounded in commit [`a6e660cc`](https://github.com/david6666666/drama-3-single-b back into the primary region and overwrote a live request's state. The repair reserves a dedicated padding band plus separate suffix mirror space and rejects any padding/live overlap. -- **CPU fixture:** [`tests/test_drama3_prefill_noninterference.py`](../tests/test_drama3_prefill_noninterference.py) +- **CPU fixture:** [`tests/campaigns/test_drama3_prefill_noninterference.py`](../tests/campaigns/test_drama3_prefill_noninterference.py) is a pure-Python reference arena that **reproduces the collision** with the original top-of-arena assignment (a live request's state is overwritten) and **preserves all live state** with the reserved-band layout, across partial diff --git a/docs/flare-qualification.md b/docs/flare-qualification.md index 2b3217866..92805e2fe 100644 --- a/docs/flare-qualification.md +++ b/docs/flare-qualification.md @@ -148,7 +148,7 @@ python tests/fixtures/flare_packet.py python -m inferrsi.benchmark.validators.flare measure \ --packet /packet.json --peer /packet.json \ --output /receipt.json -pytest tests/test_flare_adapter.py +pytest tests/benchmark/test_flare_adapter.py ``` The fixture writer saves a complete one-repetition packet, including raw SSE, diff --git a/docs/goal-checkpoints.md b/docs/goal-checkpoints.md index 39fdd4f88..5846c4f33 100644 --- a/docs/goal-checkpoints.md +++ b/docs/goal-checkpoints.md @@ -148,7 +148,7 @@ provider-side hard spending cap. A recommendation never executes anything. The deterministic regression fixture uses the existing comparison test client and real local subprocess/receipt paths, with **zero model calls**. These are software-contract fixtures, not measured agent effectiveness or paid-pilot -results. Run `python -m pytest tests/test_goal_checkpoint.py` to verify them. +results. Run `python -m pytest tests/apps/test_goal_checkpoint.py` to verify them. Before: the comparison is recorded as completed, and a merged-code record is available, but the goal owner has not accepted its criterion. A returning agent diff --git a/docs/harness-improvement.md b/docs/harness-improvement.md index d7d0abdbc..1b7366f6d 100644 --- a/docs/harness-improvement.md +++ b/docs/harness-improvement.md @@ -143,8 +143,8 @@ Requires Python 3.10+, dev dependencies and Git 2.45+ as in ```bash python -m tests.fixtures.harness_improvement_demo --output -python -m pytest tests/test_harness_improvement.py tests/test_skill_eval_compare.py \ - tests/test_skill_eval_pipeline.py tests/test_skill_eval_verifier.py tests/test_skill_evaluation.py +python -m pytest tests/harness/test_harness_improvement.py tests/skill_eval/test_skill_eval_compare.py \ + tests/skill_eval/test_skill_eval_pipeline.py tests/skill_eval/test_skill_eval_verifier.py tests/skill_eval/test_skill_evaluation.py ``` The demo runs a successful composition, a cheaper degraded candidate, composition diff --git a/docs/knowledge-model-policy.md b/docs/knowledge-model-policy.md index 33d2e9648..944fd3410 100644 --- a/docs/knowledge-model-policy.md +++ b/docs/knowledge-model-policy.md @@ -528,8 +528,8 @@ still proves nothing about a specific PR's declarations, since only the main-branch workflow's own status does. ```bash -python -m pytest tests/test_knowledge_model_policy.py -python -m ruff check tools/check_knowledge_model_policy.py tests/test_knowledge_model_policy.py +python -m pytest tests/knowledge/test_knowledge_model_policy.py +python -m ruff check tools/check_knowledge_model_policy.py tests/knowledge/test_knowledge_model_policy.py python tools/check_knowledge_model_policy.py --repository --pull-request --policy-sha --dry-run ``` diff --git a/docs/knowledge-retrieval-trace.md b/docs/knowledge-retrieval-trace.md index afd8d410f..470a6a393 100644 --- a/docs/knowledge-retrieval-trace.md +++ b/docs/knowledge-retrieval-trace.md @@ -233,9 +233,9 @@ the full assembled context. ```sh PYTHONPATH=src python tests/fixtures/knowledge_retrieval.py -pytest tests/test_retrieval_projection.py -pytest tests/test_knowledge_navigation_browser.py -pytest tests/test_round_decisions_browser.py +pytest tests/apps/test_retrieval_projection.py +pytest tests/apps/test_knowledge_navigation_browser.py +pytest tests/apps/test_round_decisions_browser.py ``` The browser tests require Playwright and Chromium. Open the generated diff --git a/docs/legacy-knowledge-manifest.json b/docs/legacy-knowledge-manifest.json index c3407528d..3ff7ce015 100644 --- a/docs/legacy-knowledge-manifest.json +++ b/docs/legacy-knowledge-manifest.json @@ -309,7 +309,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/test_knowledge_compatibility_shells.py requires the two to match exactly.", + "gate": "At base_commit the gate checked LEAF_IMPORTERS in tests/_gate_policy_support.py (https://github.com/InferMatrixLab/InferRSI/blob/aaa17a5dd333449d15fb052bb09b2012d55f2327/tests/test_knowledge_compatibility_shells.py). The current gate is tests/knowledge/test_knowledge_compatibility_shells.py.", "review": "This rule requires formal architecture review. The implementer does not self-approve it, and passing tests are not that review." } } @@ -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/test_knowledge_compatibility_shells.py requires the two to match exactly.", + "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.", "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 1796cdeff..0d262ed88 100644 --- a/docs/module-layout.md +++ b/docs/module-layout.md @@ -139,7 +139,7 @@ nothing. Neither package is a fourth core. C2 (#451) moved these out of root `_repo_pack_data.py` and `evidence_paths.py` and deleted both root files, with no forwarding shell or alias. -The flat package root is retired. `tests/test_package_root_inventory.py` pins the +The flat package root is retired. `tests/repository/test_package_root_inventory.py` pins the root to an exact file set: 23 tracked files after C1, 21 after C2, 10 after R1 (#412), 8 after A1 (#408), 6 after A2 (#408) and the final two after M1 (#452). The two are `__init__.py` and `__main__.py`. M1 moved root `mindie_project.py`, @@ -187,7 +187,7 @@ contract slice. Do not treat PR #338 as a reason to add a top-level ## CPU/offline connection `tests/architecture_closed_loop.py` is the handoff exercised by -`tests/test_architecture_closed_loop.py`. The coordinator does not import +`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. @@ -240,7 +240,7 @@ Several flat modules remain shared seams until their slice starts. ## Import gate -`tests/test_target_module_import_gate.py` fails on a new import of +`tests/repository/test_target_module_import_gate.py` fails on a new import of `inferrsi.knowledge`, `inferrsi.benchmark`, or `inferrsi.apps` from anywhere except application assembly, and on Knowledge or Benchmark importing Harness. Application assembly is the `inferrsi.apps` package, identified by its first path @@ -418,7 +418,7 @@ The leaf's own import rule and `REPO_TYPES` object identity govern it. `inferrsi.knowledge.catalog` and the moved parser `inferrsi.apps.cli.arguments`. - **Shell shape.** No shell exists after R1. The rule is kept for a pair that - review stages again, and `tests/test_first_wave_isolation_policy.py` still + review stages again, and `tests/repository/test_first_wave_isolation_policy.py` still drives it with the nine retired pair records. A staged root leaf that imports its Knowledge target or the data leaf is a compatibility shell. It may contain only a module docstring, @@ -530,7 +530,7 @@ 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 `technical_leaf.permanent_importers` in the manifest. -`tests/test_knowledge_compatibility_shells.py` requires the two to match, and +`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`. The rule is not a `compatibility_pairs` entry. It adds no blocker and does not retire, because the importer is not a shell. @@ -553,7 +553,7 @@ The rule covers that one importer, target, name and shape, and nothing wider: - A forwarding module under a retired name, a re-export through the leaf's initializer and a dynamic import from an undeclared module fail. -`tests/test_first_wave_isolation_policy.py` holds these negative controls. One +`tests/repository/test_first_wave_isolation_policy.py` holds these negative controls. One of them removes the declaration and shows that the scan then rejects the `apps.host.inspection` edge, so the edge passes by the rule and not by a relaxed scan. @@ -673,7 +673,7 @@ change that code. | Any other verdict, including missing | 2 | | `OSError`, `ValueError`, `JSONDecodeError`, or `sqlite3.Error` via `parser.error` | 2 | -`tests/test_legacy_run_v0_frozen.py` runs the `run` command for pass, fail and +`tests/apps/test_legacy_run_v0_frozen.py` runs the `run` command for pass, fail and incomplete scenarios. It compares each exit code and the `evaluation.json` bytes with goldens in `tests/fixtures/legacy_run_v0/`, which the chain wrote before its evaluation moved to Benchmark. Missing evidence decides over a failed gate. diff --git a/docs/optimization-workflow-unification.md b/docs/optimization-workflow-unification.md index 4d180576d..09d2465f9 100644 --- a/docs/optimization-workflow-unification.md +++ b/docs/optimization-workflow-unification.md @@ -297,7 +297,7 @@ Apps workflows 目录迁移会改变运行时摘要的路径和控制器源码 固定旧 wheel 的解释器,`INFERRSI_POST_MOVE_PYTHON` 指向新 wheel 的解释器后运行: ```text -python -m pytest tests/test_optimization_session.py::test_pinned_pre_move_wheel_recovers_its_original_plan +python -m pytest tests/apps/test_optimization_session.py::test_pinned_pre_move_wheel_recovers_its_original_plan ``` 未提供旧 runtime 时该安装集成用例明确跳过;默认回归仍检查旧路径的摘要表 diff --git a/docs/plans/2026-10-19-campaign-plan-rfc.md b/docs/plans/2026-10-19-campaign-plan-rfc.md index ae01625da..9dc8d459b 100644 --- a/docs/plans/2026-10-19-campaign-plan-rfc.md +++ b/docs/plans/2026-10-19-campaign-plan-rfc.md @@ -204,7 +204,7 @@ derived from a fillable table. 1. **Templates** — add the table, header fields and row-4 change log; update the plan segment README; link from [contributing.md](../contributing.md) and the delivery scaffold's evidence guide ([template/README.md](../template/README.md)). -2. **Tests** — extend [test_template_layout.py](../../tests/test_template_layout.py) +2. **Tests** — extend [test_template_layout.py](../../tests/repository/test_template_layout.py) or add `tests/test_campaign_plan_template.py`: every row present and named consistently across Markdown, YAML and README; rows 1, 2, 3, 5, 6 and 7 frozen, row 4 mutable with a change log, and the fixed preamble present verbatim; placeholders only (no 40-hex revision, no real @@ -217,7 +217,7 @@ derived from a fillable table. Slices 1 and 2 follow the existing contract (`pytest`, `ruff check src tests`, DCO sign-off, no CI lane changes). Prerequisite for slice 2: the link check reads documents with the platform default encoding (`document.read_text()` in -[test_template_layout.py](../../tests/test_template_layout.py)), so under a +[test_template_layout.py](../../tests/repository/test_template_layout.py)), so under a non-UTF-8 locale such as a Windows GBK console 114 of 167 scanned documents raise `UnicodeDecodeError`, starting with [README.md](../../README.md). Reading them explicitly as UTF-8 is a one-line existing fix. diff --git a/docs/result-delivery.md b/docs/result-delivery.md index 8fe5c182a..62b916eb9 100644 --- a/docs/result-delivery.md +++ b/docs/result-delivery.md @@ -215,7 +215,7 @@ limits of [Apps publication](apps-output.md). ## Validation scope -`tests/test_result_delivery.py` covers PASS/FAIL, missing final, baseline retention, +`tests/apps/test_result_delivery.py` covers PASS/FAIL, missing final, baseline retention, damaged evidence/code, both binding paths, usage, invalid ratios, archive authority, source changes, writer locks, publication faults, hostile text/paths and historical adapters. Project and Benchmark lifecycle tests exercise automatic export through diff --git a/docs/service-reuse-campaigns.md b/docs/service-reuse-campaigns.md index 460422990..0848b32ff 100644 --- a/docs/service-reuse-campaigns.md +++ b/docs/service-reuse-campaigns.md @@ -299,8 +299,8 @@ flag while retaining earlier events. Infrastructure/cancelled/incomplete attempt do not count; recovery does not double-count. Advisory does not pause execution; explicit pause is resumed with a reason. -The synthetic CPU controls are `tests/test_project_objectives.py`, -`tests/test_project_service_reuse.py` and `tests/test_service_backfill_recovery.py`. +The synthetic CPU controls are `tests/harness/test_project_objectives.py`, +`tests/apps/test_project_service_reuse.py` and `tests/harness/test_service_backfill_recovery.py`. The service tests use temporary loopback services and guard fingerprint helpers from before campaign creation. Run them where loopback sockets are available. They require only CPU resources. In a workspace forbidding fingerprints, run diff --git a/docs/skill-eval-budget-core.md b/docs/skill-eval-budget-core.md index 27ba40eaf..067971602 100644 --- a/docs/skill-eval-budget-core.md +++ b/docs/skill-eval-budget-core.md @@ -150,7 +150,7 @@ does not authorize any settings changes, migration, or remote writes. ## Verification and integration boundary -`pytest tests/test_skill_eval_budget.py tests/test_skill_eval_budget_git.py` +`pytest tests/skill_eval/test_skill_eval_budget.py tests/skill_eval/test_skill_eval_budget_git.py` covers cumulative limits, permanent reservations, legacy charges, duplicate plan/run bindings, malformed state, reservation/claim races, unique claim commit identities, crashes/lost responses, rules rejection, history corruption/deletion, diff --git a/docs/skill-eval-comparison.md b/docs/skill-eval-comparison.md index 74050aff7..bbdd522e4 100644 --- a/docs/skill-eval-comparison.md +++ b/docs/skill-eval-comparison.md @@ -241,8 +241,8 @@ cannot escape its code block. Run offline acceptance and the old pilot regression tests with: ```bash -python -m pytest tests/test_skill_eval_compare.py tests/test_skill_eval_pipeline.py \ - tests/test_skill_eval_verifier.py tests/test_skill_evaluation.py +python -m pytest tests/skill_eval/test_skill_eval_compare.py tests/skill_eval/test_skill_eval_pipeline.py \ + tests/skill_eval/test_skill_eval_verifier.py tests/skill_eval/test_skill_evaluation.py ``` The controlled fixtures use real temporary Git commits with different body, diff --git a/docs/skill-eval-daily-admission.md b/docs/skill-eval-daily-admission.md index 903753d6d..fc463085a 100644 --- a/docs/skill-eval-daily-admission.md +++ b/docs/skill-eval-daily-admission.md @@ -94,7 +94,7 @@ limitations remain as documented in [the accounting core](skill-eval-budget-core ## Offline validation ```sh -PYTHONPATH=src:. python -m unittest tests.test_skill_eval_daily_budget tests.test_skill_eval_auto_daily -v +PYTHONPATH=src:. python -m unittest tests.skill_eval.test_skill_eval_daily_budget tests.skill_eval.test_skill_eval_auto_daily -v ``` The controller matrix covers all four durable admission writes under conflicts, diff --git a/docs/skill-eval-generation-only.md b/docs/skill-eval-generation-only.md index 67ec6d09e..0b786f8cd 100644 --- a/docs/skill-eval-generation-only.md +++ b/docs/skill-eval-generation-only.md @@ -45,7 +45,7 @@ eligible for this deferred replay. Existing workspace-agent execution is unchanged. A passing artifact comparison is not evidence of author-agent isolation, general skill efficacy or causal improvement from a single pair. -Offline regression coverage: `tests/test_skill_eval_generation.py`. Real sandbox +Offline regression coverage: `tests/skill_eval/test_skill_eval_generation.py`. Real sandbox qualification, artifact transport and paid trial execution are separate steps; these unit tests do not establish that a particular host is qualified. diff --git a/docs/skill-eval-pr.md b/docs/skill-eval-pr.md index fa2ad49f4..19585e152 100644 --- a/docs/skill-eval-pr.md +++ b/docs/skill-eval-pr.md @@ -244,9 +244,9 @@ limits can shorten the requested 30 days. There is no background expiry monitor. Run the integration controls and original pilot regressions: ```bash -python -m pytest tests/test_skill_eval_pr.py tests/test_skill_eval_compare.py \ - tests/test_skill_eval_pipeline.py tests/test_skill_eval_verifier.py \ - tests/test_skill_evaluation.py +python -m pytest tests/skill_eval/test_skill_eval_pr.py tests/skill_eval/test_skill_eval_compare.py \ + tests/skill_eval/test_skill_eval_pipeline.py tests/skill_eval/test_skill_eval_verifier.py \ + tests/skill_eval/test_skill_evaluation.py ruff check src tests tools pytest ``` diff --git a/docs/skill-eval-quarantine.md b/docs/skill-eval-quarantine.md index 3faeea53c..d3b11f480 100644 --- a/docs/skill-eval-quarantine.md +++ b/docs/skill-eval-quarantine.md @@ -50,7 +50,7 @@ provide administrator-resistant rollback protection. Offline tests: ```sh -PYTHONPATH=src:. python -m unittest tests.test_skill_eval_quarantine -v +PYTHONPATH=src:. python -m unittest tests.skill_eval.test_skill_eval_quarantine -v ``` They cover concurrent admission, lost successful write receipt, repeat-stop diff --git a/docs/skill-evaluation.md b/docs/skill-evaluation.md index 1f42f440d..ab841a43f 100644 --- a/docs/skill-evaluation.md +++ b/docs/skill-evaluation.md @@ -94,7 +94,7 @@ only validated boolean checks enter the trial record. After the normal development setup, with checkout `src` on `PYTHONPATH`: ```console -pytest tests/test_skill_evaluation.py tests/test_skill_eval_verifier.py tests/test_skill_eval_pipeline.py +pytest tests/skill_eval/test_skill_evaluation.py tests/skill_eval/test_skill_eval_verifier.py tests/skill_eval/test_skill_eval_pipeline.py python tools/skill_eval_pilot.py prepare --output --model --effort --protected-root ``` diff --git a/docs/task-input.md b/docs/task-input.md index 07ae503e3..c8c72d959 100644 --- a/docs/task-input.md +++ b/docs/task-input.md @@ -310,9 +310,9 @@ An Agent uses the same installed CLI and the same machine-readable preview: record. InferRSI checks only that the two agree in content. The CLI and the Agent produce the same normalized task for the same file and flags. -`tests/test_task_input.py` checks this by comparing `inferrsi task preview --json` +`tests/apps/test_task_input.py` checks this by comparing `inferrsi task preview --json` with the Python `task_input.preview` on the shared complete fixture. -`tests/test_task_plan_run.py` checks that `plan --task` gives the same `task` block, +`tests/apps/test_task_plan_run.py` checks that `plan --task` gives the same `task` block, and the expected RunSpec, for that fixture. An Agent checks a task's content against its frozen gate record with the Python `task_input.frozen_gate`, the same check `run --task` applies. diff --git a/src/inferrsi/harness/device_lease.py b/src/inferrsi/harness/device_lease.py index d7a9bceb7..6efe343cc 100644 --- a/src/inferrsi/harness/device_lease.py +++ b/src/inferrsi/harness/device_lease.py @@ -1,20 +1,44 @@ """Host-local device leases. The key is the caller's device identity, not a CUDA probe.""" -import fcntl -from pathlib import Path +import os +from contextlib import AbstractContextManager +from pathlib import Path, PureWindowsPath + +from .artifact_primitives import file_lock class LeaseError(RuntimeError): - """The device identity is already held.""" + """The device identity cannot be used for a lease.""" + + +def _reserved_windows_name(device_id: str) -> bool: + is_reserved = getattr(os.path, "isreserved", None) + if is_reserved is not None: + return is_reserved(device_id) + return PureWindowsPath(device_id).is_reserved() + + +def _validate_device_id(device_id: str) -> None: + if ( + not isinstance(device_id, str) + or device_id in {"", ".", ".."} + or any(char in device_id for char in "/\\\0") + ): + raise LeaseError("device identity must be a single path segment") + if os.name == "nt" and ( + device_id.endswith((".", " ")) + or any(char in '<>:"|?*' or ord(char) < 32 for char in device_id) + or _reserved_windows_name(device_id) + ): + raise LeaseError("device identity must be a valid Windows path segment") class _Held: - def __init__(self, handle) -> None: - self._handle = handle + def __init__(self, lock: AbstractContextManager[None]) -> None: + self._lock = lock def release(self) -> None: - fcntl.flock(self._handle.fileno(), fcntl.LOCK_UN) - self._handle.close() + self._lock.__exit__(None, None, None) def __enter__(self): return self @@ -29,24 +53,27 @@ def __init__(self, directory: Path) -> None: self.directory.mkdir(parents=True, exist_ok=True) def acquire(self, device_id: str) -> _Held: - if not device_id or any(char in device_id for char in "/\\"): - raise LeaseError("device identity must be a single path segment") - handle = (self.directory / device_id).open("a+") + _validate_device_id(device_id) + lock = file_lock(self.directory / device_id) try: - fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + lock.__enter__() except BlockingIOError: - handle.close() raise LeaseError(f"device busy: {device_id}") from None - if self._marker(device_id).exists(): - _Held(handle).release() - raise LeaseError(f"device quarantined: {device_id}") - return _Held(handle) + held = _Held(lock) + try: + if self._marker(device_id).exists(): + raise LeaseError(f"device quarantined: {device_id}") + except BaseException: + held.release() + raise + return held def quarantine(self, device_id: str, reason: str) -> None: """Refuse every later acquire of ``device_id`` until the marker file is removed. Call it while holding the lease, so no acquire can slip in before the marker. """ + _validate_device_id(device_id) self._marker(device_id).write_text(reason + "\n", encoding="utf-8") def _marker(self, device_id: str) -> Path: diff --git a/src/inferrsi/harness/parallel_round.py b/src/inferrsi/harness/parallel_round.py index 7564079e7..d699a76f8 100644 --- a/src/inferrsi/harness/parallel_round.py +++ b/src/inferrsi/harness/parallel_round.py @@ -59,6 +59,7 @@ import subprocess import time from collections.abc import Callable +from contextlib import ExitStack, suppress from datetime import datetime, timezone from fnmatch import fnmatch from pathlib import Path @@ -992,17 +993,25 @@ def hold_devices(round_dir: Path, plan: dict, count: int) -> list[tuple[str, obj """Hold ``count`` free devices at once, or none. The caller releases what it gets.""" leases = DeviceLease(round_dir / "leases") held: list[tuple[str, object]] = [] - for device in plan["device_ids"]: - if len(held) == count: - break + with ExitStack() as rollback: try: - held.append((device, leases.acquire(device))) - except LeaseError: - continue - if len(held) < count: - for _device, lease in held: - lease.release() - return None + for device in plan["device_ids"]: + if len(held) == count: + break + try: + lease = leases.acquire(device) + except LeaseError: + continue + rollback.callback(lease.release) + held.append((device, lease)) + except BaseException: + # A release error must not replace the acquisition error. + with suppress(Exception): + rollback.close() + raise + if len(held) < count: + return None + rollback.pop_all() return held diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 000000000..66b86aa72 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,22 @@ +# InferRSI tests + +Run `python -m pytest` from the repository root on Linux for the full suite. +Pass a directory to run one module, for example `python -m pytest tests/harness`. +Windows can collect the suite and run the portable parallel-round cases with +`python -m pytest tests/harness/test_parallel_round.py::TestPortableParallelRound`. +Parallel-round execution tests that need POSIX directory descriptors run on Linux. + +- [Apps](apps/) covers the CLI, integrations, application workflows, and result views. +- [Benchmark](benchmark/) covers task preparation, measurements, and evaluators. +- [Campaigns](campaigns/) covers model-specific workloads, adapters, and archived campaigns. +- [Contracts](contracts/) covers shared types, schemas, and evidence paths. +- [Harness](harness/) covers execution, run state, recovery, and isolation. +- [Knowledge](knowledge/) covers the library, repository packs, search, and installation. +- [Repository](repository/) covers architecture, evidence archives, release tooling, and smoke tests. +- [Skill evaluation](skill_eval/) covers skill evaluation workflows, their graders, and automation. + +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). diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/apps/__init__.py b/tests/apps/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/apps/conftest.py b/tests/apps/conftest.py new file mode 100644 index 000000000..5026918d5 --- /dev/null +++ b/tests/apps/conftest.py @@ -0,0 +1,28 @@ +"""Browser setup shared by Apps UI tests.""" + +from contextlib import contextmanager + +import pytest + + +@contextmanager +def _chromium(**launch_options): + playwright = pytest.importorskip("playwright.sync_api") + with playwright.sync_playwright() as driver: + instance = driver.chromium.launch(**launch_options) + try: + yield instance + finally: + instance.close() + + +@pytest.fixture +def browser(): + with _chromium() as instance: + yield instance + + +@pytest.fixture(scope="module") +def cpu_browser(): + with _chromium(args=["--disable-gpu"]) as instance: + yield instance diff --git a/tests/test_agent_sessions.py b/tests/apps/test_agent_sessions.py similarity index 100% rename from tests/test_agent_sessions.py rename to tests/apps/test_agent_sessions.py diff --git a/tests/test_anthropic_agent.py b/tests/apps/test_anthropic_agent.py similarity index 100% rename from tests/test_anthropic_agent.py rename to tests/apps/test_anthropic_agent.py diff --git a/tests/test_anthropic_edit_agent.py b/tests/apps/test_anthropic_edit_agent.py similarity index 100% rename from tests/test_anthropic_edit_agent.py rename to tests/apps/test_anthropic_edit_agent.py diff --git a/tests/test_anthropic_full_context.py b/tests/apps/test_anthropic_full_context.py similarity index 100% rename from tests/test_anthropic_full_context.py rename to tests/apps/test_anthropic_full_context.py diff --git a/tests/test_apps_artifact_reader.py b/tests/apps/test_apps_artifact_reader.py similarity index 100% rename from tests/test_apps_artifact_reader.py rename to tests/apps/test_apps_artifact_reader.py diff --git a/tests/test_apps_assess.py b/tests/apps/test_apps_assess.py similarity index 99% rename from tests/test_apps_assess.py rename to tests/apps/test_apps_assess.py index 733e44e5d..1cd3a7c9c 100644 --- a/tests/test_apps_assess.py +++ b/tests/apps/test_apps_assess.py @@ -21,7 +21,7 @@ from inferrsi.harness.errors import PublicError from inferrsi.harness.run_store import RunStore -_FIXTURES = Path(__file__).resolve().parents[1] / "docs/contracts/fixtures/t108-v4" +_FIXTURES = Path(__file__).resolve().parents[2] / "docs/contracts/fixtures/t108-v4" def _fixture(name): diff --git a/tests/test_apps_capture_adapter.py b/tests/apps/test_apps_capture_adapter.py similarity index 100% rename from tests/test_apps_capture_adapter.py rename to tests/apps/test_apps_capture_adapter.py diff --git a/tests/test_apps_context_provider.py b/tests/apps/test_apps_context_provider.py similarity index 100% rename from tests/test_apps_context_provider.py rename to tests/apps/test_apps_context_provider.py diff --git a/tests/test_apps_evaluate_cli.py b/tests/apps/test_apps_evaluate_cli.py similarity index 86% rename from tests/test_apps_evaluate_cli.py rename to tests/apps/test_apps_evaluate_cli.py index d208fa8dd..c6d54ea5c 100644 --- a/tests/test_apps_evaluate_cli.py +++ b/tests/apps/test_apps_evaluate_cli.py @@ -15,12 +15,17 @@ from inferrsi.apps.cli import main from inferrsi.apps.storage import archive from inferrsi.apps.storage.archive import read_result +from inferrsi.benchmark import cpu_smoke +from inferrsi.benchmark.workers import fixture_worker as worker from inferrsi.contracts.json_v1 import decode, encode from inferrsi.harness import execution_service, run_store -from tests.test_benchmark_assessment import remove -from tests.test_benchmark_assessment import retained as retained -from tests.test_benchmark_preparation import preparation as preparation -from tests.test_harness_entry_verification import evaluation as evaluation +from tests.apps.test_apps_generation_plan import generation as generation +from tests.benchmark.test_benchmark_assessment import remove +from tests.benchmark.test_benchmark_assessment import retained as retained +from tests.benchmark.test_benchmark_preparation import preparation as preparation +from tests.harness.test_harness_entry_verification import evaluation as evaluation +from tests.harness.test_harness_generation_lineage import lineage as lineage +from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation def save(tmp_path, name, value): @@ -97,7 +102,7 @@ def test_execute_and_cross_process_replay_keep_original_attempt(evaluation, tmp_ (case["modules"] / "fixture_worker.py").unlink() runtime["target"].update(target_id="retired", config_revision="2", module_root=None) command = arguments(tmp_path, "execute", request, config, runtime, output="replay") - env = {**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[1] / "src")} + env = {**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[2] / "src")} child = subprocess.run([sys.executable, "-m", "inferrsi", *command], cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30) assert child.returncode == 0, child.stderr @@ -351,3 +356,36 @@ def forbidden(*args, **kwargs): main(command) assert error.value.code == 2 assert "Traceback" not in capsys.readouterr().err + + +def test_generated_candidate_through_saved_commands(lineage, tmp_path, capsys): + config = lineage["config"] + runtime = target_config({"target": lineage["evaluation_target"]}) + code = Path(worker.__file__) + protocol = cpu_smoke.protocol( + code.read_bytes(), control_domain=execution_service._CONTROL_DOMAIN, + ) + runtime["benchmark"] = { + "protocol": str(save(tmp_path, "protocol.json", protocol)), "worker_role": "worker-code", + "resources": {"worker-code": str(code), "baseline-code": str(code)}, + } + prepare = {"schema_version": 1, "request": cpu_smoke.default_request()} + assert main(arguments(tmp_path, "prepare", prepare, config, runtime, output="cli-prepare")) == 0 + request = execute_request(lineage) + request["prepared_ref"] = json.loads(capsys.readouterr().out)["prepared_ref"] + generation_ref = lineage["generated"]["record_ref"] + assert request["attempt"]["attempt_id"] != generation_ref["attempt_id"] + + assert main(arguments(tmp_path, "execute", request, config, runtime, output="cli-execute") + + ["--capture-evidence"]) == 0 + executed = json.loads(capsys.readouterr().out) + assert executed["execution"]["generation_record_ref"] == generation_ref + assert executed["record_ref"]["attempt_id"] == request["attempt"]["attempt_id"] + assessment = {"schema_version": 1, "record_ref": executed["record_ref"], + "primary_scope": "p1", "primary_claim_id": "C"} + assert main(arguments(tmp_path, "assess", assessment, config, output="cli-assess")) == 8 + assessed = json.loads(capsys.readouterr().out)["assessment"] + assert assessed["record_ref"] == executed["record_ref"] + assert [(item["claim_id"], item["verdict"]) for item in assessed["claims"]] == [ + ("F", "PASS"), ("C", "FAIL"), ("M", "PASS"), + ] diff --git a/tests/test_apps_evidence.py b/tests/apps/test_apps_evidence.py similarity index 98% rename from tests/test_apps_evidence.py rename to tests/apps/test_apps_evidence.py index 1c73a8018..131113132 100644 --- a/tests/test_apps_evidence.py +++ b/tests/apps/test_apps_evidence.py @@ -9,7 +9,7 @@ from inferrsi.contracts.json_v1 import decode, encode from inferrsi.harness.errors import PublicError -_FIXTURES = Path(__file__).resolve().parents[1] / "docs/contracts/fixtures/t108-v4" +_FIXTURES = Path(__file__).resolve().parents[2] / "docs/contracts/fixtures/t108-v4" @pytest.fixture diff --git a/tests/test_apps_evidence_capture.py b/tests/apps/test_apps_evidence_capture.py similarity index 98% rename from tests/test_apps_evidence_capture.py rename to tests/apps/test_apps_evidence_capture.py index 08126d88a..5c0ab1090 100644 --- a/tests/test_apps_evidence_capture.py +++ b/tests/apps/test_apps_evidence_capture.py @@ -21,9 +21,9 @@ from inferrsi.contracts.json_v1 import decode, encode from inferrsi.harness import execution_service, run_store from inferrsi.harness.api import Harness, LocalCpuTarget -from tests.test_benchmark_preparation import preparation as preparation +from tests.benchmark.test_benchmark_preparation import preparation as preparation -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] @pytest.mark.parametrize("candidate_bytes,worker_status,publish_failure", [ diff --git a/tests/test_apps_execution_binding.py b/tests/apps/test_apps_execution_binding.py similarity index 99% rename from tests/test_apps_execution_binding.py rename to tests/apps/test_apps_execution_binding.py index b987005bf..2cdc16cd7 100644 --- a/tests/test_apps_execution_binding.py +++ b/tests/apps/test_apps_execution_binding.py @@ -12,7 +12,7 @@ from inferrsi.harness.errors import PublicError from inferrsi.harness.execution_spec import request_digest -_FIXTURES = Path(__file__).resolve().parents[1] / "docs/contracts/fixtures" +_FIXTURES = Path(__file__).resolve().parents[2] / "docs/contracts/fixtures" _ATTEMPT = ( "request_id", "run_id", "attempt_id", "owner", "target_request", "deadline_utc", "resources", "budget", "retry_of", "retry_reason", diff --git a/tests/test_apps_fixed_cpu_views.py b/tests/apps/test_apps_fixed_cpu_views.py similarity index 96% rename from tests/test_apps_fixed_cpu_views.py rename to tests/apps/test_apps_fixed_cpu_views.py index 91172f026..15ea29269 100644 --- a/tests/test_apps_fixed_cpu_views.py +++ b/tests/apps/test_apps_fixed_cpu_views.py @@ -18,9 +18,9 @@ from inferrsi.harness.api import Harness from inferrsi.harness.generation import prepare_generation from inferrsi.harness.run_store import Claim, RunStore, RunStoreReader -from tests import test_harness_generation_seal as seal_tests -from tests.test_apps_generation_plan import generation as generation -from tests.test_harness_generation_seal import cpu_generation as cpu_generation +from tests.apps.test_apps_generation_plan import generation as generation +from tests.harness import test_harness_generation_seal as seal_tests +from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation @pytest.mark.parametrize("linked", [False, True], ids=["unlinked", "controlled-link"]) @@ -156,7 +156,7 @@ def forbidden(*args, **kwargs): ) print(json.dumps(view)) """ - source = str(Path(seal_tests.__file__).resolve().parents[1] / "src") + source = str(Path(seal_tests.__file__).resolve().parents[2] / "src") result = subprocess.run( [sys.executable, "-I", "-c", child, source, str(tmp_path / "record-ref.json"), str(tmp_path / "storage-config.json")], diff --git a/tests/test_apps_generation_plan.py b/tests/apps/test_apps_generation_plan.py similarity index 99% rename from tests/test_apps_generation_plan.py rename to tests/apps/test_apps_generation_plan.py index 338851440..dabd850c6 100644 --- a/tests/test_apps_generation_plan.py +++ b/tests/apps/test_apps_generation_plan.py @@ -16,7 +16,7 @@ from inferrsi.harness.execution_service import LocalCpuTarget, validate from inferrsi.harness.run_store import RunStore -_FIXTURES = Path(__file__).resolve().parents[1] / "docs/contracts/fixtures/t108-v4" +_FIXTURES = Path(__file__).resolve().parents[2] / "docs/contracts/fixtures/t108-v4" _ATTEMPT_FIELDS = ( "request_id", "run_id", "attempt_id", "owner", "target_request", "deadline_utc", "resources", "budget", "retry_of", "retry_reason", diff --git a/tests/test_apps_generation_views.py b/tests/apps/test_apps_generation_views.py similarity index 97% rename from tests/test_apps_generation_views.py rename to tests/apps/test_apps_generation_views.py index 09cdf0328..73998b8f5 100644 --- a/tests/test_apps_generation_views.py +++ b/tests/apps/test_apps_generation_views.py @@ -11,8 +11,8 @@ from inferrsi.contracts.json_v1 import encode from inferrsi.harness.errors import PublicError from inferrsi.harness.generation import prepare_generation -from tests.test_apps_generation_plan import generation as generation -from tests.test_harness_generation_seal import cpu_generation as cpu_generation +from tests.apps.test_apps_generation_plan import generation as generation +from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation @pytest.fixture diff --git a/tests/test_apps_knowledge.py b/tests/apps/test_apps_knowledge.py similarity index 100% rename from tests/test_apps_knowledge.py rename to tests/apps/test_apps_knowledge.py diff --git a/tests/test_apps_module_migrations.py b/tests/apps/test_apps_module_migrations.py similarity index 99% rename from tests/test_apps_module_migrations.py rename to tests/apps/test_apps_module_migrations.py index d1989fc42..9b2bd56ba 100644 --- a/tests/test_apps_module_migrations.py +++ b/tests/apps/test_apps_module_migrations.py @@ -13,9 +13,9 @@ import pytest from tests import _gate_policy_support as support -from tests.test_contracts_package import IO_CONTROL, IO_PROBE, _fresh +from tests.contracts.test_contracts_package import IO_CONTROL, IO_PROBE, _fresh -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] ROOT = REPO / "src/inferrsi" MIGRATIONS = json.loads((REPO / "docs/apps-module-migrations.json").read_text(encoding="utf-8")) diff --git a/tests/test_apps_output.py b/tests/apps/test_apps_output.py similarity index 99% rename from tests/test_apps_output.py rename to tests/apps/test_apps_output.py index f1238bae9..a9e8d9a83 100644 --- a/tests/test_apps_output.py +++ b/tests/apps/test_apps_output.py @@ -18,7 +18,7 @@ from inferrsi.harness.errors import PublicError from inferrsi.harness.run_store import Claim, RunStore, flatten, request_digest, utc_now -_ROOT = Path(__file__).resolve().parents[1] +_ROOT = Path(__file__).resolve().parents[2] _FIXTURES = _ROOT / "docs/contracts/fixtures" _V4 = _FIXTURES / "t108-v4" _ATTEMPT_FIELDS = ( diff --git a/tests/test_apps_port_validation.py b/tests/apps/test_apps_port_validation.py similarity index 98% rename from tests/test_apps_port_validation.py rename to tests/apps/test_apps_port_validation.py index 815140a4c..b384adce7 100644 --- a/tests/test_apps_port_validation.py +++ b/tests/apps/test_apps_port_validation.py @@ -10,7 +10,7 @@ from inferrsi.harness.errors import PartialExecutionFacts, PublicError from inferrsi.harness.execution_spec import request_digest from inferrsi.harness.run_store import request_digest as legacy_digest -from tests.test_apps_output import _bind, _fixture, _request, _submit_to_run_store +from tests.apps.test_apps_output import _bind, _fixture, _request, _submit_to_run_store def _run(tmp_path, reply): diff --git a/tests/test_apps_prepare.py b/tests/apps/test_apps_prepare.py similarity index 99% rename from tests/test_apps_prepare.py rename to tests/apps/test_apps_prepare.py index 077dfbe25..fb8fae102 100644 --- a/tests/test_apps_prepare.py +++ b/tests/apps/test_apps_prepare.py @@ -17,7 +17,7 @@ from inferrsi.contracts.json_v1 import decode, encode from inferrsi.harness.errors import PublicError -_ROOT = Path(__file__).resolve().parents[1] +_ROOT = Path(__file__).resolve().parents[2] _FIXTURES = _ROOT / "docs/contracts/fixtures/t108-v4" diff --git a/tests/test_apps_production_cli.py b/tests/apps/test_apps_production_cli.py similarity index 99% rename from tests/test_apps_production_cli.py rename to tests/apps/test_apps_production_cli.py index b78447201..899c1c5bf 100644 --- a/tests/test_apps_production_cli.py +++ b/tests/apps/test_apps_production_cli.py @@ -18,9 +18,9 @@ from inferrsi.benchmark.workers import fixture_worker as worker from inferrsi.contracts.json_v1 import decode, encode from inferrsi.harness import execution_service, run_store -from tests.test_apps_evaluate_cli import arguments, save +from tests.apps.test_apps_evaluate_cli import arguments, save -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] @pytest.fixture(params=["correct", "wrong", "invalid-utf8", "missing"]) diff --git a/tests/test_apps_publication.py b/tests/apps/test_apps_publication.py similarity index 98% rename from tests/test_apps_publication.py rename to tests/apps/test_apps_publication.py index 97e5df6d2..5f0cb5a6d 100644 --- a/tests/test_apps_publication.py +++ b/tests/apps/test_apps_publication.py @@ -11,7 +11,7 @@ def _result(): - root = Path(__file__).resolve().parents[1] + root = Path(__file__).resolve().parents[2] path = root / "docs/contracts/fixtures/t108-v4/apps-not-started.json" return json.loads(path.read_text(encoding="utf-8")) diff --git a/tests/test_apps_replay.py b/tests/apps/test_apps_replay.py similarity index 97% rename from tests/test_apps_replay.py rename to tests/apps/test_apps_replay.py index 2762e56f5..0f77d83ff 100644 --- a/tests/test_apps_replay.py +++ b/tests/apps/test_apps_replay.py @@ -14,9 +14,9 @@ from inferrsi.apps.api import execute from inferrsi.apps.storage.archive import read_result from inferrsi.harness.run_store import Claim, RunStore, request_digest -from tests.test_apps_output import _bind, _request, _submit_to_run_store +from tests.apps.test_apps_output import _bind, _request, _submit_to_run_store -_ROOT = Path(__file__).resolve().parents[1] +_ROOT = Path(__file__).resolve().parents[2] _HOLDER = """ import json, sys from pathlib import Path diff --git a/tests/test_campaign_record_injection.py b/tests/apps/test_campaign_record_injection.py similarity index 100% rename from tests/test_campaign_record_injection.py rename to tests/apps/test_campaign_record_injection.py diff --git a/tests/test_campaign_records.py b/tests/apps/test_campaign_records.py similarity index 100% rename from tests/test_campaign_records.py rename to tests/apps/test_campaign_records.py diff --git a/tests/test_campaign_task_selection.py b/tests/apps/test_campaign_task_selection.py similarity index 100% rename from tests/test_campaign_task_selection.py rename to tests/apps/test_campaign_task_selection.py diff --git a/tests/test_cannbot_boundaries.py b/tests/apps/test_cannbot_boundaries.py similarity index 99% rename from tests/test_cannbot_boundaries.py rename to tests/apps/test_cannbot_boundaries.py index 0db06500e..77d892f6f 100644 --- a/tests/test_cannbot_boundaries.py +++ b/tests/apps/test_cannbot_boundaries.py @@ -14,7 +14,7 @@ from inferrsi.apps.integrations.cannbot import project from inferrsi.apps.integrations.cannbot.read_worker import _MAX_UPSTREAM -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] REVISION = "ab" * 20 diff --git a/tests/test_cannbot_channel_acceptance.py b/tests/apps/test_cannbot_channel_acceptance.py similarity index 99% rename from tests/test_cannbot_channel_acceptance.py rename to tests/apps/test_cannbot_channel_acceptance.py index 9f46e6d5c..321900b04 100644 --- a/tests/test_cannbot_channel_acceptance.py +++ b/tests/apps/test_cannbot_channel_acceptance.py @@ -15,7 +15,7 @@ import pytest -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] QUERIES = ( "AscendC tiling 参数怎么计算", "CeilDivision 向上取整", diff --git a/tests/test_cli_catalog.py b/tests/apps/test_cli_catalog.py similarity index 99% rename from tests/test_cli_catalog.py rename to tests/apps/test_cli_catalog.py index 7ab636546..2b82a35ff 100644 --- a/tests/test_cli_catalog.py +++ b/tests/apps/test_cli_catalog.py @@ -19,7 +19,7 @@ from inferrsi.knowledge.catalog import get_knowledge, knowledge_records, search_knowledge from inferrsi.resources.repository_packs import REPO_TYPES, repository_pack -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] SOURCE_REPOSITORIES = { "strata": "Niko1221/Strata", "vllm": "vllm-project/vllm", diff --git a/tests/test_codex_knowledge_search.py b/tests/apps/test_codex_knowledge_search.py similarity index 99% rename from tests/test_codex_knowledge_search.py rename to tests/apps/test_codex_knowledge_search.py index d427e8d21..1f6bf1768 100644 --- a/tests/test_codex_knowledge_search.py +++ b/tests/apps/test_codex_knowledge_search.py @@ -9,7 +9,7 @@ import pytest -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] LIBRARY = ROOT / "src/inferrsi/knowledge/data/skill_library" QUERY = "cache per-step masks ran out of device memory" REF = "checkout:case.qwen-ascend-rejected-directions" diff --git a/tests/test_codex_plugin.py b/tests/apps/test_codex_plugin.py similarity index 100% rename from tests/test_codex_plugin.py rename to tests/apps/test_codex_plugin.py diff --git a/tests/test_codex_search_delivery.py b/tests/apps/test_codex_search_delivery.py similarity index 100% rename from tests/test_codex_search_delivery.py rename to tests/apps/test_codex_search_delivery.py diff --git a/tests/test_dashboard_data.py b/tests/apps/test_dashboard_data.py similarity index 100% rename from tests/test_dashboard_data.py rename to tests/apps/test_dashboard_data.py diff --git a/tests/test_dashboard_experiments.py b/tests/apps/test_dashboard_experiments.py similarity index 99% rename from tests/test_dashboard_experiments.py rename to tests/apps/test_dashboard_experiments.py index 379b6ec65..436958f6d 100644 --- a/tests/test_dashboard_experiments.py +++ b/tests/apps/test_dashboard_experiments.py @@ -16,7 +16,7 @@ timestamp, ) -FIXTURE = runpy.run_path(str(Path(__file__).parent / "fixtures/dashboard_experiments.py")) +FIXTURE = runpy.run_path(str(Path(__file__).parents[1] / "fixtures/dashboard_experiments.py")) @pytest.fixture diff --git a/tests/test_dashboard_experiments_browser.py b/tests/apps/test_dashboard_experiments_browser.py similarity index 97% rename from tests/test_dashboard_experiments_browser.py rename to tests/apps/test_dashboard_experiments_browser.py index bc768a186..cf7221d8e 100644 --- a/tests/test_dashboard_experiments_browser.py +++ b/tests/apps/test_dashboard_experiments_browser.py @@ -7,23 +7,15 @@ from pathlib import Path import pytest -from test_optimization_session import session as session -from test_optimization_session import submit -from test_optimization_session import task as task from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard from inferrsi.apps.views.dashboard_live import DashboardServer +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 playwright = pytest.importorskip("playwright.sync_api") -FIXTURE = runpy.run_path(str(Path(__file__).parent / "fixtures/dashboard_experiments.py")) - - -@pytest.fixture -def browser(): - with playwright.sync_playwright() as driver: - instance = driver.chromium.launch() - yield instance - instance.close() +FIXTURE = runpy.run_path(str(Path(__file__).parents[1] / "fixtures/dashboard_experiments.py")) @pytest.fixture @@ -254,7 +246,7 @@ def test_profile_layout_preserves_partial_summary_and_keyboard_drilldown(browser def test_profile_home_shows_absolute_trend_and_links_exact_round(browser, tmp_path): - from test_dashboard_data import candidate, run, write_json + from tests.apps.test_dashboard_data import candidate, run, write_json write_json(tmp_path / "campaign.json", { "campaign_id": "paired", "review_layout": "profile_first", @@ -286,7 +278,7 @@ def test_profile_home_shows_absolute_trend_and_links_exact_round(browser, tmp_pa def test_mixed_profile_keeps_native_paired_reference(browser, tmp_path): - from test_dashboard_data import candidate, run, write_json + from tests.apps.test_dashboard_data import candidate, run, write_json write_json(tmp_path / "campaign.json", { "campaign_id": "mixed", "review_layout": "profile_first", diff --git a/tests/test_dashboard_external.py b/tests/apps/test_dashboard_external.py similarity index 100% rename from tests/test_dashboard_external.py rename to tests/apps/test_dashboard_external.py diff --git a/tests/test_dashboard_live.py b/tests/apps/test_dashboard_live.py similarity index 98% rename from tests/test_dashboard_live.py rename to tests/apps/test_dashboard_live.py index e23fe0f37..ce908a040 100644 --- a/tests/test_dashboard_live.py +++ b/tests/apps/test_dashboard_live.py @@ -147,7 +147,7 @@ def test_compact_live_transport_interns_repeated_context_without_changing_legacy @pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for the UI regression") def test_compact_contexts_are_restored_exactly_in_the_browser(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/template.html" + template = Path(__file__).parents[2] / "src/inferrsi/apps/views/template.html" script = r""" const fs = require('node:fs'), assert = require('node:assert/strict'); const html = fs.readFileSync(process.argv[1], 'utf8'); @@ -226,7 +226,7 @@ def test_live_cli_rejects_incompatible_flags(tmp_path): @pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for the UI regression") def test_live_selection_matches_identity_after_rows_change(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/template.html" + template = Path(__file__).parents[2] / "src/inferrsi/apps/views/template.html" script = r""" const fs = require('node:fs'), assert = require('node:assert/strict'); const html = fs.readFileSync(process.argv[1], 'utf8'); diff --git a/tests/test_dashboard_translation_ui.py b/tests/apps/test_dashboard_translation_ui.py similarity index 81% rename from tests/test_dashboard_translation_ui.py rename to tests/apps/test_dashboard_translation_ui.py index 6e0cce8e6..25e8243de 100644 --- a/tests/test_dashboard_translation_ui.py +++ b/tests/apps/test_dashboard_translation_ui.py @@ -1,4 +1,4 @@ -"""The narrative overlay must not relabel evidence-derived UI text.""" +"""Dashboard UI preserves recorded evidence through rendering and translation.""" import shutil import subprocess @@ -6,13 +6,22 @@ import pytest +NODE = shutil.which("node") +TEMPLATES = Path(__file__).parents[2] / "src/inferrsi/apps/views" +pytestmark = pytest.mark.skipif(NODE is None, reason="Node.js is needed for dashboard UI scripts") + + +def run_template_script(script, template="template.html"): + setup = """\ +const fs = require('node:fs'); +const assert = require('node:assert/strict'); +const html = fs.readFileSync(process.argv[1], 'utf8'); +""" + subprocess.run([NODE, "-e", setup + script, str(TEMPLATES / template)], check=True) + -@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for the UI regression") def test_round_outcome_and_stage_strip_follow_recorded_evidence(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/template.html" script = r""" -const fs=require('node:fs'),assert=require('node:assert/strict'); -const html=fs.readFileSync(process.argv[1],'utf8'); const source=html.slice(html.indexOf(' function duration('), html.indexOf(' function outcomeTone('))+ html.slice(html.indexOf(' function stageFacts('), @@ -68,16 +77,11 @@ def test_round_outcome_and_stage_strip_follow_recorded_evidence(): const ended=api.stageFacts();assert.equal(ended.validation.open,false); assert.equal(ended.validation.failed,true);assert.equal(ended.diagnosis.failed,false); """ - subprocess.run([shutil.which("node"), "-e", script, str(template)], check=True, - capture_output=True, text=True) + run_template_script(script) -@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for the UI regression") def test_profile_reader_matches_baseline_and_keeps_unavailable_capture_ids(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/review_template.html" script = r""" -const fs=require('node:fs'),assert=require('node:assert/strict'); -const html=fs.readFileSync(process.argv[1],'utf8'); const source=html.slice(html.indexOf('function renderCaptures('), html.indexOf('function render(){')); const box={replaceChildren(){}},section={},log=[],calls=[]; @@ -97,17 +101,12 @@ def test_profile_reader_matches_baseline_and_keeps_unavailable_capture_ids(): data.profile_captures.unshift(cap('ambiguous','baseline','b')); run(new Set());assert.deepEqual(calls.at(-1),['test',undefined]); """ - subprocess.run([shutil.which("node"), "-e", script, str(template)], check=True, - capture_output=True, text=True) + run_template_script(script, "review_template.html") -@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for trace decoding") def test_full_profile_reader_checks_original_bytes_and_tracks_overlapping_events(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/review_template.html" script = r""" -const fs=require('node:fs'),assert=require('node:assert/strict'); const {gzipSync}=require('node:zlib'),{createHash,webcrypto}=require('node:crypto'); -const html=fs.readFileSync(process.argv[1],'utf8'); const code=html.slice(html.indexOf('function profileLabel('),html.indexOf('function timeline(')); const {read,profileStatKey}=new Function('tr','crypto',code+ '\nreturn {read:readTraceFile,profileStatKey};')((zh,en)=>en,webcrypto); @@ -140,16 +139,11 @@ def test_full_profile_reader_checks_original_bytes_and_tracks_overlapping_events assert.deepEqual(imported.tracks[0].events.map(e=>e.name),names); })().catch(e=>{console.error(e);process.exitCode=1;}); """ - subprocess.run([shutil.which("node"), "-e", script, str(template)], check=True, - capture_output=True, text=True) + run_template_script(script, "review_template.html") -@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for the UI regression") def test_round_review_shows_only_linked_retrievals_in_declared_order(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/template.html" script = r""" -const fs=require('node:fs'), assert=require('node:assert/strict'); -const html=fs.readFileSync(process.argv[1],'utf8'); const source=html.slice( html.indexOf(' function renderRoundInputs('),html.indexOf(' function renderRunReview(')); const story={iterations:[ @@ -169,17 +163,11 @@ def test_round_review_shows_only_linked_retrievals_in_declared_order(): assert.deepEqual(captures(1,'b',story),[]); assert.deepEqual(captures(1,'a',{state:'not_recorded'}),[]); """ - subprocess.run([shutil.which("node"), "-e", script, str(template)], check=True, - capture_output=True, text=True) + run_template_script(script) -@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for the UI regression") def test_translation_overlay_cannot_relabel_verdicts_or_evidence(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/template.html" script = r""" -const fs = require('node:fs'); -const assert = require('node:assert/strict'); -const html = fs.readFileSync(process.argv[1], 'utf8'); const source = html.slice(html.indexOf(' const chinese = {'), html.indexOf(' const stageNames = {')) + html.slice(html.indexOf(' function renderIntegration('), @@ -281,16 +269,11 @@ def test_translation_overlay_cannot_relabel_verdicts_or_evidence(): assert.equal(attr.value, 'FAIL'); assert.equal(narrative.nodeValue, 'English explanation'); """ - subprocess.run([shutil.which("node"), "-e", script, str(template)], check=True, - capture_output=True, text=True) + run_template_script(script) -@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for the UI regression") def test_mixed_campaign_counts_native_and_external_failures_separately(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/template.html" script = r""" -const fs=require('node:fs'), assert=require('node:assert/strict'); -const html=fs.readFileSync(process.argv[1],'utf8'); const render=html.slice(html.indexOf(' function renderStats()'), html.indexOf(' function renderWorkflow()')); function node(tag,text){return {tag,text,children:[], @@ -334,16 +317,11 @@ def test_mixed_campaign_counts_native_and_external_failures_separately(): cards=stats([]); assert.equal(cards['Failed / regressed'].value,'Not recorded'); """ - subprocess.run([shutil.which("node"), "-e", script, str(template)], check=True, - capture_output=True, text=True) + run_template_script(script) -@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js runs the exported dashboard") def test_profile_history_partitions_clocks_and_preserves_missing_measurements(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/review_template.html" script = r""" -const fs=require('node:fs'), assert=require('node:assert/strict'); -const html=fs.readFileSync(process.argv[1],'utf8'); const source=html.slice(html.indexOf('function stageHistory('), html.indexOf('function renderCaptures(')); const cap=(id,round,basis,stages_ms)=>({id,phase:round?'candidate':'baseline',round, @@ -362,4 +340,57 @@ def test_profile_history_partitions_clocks_and_preserves_missing_measurements(): [['Stage (ms)','R2 · cpu'],[['worker','12']]]]); assert.ok(notes.includes('R3 · No candidate profile attached')); """ - subprocess.run([shutil.which("node"), "-e", script, str(template)], check=True) + run_template_script(script, "review_template.html") + + +def test_candidate_event_disclosure_and_live_elapsed(): + script = r""" +const section=(a,b)=>html.slice(html.indexOf(' function '+a+'('), + html.indexOf(' function '+b+'(')); +const source=section('jumpToEvent','renderRoundInputs')+ + section('refreshElapsed','eventLabel')+section('eventLabel','stageFacts')+ + section('renderCandidateEvents','renderCandidate'); +const bound=[ + {source:'events',line:1,phase:'complete',details:{state:'completed'},refs:[]}, + {source:'agent_trace',line:1,type:'agent.tool',stage:'search',tool:'submit_candidate', + details:{count:3},refs:[{sha256:'a'.repeat(64)}]}]; +const row={candidate_id:'first',round:1,run_id:'run',events:bound,optimization_trace:null, + unlinked_agent_events:[{source:'agent_trace',line:2,details:{name:'UNBOUND_PAYLOAD'}}], + agent_trace_links:{unlinked:[2],mismatched:[3]},corrupt_event_sources:{events:[],agent_trace:[4]}}; +const node=(tag,text='')=>({tag,textContent:text,children:[],dataset:{},listeners:{},open:false, + get childElementCount(){return this.children.length}, + append(...nodes){this.children.push(...nodes)},setAttribute(){}, + addEventListener(name,fn){this.listeners[name]=fn},showModal(){this.open=true}}); +const all=n=>[n,...n.children.flatMap(all)]; +const panels=Object.fromEntries( + ['event-body','event-heading','event-record'].map(id=>[id,node(id)])); +const clockCell=node('td');clockCell.dataset.started='2026-01-01T00:00:00Z'; +const env={data:{candidates:[row]},selected:0,identity:()=>row.candidate_id,byId:id=>panels[id], + clear:n=>n.children=[],node,translated:s=>s,workNames:{},stageNames:{search:'Candidate search'}, + refText:ref=>ref.sha256,liveMode:true,serverTime:Date.parse('2026-01-01T00:00:07Z'), + document:{querySelectorAll:()=>[clockCell]},duration:s=>s+' s'}; +const api=new Function(...Object.keys(env),source+ + '\nreturn {renderCandidateEvents,refreshElapsed,jumpToEvent};')(...Object.values(env)); +const root=node('div'); +api.renderCandidateEvents(root,row); +const fold=root.children[0]; +assert.equal(fold.tag,'details');assert.equal(fold.open,false); +assert.equal(all(fold).filter(n=>n.tag==='button').length,0); +fold.open=true;fold.listeners.toggle(); +fold.listeners.toggle(); +const buttons=all(fold).filter(n=>n.tag==='button'); +assert.equal(buttons.length,2); +const button=buttons.find(b=>b.textContent.includes('submit_candidate')); +assert(button.textContent.includes('agent_trace:1'));button.listeners.click(); +assert(panels['event-record'].open);assert.equal(panels['event-heading'].textContent,'Tool call'); +const content=all(panels['event-body']).map(n=>n.textContent).join('\n'); +assert(content.includes('agent_trace:1') && content.includes('submit_candidate')); +assert(content.includes('"count": 3') && content.includes('a'.repeat(64))); +const labels=all(fold).map(n=>n.textContent).join('\n'); +for(const ref of ['agent_trace:2','agent_trace:3','agent_trace:4'])assert(labels.includes(ref)); +assert(!labels.includes('UNBOUND_PAYLOAD')); +panels['event-record'].open=false;api.jumpToEvent('agent_trace',2); +assert.equal(panels['event-record'].open,false); +api.refreshElapsed();assert.equal(clockCell.textContent,'Elapsed since start · 7 s'); +""" + run_template_script(script) diff --git a/tests/test_dashboard_workflow.py b/tests/apps/test_dashboard_workflow.py similarity index 100% rename from tests/test_dashboard_workflow.py rename to tests/apps/test_dashboard_workflow.py diff --git a/tests/test_dsh_plugin.py b/tests/apps/test_dsh_plugin.py similarity index 100% rename from tests/test_dsh_plugin.py rename to tests/apps/test_dsh_plugin.py diff --git a/tests/test_engine_progress_plot.py b/tests/apps/test_engine_progress_plot.py similarity index 97% rename from tests/test_engine_progress_plot.py rename to tests/apps/test_engine_progress_plot.py index 82d1648fa..3c32f05e2 100644 --- a/tests/test_engine_progress_plot.py +++ b/tests/apps/test_engine_progress_plot.py @@ -6,7 +6,7 @@ import pytest -ENGINE_TEMPLATE = Path(__file__).resolve().parents[1] / "docs/template/engine-repo" +ENGINE_TEMPLATE = Path(__file__).resolve().parents[2] / "docs/template/engine-repo" SPEC = importlib.util.spec_from_file_location( "engine_progress_plot", ENGINE_TEMPLATE / "tools/plot_optimization_progress.py" ) diff --git a/tests/test_engineering_benchmark_plugins.py b/tests/apps/test_engineering_benchmark_plugins.py similarity index 96% rename from tests/test_engineering_benchmark_plugins.py rename to tests/apps/test_engineering_benchmark_plugins.py index 48979befe..1a80411c3 100644 --- a/tests/test_engineering_benchmark_plugins.py +++ b/tests/apps/test_engineering_benchmark_plugins.py @@ -2,10 +2,10 @@ import json +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.test_codex_plugin import distribution as distribution -from tests.test_codex_plugin import invoke -from tests.test_project_optimization import project as project def test_isolated_benchmark_child_uses_its_bundled_runtime(distribution, tmp_path, monkeypatch): diff --git a/tests/test_experiment_timing.py b/tests/apps/test_experiment_timing.py similarity index 100% rename from tests/test_experiment_timing.py rename to tests/apps/test_experiment_timing.py diff --git a/tests/test_goal_checkpoint.py b/tests/apps/test_goal_checkpoint.py similarity index 100% rename from tests/test_goal_checkpoint.py rename to tests/apps/test_goal_checkpoint.py diff --git a/tests/test_inspection.py b/tests/apps/test_inspection.py similarity index 99% rename from tests/test_inspection.py rename to tests/apps/test_inspection.py index 76004ee74..ba8421e8a 100644 --- a/tests/test_inspection.py +++ b/tests/apps/test_inspection.py @@ -183,7 +183,7 @@ def test_rocm_empty_output_never_qualifies_a_device(self): class PythonInspectionTests(unittest.TestCase): def test_real_python_reports_requested_versions(self): result = inspect_environment( - str(Path(__file__).resolve().parents[1]), + str(Path(__file__).resolve().parents[2]), "vllm_omni", "cpu", python=sys.executable, @@ -349,7 +349,7 @@ def test_retired_root_inspection_is_gone_and_host_facts_load_no_core(): ) result = subprocess.run( [sys.executable, "-c", script], capture_output=True, text=True, check=False, - env={**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[1] / "src")}, + env={**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[2] / "src")}, ) assert result.returncode == 0, result.stderr diff --git a/tests/test_knowledge_navigation_browser.py b/tests/apps/test_knowledge_navigation_browser.py similarity index 97% rename from tests/test_knowledge_navigation_browser.py rename to tests/apps/test_knowledge_navigation_browser.py index a23ebdc45..39694ddb9 100644 --- a/tests/test_knowledge_navigation_browser.py +++ b/tests/apps/test_knowledge_navigation_browser.py @@ -4,25 +4,17 @@ import threading import pytest -from test_optimization_story import FakeReader, context, log_document, write_log -from test_optimization_story import campaign as make_campaign -from test_retrieval_projection import FIXTURE from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard from inferrsi.apps.views.dashboard_live import DashboardServer from inferrsi.apps.workflows.campaign import capture_context +from tests.apps.test_optimization_story import FakeReader, context, log_document, write_log +from tests.apps.test_optimization_story import campaign as make_campaign +from tests.apps.test_retrieval_projection import FIXTURE playwright = pytest.importorskip("playwright.sync_api") -@pytest.fixture -def browser(): - with playwright.sync_playwright() as driver: - instance = driver.chromium.launch() - yield instance - instance.close() - - @pytest.mark.parametrize("profile_first", [False, True]) @pytest.mark.parametrize("live", [False, True]) def test_redacted_context_tail_and_original_hash_note(browser, tmp_path, profile_first, live): diff --git a/tests/test_legacy_run_split.py b/tests/apps/test_legacy_run_split.py similarity index 100% rename from tests/test_legacy_run_split.py rename to tests/apps/test_legacy_run_split.py diff --git a/tests/test_legacy_run_v0_frozen.py b/tests/apps/test_legacy_run_v0_frozen.py similarity index 99% rename from tests/test_legacy_run_v0_frozen.py rename to tests/apps/test_legacy_run_v0_frozen.py index 3ab2f3a94..ce80c7453 100644 --- a/tests/test_legacy_run_v0_frozen.py +++ b/tests/apps/test_legacy_run_v0_frozen.py @@ -19,7 +19,7 @@ from inferrsi.apps.cli import main -FIXTURES = Path(__file__).resolve().parent / "fixtures" +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" GOLDENS = FIXTURES / "legacy_run_v0" _WRITE = "import sys; open(sys.argv[1], 'w', encoding='utf-8').write(sys.argv[2])" diff --git a/tests/test_mindie_context.py b/tests/apps/test_mindie_context.py similarity index 100% rename from tests/test_mindie_context.py rename to tests/apps/test_mindie_context.py diff --git a/tests/test_mindie_project.py b/tests/apps/test_mindie_project.py similarity index 100% rename from tests/test_mindie_project.py rename to tests/apps/test_mindie_project.py diff --git a/tests/test_mindie_runtime.py b/tests/apps/test_mindie_runtime.py similarity index 99% rename from tests/test_mindie_runtime.py rename to tests/apps/test_mindie_runtime.py index 5eb9ec854..db18c4074 100644 --- a/tests/test_mindie_runtime.py +++ b/tests/apps/test_mindie_runtime.py @@ -236,7 +236,7 @@ def test_mcp_stdio_round_trip(reader, tmp_path, monkeypatch, oversized_line): wire += "\n" if oversized_line != "eof": wire += '{"jsonrpc":"2.0","id":7,"method":"ping"}\n' - source = str(Path(__file__).resolve().parents[1] / "src") + source = str(Path(__file__).resolve().parents[2] / "src") process = subprocess.run( [sys.executable, "-I", "-B", "-c", f"import sys; sys.path.insert(0, {source!r}); " "from inferrsi.apps.cli import main; raise SystemExit(main(['mindie', 'serve']))"], diff --git a/tests/test_mlx_discovery.py b/tests/apps/test_mlx_discovery.py similarity index 99% rename from tests/test_mlx_discovery.py rename to tests/apps/test_mlx_discovery.py index 73badfce9..d82fb5cec 100644 --- a/tests/test_mlx_discovery.py +++ b/tests/apps/test_mlx_discovery.py @@ -14,7 +14,7 @@ from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.resources.repository_packs import REPO_TYPES -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] IDS = { "mlx.mlx.execution.evaluation_completion", "mlx.mlx.execution.cross_stream_dependency", diff --git a/tests/test_optimization_session.py b/tests/apps/test_optimization_session.py similarity index 99% rename from tests/test_optimization_session.py rename to tests/apps/test_optimization_session.py index 485fe155d..bc24c96b3 100644 --- a/tests/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -805,7 +805,7 @@ def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executo assert identity["apps/workflows/campaign.py"] == sha256(root / "apps/workflows/campaign.py") -PRE_SERVING = (Path(__file__).resolve().parent / "fixtures" / "optimization-session" +PRE_SERVING = (Path(__file__).resolve().parents[1] / "fixtures" / "optimization-session" / "pre-serving-runtime-identity.json") @@ -836,7 +836,7 @@ def test_a_plan_from_before_the_serving_move_is_refused_and_left_unchanged(sessi assert path.read_bytes() == before -PRE_CHANGE_SESSIONS = Path(__file__).resolve().parent / "fixtures" / "optimization-session" +PRE_CHANGE_SESSIONS = Path(__file__).resolve().parents[1] / "fixtures" / "optimization-session" def _session_bytes(root): @@ -957,7 +957,7 @@ def interrupt(*args): """ post_move_python = os.environ.get("INFERRSI_POST_MOVE_PYTHON", sys.executable) current_source = "" if "INFERRSI_POST_MOVE_PYTHON" in os.environ else str( - Path(__file__).resolve().parents[1] / "src" + Path(__file__).resolve().parents[2] / "src" ) def run(python, source, arguments, expected=0): @@ -1007,7 +1007,7 @@ def start(root): assert "apps/workflows/campaign.py" in new_identity and "apps/campaign.py" not in new_identity from inferrsi.harness.artifact_primitives import sha256 - canonical = Path(__file__).resolve().parents[1] / "src/inferrsi/apps/workflows/campaign.py" + canonical = Path(__file__).resolve().parents[2] / "src/inferrsi/apps/workflows/campaign.py" assert new_identity["apps/workflows/campaign.py"] == sha256(canonical) diff --git a/tests/test_optimization_story.py b/tests/apps/test_optimization_story.py similarity index 99% rename from tests/test_optimization_story.py rename to tests/apps/test_optimization_story.py index caf7392f0..91c72f4ce 100644 --- a/tests/test_optimization_story.py +++ b/tests/apps/test_optimization_story.py @@ -338,7 +338,7 @@ def test_summary_navigates_to_run_without_outcome_but_not_missing_runs(tmp_path) {"ref": "candidate:duplicate", "state": "ambiguous"}, ]) - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/template.html" + template = Path(__file__).parents[2] / "src/inferrsi/apps/views/template.html" script = r""" const fs = require('node:fs'), assert = require('node:assert/strict'); const data = JSON.parse(fs.readFileSync(0, 'utf8')); diff --git a/tests/test_optimization_trace.py b/tests/apps/test_optimization_trace.py similarity index 100% rename from tests/test_optimization_trace.py rename to tests/apps/test_optimization_trace.py diff --git a/tests/test_plugin_source_version.py b/tests/apps/test_plugin_source_version.py similarity index 100% rename from tests/test_plugin_source_version.py rename to tests/apps/test_plugin_source_version.py diff --git a/tests/test_profile_story_checks.py b/tests/apps/test_profile_story_checks.py similarity index 74% rename from tests/test_profile_story_checks.py rename to tests/apps/test_profile_story_checks.py index 76d99ac95..37b9fa848 100644 --- a/tests/test_profile_story_checks.py +++ b/tests/apps/test_profile_story_checks.py @@ -7,15 +7,15 @@ from pathlib import Path import pytest -from test_optimization_story import campaign, log_document, write_log -from test_profile_timeline import fixture as profile_fixture from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard, write_dashboard from inferrsi.harness.records.profile_timeline import attach_profile +from tests.apps.test_optimization_story import campaign, log_document, write_log +from tests.apps.test_profile_timeline import fixture as profile_fixture def test_published_profile_example_matches_fixture(tmp_path): - repo = Path(__file__).resolve().parents[1] + repo = Path(__file__).resolve().parents[2] script = repo / "tests/fixtures/dashboard_profile_review.py" subprocess.run([sys.executable, str(script), str(tmp_path)], check=True) published = repo / "docs/examples/dashboard-profile-review.html" @@ -39,7 +39,7 @@ def test_profile_review_displays_narrative_evidence_conflicts(tmp_path, conflict def _check_page(html, mode): - script = Path(__file__).with_name("check_profile_review.cjs") + script = Path(__file__).parents[1] / "check_profile_review.cjs" subprocess.run([shutil.which("node"), str(script), str(html), mode], check=True) @@ -78,29 +78,26 @@ def test_profile_review_renders_baseline_link_states_and_partial_timings(tmp_pat _check_page(html, "timing") -def test_profile_and_trace_shortcuts_open_recorded_evidence(tmp_path): +def test_profile_and_trace_shortcuts_open_recorded_evidence(browser, tmp_path): playwright = pytest.importorskip("playwright.sync_api") source, review = profile_fixture(tmp_path) review.write_text(json.dumps({**json.loads(review.read_bytes()), "started_at": "2026-11-11T08:41:43Z"})) attach_profile(tmp_path, capture_id="baseline", source=f"profiles/{source.name}", review=review) url = write_dashboard(tmp_path).as_uri() - with playwright.sync_playwright() as driver: - browser = driver.chromium.launch() - page = browser.new_page() - page.goto(url + "#profiles") - profile = page.locator('[data-key="profile:baseline-timeline"]') - playwright.expect(profile.locator("canvas:visible").first).to_be_visible() - playwright.expect(profile.locator(":scope > summary")).to_be_focused() - page.locator('[data-key="profile:baseline"] > summary').click() - page.locator("#profiles-link").click() - playwright.expect(profile.locator("canvas:visible").first).to_be_visible() - page.locator("#trace-link").click() - trace = page.locator('[data-key="experiment-all"]') - playwright.expect(trace.locator("tbody")).to_contain_text("Warm worker") - playwright.expect(trace.locator(":scope > summary")).to_be_focused() - page.locator("#language").click() - playwright.expect(trace.locator("tbody")).to_be_visible() - page.reload() - playwright.expect(trace.locator("tbody")).to_be_visible() - browser.close() + page = browser.new_page() + page.goto(url + "#profiles") + profile = page.locator('[data-key="profile:baseline-timeline"]') + playwright.expect(profile.locator("canvas:visible").first).to_be_visible() + playwright.expect(profile.locator(":scope > summary")).to_be_focused() + page.locator('[data-key="profile:baseline"] > summary').click() + page.locator("#profiles-link").click() + playwright.expect(profile.locator("canvas:visible").first).to_be_visible() + page.locator("#trace-link").click() + trace = page.locator('[data-key="experiment-all"]') + playwright.expect(trace.locator("tbody")).to_contain_text("Warm worker") + playwright.expect(trace.locator(":scope > summary")).to_be_focused() + page.locator("#language").click() + playwright.expect(trace.locator("tbody")).to_be_visible() + page.reload() + playwright.expect(trace.locator("tbody")).to_be_visible() diff --git a/tests/test_profile_timeline.py b/tests/apps/test_profile_timeline.py similarity index 99% rename from tests/test_profile_timeline.py rename to tests/apps/test_profile_timeline.py index 9a10e05f3..e3b076df4 100644 --- a/tests/test_profile_timeline.py +++ b/tests/apps/test_profile_timeline.py @@ -253,7 +253,7 @@ def test_profile_and_search_parse_equivalent_stamps_at_attach_and_read(tmp_path, def test_snapshot_joins_verified_search_to_registered_profile(tmp_path): - from test_optimization_story import campaign, log_document, write_log + from tests.apps.test_optimization_story import campaign, log_document, write_log write_log(tmp_path, log_document(campaign(tmp_path))) manifest = tmp_path / "campaign.json" diff --git a/tests/test_project_explanation.py b/tests/apps/test_project_explanation.py similarity index 100% rename from tests/test_project_explanation.py rename to tests/apps/test_project_explanation.py diff --git a/tests/test_project_optimization.py b/tests/apps/test_project_optimization.py similarity index 100% rename from tests/test_project_optimization.py rename to tests/apps/test_project_optimization.py diff --git a/tests/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py similarity index 91% rename from tests/test_project_service_reuse.py rename to tests/apps/test_project_service_reuse.py index 6f40dc38d..c5e345933 100644 --- a/tests/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -10,180 +10,12 @@ import pytest -from inferrsi.apps import artifacts from inferrsi.apps.cli import main from inferrsi.apps.cli.arguments import parser -from inferrsi.harness import artifact_primitives, optimization, project_service -from inferrsi.harness.records import evidence, knowledge_capture -from inferrsi.knowledge import knowledge_operations -from tests.diagnosis_support import diagnosis_args - - -@pytest.fixture(autouse=True) -def no_fingerprints(monkeypatch): - calls = [] - - def forbidden(*args, **kwargs): - calls.append(True) - raise AssertionError("This test must not calculate or verify a file fingerprint") - - # Keep imported functions intact; only their defining modules see the guard. - for module in ( - artifact_primitives, artifacts, evidence, knowledge_capture, knowledge_operations, - ): - monkeypatch.setattr(module, "hashlib", SimpleNamespace(sha256=forbidden)) - yield - assert not calls, "A fingerprint call was attempted, even if execution caught its exception" - - -def commit(repo, **changes): - config = {"version": "baseline", "a": 100, "b": 100, "quality": 1} - config.update(changes) - (repo / "engine.py").write_text("CONFIG = " + repr(config) + "\n", encoding="utf-8") - for args in ( - ("add", "engine.py"), - ( - "-c", - "user.name=Fixture", - "-c", - "user.email=fixture@example.invalid", - "-c", - "commit.gpgsign=false", - "commit", - "-qm", - "Synthetic version", - ), - ): - subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True) - - -def settings(): - return { - "schema_version": 1, - "protocol_id": "synthetic-service-control", - "conditions": { - "id": "c0", - "workload": "synthetic", - "model": "synthetic", - "precision": "integers", - "topology": "one-cpu-process", - "runtime": "stdlib", - "timing_scope": "synthetic-value", - "effective_config": {"mode": "fixture"}, - }, - "commands": { - name: [ - "{python}", - "{protocol}/protocol.py", - name, - "{candidate}", - "{service_receipt}", - "{result}", - ] - for name in ( - "precheck", - "service", - "ready", - "warmup", - "measure", - "quality", - "profile", - "stop", - ) - }, - "sampling": { - "stage_timeout_seconds": 8, - **{ - role: {"repetitions": 2, "warmups": 1} - for role in ("baseline", "candidate", "final") - }, - }, - "scenarios": [ - {"id": name, "workload": "synthetic-" + name, "requests": 2, "required_successes": 2} - for name in ("a", "b") - ], - "objectives": [ - { - "id": name, - "scenario": name, - "key": "latency", - "unit": "ms", - "domain": {"min": 0, "max": 10000}, - "direction": "minimize", - "aggregate": "median", - "threshold_type": "relative_percent", - "gain": True, - "gain_threshold": 4, - "parent_regression_limit": 3, - "cumulative_regression_limit": 3, - } - for name in ("a", "b") - ], - "ranking": ["a", "b"], - "quality": { - "mode": "absolute", - "dataset": "synthetic", - "scorer": "exact-v1", - "samples": 2, - "key": "quality", - "direction": "maximize", - "threshold": 1, - }, - "stagnation": {"rounds": 2, "action": "advisory"}, - } - - -@pytest.fixture -def campaign(tmp_path, capsys): - repo, protocol, root = (tmp_path / name for name in ("repo", "protocol", "campaign")) - repo.mkdir() - subprocess.run(["git", "-C", str(repo), "init", "-q"], check=True) - commit(repo) - protocol.mkdir() - shutil.copyfile( - Path(__file__).parent / "fixtures/service_reuse_protocol.py", protocol / "protocol.py" - ) - instructions = tmp_path / "TASK.md" - instructions.write_text("Synthetic service control; no model claims.") - configuration = tmp_path / "evaluation.json" - configuration.write_text(json.dumps(settings())) - args = [ - "campaign", - "start", - "--session", - str(root), - "--repo", - str(repo), - "--include", - "engine.py", - "--protocol", - str(protocol), - "--instructions", - str(instructions), - "--evaluation-mode", - "service_reuse", - "--evaluation-config", - str(configuration), - "--rounds", - "8", - "--max-minutes", - "10", - "--evaluation-timeout-seconds", - "25", - "--final-reserve-seconds", - "30", - ] - return {"repo": repo, "root": root, "start": args, "config": configuration, "capsys": capsys} - - -def call(campaign, action, *extra, expected=0): - args = ( - campaign["start"] - if action == "start" - else ["campaign", action, "--session", str(campaign["root"]), *map(str, extra)] - ) - assert main(args) == expected - return json.loads(campaign["capsys"].readouterr().out) +from inferrsi.harness import optimization, project_service +from tests.fixtures.service_reuse import begin, call, commit, diagnose, rejected, settings, submit +from tests.fixtures.service_reuse import campaign as campaign +from tests.fixtures.service_reuse import no_fingerprints as no_fingerprints def test_diagnosis_gate_applies_to_service_knowledge(campaign, tmp_path): @@ -230,29 +62,6 @@ def test_diagnosis_gate_applies_to_service_knowledge(campaign, tmp_path): optimization.read_records(campaign["root"]) -def diagnose(campaign): - assert main(diagnosis_args(campaign["root"], "campaign")) == 0 - campaign["capsys"].readouterr() - - -def begin(campaign): - result = call(campaign, "start") - assert result["next_action"] == "campaign_baseline" - assert not (campaign["root"] / "baseline").exists() - result = call(campaign, "baseline") - assert result["best"]["kind"] == "baseline" - diagnose(campaign) - return result - - -def submit(campaign, *, expected=0, retry=None, **changes): - commit(campaign["repo"], **changes) - args = ["--candidate", campaign["repo"], "--hypothesis", "Synthetic committed candidate"] - if retry: - args += ["--retry-of", retry, "--repair-reason", "Investigated and repaired fixture"] - return call(campaign, "round", *args, expected=expected) - - def events(campaign, attempt): path = campaign["root"] / attempt["path"] / "events.jsonl" return [json.loads(line) for line in path.read_text().splitlines()] @@ -764,12 +573,6 @@ def test_invalid_protocol_containers_rejected_before_campaign_writes(campaign, b assert not campaign["root"].exists() -def rejected(arguments): - with pytest.raises(SystemExit) as raised: - main(arguments) - return raised.value.code - - def test_live_dashboard_state_has_no_content_fingerprint(campaign): import threading from urllib.request import urlopen diff --git a/tests/test_request_guard.py b/tests/apps/test_request_guard.py similarity index 100% rename from tests/test_request_guard.py rename to tests/apps/test_request_guard.py diff --git a/tests/test_request_guard_deadline.py b/tests/apps/test_request_guard_deadline.py similarity index 100% rename from tests/test_request_guard_deadline.py rename to tests/apps/test_request_guard_deadline.py diff --git a/tests/test_result_delivery.py b/tests/apps/test_result_delivery.py similarity index 97% rename from tests/test_result_delivery.py rename to tests/apps/test_result_delivery.py index 1b92fbbeb..40450c3e7 100644 --- a/tests/test_result_delivery.py +++ b/tests/apps/test_result_delivery.py @@ -749,32 +749,29 @@ def changed(snapshot): @pytest.mark.parametrize("missing_observation", [False, True]) -def test_offline_html_remains_readable_without_scripts_or_network(tmp_path, missing_observation): - playwright = pytest.importorskip("playwright.sync_api") +def test_offline_html_remains_readable_without_scripts_or_network( + browser, tmp_path, missing_observation): root = make_campaign(tmp_path) if missing_observation: (root / state(root)["final"]["path"] / "observation.json").unlink() _, output = export(root, tmp_path) - with playwright.sync_playwright() as driver: - browser = driver.chromium.launch() - page = browser.new_page(java_script_enabled=False, offline=True) - requests = [] - page.on("request", lambda request: requests.append(request.url)) - page.goto((output / "report.html").as_uri()) - assert page.locator("h1").inner_text() == "RSI result report" - conclusion = page.locator("body > p").first.inner_text() - expected = "completed: undetermined" if missing_observation else "completed: improved" - assert expected in conclusion - if missing_observation: - assert "Original assessment: PASS (cached state; unverified)" in conclusion - assert "Cached historical assessment" in page.locator(".gaps").inner_text() - assert page.get_by_role("img").count() == 1 - page.locator("details summary").click() - assert ( - '"schema_id": "inferrsi.campaign-delivery"' in page.locator("details pre").inner_text() - ) - assert not [url for url in requests if url.startswith(("http:", "https:"))] - browser.close() + page = browser.new_page(java_script_enabled=False, offline=True) + requests = [] + page.on("request", lambda request: requests.append(request.url)) + page.goto((output / "report.html").as_uri()) + assert page.locator("h1").inner_text() == "RSI result report" + conclusion = page.locator("body > p").first.inner_text() + expected = "completed: undetermined" if missing_observation else "completed: improved" + assert expected in conclusion + if missing_observation: + assert "Original assessment: PASS (cached state; unverified)" in conclusion + assert "Cached historical assessment" in page.locator(".gaps").inner_text() + assert page.get_by_role("img").count() == 1 + page.locator("details summary").click() + assert ( + '"schema_id": "inferrsi.campaign-delivery"' in page.locator("details pre").inner_text() + ) + assert not [url for url in requests if url.startswith(("http:", "https:"))] @pytest.fixture diff --git a/tests/test_retrieval_projection.py b/tests/apps/test_retrieval_projection.py similarity index 99% rename from tests/test_retrieval_projection.py rename to tests/apps/test_retrieval_projection.py index 7e0200114..b89844c1d 100644 --- a/tests/test_retrieval_projection.py +++ b/tests/apps/test_retrieval_projection.py @@ -16,7 +16,7 @@ from inferrsi.apps.views.search_attribution import import_search from inferrsi.knowledge.catalog import search_knowledge -FIXTURE = runpy.run_path(str(Path(__file__).parent / "fixtures/knowledge_retrieval.py")) +FIXTURE = runpy.run_path(str(Path(__file__).parents[1] / "fixtures/knowledge_retrieval.py")) @pytest.fixture diff --git a/tests/test_round_citations.py b/tests/apps/test_round_citations.py similarity index 95% rename from tests/test_round_citations.py rename to tests/apps/test_round_citations.py index cc13c34db..6d80e980f 100644 --- a/tests/test_round_citations.py +++ b/tests/apps/test_round_citations.py @@ -4,16 +4,16 @@ import sys import pytest -from test_codex_knowledge_search import QUERY, REF, _cli, _import, _operation -from test_optimization_session import session as session -from test_optimization_session import task as task -from test_optimization_story import log_document -from test_project_optimization import project as project -from test_project_optimization import start from inferrsi.apps.cli import main from inferrsi.apps.views.dashboard import dashboard_snapshot from inferrsi.apps.workflows.campaign import create_campaign +from tests.apps.test_codex_knowledge_search import QUERY, REF, _cli, _import, _operation +from tests.apps.test_optimization_session import session as session +from tests.apps.test_optimization_session import task as task +from tests.apps.test_optimization_story import log_document +from tests.apps.test_project_optimization import project as project +from tests.apps.test_project_optimization import start QUOTE = "NPU OOM." REASON = f"Score each row immediately to avoid retaining all masks [use {REF} | {QUOTE}]." diff --git a/tests/test_round_decisions_browser.py b/tests/apps/test_round_decisions_browser.py similarity index 90% rename from tests/test_round_decisions_browser.py rename to tests/apps/test_round_decisions_browser.py index 2daa856b7..4d47ac14d 100644 --- a/tests/test_round_decisions_browser.py +++ b/tests/apps/test_round_decisions_browser.py @@ -5,26 +5,18 @@ from contextlib import contextmanager import pytest -from test_optimization_story import campaign, log_document, write_log -from test_optimization_trace import record, setup_campaign, trace_document, write_trace -from test_retrieval_projection import FIXTURE from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard from inferrsi.apps.views.dashboard_live import DashboardServer from inferrsi.harness.records.campaign_records import record_decision +from tests.apps.test_optimization_story import campaign, log_document, write_log +from tests.apps.test_optimization_trace import record, setup_campaign, trace_document, write_trace +from tests.apps.test_retrieval_projection import FIXTURE playwright = pytest.importorskip("playwright.sync_api") expect = playwright.expect -@pytest.fixture(scope="module") -def browser(): - with playwright.sync_playwright() as driver: - instance = driver.chromium.launch(args=["--disable-gpu"]) - yield instance - instance.close() - - @contextmanager def dashboard(browser, root, profile, live=False, snapshot=None): manifest = root / "campaign.json" @@ -70,12 +62,12 @@ def dashboard(browser, root, profile, live=False, snapshot=None): @pytest.mark.parametrize("profile", [False, True]) @pytest.mark.parametrize("live", [False, True]) -def test_round_chain_navigation_and_refresh(browser, tmp_path, profile, live): +def test_round_chain_navigation_and_refresh(cpu_browser, tmp_path, profile, live): doc = log_document(campaign(tmp_path)) record_decision(tmp_path, candidate_id="b", round_number=2, outcome="rejected") write_log(tmp_path, doc) row = dashboard_snapshot(tmp_path)["data"]["candidates"][0] - with dashboard(browser, tmp_path, profile, live) as page: + with dashboard(cpu_browser, tmp_path, profile, live) as page: root = page.locator("#round-decisions") stages = [root.locator(f'[data-rd-stage="{i}"]') for i in range(1, 5)] retrieval, alternatives, choice, result = stages @@ -134,13 +126,13 @@ def test_round_chain_navigation_and_refresh(browser, tmp_path, profile, live): @pytest.mark.parametrize("profile", [False, True]) -def test_missing_round_and_snapshot_do_not_invent_first_round(browser, tmp_path, profile): +def test_missing_round_and_snapshot_do_not_invent_first_round(cpu_browser, tmp_path, profile): campaign(tmp_path) snapshot = dashboard_snapshot(tmp_path) for row in snapshot["data"]["candidates"]: row["round"] = None row["decision"] = "not_recorded" - with dashboard(browser, tmp_path, profile, snapshot=snapshot) as page: + with dashboard(cpu_browser, tmp_path, profile, snapshot=snapshot) as page: root = page.locator("#round-decisions") expect(root.locator("select option")).to_have_text(["Round not recorded"]) expect(root).to_contain_text("Their order does not establish a first round") @@ -152,13 +144,13 @@ def test_missing_round_and_snapshot_do_not_invent_first_round(browser, tmp_path, @pytest.mark.parametrize("profile", [False, True]) -def test_round_trace_preserves_declared_alternatives_and_attempt(browser, tmp_path, profile): +def test_round_trace_preserves_declared_alternatives_and_attempt(cpu_browser, tmp_path, profile): setup_campaign(tmp_path) doc = trace_document() doc["search_space"]["items"][0]["description"] = "" write_trace(tmp_path / "optimization.json", doc) record(tmp_path) - with dashboard(browser, tmp_path, profile) as page: + with dashboard(cpu_browser, tmp_path, profile) as page: root = page.locator("#round-decisions") alternatives = root.locator('[data-rd-stage="2"]') expect(alternatives).to_contain_text("An option not yet attempted") @@ -174,12 +166,12 @@ def test_round_trace_preserves_declared_alternatives_and_attempt(browser, tmp_pa @pytest.mark.parametrize("profile", [False, True]) -def test_multiple_runs_and_conflicts_remain_visible(browser, tmp_path, profile): +def test_multiple_runs_and_conflicts_remain_visible(cpu_browser, tmp_path, profile): FIXTURE["build"](tmp_path) snapshot = dashboard_snapshot(tmp_path) rows = snapshot["data"]["candidates"] round_number = next(row["round"] for row in rows if row["run_id"] == "retry") - with dashboard(browser, tmp_path, profile) as page: + with dashboard(cpu_browser, tmp_path, profile) as page: root = page.locator("#round-decisions") root.locator("select").select_option(str(round_number)) result = root.locator('[data-rd-stage="4"]') @@ -202,7 +194,7 @@ def test_multiple_runs_and_conflicts_remain_visible(browser, tmp_path, profile): @pytest.mark.parametrize("profile", [False, True]) -def test_tampered_capture_and_decision_conflict_are_not_hidden(browser, tmp_path, profile): +def test_tampered_capture_and_decision_conflict_are_not_hidden(cpu_browser, tmp_path, profile): doc = log_document(campaign(tmp_path)) doc["iterations"][0]["decision"]["outcome"] = "rejected" write_log(tmp_path, doc) @@ -211,7 +203,7 @@ def test_tampered_capture_and_decision_conflict_are_not_hidden(browser, tmp_path capture = json.loads(path.read_text()) capture["assembled_text"] += "tampered" path.write_text(json.dumps(capture)) - with dashboard(browser, tmp_path, profile) as page: + with dashboard(cpu_browser, tmp_path, profile) as page: root = page.locator("#round-decisions") retrieval = root.locator('[data-rd-stage="1"]') expect(retrieval).not_to_contain_text("Context assembled") @@ -222,12 +214,12 @@ def test_tampered_capture_and_decision_conflict_are_not_hidden(browser, tmp_path @pytest.mark.parametrize("profile", [False, True]) -def test_shared_context_conflict_and_zero_hits_stay_distinct(browser, tmp_path, profile): +def test_shared_context_conflict_and_zero_hits_stay_distinct(cpu_browser, tmp_path, profile): FIXTURE["build"](tmp_path) doc = json.loads((tmp_path / "review-input.json").read_text()) doc["iterations"][1]["context_ids"].append("capture") write_log(tmp_path, doc) - with dashboard(browser, tmp_path, profile) as page: + with dashboard(cpu_browser, tmp_path, profile) as page: root = page.locator("#round-decisions") root.locator("select").select_option("2") retrieval = root.locator('[data-rd-stage="1"]') @@ -243,12 +235,12 @@ def test_shared_context_conflict_and_zero_hits_stay_distinct(browser, tmp_path, @pytest.mark.parametrize("profile", [False, True]) def test_run_navigation_without_experiment_ids_uses_exact_round_candidate_run( - browser, tmp_path, profile): + cpu_browser, tmp_path, profile): campaign(tmp_path) snapshot = dashboard_snapshot(tmp_path) for row in snapshot["data"]["candidates"]: row.pop("experiment_id") - with dashboard(browser, tmp_path, profile, snapshot=snapshot) as page: + with dashboard(cpu_browser, tmp_path, profile, snapshot=snapshot) as page: root = page.locator("#round-decisions") root.locator("select").select_option("2") root.get_by_role("button", name="Open run evidence").click() @@ -262,14 +254,16 @@ def test_run_navigation_without_experiment_ids_uses_exact_round_candidate_run( @pytest.mark.parametrize("profile", [False, True]) @pytest.mark.parametrize("experiment_ids", [False, True]) -def test_duplicate_run_identities_disable_navigation(browser, tmp_path, profile, experiment_ids): +def test_duplicate_run_identities_disable_navigation( + cpu_browser, tmp_path, profile, experiment_ids, +): campaign(tmp_path) snapshot = dashboard_snapshot(tmp_path) rows = snapshot["data"]["candidates"] if not experiment_ids: rows[0].pop("experiment_id") rows.append(dict(rows[0])) - with dashboard(browser, tmp_path, profile, snapshot=snapshot) as page: + with dashboard(cpu_browser, tmp_path, profile, snapshot=snapshot) as page: result = page.locator('#round-decisions [data-rd-stage="4"]') expect(result.get_by_text("Ambiguous candidate/run identity", exact=True)).to_have_count(2) expect(result.get_by_role("button", name="Open run evidence")).to_have_count(0) @@ -277,7 +271,9 @@ def test_duplicate_run_identities_disable_navigation(browser, tmp_path, profile, @pytest.mark.parametrize("profile", [False, True]) @pytest.mark.parametrize("live", [False, True]) -def test_shared_search_only_round_preserves_queries_and_requests(browser, tmp_path, profile, live): +def test_shared_search_only_round_preserves_queries_and_requests( + cpu_browser, tmp_path, profile, live, +): FIXTURE["build"](tmp_path) path = tmp_path / "search/round-3.json" search = json.loads(path.read_text()) @@ -293,7 +289,7 @@ def test_shared_search_only_round_preserves_queries_and_requests(browser, tmp_pa {"id": "missing:1", "action": "search", "tool": "rg", "materials": []}, ] path.write_text(json.dumps(search)) - with dashboard(browser, tmp_path, profile, live) as page: + with dashboard(cpu_browser, tmp_path, profile, live) as page: root = page.locator("#round-decisions") root.locator("select").select_option("3") retrieval = root.locator('[data-rd-stage="1"]') @@ -317,12 +313,12 @@ def test_shared_search_only_round_preserves_queries_and_requests(browser, tmp_pa @pytest.mark.parametrize("profile", [False, True]) -def test_external_experiment_ids_disambiguate_missing_round_run(browser, tmp_path, profile): +def test_external_experiment_ids_disambiguate_missing_round_run(cpu_browser, tmp_path, profile): campaign(tmp_path) snapshot = dashboard_snapshot(tmp_path) for row in snapshot["data"]["candidates"]: row.update(round=None, candidate_id="external", run_id=None) - with dashboard(browser, tmp_path, profile, snapshot=snapshot) as page: + with dashboard(cpu_browser, tmp_path, profile, snapshot=snapshot) as page: result = page.locator('#round-decisions [data-rd-stage="4"]') expect(result.get_by_role("button", name="Open run evidence")).to_have_count(2) expect(result).not_to_contain_text("Ambiguous") @@ -334,7 +330,7 @@ def test_external_experiment_ids_disambiguate_missing_round_run(browser, tmp_pat expect(page.locator("#run-review strong").first).to_have_text("B") -def test_managed_round_knowledge_and_measured_score(browser, tmp_path): +def test_managed_round_knowledge_and_measured_score(cpu_browser, tmp_path): campaign(tmp_path) snapshot = dashboard_snapshot(tmp_path) data = snapshot["data"] @@ -362,7 +358,7 @@ def test_managed_round_knowledge_and_measured_score(browser, tmp_path): "retrieval_round": 1, "page": 1}], } data["candidates"] = [row] - with dashboard(browser, tmp_path, False, snapshot=snapshot) as page: + with dashboard(cpu_browser, tmp_path, False, snapshot=snapshot) as page: root = page.locator("#round-decisions") retrieval, result = (root.locator(f'[data-rd-stage="{i}"]') for i in (1, 4)) expect(retrieval).to_contain_text("Query · tile sizes") diff --git a/tests/test_runtime.py b/tests/apps/test_runtime.py similarity index 98% rename from tests/test_runtime.py rename to tests/apps/test_runtime.py index ae6987ae0..200744374 100644 --- a/tests/test_runtime.py +++ b/tests/apps/test_runtime.py @@ -398,10 +398,7 @@ def test_non_utf8_name_does_not_cost_a_complete_run_its_artifacts(self): self.assertEqual(evaluation["verdict"], "INCONCLUSIVE") self.assertFalse(evaluation["source_integrity"]["verified"]) - def test_unreadable_submodule_identity_names_the_path_instead_of_a_key_error(self): - # repository_identity returns only path/available/error on failure, so - # reading snapshot_hash raised KeyError inside the run's finally block. - superproject = self.make_superproject() + def unreadable_submodule(self, superproject): submodule = (superproject / "sub").resolve() real_run = subprocess.run @@ -412,7 +409,13 @@ def ls_files_only(argv, **kwargs): return subprocess.CompletedProcess(argv, 0, stdout=stdout, stderr=b"") return real_run(argv, **kwargs) - with patch("subprocess.run", side_effect=ls_files_only): + return patch("subprocess.run", side_effect=ls_files_only) + + def test_unreadable_submodule_identity_names_the_path_instead_of_a_key_error(self): + # repository_identity returns only path/available/error on failure, so + # reading snapshot_hash raised KeyError inside the run's finally block. + superproject = self.make_superproject() + with self.unreadable_submodule(superproject): identity = repository_identity(superproject) self.assertFalse(identity["available"]) self.assertIn("Submodule sub", identity["error"]) @@ -420,17 +423,7 @@ def ls_files_only(argv, **kwargs): def test_unreadable_submodule_identity_keeps_run_artifacts(self): superproject = self.make_superproject() - submodule = (superproject / "sub").resolve() - real_run = subprocess.run - - def ls_files_only(argv, **kwargs): - if "ls-files" in argv and "--others" in argv: - target = Path(argv[argv.index("-C") + 1]).resolve() - stdout = b"bad-\xff.txt\x00" if target == submodule else b"" - return subprocess.CompletedProcess(argv, 0, stdout=stdout, stderr=b"") - return real_run(argv, **kwargs) - - with patch("subprocess.run", side_effect=ls_files_only): + with self.unreadable_submodule(superproject): path, evaluation = self.run_spec(candidate_repo=str(superproject), repetitions=1) self.assertTrue((path / "evaluation.json").is_file()) self.assertTrue((path / "report.html").is_file()) diff --git a/tests/test_search_archive.py b/tests/apps/test_search_archive.py similarity index 100% rename from tests/test_search_archive.py rename to tests/apps/test_search_archive.py diff --git a/tests/test_search_attribution.py b/tests/apps/test_search_attribution.py similarity index 99% rename from tests/test_search_attribution.py rename to tests/apps/test_search_attribution.py index 9d299226a..8669db1ea 100644 --- a/tests/test_search_attribution.py +++ b/tests/apps/test_search_attribution.py @@ -13,7 +13,7 @@ from inferrsi.apps.workflows.campaign import capture_context, create_campaign from inferrsi.harness.records.optimization_log import record_log -FIXTURE = runpy.run_path(str(Path(__file__).parent / "fixtures/knowledge_retrieval.py")) +FIXTURE = runpy.run_path(str(Path(__file__).parents[1] / "fixtures/knowledge_retrieval.py")) def command(corpus, cmd, output, event_id, exit_code=0): diff --git a/tests/test_search_capture_delivery.py b/tests/apps/test_search_capture_delivery.py similarity index 100% rename from tests/test_search_capture_delivery.py rename to tests/apps/test_search_capture_delivery.py diff --git a/tests/test_summary_chart.py b/tests/apps/test_summary_chart.py similarity index 99% rename from tests/test_summary_chart.py rename to tests/apps/test_summary_chart.py index 8248badd1..e09f5367a 100644 --- a/tests/test_summary_chart.py +++ b/tests/apps/test_summary_chart.py @@ -9,7 +9,7 @@ from inferrsi.apps.legacy.reporting import write_report from inferrsi.apps.views import summary_chart -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] EXAMPLES = PROJECT / "evidence" / "_template" / "results" NS = "{http://www.w3.org/2000/svg}" diff --git a/tests/test_task_input.py b/tests/apps/test_task_input.py similarity index 99% rename from tests/test_task_input.py rename to tests/apps/test_task_input.py index 6e0774779..bf3b14a34 100644 --- a/tests/test_task_input.py +++ b/tests/apps/test_task_input.py @@ -19,7 +19,7 @@ except ModuleNotFoundError: # Python 3.10: pytest supplies tomli. import tomli as tomllib -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] FIXTURES = REPO / "tests" / "fixtures" / "task-input" COMPLETE = FIXTURES / "complete.yaml" PARTIAL = FIXTURES / "partial.yaml" diff --git a/tests/test_task_plan_run.py b/tests/apps/test_task_plan_run.py similarity index 99% rename from tests/test_task_plan_run.py rename to tests/apps/test_task_plan_run.py index 4ae716125..8d77f6fda 100644 --- a/tests/test_task_plan_run.py +++ b/tests/apps/test_task_plan_run.py @@ -19,7 +19,7 @@ from inferrsi.apps.legacy import run as legacy_run from inferrsi.contracts import RunSpec -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] FIXTURES = REPO / "tests" / "fixtures" / "task-input" COMPLETE = FIXTURES / "complete.yaml" PARTIAL = FIXTURES / "partial.yaml" diff --git a/tests/test_trial_checks.py b/tests/apps/test_trial_checks.py similarity index 59% rename from tests/test_trial_checks.py rename to tests/apps/test_trial_checks.py index 80c4c2086..643858461 100644 --- a/tests/test_trial_checks.py +++ b/tests/apps/test_trial_checks.py @@ -1,4 +1,4 @@ -"""Qualification evidence must survive CLI, execution and adjudication.""" +"""Required trial checks govern execution, adjudication, and reporting.""" import json import subprocess @@ -9,23 +9,29 @@ from inferrsi.apps.cli.arguments import make_spec, parser from inferrsi.apps.legacy.evaluation import evaluate +from inferrsi.apps.legacy.reporting import write_report from inferrsi.apps.legacy.run import run_experiment +from inferrsi.apps.views.summary_chart import SpecError, spec_from_evaluation from inferrsi.contracts import RunSpec from inferrsi.harness.trials.external import collect_trial_checks -@pytest.mark.parametrize("value", [None, False, "true", 1, {}, []]) -@pytest.mark.parametrize("side", ["baseline", "candidate"]) -def test_unqualified_trial_cannot_publish_gain(value, side): +def evaluated_pair(checks, side="candidate"): spec = RunSpec(repo=".", repetitions=1, required_trial_checks=("evidence.closed",)) trials = { name: [{"status": "completed", "metric": metric, "trial_checks": {"evidence.closed": True}}] for name, metric in (("baseline", 100), ("candidate", 80)) } - trials[side][0]["trial_checks"]["evidence.closed"] = value - result = evaluate( + trials[side][0]["trial_checks"] = checks + return evaluate( spec, trials["baseline"], trials["candidate"], {"status": "completed"}, {"verified": True} ) + + +@pytest.mark.parametrize("value", [None, False, "true", 1, {}, []]) +@pytest.mark.parametrize("side", ["baseline", "candidate"]) +def test_unqualified_trial_cannot_publish_gain(value, side): + result = evaluated_pair({"evidence.closed": value}, side) assert result["verdict"] == "INCONCLUSIVE" assert result["improvement_pct"] is None assert any(f"{side} trial 1: required check evidence.closed" in r for r in result["reasons"]) @@ -127,3 +133,70 @@ def test_invalid_check_keys_rejected(tmp_path, keys): ) with pytest.raises(ValueError, match="required_trial_checks"): spec.validate() + + +def persist_report(directory, evaluation): + (directory / "evaluation.json").write_text(json.dumps(evaluation), encoding="utf-8") + return write_report(directory).read_text(encoding="utf-8") + + +@pytest.mark.parametrize("campaign", [False, True]) +@pytest.mark.parametrize( + ("checks", "side"), + [ + pytest.param(checks, side, id=f"{label}-{side}") + for checks, label in ( + ({}, "missing"), + ({"evidence.closed": False}, "false"), + ({"evidence.closed": "true"}, "not-boolean"), + ) + for side in ("baseline", "candidate") + ] + [pytest.param({"evidence.closed": True}, "candidate", id="qualified-candidate")], +) +def test_trial_evidence_controls_report_chart(tmp_path, checks, side, campaign): + if campaign: + historical = json.dumps(spec_from_evaluation(evaluated_pair({"evidence.closed": True}))) + specification = tmp_path / "summary-chart.json" + specification.write_text(historical, encoding="utf-8") + + result = evaluated_pair(checks, side) + html = persist_report(tmp_path, result) + svg = tmp_path / "summary-chart.svg" + if checks.get("evidence.closed") is True: + assert result["verdict"] == "PASS" + assert "0.80×" in html + assert "0.80×" in svg.read_text(encoding="utf-8") + else: + assert result["verdict"] == "INCONCLUSIVE" + assert result["improvement_pct"] is None + assert "raw measurements" in html + assert "required trial checks" in html + assert " None: + assert [(verdict.name, verdict.value) for verdict in Verdict] == [ + ("PASS", "PASS"), ("FAIL", "FAIL"), ("INCONCLUSIVE", "INCONCLUSIVE"), + ] + assert isinstance(Verdict.PASS, str) and Verdict.PASS == "PASS" + assert parse_verdict("pass") is Verdict.PASS + assert parse_verdict("FAIL") is Verdict.FAIL + + +def test_invalid_verdict() -> None: + with pytest.raises(ValueError) as caught: + parse_verdict("maybe") + assert str(caught.value) == "Invalid verdict 'maybe'; expected one of PASS, FAIL, INCONCLUSIVE" + + +def test_pass_requires_pins() -> None: + assert claim_requires_pinned_shas(Verdict.PASS) is True + assert claim_requires_pinned_shas(Verdict.FAIL) is False + assert claim_requires_pinned_shas(Verdict.INCONCLUSIVE) is False diff --git a/tests/test_contract_schema_patterns.py b/tests/contracts/test_contract_schema_patterns.py similarity index 98% rename from tests/test_contract_schema_patterns.py rename to tests/contracts/test_contract_schema_patterns.py index 5590d024d..ba1501910 100644 --- a/tests/test_contract_schema_patterns.py +++ b/tests/contracts/test_contract_schema_patterns.py @@ -18,7 +18,7 @@ import jsonschema import pytest -CONTRACTS = Path(__file__).resolve().parents[1] / "docs" / "contracts" +CONTRACTS = Path(__file__).resolve().parents[2] / "docs" / "contracts" SCHEMA = json.loads((CONTRACTS / "schemas" / "contract-v1.schema.json").read_text("utf-8")) VECTORS = json.loads( (CONTRACTS / "fixtures" / "pattern-boundary-cases.json").read_text("utf-8") diff --git a/tests/test_contracts_package.py b/tests/contracts/test_contracts_package.py similarity index 95% rename from tests/test_contracts_package.py rename to tests/contracts/test_contracts_package.py index 7ac566f68..6b66632b4 100644 --- a/tests/test_contracts_package.py +++ b/tests/contracts/test_contracts_package.py @@ -27,7 +27,7 @@ from inferrsi.contracts import RunSpec, claim, json_v1, runspec from inferrsi.harness import runner -SRC = Path(__file__).resolve().parents[1] / "src" +SRC = Path(__file__).resolve().parents[2] / "src" ROOT = SRC / "inferrsi" RETIRED = { "inferrsi._json_v1": ("_json_v1.py", "CanonicalError"), @@ -134,16 +134,6 @@ def test_harness_reexports_the_same_verdict_objects() -> None: assert harness.Verdict is claim.Verdict assert harness.parse_verdict is claim.parse_verdict assert claim.Verdict.__module__ == "inferrsi.contracts.claim" - assert [(verdict.name, verdict.value) for verdict in claim.Verdict] == [ - ("PASS", "PASS"), ("FAIL", "FAIL"), ("INCONCLUSIVE", "INCONCLUSIVE"), - ] - assert claim.parse_verdict("pass") is claim.Verdict.PASS - assert isinstance(claim.Verdict.PASS, str) and claim.Verdict.PASS == "PASS" - assert claim.claim_requires_pinned_shas(claim.Verdict.PASS) is True - assert claim.claim_requires_pinned_shas(claim.Verdict.FAIL) is False - with pytest.raises(ValueError) as caught: - claim.parse_verdict("maybe") - assert str(caught.value) == "Invalid verdict 'maybe'; expected one of PASS, FAIL, INCONCLUSIVE" @pytest.mark.parametrize("module", MODULES) diff --git a/tests/test_evidence_paths.py b/tests/contracts/test_evidence_paths.py similarity index 99% rename from tests/test_evidence_paths.py rename to tests/contracts/test_evidence_paths.py index d263c0a8d..ff7493b81 100644 --- a/tests/test_evidence_paths.py +++ b/tests/contracts/test_evidence_paths.py @@ -28,7 +28,7 @@ evidence_subpaths, ) -SRC = Path(__file__).resolve().parents[1] / "src" +SRC = Path(__file__).resolve().parents[2] / "src" ROOT = SRC / "inferrsi" RETIRED = "inferrsi.evidence_paths" # Path rules run first and must emit nothing; directory creation runs second under the diff --git a/tests/fixtures/find/README.md b/tests/fixtures/find/README.md index 06e56f8d6..f252671fa 100644 --- a/tests/fixtures/find/README.md +++ b/tests/fixtures/find/README.md @@ -47,4 +47,4 @@ Known qualifications, retained rather than repaired after seeing results: - Labels are one model's judgement, unreviewed by a second. `confidence` is self-reported. -Reproduce with `tests/test_knowledge_find.py::test_external_label_set_retrieval`. +Reproduce with `tests/knowledge/test_knowledge_find.py::test_external_label_set_retrieval`. diff --git a/tests/fixtures/harness-prepared-binding/README.md b/tests/fixtures/harness-prepared-binding/README.md index 8d0d8b008..9933dbc21 100644 --- a/tests/fixtures/harness-prepared-binding/README.md +++ b/tests/fixtures/harness-prepared-binding/README.md @@ -11,7 +11,7 @@ This is immutable contract-conformance input, not observed execution evidence or an available worker implementation. Tests compare the canonical Apps binder, Harness digest and read-only prepared projection. No process is started by these binding tests. Post-registration T37 is covered separately in -`tests/test_harness_entry_verification.py`; deadline/budget and T40 replay have -their own tests in `tests/test_harness_evaluation_replay.py`. Whole production +`tests/harness/test_harness_entry_verification.py`; deadline/budget and T40 replay have +their own tests in `tests/harness/test_harness_evaluation_replay.py`. Whole production integration retains its separate acceptance dependencies. The original documentary fixtures are not rewritten. diff --git a/tests/fixtures/optimization-session/README.md b/tests/fixtures/optimization-session/README.md index d5c641ed8..795ce12f0 100644 --- a/tests/fixtures/optimization-session/README.md +++ b/tests/fixtures/optimization-session/README.md @@ -17,7 +17,7 @@ that is not settled: | `pre-trials-rename-session/` | `75b9872`, `main` `7a7ab84` plus a docs-only commit | #558 renamed `harness/scenarios` to `harness/trials` | `harness/scenarios/external.py` | The current runtime refuses every one of them for `status` and `recover` before any operation runs -and leaves every file unchanged. `tests/test_optimization_session.py` checks this against the +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 `INFERRSI_PRE_CHANGE_SESSIONS`, which names this directory. Neither can run the old runtime: that needs the old commit installed in its own environment. @@ -39,7 +39,7 @@ Step 3 shows that recovery used the receipt and did not run the candidate again. To redo it for a later runtime change: build and install the old and the new wheel in separate environments, start the session with the old one (the synthetic task of -`tests/test_optimization_session.py`, `--rounds 3 --max-minutes 5 --evaluation-timeout-seconds 15 +`tests/apps/test_optimization_session.py`, `--rounds 3 --max-minutes 5 --evaluation-timeout-seconds 15 --python python`, run from a neutral directory so no host path enters the plan), stop its coordinator after the child completes, remove the empty `.session.lock`, and keep everything else. Add the new directory and its removed identity file to both tests. diff --git a/tests/fixtures/service_reuse.py b/tests/fixtures/service_reuse.py new file mode 100644 index 000000000..3257d6adf --- /dev/null +++ b/tests/fixtures/service_reuse.py @@ -0,0 +1,212 @@ +"""Synthetic campaign and CLI helpers for service-reuse tests.""" + +import json +import shutil +import subprocess +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from inferrsi.apps import artifacts +from inferrsi.apps.cli import main +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 + + +@pytest.fixture(autouse=True) +def no_fingerprints(monkeypatch): + calls = [] + + def forbidden(*args, **kwargs): + calls.append(True) + raise AssertionError("This test must not calculate or verify a file fingerprint") + + # Keep imported functions intact; only their defining modules see the guard. + for module in ( + artifact_primitives, artifacts, evidence, knowledge_capture, knowledge_operations, + ): + monkeypatch.setattr(module, "hashlib", SimpleNamespace(sha256=forbidden)) + yield + assert not calls, "A fingerprint call was attempted, even if execution caught its exception" + + +def commit(repo, **changes): + config = {"version": "baseline", "a": 100, "b": 100, "quality": 1} + config.update(changes) + (repo / "engine.py").write_text("CONFIG = " + repr(config) + "\n", encoding="utf-8") + for args in ( + ("add", "engine.py"), + ( + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "-c", + "commit.gpgsign=false", + "commit", + "-qm", + "Synthetic version", + ), + ): + subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True) + + +def settings(): + return { + "schema_version": 1, + "protocol_id": "synthetic-service-control", + "conditions": { + "id": "c0", + "workload": "synthetic", + "model": "synthetic", + "precision": "integers", + "topology": "one-cpu-process", + "runtime": "stdlib", + "timing_scope": "synthetic-value", + "effective_config": {"mode": "fixture"}, + }, + "commands": { + name: [ + "{python}", + "{protocol}/protocol.py", + name, + "{candidate}", + "{service_receipt}", + "{result}", + ] + for name in ( + "precheck", + "service", + "ready", + "warmup", + "measure", + "quality", + "profile", + "stop", + ) + }, + "sampling": { + "stage_timeout_seconds": 8, + **{ + role: {"repetitions": 2, "warmups": 1} + for role in ("baseline", "candidate", "final") + }, + }, + "scenarios": [ + {"id": name, "workload": "synthetic-" + name, "requests": 2, "required_successes": 2} + for name in ("a", "b") + ], + "objectives": [ + { + "id": name, + "scenario": name, + "key": "latency", + "unit": "ms", + "domain": {"min": 0, "max": 10000}, + "direction": "minimize", + "aggregate": "median", + "threshold_type": "relative_percent", + "gain": True, + "gain_threshold": 4, + "parent_regression_limit": 3, + "cumulative_regression_limit": 3, + } + for name in ("a", "b") + ], + "ranking": ["a", "b"], + "quality": { + "mode": "absolute", + "dataset": "synthetic", + "scorer": "exact-v1", + "samples": 2, + "key": "quality", + "direction": "maximize", + "threshold": 1, + }, + "stagnation": {"rounds": 2, "action": "advisory"}, + } + + +@pytest.fixture +def campaign(tmp_path, capsys): + repo, protocol, root = (tmp_path / name for name in ("repo", "protocol", "campaign")) + repo.mkdir() + subprocess.run(["git", "-C", str(repo), "init", "-q"], check=True) + commit(repo) + protocol.mkdir() + shutil.copyfile( + Path(__file__).with_name("service_reuse_protocol.py"), protocol / "protocol.py" + ) + instructions = tmp_path / "TASK.md" + instructions.write_text("Synthetic service control; no model claims.") + configuration = tmp_path / "evaluation.json" + configuration.write_text(json.dumps(settings())) + args = [ + "campaign", + "start", + "--session", + str(root), + "--repo", + str(repo), + "--include", + "engine.py", + "--protocol", + str(protocol), + "--instructions", + str(instructions), + "--evaluation-mode", + "service_reuse", + "--evaluation-config", + str(configuration), + "--rounds", + "8", + "--max-minutes", + "10", + "--evaluation-timeout-seconds", + "25", + "--final-reserve-seconds", + "30", + ] + return {"repo": repo, "root": root, "start": args, "config": configuration, "capsys": capsys} + + +def call(campaign, action, *extra, expected=0): + args = ( + campaign["start"] + if action == "start" + else ["campaign", action, "--session", str(campaign["root"]), *map(str, extra)] + ) + assert main(args) == expected + return json.loads(campaign["capsys"].readouterr().out) + + +def diagnose(campaign): + assert main(diagnosis_args(campaign["root"], "campaign")) == 0 + campaign["capsys"].readouterr() + + +def begin(campaign): + result = call(campaign, "start") + assert result["next_action"] == "campaign_baseline" + assert not (campaign["root"] / "baseline").exists() + result = call(campaign, "baseline") + assert result["best"]["kind"] == "baseline" + diagnose(campaign) + return result + + +def submit(campaign, *, expected=0, retry=None, **changes): + commit(campaign["repo"], **changes) + args = ["--candidate", campaign["repo"], "--hypothesis", "Synthetic committed candidate"] + if retry: + args += ["--retry-of", retry, "--repair-reason", "Investigated and repaired fixture"] + return call(campaign, "round", *args, expected=expected) + + +def rejected(arguments): + with pytest.raises(SystemExit) as raised: + main(arguments) + return raised.value.code diff --git a/tests/fixtures/skill-eval-pr/summary-example.md b/tests/fixtures/skill-eval-pr/summary-example.md index 26c9dc7db..c6aa2f37d 100644 --- a/tests/fixtures/skill-eval-pr/summary-example.md +++ b/tests/fixtures/skill-eval-pr/summary-example.md @@ -29,7 +29,7 @@ observed-token stop threshold 200. The fixed client records **10 calls**; no rea model calls occur. Monetary cost is unknown. Publication retry updates the same single simulated comment with **zero additional evaluation calls**. -The [offline integration control](../../../tests/test_skill_eval_pr.py) verifies +The [offline integration control](../../skill_eval/test_skill_eval_pr.py) verifies these outcomes, including addition/update, lost publication response, stale heads and retained evidence validation. The [demo command](../../../tests/fixtures/skill_eval_pr_demo.py) saves the complete diff --git a/tests/fixtures/task-input/README.md b/tests/fixtures/task-input/README.md index 865245aee..9f7dfcacb 100644 --- a/tests/fixtures/task-input/README.md +++ b/tests/fixtures/task-input/README.md @@ -11,9 +11,9 @@ template under `src/inferrsi/apps/cli/task-input/v1/`). See | `partial.yaml` | The partial draft from the governing issue: valid, with field-level blockers | | `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/test_task_input.py` checks the Python contract and the packaged JSON Schema +`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 -installed wheel outside the checkout. `tests/test_task_plan_run.py` uses `complete.yaml` +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 acceptance flags, field errors before any probe or write, and the run's frozen gate and diff --git a/tests/harness/__init__.py b/tests/harness/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_campaign_trace.py b/tests/harness/test_campaign_trace.py similarity index 100% rename from tests/test_campaign_trace.py rename to tests/harness/test_campaign_trace.py diff --git a/tests/test_confinement.py b/tests/harness/test_confinement.py similarity index 99% rename from tests/test_confinement.py rename to tests/harness/test_confinement.py index 13542118b..0c4d656c4 100644 --- a/tests/test_confinement.py +++ b/tests/harness/test_confinement.py @@ -289,7 +289,7 @@ def test_runtime_roots_under_system_python_exclude_usr(): stdlib=sysconfig.get_path("stdlib"), ) return - repo = Path(__file__).resolve().parents[1] + repo = Path(__file__).resolve().parents[2] script = ( "import json, sys, sysconfig\n" "sys.path[:0] = %r\n" diff --git a/tests/test_harness_entry_verification.py b/tests/harness/test_harness_entry_verification.py similarity index 87% rename from tests/test_harness_entry_verification.py rename to tests/harness/test_harness_entry_verification.py index 727c213f4..748753f51 100644 --- a/tests/test_harness_entry_verification.py +++ b/tests/harness/test_harness_entry_verification.py @@ -1,4 +1,4 @@ -"""T37 happens after registration; declaration-only refusals remain in their own test file.""" +"""Capture actual entry bytes and verify them after registration.""" import json import sqlite3 @@ -18,12 +18,44 @@ from inferrsi.apps.storage.artifact_reader import ArtifactReader from inferrsi.benchmark import preparation as benchmark from inferrsi.contracts.json_v1 import decode -from inferrsi.harness import execution_service, run_store +from inferrsi.harness import entry_code, execution_service, run_store from inferrsi.harness.api import Harness, LocalCpuTarget from inferrsi.harness.errors import PublicError -from tests.test_benchmark_preparation import preparation as preparation +from tests.benchmark.test_benchmark_preparation import preparation as preparation -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] + + +def test_capture_reads_actual_source_without_importing_or_executing_it(tmp_path): + root = tmp_path / "trusted" + root.mkdir() + source = b"raise RuntimeError('this worker must never be imported during binding')\n" + (root / "fixture_worker.py").write_bytes(source) + result = entry_code.capture_module(root, "fixture_worker", tmp_path / "captures") + assert result.path.read_bytes() == source + assert (result.sha256, result.size_bytes) == (sha256(source).hexdigest(), len(source)) + (root / "fixture_worker.py").write_bytes(b"changed after capture\n") + assert result.path.read_bytes() == source + + +@pytest.mark.parametrize("module", ["missing", "package.worker", "../outside", "worker.py"]) +def test_unresolvable_entry_has_no_actual_digest_or_capture(tmp_path, module): + with pytest.raises(entry_code.EntryUnavailable): + entry_code.capture_module(tmp_path, module, tmp_path / "captures") + assert not (tmp_path / "captures").exists() + + +def test_existing_snapshot_is_preserved_instead_of_replaced(tmp_path): + root = tmp_path / "trusted" + root.mkdir() + (root / "worker.py").write_bytes(b"new bytes") + captures = tmp_path / "captures" + captures.mkdir() + retained = captures / "worker.py" + retained.write_bytes(b"already retained") + with pytest.raises(entry_code.EntryCaptureError): + entry_code.capture_module(root, "worker", captures) + assert retained.read_bytes() == b"already retained" @pytest.fixture diff --git a/tests/test_harness_evaluation_replay.py b/tests/harness/test_harness_evaluation_replay.py similarity index 98% rename from tests/test_harness_evaluation_replay.py rename to tests/harness/test_harness_evaluation_replay.py index 570b50087..cb6eefb3d 100644 --- a/tests/test_harness_evaluation_replay.py +++ b/tests/harness/test_harness_evaluation_replay.py @@ -15,8 +15,8 @@ from inferrsi.harness import execution_service, run_store from inferrsi.harness.api import Harness, LocalCpuTarget from inferrsi.harness.errors import PublicError -from tests.test_benchmark_preparation import preparation as preparation -from tests.test_harness_entry_verification import evaluation as evaluation +from tests.benchmark.test_benchmark_preparation import preparation as preparation +from tests.harness.test_harness_entry_verification import evaluation as evaluation def counts(case): diff --git a/tests/test_harness_evidence_capture.py b/tests/harness/test_harness_evidence_capture.py similarity index 99% rename from tests/test_harness_evidence_capture.py rename to tests/harness/test_harness_evidence_capture.py index 6fb6b3cb0..d4f31484f 100644 --- a/tests/test_harness_evidence_capture.py +++ b/tests/harness/test_harness_evidence_capture.py @@ -15,8 +15,8 @@ from inferrsi.harness import evidence_capture, execution_service, run_store from inferrsi.harness.api import Harness, LocalCpuTarget from inferrsi.harness.errors import PublicError -from tests.test_benchmark_preparation import preparation as preparation -from tests.test_harness_entry_verification import evaluation as evaluation +from tests.benchmark.test_benchmark_preparation import preparation as preparation +from tests.harness.test_harness_entry_verification import evaluation as evaluation WORKER = b"""import json, pathlib, sys data = pathlib.Path(sys.argv[1]).read_bytes() diff --git a/tests/test_harness_execute.py b/tests/harness/test_harness_execute.py similarity index 100% rename from tests/test_harness_execute.py rename to tests/harness/test_harness_execute.py diff --git a/tests/test_harness_feedback_policy.py b/tests/harness/test_harness_feedback_policy.py similarity index 98% rename from tests/test_harness_feedback_policy.py rename to tests/harness/test_harness_feedback_policy.py index 713d5af7b..4ded5d45d 100644 --- a/tests/test_harness_feedback_policy.py +++ b/tests/harness/test_harness_feedback_policy.py @@ -15,11 +15,11 @@ from inferrsi.harness import run_store from inferrsi.harness.errors import PublicError from inferrsi.harness.generation import prepare_generation -from tests.test_apps_generation_plan import _fixed_input, _provider -from tests.test_apps_generation_plan import generation as generation -from tests.test_harness_generation_seal import cpu_generation as cpu_generation +from tests.apps.test_apps_generation_plan import _fixed_input, _provider +from tests.apps.test_apps_generation_plan import generation as generation +from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation -FIXTURES = Path(__file__).resolve().parents[1] / "docs/contracts/fixtures/t108-v4" +FIXTURES = Path(__file__).resolve().parents[2] / "docs/contracts/fixtures/t108-v4" class Reader: @@ -388,7 +388,7 @@ def open(self, ref): """ result = subprocess.run( [sys.executable, "-I", "-B", "-c", child, - str(Path(__file__).resolve().parents[1] / "src"), str(path)], + str(Path(__file__).resolve().parents[2] / "src"), str(path)], cwd=tmp_path, capture_output=True, text=True, encoding="utf-8", timeout=30, ) assert result.returncode == 0, result.stderr diff --git a/tests/test_harness_generation_bounds.py b/tests/harness/test_harness_generation_bounds.py similarity index 98% rename from tests/test_harness_generation_bounds.py rename to tests/harness/test_harness_generation_bounds.py index 187b3bd45..7c4db4b75 100644 --- a/tests/test_harness_generation_bounds.py +++ b/tests/harness/test_harness_generation_bounds.py @@ -15,8 +15,8 @@ from inferrsi.harness import run_store from inferrsi.harness.errors import PublicError from inferrsi.harness.generation import prepare_generation -from tests.test_apps_generation_plan import generation as generation -from tests.test_harness_generation_seal import cpu_generation as cpu_generation +from tests.apps.test_apps_generation_plan import generation as generation +from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation def expected_bounds(spec, plan_ref): @@ -63,7 +63,7 @@ def test_bounds_are_committed_with_the_unchanged_plan_and_read_in_a_new_process( )) """ received = subprocess.check_output( - [sys.executable, "-I", "-B", "-c", child, str(Path(__file__).resolve().parents[1] / "src"), + [sys.executable, "-I", "-B", "-c", child, str(Path(__file__).resolve().parents[2] / "src"), str(store.root), attempt_id], cwd=tmp_path, timeout=30, ) assert decode(received) == expected diff --git a/tests/test_harness_generation_lineage.py b/tests/harness/test_harness_generation_lineage.py similarity index 99% rename from tests/test_harness_generation_lineage.py rename to tests/harness/test_harness_generation_lineage.py index 5713c9a58..12575daef 100644 --- a/tests/test_harness_generation_lineage.py +++ b/tests/harness/test_harness_generation_lineage.py @@ -22,9 +22,9 @@ from inferrsi.harness.api import Harness from inferrsi.harness.errors import PublicError from inferrsi.harness.generation import prepare_generation -from tests.test_apps_generation_plan import _fixed_input -from tests.test_apps_generation_plan import generation as generation -from tests.test_harness_generation_seal import cpu_generation as cpu_generation +from tests.apps.test_apps_generation_plan import _fixed_input +from tests.apps.test_apps_generation_plan import generation as generation +from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation @pytest.fixture @@ -632,7 +632,7 @@ def forbidden(*args, **kwargs): """ child = subprocess.run( [sys.executable, "-I", "-B", "-c", script, - str(Path(__file__).resolve().parents[1] / "src"), str(tmp_path)], + str(Path(__file__).resolve().parents[2] / "src"), str(tmp_path)], cwd=tmp_path, capture_output=True, text=True, encoding="utf-8", check=True, ) assert decode(child.stdout.strip().encode("utf-8")) == committed.record_ref diff --git a/tests/test_harness_generation_seal.py b/tests/harness/test_harness_generation_seal.py similarity index 98% rename from tests/test_harness_generation_seal.py rename to tests/harness/test_harness_generation_seal.py index f1f9af0b8..1b88be135 100644 --- a/tests/test_harness_generation_seal.py +++ b/tests/harness/test_harness_generation_seal.py @@ -19,8 +19,8 @@ from inferrsi.harness.api import Harness, LocalCpuTarget from inferrsi.harness.errors import PublicError from inferrsi.harness.generation import prepare_generation -from tests.test_apps_generation_plan import _fixed_input, _provider -from tests.test_apps_generation_plan import generation as generation +from tests.apps.test_apps_generation_plan import _fixed_input, _provider +from tests.apps.test_apps_generation_plan import generation as generation _KNOWLEDGE = "package:inferrsi.common.skills.cgroup_resource_controls" @@ -114,7 +114,7 @@ def test_seal_commits_context_and_plan_before_cpu_execution(cpu_generation): delivery = reader.read_delivered_context(sys.argv[2]) sys.stdout.buffer.write(encode(delivery) + b'\\n' + reader.open(delivery['artifact']).read()) """ - source = str(Path(__file__).resolve().parents[1] / "src") + source = str(Path(__file__).resolve().parents[2] / "src") received = subprocess.check_output( [sys.executable, "-c", child, str(store.root), attempt_id], env={**os.environ, "PYTHONPATH": source}, timeout=30, diff --git a/tests/test_harness_improvement.py b/tests/harness/test_harness_improvement.py similarity index 100% rename from tests/test_harness_improvement.py rename to tests/harness/test_harness_improvement.py diff --git a/tests/test_harness_measurement.py b/tests/harness/test_harness_measurement.py similarity index 100% rename from tests/test_harness_measurement.py rename to tests/harness/test_harness_measurement.py diff --git a/tests/test_harness_prepared_binding.py b/tests/harness/test_harness_prepared_binding.py similarity index 99% rename from tests/test_harness_prepared_binding.py rename to tests/harness/test_harness_prepared_binding.py index 61027fac3..f0d3911de 100644 --- a/tests/test_harness_prepared_binding.py +++ b/tests/harness/test_harness_prepared_binding.py @@ -14,7 +14,7 @@ from inferrsi.harness.api import Harness, LocalCpuTarget from inferrsi.harness.errors import PublicError -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] GOLDEN = ROOT / "docs/contracts/fixtures/t108-v4" VECTOR = ROOT / "tests/fixtures/harness-prepared-binding/d023-null-timeout.json" DIGEST = "sha256:62ce11e6d458b5c581245d0988189e1bd834f2ed1e1880d15242faf70c5b6fe9" diff --git a/tests/test_harness_run_store.py b/tests/harness/test_harness_run_store.py similarity index 100% rename from tests/test_harness_run_store.py rename to tests/harness/test_harness_run_store.py diff --git a/tests/test_local_executor.py b/tests/harness/test_local_executor.py similarity index 97% rename from tests/test_local_executor.py rename to tests/harness/test_local_executor.py index 1cbc0d8da..311f5e238 100644 --- a/tests/test_local_executor.py +++ b/tests/harness/test_local_executor.py @@ -25,7 +25,7 @@ def test_local_executor_does_not_inherit_parent_stdin(tmp_path): "print(json.dumps({'status': result['status']}))\n", encoding="utf-8", ) - environment = dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1] / "src")) + environment = dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[2] / "src")) completed = subprocess.run( (sys.executable, str(parent)), cwd=tmp_path, diff --git a/tests/test_moe_optimization_protocol.py b/tests/harness/test_moe_optimization_protocol.py similarity index 100% rename from tests/test_moe_optimization_protocol.py rename to tests/harness/test_moe_optimization_protocol.py diff --git a/tests/test_parallel_round.py b/tests/harness/test_parallel_round.py similarity index 88% rename from tests/test_parallel_round.py rename to tests/harness/test_parallel_round.py index eb6cb7029..f3ef60ae4 100644 --- a/tests/test_parallel_round.py +++ b/tests/harness/test_parallel_round.py @@ -88,6 +88,173 @@ def _spec(**overrides): return spec +requires_posix_round_storage = pytest.mark.skipif( + os.name != "posix", + reason="Round storage requires POSIX directory descriptors and executable bits", +) + + +class TestPortableParallelRound: + def test_prepare_rejects_bad_devices_and_metric(self, tmp_path): + incumbent = tmp_path / "incumbent" + devices = ([], ["cpu-0", "cpu-0"], ["a/b"], "cpu-0", ["."], [".."], ["0,1", "2"]) + for invalid in devices: + with pytest.raises(RoundPlanError, match="device_ids"): + prepare(_spec(device_ids=invalid), incumbent, tmp_path / "round-devices") + for metric in ( + None, + {"name": "latency_ms"}, + {"name": "", "better": "lower"}, + {"name": "latency_ms", "better": "faster"}, + {"name": "latency_ms", "better": ["lower"]}, + ): + with pytest.raises(RoundPlanError, match="metric"): + prepare(_spec(metric=metric), incumbent, tmp_path / "round-metric") + + def test_prepare_rejects_bad_repeats_and_timeout(self, tmp_path): + incumbent = tmp_path / "incumbent" + base = {"name": "latency_ms", "better": "lower"} + for extra, message in ( + ({"repeats": 0}, "repeats"), + ({"repeats": True}, "repeats"), + ({"margin": 0.03}, "metric needs"), + ({"spread": 1}, "metric needs"), + ({"min_improvement_pct": -1}, "min_improvement_pct"), + ({"min_improvement_pct": float("nan")}, "min_improvement_pct"), + ): + with pytest.raises(RoundPlanError, match=message): + prepare(_spec(metric={**base, **extra}), incumbent, tmp_path / "round-metric") + for timeout in (0, -1, "30", float("inf")): + with pytest.raises(RoundPlanError, match="command_timeout_seconds"): + prepare(_spec(command_timeout_seconds=timeout), incumbent, tmp_path / "round-t") + for overrides, message in ( + ({"validation": "pytest"}, "validation"), + ({"validation": []}, "validation"), + ({"device_model": ""}, "device_model"), + ): + with pytest.raises(RoundPlanError, match=message): + prepare(_spec(**overrides), incumbent, tmp_path / "round-fields") + + def test_prepare_rejects_bad_device_paths_and_env(self, tmp_path): + incumbent = tmp_path / "incumbent" + device_dir = tmp_path / "dev" + for overrides, message in ( + ({"device_paths": {"cpu-0": [str(device_dir / "a")]}}, "every device id"), + ({"device_paths": {"cpu-0": ["dev/a"], "cpu-1": []}}, "absolute host paths"), + ({"device_paths": {"cpu-0": ["/"], "cpu-1": []}}, "absolute host paths"), + ({"shared_device_paths": [str(device_dir / ".." / "etc")]}, "absolute host paths"), + ({"runtime_paths": str(tmp_path / "lib")}, "absolute host paths"), + ({"env": {"CUDA_VISIBLE_DEVICES": 0}}, "env"), + ): + with pytest.raises(RoundPlanError, match=message): + prepare(_spec(**overrides), incumbent, tmp_path / "round-paths") + + def test_ticket_status_reads_queued_and_finished_results(self, tmp_path): + assert ticket_status(tmp_path, "t1") == {"ticket": "t1", "status": "queued"} + receipt = {"ticket": "t1", "status": "measured"} + results = tmp_path / "results" + results.mkdir() + (results / "t1.json").write_text(json.dumps(receipt), encoding="utf-8") + assert ticket_status(tmp_path, "t1") == receipt + + def test_two_acquires_do_not_share_one_device(self, tmp_path): + lease = DeviceLease(tmp_path) + (tmp_path / "cpu-0").touch() # An empty lock file can remain from an older release. + worker = """ +import sys +from pathlib import Path +from inferrsi.harness.device_lease import DeviceLease, LeaseError + +try: + with DeviceLease(Path(sys.argv[1])).acquire("cpu-0"): + print("acquired") +except LeaseError as error: + print(error) +""" + + def probe(): + completed = subprocess.run( + [sys.executable, "-c", worker, str(tmp_path)], + env={**os.environ, "PYTHONPATH": str(Path(__file__).parents[2] / "src")}, + capture_output=True, + text=True, + check=False, + timeout=10, + ) + assert completed.returncode == 0, completed.stderr + return completed.stdout.strip() + + with lease.acquire("cpu-0"): + with pytest.raises(LeaseError, match="device busy: cpu-0"): + lease.acquire("cpu-0") + assert probe() == "device busy: cpu-0" + lease.acquire("cpu-1").release() + lease.quarantine("cpu-0", "command outlived its deadline") + + marker = tmp_path / "cpu-0.quarantined" + assert marker.read_text(encoding="utf-8") == "command outlived its deadline\n" + assert probe() == "device quarantined: cpu-0" + marker.unlink() + assert probe() == "acquired" + + def test_hold_devices_releases_a_partial_claim(self, tmp_path): + lease = DeviceLease(tmp_path / "leases") + with lease.acquire("cpu-1"): + assert hold_devices(tmp_path, {"device_ids": ["cpu-0", "cpu-1"]}, 2) is None + lease.acquire("cpu-0").release() + + def test_hold_devices_rolls_back_on_acquire_error(self, tmp_path, monkeypatch): + devices = ["cpu-0", "cpu-1", "cpu-2"] + acquire = DeviceLease.acquire + failure = PermissionError("cannot open the third device lock") + held = [] # Keep the original handles alive until after the reacquire check. + released = [] + + def fail_on_third(leases, device): + if device == devices[2]: + raise failure + lock = acquire(leases, device) + held.append(lock) + release = lock.release + + def record_release(): + released.append(device) + release() + + monkeypatch.setattr(lock, "release", record_release) + return lock + + monkeypatch.setattr(DeviceLease, "acquire", fail_on_third) + with pytest.raises(PermissionError) as raised: + hold_devices(tmp_path, {"device_ids": devices}, 3) + + assert raised.value is failure + assert released == ["cpu-1", "cpu-0"] + leases = DeviceLease(tmp_path / "leases") + with acquire(leases, "cpu-0"), acquire(leases, "cpu-1"): + pass + + def test_leases_reject_invalid_path_segments(self, tmp_path): + lease = DeviceLease(tmp_path) + for invalid in ("", ".", "..", "a/b", "a\\b", "a\0b"): + with pytest.raises(LeaseError, match="single path segment"): + lease.acquire(invalid) + with pytest.raises(LeaseError, match="single path segment"): + lease.quarantine(invalid, "bad identity") + assert not list(tmp_path.iterdir()) + + @pytest.mark.skipif(os.name != "nt", reason="Windows filename rules") + def test_leases_reject_invalid_windows_path_segments(self, tmp_path): + lease = DeviceLease(tmp_path) + for invalid in ("C:cpu-0", "cpu-0:stream", "cpu-0.", "cpu-0 ", "cpu-*", "NUL.txt", "COM1"): + with pytest.raises(LeaseError, match="Windows path segment"): + lease.acquire(invalid) + with pytest.raises(LeaseError, match="Windows path segment"): + lease.quarantine(invalid, "bad identity") + assert not list(tmp_path.iterdir()) + + +@requires_posix_round_storage def test_prepare_rejects_overlapping_globs_protected_paths_and_shared_entries(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -140,28 +307,18 @@ def test_prepare_rejects_overlapping_globs_protected_paths_and_shared_entries(tm prepare(many, incumbent, tmp_path / "round-plane") -def test_prepare_rejects_bad_devices_and_metric(tmp_path): +@requires_posix_round_storage +def test_prepare_rejects_dotted_lane_ids(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") - for devices in ([], ["cpu-0", "cpu-0"], ["a/b"], "cpu-0", ["."], [".."], ["0,1", "2"]): - with pytest.raises(RoundPlanError, match="device_ids"): - prepare(_spec(device_ids=devices), incumbent, tmp_path / "round-devices") for lane_id in (".", ".."): dotted = _spec() dotted["lanes"][0]["id"] = lane_id with pytest.raises(RoundPlanError, match="own id"): prepare(dotted, incumbent, tmp_path / "round-lane-id") - for metric in ( - None, - {"name": "latency_ms"}, - {"name": "", "better": "lower"}, - {"name": "latency_ms", "better": "faster"}, - {"name": "latency_ms", "better": ["lower"]}, - ): - with pytest.raises(RoundPlanError, match="metric"): - prepare(_spec(metric=metric), incumbent, tmp_path / "round-metric") +@requires_posix_round_storage def test_prepare_records_plan_cap_and_deadline(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -173,6 +330,7 @@ def test_prepare_records_plan_cap_and_deadline(tmp_path): assert len(written["round_digest"]) == 64 +@requires_posix_round_storage def test_submit_rejects_paths_outside_the_lane_and_is_idempotent(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -192,6 +350,7 @@ def test_submit_rejects_paths_outside_the_lane_and_is_idempotent(tmp_path): assert first["ticket"] == second["ticket"] +@requires_posix_round_storage def test_submit_rejects_new_protected_and_cross_lane_owned_paths(tmp_path): """prepare only sees the incumbent; submit must police concrete new paths.""" incumbent = tmp_path / "incumbent" @@ -243,6 +402,7 @@ def test_submit_rejects_new_protected_and_cross_lane_owned_paths(tmp_path): assert not (round_dir / "outbox").exists() +@requires_posix_round_storage def test_serve_records_a_synthetic_gain_and_a_held_device_stays_queued(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -272,6 +432,7 @@ def test_serve_records_a_synthetic_gain_and_a_held_device_stays_queued(tmp_path) assert (round_dir / "candidates" / ticket / "build-stamp").read_text(encoding="utf-8") == "ok" +@requires_posix_round_storage def test_prepare_rejects_bad_device_counts_and_lanes_that_need_more_devices(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -289,6 +450,7 @@ def test_prepare_rejects_bad_device_counts_and_lanes_that_need_more_devices(tmp_ assert [lane["device_count"] for lane in plan["lanes"]] == [1, 2] +@requires_posix_round_storage def test_a_lane_needing_two_devices_waits_until_it_can_hold_both(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -318,52 +480,23 @@ def test_a_lane_needing_two_devices_waits_until_it_can_hold_both(tmp_path): assert stamp.read_text(encoding="utf-8") == "1,2" -def test_prepare_rejects_bad_repeats_and_timeout(tmp_path): +@requires_posix_round_storage +def test_prepare_records_execution_defaults(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") - base = {"name": "latency_ms", "better": "lower"} - for extra, message in ( - ({"repeats": 0}, "repeats"), - ({"repeats": True}, "repeats"), - ({"margin": 0.03}, "metric needs"), - ({"spread": 1}, "metric needs"), - ({"min_improvement_pct": -1}, "min_improvement_pct"), - ({"min_improvement_pct": float("nan")}, "min_improvement_pct"), - ): - with pytest.raises(RoundPlanError, match=message): - prepare(_spec(metric={**base, **extra}), incumbent, tmp_path / "round-metric") - for timeout in (0, -1, "30", float("inf")): - with pytest.raises(RoundPlanError, match="command_timeout_seconds"): - prepare(_spec(command_timeout_seconds=timeout), incumbent, tmp_path / "round-t") - for overrides, message in ( - ({"validation": "pytest"}, "validation"), - ({"validation": []}, "validation"), - ({"device_model": ""}, "device_model"), - ): - with pytest.raises(RoundPlanError, match=message): - prepare(_spec(**overrides), incumbent, tmp_path / "round-fields") plan = prepare(_spec(), incumbent, tmp_path / "round-defaults") - assert plan["metric"] == {**base, "repeats": 1, "min_improvement_pct": 0} + assert plan["metric"] == { + "name": "latency_ms", + "better": "lower", + "repeats": 1, + "min_improvement_pct": 0, + } assert plan["validation"] is None assert plan["device_model"] is None assert plan["command_timeout_seconds"] == 30 -def test_prepare_rejects_bad_device_paths_and_env(tmp_path): - incumbent = tmp_path / "incumbent" - _tree(incumbent, "10") - for overrides, message in ( - ({"device_paths": {"cpu-0": ["/dev/a"]}}, "every device id"), - ({"device_paths": {"cpu-0": ["dev/a"], "cpu-1": []}}, "absolute host paths"), - ({"device_paths": {"cpu-0": ["/"], "cpu-1": []}}, "absolute host paths"), - ({"shared_device_paths": ["/dev/../etc"]}, "absolute host paths"), - ({"runtime_paths": "/usr/lib64"}, "absolute host paths"), - ({"env": {"CUDA_VISIBLE_DEVICES": 0}}, "env"), - ): - with pytest.raises(RoundPlanError, match=message): - prepare(_spec(**overrides), incumbent, tmp_path / "round-paths") - - +@requires_posix_round_storage def test_serve_passes_only_the_held_device_nodes_and_env(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -402,6 +535,7 @@ def run(self, argv, *args, **kwargs): assert seen[0]["env"] == {"CUDA_VISIBLE_DEVICES": "cpu-1"} +@requires_posix_round_storage def test_repeats_alternate_abba_and_report_medians(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -441,6 +575,7 @@ def run(self, argv, *args, **kwargs): assert measured["improvement_pct"] == pytest.approx(10) +@requires_posix_round_storage def test_higher_is_better_metric_reports_gain_in_the_better_direction(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -455,6 +590,7 @@ def test_higher_is_better_metric_reports_gain_in_the_better_direction(tmp_path): assert measured["improvement_pct"] == pytest.approx(-20) +@requires_posix_round_storage def test_serve_uses_a_free_device_and_passes_its_identity_to_the_commands(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -479,6 +615,7 @@ def test_serve_uses_a_free_device_and_passes_its_identity_to_the_commands(tmp_pa assert stamp.read_text(encoding="utf-8") == "gpu-1" +@requires_posix_round_storage def test_a_busy_lane_stays_queued_without_touching_its_ledger(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -497,6 +634,7 @@ def test_a_busy_lane_stays_queued_without_touching_its_ledger(tmp_path): assert not (round_dir / "results").exists() +@requires_posix_round_storage def test_a_non_numeric_metric_is_an_unsettled_receipt(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -523,25 +661,7 @@ def run(self, argv, *args, **kwargs): assert [entry["phase"] for entry in ledger["entries"]] == ["claimed"] -def test_two_acquires_do_not_share_one_device(tmp_path): - lease = DeviceLease(tmp_path) - held = lease.acquire("cpu-0") - failed = threading.Event() - - def other() -> None: - try: - lease.acquire("cpu-0") - except LeaseError: - failed.set() - - thread = threading.Thread(target=other) - thread.start() - thread.join(2) - assert failed.is_set() - held.release() - lease.acquire("cpu-1").release() - - +@requires_posix_round_storage def test_submit_rejects_symlink_without_reading_the_target(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -561,6 +681,7 @@ def test_submit_rejects_symlink_without_reading_the_target(tmp_path): assert "CANARY-SECRET" not in json.dumps(rejected) +@requires_posix_round_storage def test_in_scope_deletion_is_rejected_before_hashing_and_serve_does_not_run(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -591,6 +712,7 @@ def test_in_scope_deletion_is_rejected_before_hashing_and_serve_does_not_run(tmp assert not (round_dir / "candidates").exists() +@requires_posix_round_storage def test_changed_root_manifest_is_the_project_file(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -629,6 +751,7 @@ def test_changed_root_manifest_is_the_project_file(tmp_path): assert (destination / "manifest.json").read_bytes() == payload +@requires_posix_round_storage def test_unchanged_manifest_files_reach_the_successor(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -661,6 +784,7 @@ def test_unchanged_manifest_files_reach_the_successor(tmp_path): assert (successor / "pkg" / "manifest.json").read_bytes() == nested_manifest +@requires_posix_round_storage def test_submit_after_deadline_is_refused_on_a_fresh_read(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -677,6 +801,7 @@ def test_submit_after_deadline_is_refused_on_a_fresh_read(tmp_path): assert not (round_dir / "outbox").exists() +@requires_posix_round_storage def test_launch_after_deadline_cancels_before_claim(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -700,6 +825,7 @@ def clock(): assert not (round_dir / "candidates" / ticket / "build-stamp").exists() +@requires_posix_round_storage def test_deadline_expiring_between_build_and_candidate_stops_the_trial(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -738,6 +864,7 @@ def run(self, *args, **kwargs): assert ticket_status(round_dir, ticket)["status"] == "unsettled" +@requires_posix_round_storage def test_namespace_timeout_after_claim_is_an_unsettled_receipt(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -763,6 +890,7 @@ def run(self, *args, **kwargs): assert ticket_status(round_dir, ticket)["status"] == "unsettled" +@requires_posix_round_storage def test_failure_after_claim_stays_unsettled_across_restart(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -812,6 +940,7 @@ def _phases(round_dir): return [entry["phase"] for entry in ledger["entries"]] +@requires_posix_round_storage def test_restart_after_reserve_resumes_the_same_attempt(tmp_path, monkeypatch): incumbent, round_dir, ticket = _one_ticket(tmp_path) @@ -829,6 +958,7 @@ def crash(*args, **kwargs): assert _phases(round_dir) == ["finished"] +@requires_posix_round_storage def test_restart_after_finish_writes_a_receipt_without_rerunning(tmp_path): incumbent, round_dir, ticket = _one_ticket(tmp_path) first = serve_ticket(round_dir, ticket, incumbent, backend=FixtureBackend(), now=WHEN) @@ -847,6 +977,7 @@ def run(self, *args, **kwargs): assert _phases(round_dir) == ["finished"] +@requires_posix_round_storage def test_a_queued_ticket_past_its_deadline_is_rejected_without_a_reservation(tmp_path): incumbent, round_dir, ticket = _one_ticket(tmp_path) leases = DeviceLease(round_dir / "leases") @@ -869,6 +1000,7 @@ def test_a_queued_ticket_past_its_deadline_is_rejected_without_a_reservation(tmp assert not (round_dir / "ledgers" / "L1.json").exists() +@requires_posix_round_storage def test_an_unreaped_command_quarantines_its_device(tmp_path): incumbent, round_dir, ticket = _one_ticket(tmp_path) @@ -895,6 +1027,7 @@ def run(self, *args, **kwargs): DeviceLease(round_dir / "leases").acquire("cpu-0").release() +@requires_posix_round_storage def test_reading_a_fifo_does_not_block(tmp_path): os.mkfifo(tmp_path / "pipe") found = [] @@ -906,6 +1039,7 @@ def test_reading_a_fifo_does_not_block(tmp_path): assert found == [None] +@requires_posix_round_storage def test_completed_trial_without_a_latency_file_is_unsettled(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -940,6 +1074,7 @@ def _git_tree(root: Path, knob: str) -> None: subprocess.run(["git", "-C", str(root), *argv], check=True) +@requires_posix_round_storage def test_a_git_incumbent_with_validation_gets_a_verdict(tmp_path): incumbent = tmp_path / "incumbent" _git_tree(incumbent, "10") @@ -957,6 +1092,7 @@ def test_a_git_incumbent_with_validation_gets_a_verdict(tmp_path): assert measured["improvement_pct"] == pytest.approx(20) +@requires_posix_round_storage def test_a_failing_validation_is_a_measured_fail(tmp_path): incumbent = tmp_path / "incumbent" _git_tree(incumbent, "10") @@ -973,6 +1109,7 @@ def test_a_failing_validation_is_a_measured_fail(tmp_path): assert [entry["phase"] for entry in ledger["entries"]] == ["finished"] +@requires_posix_round_storage def test_device_model_checks_the_held_devices_before_reserving(tmp_path, monkeypatch): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1002,6 +1139,7 @@ def busy(*, count, device_model): assert measured["status"] == "measured" +@requires_posix_round_storage def test_serve_cli_runs_without_a_caller_supplied_clock(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1010,7 +1148,7 @@ def test_serve_cli_runs_without_a_caller_supplied_clock(tmp_path): work = tmp_path / "work" _tree(work, "8") ticket = submit(round_dir, "L1", incumbent, work, now=WHEN)["ticket"] - tool = Path(__file__).parents[1] / "tools" / "parallel_round.py" + tool = Path(__file__).parents[2] / "tools" / "parallel_round.py" completed = subprocess.run( [ sys.executable, @@ -1023,8 +1161,8 @@ def test_serve_cli_runs_without_a_caller_supplied_clock(tmp_path): "--incumbent", str(incumbent), ], - cwd=Path(__file__).parents[1], - env={**os.environ, "PYTHONPATH": str(Path(__file__).parents[1] / "src")}, + cwd=Path(__file__).parents[2], + env={**os.environ, "PYTHONPATH": str(Path(__file__).parents[2] / "src")}, capture_output=True, text=True, check=False, @@ -1065,6 +1203,7 @@ def _sum_spec(**overrides): ) +@requires_posix_round_storage def test_close_composes_pass_lanes_once_and_writes_a_successor(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1092,6 +1231,7 @@ def test_close_composes_pass_lanes_once_and_writes_a_successor(tmp_path): assert again == closed +@requires_posix_round_storage def test_close_with_no_pass_lanes_retains_the_incumbent(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1110,6 +1250,7 @@ def test_close_with_no_pass_lanes_retains_the_incumbent(tmp_path): assert not (round_dir / "successor").exists() +@requires_posix_round_storage def test_close_refuses_while_a_ticket_is_unsettled(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1132,6 +1273,7 @@ def run(self, *args, **kwargs): assert not (round_dir / "close.json").exists() +@requires_posix_round_storage def test_build_planted_git_hooks_do_not_run_on_the_host(tmp_path): canary = tmp_path / "hook-ran" hook = tmp_path / "evil-hook.py" @@ -1167,6 +1309,7 @@ def test_build_planted_git_hooks_do_not_run_on_the_host(tmp_path): ) +@requires_posix_round_storage def test_validation_confinement_failure_stays_unsettled(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1218,6 +1361,7 @@ def _combo_lane(): ] +@requires_posix_round_storage def test_one_winner_per_lane_is_promoted_when_the_joint_passes(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1246,6 +1390,7 @@ def test_one_winner_per_lane_is_promoted_when_the_joint_passes(tmp_path): assert not (round_dir / "knowledge" / "joint-failure.json").exists() +@requires_posix_round_storage def test_joint_failure_of_lane_winners_writes_the_summary(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1274,6 +1419,7 @@ def test_joint_failure_of_lane_winners_writes_the_summary(tmp_path): assert {item["lane_id"] for item in note["tickets"]} == {"L1", "L2"} +@requires_posix_round_storage def test_successor_keeps_the_frozen_incumbent_bytes(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1301,6 +1447,7 @@ def run(self, *args, **kwargs): assert (incumbent / "knobs" / "b.txt").read_text(encoding="utf-8") == "99" +@requires_posix_round_storage def test_joint_confinement_failure_does_not_seal_the_round(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1326,6 +1473,7 @@ def run(self, *args, **kwargs): assert (round_dir / "close.json").exists() +@requires_posix_round_storage def test_joint_build_confinement_failure_does_not_seal_the_round(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1371,6 +1519,7 @@ def test_unshare_failing_validation_is_a_measured_fail(tmp_path): assert (round_dir / "close.json").exists() +@requires_posix_round_storage def test_submit_streams_a_file_larger_than_one_chunk(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1390,6 +1539,7 @@ def test_submit_streams_a_file_larger_than_one_chunk(tmp_path): assert not (round_dir / "submit-staging").exists() +@requires_posix_round_storage def test_metadata_write_failure_retries_without_a_false_success(tmp_path, monkeypatch): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1427,6 +1577,7 @@ def write_json(path, value): assert json.loads(metadata.read_text(encoding="utf-8"))["lane_id"] == "L1" +@requires_posix_round_storage def test_retry_repairs_a_payload_that_does_not_match_the_manifest(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1449,6 +1600,7 @@ def test_retry_repairs_a_payload_that_does_not_match_the_manifest(tmp_path): assert stored.read_text(encoding="utf-8") == "8" +@requires_posix_round_storage def test_serve_and_close_apply_an_executable_bit_downgrade(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1472,6 +1624,7 @@ def test_serve_and_close_apply_an_executable_bit_downgrade(tmp_path): assert successor.stat().st_mode & 0o111 == 0 +@requires_posix_round_storage def test_serve_rejects_a_truncated_payload_without_retrying_submit(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1495,6 +1648,7 @@ def run(self, *args, **kwargs): assert not (round_dir / "ledgers" / "L1.json").exists() +@requires_posix_round_storage def test_close_refuses_a_truncated_payload_without_measuring_it(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1520,6 +1674,7 @@ def run(self, *args, **kwargs): assert not (round_dir / "candidates" / "joint-close").exists() +@requires_posix_round_storage def test_submit_refuses_a_file_that_changes_after_the_scan(tmp_path, monkeypatch): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1543,6 +1698,7 @@ def snapshot(root): assert not (round_dir / "outbox").exists() +@requires_posix_round_storage def test_submit_refuses_an_executable_bit_that_changes_after_the_scan(tmp_path, monkeypatch): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1588,6 +1744,7 @@ def snapshot(root): assert not (round_dir / "outbox").exists() +@requires_posix_round_storage def test_executable_bit_is_part_of_identity_and_the_entrypoint_runs(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") @@ -1633,6 +1790,7 @@ def test_executable_bit_is_part_of_identity_and_the_entrypoint_runs(tmp_path): assert (candidate / "build-stamp").read_text(encoding="utf-8").strip() == "built" +@requires_posix_round_storage def test_joint_build_nonzero_exit_closes_with_the_returncode(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1663,6 +1821,7 @@ def run(self, argv, cwd, writable, readable, deadline, **kwargs): assert again == closed +@requires_posix_round_storage def test_successor_keeps_files_the_build_wrote_into_the_measured_tree(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1686,6 +1845,7 @@ def test_successor_keeps_files_the_build_wrote_into_the_measured_tree(tmp_path): assert (successor / "knobs" / "generated.txt").read_text(encoding="utf-8") == "from-build" +@requires_posix_round_storage def test_promotion_does_not_publish_or_follow_repository_metadata(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1722,6 +1882,7 @@ def test_promotion_does_not_publish_or_follow_repository_metadata(tmp_path): assert outside.read_text(encoding="utf-8") == "SECRET-OUTSIDE" +@requires_posix_round_storage def test_promotion_refuses_a_symlink_without_following_it(tmp_path): source = tmp_path / "source" _tree(source, "8") @@ -1735,6 +1896,7 @@ def test_promotion_refuses_a_symlink_without_following_it(tmp_path): assert outside.read_text(encoding="utf-8") == "SECRET-OUTSIDE" +@requires_posix_round_storage def test_promotion_refuses_a_file_changed_after_measurement(tmp_path, monkeypatch): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1763,6 +1925,7 @@ def run_experiment(*args, **kwargs): assert joint.read_text(encoding="utf-8") == "changed-after-measure" +@requires_posix_round_storage def test_submit_refuses_while_close_runs_and_after_it_finishes(tmp_path): incumbent = tmp_path / "incumbent" _sum_tree(incumbent, "10", "10") @@ -1803,6 +1966,7 @@ def go() -> None: assert after["reason"] == "round closed" +@requires_posix_round_storage def test_changed_incumbent_bytes_are_refused(tmp_path): incumbent = tmp_path / "incumbent" _tree(incumbent, "10") diff --git a/tests/test_project_objectives.py b/tests/harness/test_project_objectives.py similarity index 100% rename from tests/test_project_objectives.py rename to tests/harness/test_project_objectives.py diff --git a/tests/test_round_budget.py b/tests/harness/test_round_budget.py similarity index 100% rename from tests/test_round_budget.py rename to tests/harness/test_round_budget.py diff --git a/tests/test_server_processes.py b/tests/harness/test_server_processes.py similarity index 100% rename from tests/test_server_processes.py rename to tests/harness/test_server_processes.py diff --git a/tests/test_service_backfill_recovery.py b/tests/harness/test_service_backfill_recovery.py similarity index 99% rename from tests/test_service_backfill_recovery.py rename to tests/harness/test_service_backfill_recovery.py index c407f9f4a..4bb869e6f 100644 --- a/tests/test_service_backfill_recovery.py +++ b/tests/harness/test_service_backfill_recovery.py @@ -5,12 +5,12 @@ from types import SimpleNamespace import pytest -from test_project_service_reuse import begin, call, settings, submit -from test_project_service_reuse import campaign as campaign from inferrsi.harness import optimization, service_backfill from inferrsi.harness import project_service as service from inferrsi.harness.atomic_json import atomic_write_json +from tests.fixtures.service_reuse import begin, call, settings, submit +from tests.fixtures.service_reuse import campaign as campaign @pytest.mark.parametrize("proven", [0, 3]) diff --git a/tests/test_service_capture_accounting.py b/tests/harness/test_service_capture_accounting.py similarity index 96% rename from tests/test_service_capture_accounting.py rename to tests/harness/test_service_capture_accounting.py index b86be6f9e..d2d98bef6 100644 --- a/tests/test_service_capture_accounting.py +++ b/tests/harness/test_service_capture_accounting.py @@ -4,10 +4,10 @@ import time import pytest -from test_project_service_reuse import begin, call, submit -from test_project_service_reuse import campaign as campaign from inferrsi.harness import project_service as service +from tests.fixtures.service_reuse import begin, call, submit +from tests.fixtures.service_reuse import campaign as campaign def test_crash_after_profile_process_receipt_before_capture_progress(campaign, monkeypatch): diff --git a/tests/test_service_fingerprint_isolation.py b/tests/harness/test_service_fingerprint_isolation.py similarity index 81% rename from tests/test_service_fingerprint_isolation.py rename to tests/harness/test_service_fingerprint_isolation.py index 31c86a398..80523cfe9 100644 --- a/tests/test_service_fingerprint_isolation.py +++ b/tests/harness/test_service_fingerprint_isolation.py @@ -19,10 +19,10 @@ def test_service_guard_restores_lazy_import_aliases(tmp_path): ) result = subprocess.run( [sys.executable, "-B", "-m", "pytest", "-p", "no:cacheprovider", "-q", - "tests/test_project_service_reuse.py::test_exact_round_policy_and_legacy_argument_validation", - "tests/test_optimization_session.py::test_started_task_uses_frozen_protocol_without_registry", + "tests/apps/test_project_service_reuse.py::test_exact_round_policy_and_legacy_argument_validation", + "tests/apps/test_optimization_session.py::test_started_task_uses_frozen_protocol_without_registry", str(check)], - cwd=Path(__file__).resolve().parents[1], + cwd=Path(__file__).resolve().parents[2], env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"}, capture_output=True, text=True, timeout=90, ) @@ -30,7 +30,7 @@ def test_service_guard_restores_lazy_import_aliases(tmp_path): def test_guard_blocks_lazily_imported_fingerprints_even_when_caught(monkeypatch, tmp_path): - from tests.test_project_service_reuse import no_fingerprints + from tests.fixtures.service_reuse import no_fingerprints guard = no_fingerprints.__wrapped__(monkeypatch) next(guard) diff --git a/tests/test_service_profile_diagnostics.py b/tests/harness/test_service_profile_diagnostics.py similarity index 99% rename from tests/test_service_profile_diagnostics.py rename to tests/harness/test_service_profile_diagnostics.py index ee2e9aaeb..9ad3c6a00 100644 --- a/tests/test_service_profile_diagnostics.py +++ b/tests/harness/test_service_profile_diagnostics.py @@ -3,10 +3,10 @@ import json import pytest -from test_project_service_reuse import begin, call, submit -from test_project_service_reuse import campaign as campaign from inferrsi.harness import project_service as service +from tests.fixtures.service_reuse import begin, call, submit +from tests.fixtures.service_reuse import campaign as campaign # A valid protocol receipt below the JSON size limit but too large to copy twice. ERROR_EXPRESSION = '"collector detail\\n" * 155000' diff --git a/tests/test_service_reference_evidence.py b/tests/harness/test_service_reference_evidence.py similarity index 97% rename from tests/test_service_reference_evidence.py rename to tests/harness/test_service_reference_evidence.py index 0001da760..1f1e1fbfc 100644 --- a/tests/test_service_reference_evidence.py +++ b/tests/harness/test_service_reference_evidence.py @@ -4,10 +4,10 @@ import subprocess import pytest -from test_project_service_reuse import begin, call, rejected, settings, submit -from test_project_service_reuse import campaign as campaign from inferrsi.harness import optimization +from tests.fixtures.service_reuse import begin, call, rejected, settings, submit +from tests.fixtures.service_reuse import campaign as campaign def assert_round_blocked(campaign): diff --git a/tests/test_session_lock_across_processes.py b/tests/harness/test_session_lock_across_processes.py similarity index 97% rename from tests/test_session_lock_across_processes.py rename to tests/harness/test_session_lock_across_processes.py index 28e2554f1..73e5fa77f 100644 --- a/tests/test_session_lock_across_processes.py +++ b/tests/harness/test_session_lock_across_processes.py @@ -21,8 +21,8 @@ import pytest -SRC = str(Path(__file__).resolve().parents[1] / "src") -PROBE_SCRIPT = Path(__file__).with_name("session_lock_probe.py") +SRC = str(Path(__file__).resolve().parents[2] / "src") +PROBE_SCRIPT = Path(__file__).parents[1] / "session_lock_probe.py" # A child process takes the named lock, reports it, then waits for a release file. HOLDER = """ diff --git a/tests/test_task_protocol_child.py b/tests/harness/test_task_protocol_child.py similarity index 100% rename from tests/test_task_protocol_child.py rename to tests/harness/test_task_protocol_child.py diff --git a/tests/knowledge/__init__.py b/tests/knowledge/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_ascend_video_diffusion_skill.py b/tests/knowledge/test_ascend_video_diffusion_skill.py similarity index 99% rename from tests/test_ascend_video_diffusion_skill.py rename to tests/knowledge/test_ascend_video_diffusion_skill.py index 94bf8199b..3f43ead9d 100644 --- a/tests/test_ascend_video_diffusion_skill.py +++ b/tests/knowledge/test_ascend_video_diffusion_skill.py @@ -7,7 +7,7 @@ from inferrsi.knowledge.skill_catalog import get_skill, skill_instructions, skill_records -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] SKILL_ROOT = ROOT / "src/inferrsi/knowledge/data/skill_library" SKILL_NAME = "ascend-video-diffusion-optimization" SKILL = SKILL_ROOT / "systems/platforms/ascend" / SKILL_NAME diff --git a/tests/test_bundle_manifest.py b/tests/knowledge/test_bundle_manifest.py similarity index 100% rename from tests/test_bundle_manifest.py rename to tests/knowledge/test_bundle_manifest.py diff --git a/tests/test_collect_limit_serialization.py b/tests/knowledge/test_collect_limit_serialization.py similarity index 100% rename from tests/test_collect_limit_serialization.py rename to tests/knowledge/test_collect_limit_serialization.py diff --git a/tests/test_collect_selection.py b/tests/knowledge/test_collect_selection.py similarity index 99% rename from tests/test_collect_selection.py rename to tests/knowledge/test_collect_selection.py index b03d82d70..bbbfda4f8 100644 --- a/tests/test_collect_selection.py +++ b/tests/knowledge/test_collect_selection.py @@ -8,7 +8,7 @@ from inferrsi.knowledge.knowledge_operations import Bundle, KnowledgeReader, _hash, _json from inferrsi.knowledge.knowledge_store import KnowledgeStore -ROOT = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library" +ROOT = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" CGROUP = "inferrsi.common.skills.cgroup_resource_controls" H3 = "inferrsi.common.skills.audit_h3_runtime_residency" AFD = "inferrsi.cuda.skills.audit_afd_p2p_exchanges" diff --git a/tests/test_compare_find_layouts.py b/tests/knowledge/test_compare_find_layouts.py similarity index 100% rename from tests/test_compare_find_layouts.py rename to tests/knowledge/test_compare_find_layouts.py diff --git a/tests/test_flare_knowledge.py b/tests/knowledge/test_flare_knowledge.py similarity index 97% rename from tests/test_flare_knowledge.py rename to tests/knowledge/test_flare_knowledge.py index 7bd41456a..84a5cee9a 100644 --- a/tests/test_flare_knowledge.py +++ b/tests/knowledge/test_flare_knowledge.py @@ -5,7 +5,7 @@ from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.knowledge.skill_catalog import get_skill, skill_metadata, skill_resource -ROOT = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library" +ROOT = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" NAME = "audit-flare-session-lifecycle" RELATIVE = f"systems/engines/flare-local-inference/{NAME}" IDENTITY = "inferrsi.cuda.skills.audit_flare_session_lifecycle" diff --git a/tests/test_h3_knowledge.py b/tests/knowledge/test_h3_knowledge.py similarity index 98% rename from tests/test_h3_knowledge.py rename to tests/knowledge/test_h3_knowledge.py index f9a120fec..a61db85ed 100644 --- a/tests/test_h3_knowledge.py +++ b/tests/knowledge/test_h3_knowledge.py @@ -10,7 +10,7 @@ from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.knowledge.skill_catalog import get_skill, skill_metadata, skill_resource -ROOT = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library" +ROOT = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" NAME = "audit-h3-runtime-residency" OWNER = ROOT / "systems/engines/h3-c" / NAME IDENTITY = "inferrsi.common.skills.audit_h3_runtime_residency" diff --git a/tests/test_h3_metal_knowledge.py b/tests/knowledge/test_h3_metal_knowledge.py similarity index 99% rename from tests/test_h3_metal_knowledge.py rename to tests/knowledge/test_h3_metal_knowledge.py index 65e5f1ac1..168670468 100644 --- a/tests/test_h3_metal_knowledge.py +++ b/tests/knowledge/test_h3_metal_knowledge.py @@ -22,7 +22,7 @@ from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.knowledge.skill_catalog import get_skill, skill_metadata -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] LIBRARY = PROJECT / "src/inferrsi/knowledge/data/skill_library" NAME = "audit-h3-metal-fasth3-semantics" OWNER = LIBRARY / "systems/engines/h3-metal" / NAME diff --git a/tests/test_hopper_knowledge.py b/tests/knowledge/test_hopper_knowledge.py similarity index 98% rename from tests/test_hopper_knowledge.py rename to tests/knowledge/test_hopper_knowledge.py index fb2cf18dc..e3c33dab2 100644 --- a/tests/test_hopper_knowledge.py +++ b/tests/knowledge/test_hopper_knowledge.py @@ -14,7 +14,7 @@ skill_resource, ) -ROOT = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library" +ROOT = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" NAME = "reason-hopper-kernels" OWNER = ROOT / "systems/platforms/cuda" / NAME IDENTITY = "inferrsi.cuda.skills.reason_hopper_kernels" diff --git a/tests/test_husky_document_research.py b/tests/knowledge/test_husky_document_research.py similarity index 99% rename from tests/test_husky_document_research.py rename to tests/knowledge/test_husky_document_research.py index 783144c62..ecf1f0b43 100644 --- a/tests/test_husky_document_research.py +++ b/tests/knowledge/test_husky_document_research.py @@ -14,7 +14,7 @@ from inferrsi.knowledge.skill_catalog import skill_metadata -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / 'src/inferrsi/knowledge/data/skill_library/systems/engines/husky' FIXTURES = PROJECT / 'tests/fixtures/repo_to_skill/husky' diff --git a/tests/test_indexer_evaluation_summary.py b/tests/knowledge/test_indexer_evaluation_summary.py similarity index 100% rename from tests/test_indexer_evaluation_summary.py rename to tests/knowledge/test_indexer_evaluation_summary.py diff --git a/tests/test_knowledge_channels.py b/tests/knowledge/test_knowledge_channels.py similarity index 100% rename from tests/test_knowledge_channels.py rename to tests/knowledge/test_knowledge_channels.py diff --git a/tests/test_knowledge_cli.py b/tests/knowledge/test_knowledge_cli.py similarity index 99% rename from tests/test_knowledge_cli.py rename to tests/knowledge/test_knowledge_cli.py index 8715e474d..98a365a54 100644 --- a/tests/test_knowledge_cli.py +++ b/tests/knowledge/test_knowledge_cli.py @@ -13,7 +13,7 @@ from inferrsi.knowledge.knowledge_operations import Bundle, KnowledgeReader from inferrsi.knowledge.knowledge_store import KnowledgeStore -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] SKILLS = REPO / "src/inferrsi/knowledge/data/skill_library" SOURCE = "calibrate-serving-simulation" LOCAL = f"{SOURCE}-local" diff --git a/tests/test_knowledge_compatibility_shells.py b/tests/knowledge/test_knowledge_compatibility_shells.py similarity index 100% rename from tests/test_knowledge_compatibility_shells.py rename to tests/knowledge/test_knowledge_compatibility_shells.py diff --git a/tests/test_knowledge_contract.py b/tests/knowledge/test_knowledge_contract.py similarity index 99% rename from tests/test_knowledge_contract.py rename to tests/knowledge/test_knowledge_contract.py index 359749541..05960b2c6 100644 --- a/tests/test_knowledge_contract.py +++ b/tests/knowledge/test_knowledge_contract.py @@ -14,7 +14,7 @@ skill_reference, ) -ROOT = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library" +ROOT = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" def test_local_profiles_preserve_core_and_structured_ownership(): diff --git a/tests/test_knowledge_declaration_paths.py b/tests/knowledge/test_knowledge_declaration_paths.py similarity index 100% rename from tests/test_knowledge_declaration_paths.py rename to tests/knowledge/test_knowledge_declaration_paths.py diff --git a/tests/test_knowledge_find.py b/tests/knowledge/test_knowledge_find.py similarity index 99% rename from tests/test_knowledge_find.py rename to tests/knowledge/test_knowledge_find.py index d76741a0a..fd5aa78d4 100644 --- a/tests/test_knowledge_find.py +++ b/tests/knowledge/test_knowledge_find.py @@ -28,7 +28,7 @@ tokens, ) -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] ROOT = Path(files("inferrsi").joinpath("knowledge", "data", "skill_library")) diff --git a/tests/test_knowledge_fresh_install.py b/tests/knowledge/test_knowledge_fresh_install.py similarity index 98% rename from tests/test_knowledge_fresh_install.py rename to tests/knowledge/test_knowledge_fresh_install.py index d56eaf024..84969c573 100644 --- a/tests/test_knowledge_fresh_install.py +++ b/tests/knowledge/test_knowledge_fresh_install.py @@ -8,7 +8,7 @@ (minutes of I/O, network access for the build-isolation backend, and an install backend). Run with: - RUN_FRESH_VENV=1 pytest tests/test_knowledge_fresh_install.py + 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 @@ -26,7 +26,7 @@ import pytest -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] SKILLS = REPO / "src" / "inferrsi" / "knowledge" / "data" / "skill_library" SOURCE = "calibrate-serving-simulation" diff --git a/tests/test_knowledge_install.py b/tests/knowledge/test_knowledge_install.py similarity index 99% rename from tests/test_knowledge_install.py rename to tests/knowledge/test_knowledge_install.py index d1b0ff313..95c5ba7b6 100644 --- a/tests/test_knowledge_install.py +++ b/tests/knowledge/test_knowledge_install.py @@ -11,7 +11,7 @@ from inferrsi.knowledge.knowledge_operations import KnowledgeReader -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] SKILLS = REPO / "src" / "inferrsi" / "knowledge" / "data" / "skill_library" SOURCE = "calibrate-serving-simulation" diff --git a/tests/test_knowledge_model_policy.py b/tests/knowledge/test_knowledge_model_policy.py similarity index 99% rename from tests/test_knowledge_model_policy.py rename to tests/knowledge/test_knowledge_model_policy.py index a1d0ef6fa..fe813bfc8 100644 --- a/tests/test_knowledge_model_policy.py +++ b/tests/knowledge/test_knowledge_model_policy.py @@ -43,7 +43,7 @@ within_budget, ) -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] HEAD = "a" * 40 BASE = "b" * 40 KNOWLEDGE = "src/inferrsi/knowledge/data/skill_library/records/cuda/case.json" @@ -220,7 +220,8 @@ def test_explicit_protected_paths_require_declarations(policy, path): # Their exact paths left the scope with the files; the implementations above stay in it. @pytest.mark.parametrize("path", ["README.md", "src/inferrsi/cli.py", "src/inferrsi/contracts/__init__.py", - "src/inferrsi/knowledge_store.py", "tests/test_claim.py", + "src/inferrsi/knowledge_store.py", + "tests/contracts/test_claim.py", "src/inferrsi/catalog.py", "src/inferrsi/skill_catalog.py", "src/inferrsi/knowledge_operations.py"]) def test_no_blanket_source_scope_and_stable_not_applicable(policy, path): diff --git a/tests/test_knowledge_operations.py b/tests/knowledge/test_knowledge_operations.py similarity index 97% rename from tests/test_knowledge_operations.py rename to tests/knowledge/test_knowledge_operations.py index ff2440faf..260953c7d 100644 --- a/tests/test_knowledge_operations.py +++ b/tests/knowledge/test_knowledge_operations.py @@ -13,7 +13,7 @@ safe_path, ) -ROOT = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library" +ROOT = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" def test_normalized_sources_and_original_catalog_identity(): @@ -347,21 +347,6 @@ def test_metadata_without_a_json_form_names_the_field_at_ingestion(): Bundle(metadata, {"x/SKILL.md": b"Body"}, {}) -def test_unrepresentable_metadata_names_the_offending_field(): - metadata = { - "id": "x", - "kind": "skill", - "entrypoint": "x/SKILL.md", - "sources": [{"type": "unknown", "tags": {1, 2}}], - "applicability": {}, - "state": "candidate", - "limitations": [], - "attribution": [], - } - with pytest.raises(ValueError, match="metadata.sources\\[0\\].tags.*set"): - Bundle(metadata, {"x/SKILL.md": b"Body"}, {}) - - def test_cyclic_alias_is_an_invalid_omission_not_a_crash(tmp_path): # YAML aliases can make a container its own descendant; normalization must # report that field instead of recursing until the interpreter gives up. diff --git a/tests/test_knowledge_policy_comment_routing.py b/tests/knowledge/test_knowledge_policy_comment_routing.py similarity index 99% rename from tests/test_knowledge_policy_comment_routing.py rename to tests/knowledge/test_knowledge_policy_comment_routing.py index 42a042e76..436479bd7 100644 --- a/tests/test_knowledge_policy_comment_routing.py +++ b/tests/knowledge/test_knowledge_policy_comment_routing.py @@ -11,7 +11,7 @@ from tools import check_knowledge_model_policy as policy -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] ELIGIBILITY = ( "github.event_name != 'issue_comment' || !github.event.issue || " "!github.event.comment || !github.event.action || " diff --git a/tests/test_knowledge_policy_http.py b/tests/knowledge/test_knowledge_policy_http.py similarity index 100% rename from tests/test_knowledge_policy_http.py rename to tests/knowledge/test_knowledge_policy_http.py diff --git a/tests/test_knowledge_policy_impact_routing.py b/tests/knowledge/test_knowledge_policy_impact_routing.py similarity index 100% rename from tests/test_knowledge_policy_impact_routing.py rename to tests/knowledge/test_knowledge_policy_impact_routing.py diff --git a/tests/test_knowledge_policy_push_health.py b/tests/knowledge/test_knowledge_policy_push_health.py similarity index 100% rename from tests/test_knowledge_policy_push_health.py rename to tests/knowledge/test_knowledge_policy_push_health.py diff --git a/tests/test_knowledge_policy_reporting.py b/tests/knowledge/test_knowledge_policy_reporting.py similarity index 99% rename from tests/test_knowledge_policy_reporting.py rename to tests/knowledge/test_knowledge_policy_reporting.py index 9dbf4f0da..87d850ca2 100644 --- a/tests/test_knowledge_policy_reporting.py +++ b/tests/knowledge/test_knowledge_policy_reporting.py @@ -196,7 +196,7 @@ def test_issue_comment_still_uses_current_head(self): class RunnerTests(unittest.TestCase): def run_runner(self, mode, event_name="pull_request_target"): - root = Path(__file__).resolve().parents[1] + root = Path(__file__).resolve().parents[2] with tempfile.TemporaryDirectory() as directory: temp = Path(directory) event = temp / "event.json" diff --git a/tests/test_knowledge_store.py b/tests/knowledge/test_knowledge_store.py similarity index 99% rename from tests/test_knowledge_store.py rename to tests/knowledge/test_knowledge_store.py index 9faf8d9ee..5296bba49 100644 --- a/tests/test_knowledge_store.py +++ b/tests/knowledge/test_knowledge_store.py @@ -19,7 +19,7 @@ ) from inferrsi.knowledge.knowledge_store import KnowledgeStore -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] ROOT = REPO / "src/inferrsi/knowledge/data/skill_library" NOTES = "playbooks/measurement/calibrate-serving-simulation/references/source-notes.md" LOCAL = "calibrate-serving-simulation-local" diff --git a/tests/test_knowledge_tiers.py b/tests/knowledge/test_knowledge_tiers.py similarity index 98% rename from tests/test_knowledge_tiers.py rename to tests/knowledge/test_knowledge_tiers.py index 383c2aa56..56f572e3b 100644 --- a/tests/test_knowledge_tiers.py +++ b/tests/knowledge/test_knowledge_tiers.py @@ -12,7 +12,7 @@ from inferrsi.knowledge.catalog import get_knowledge, search_knowledge from inferrsi.resources.repository_packs import repository_pack -ROOT = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library/records" +ROOT = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library/records" def test_external_snapshot_has_complete_navigation_and_pinned_sources(): diff --git a/tests/test_local_dream_repo_to_skill.py b/tests/knowledge/test_local_dream_repo_to_skill.py similarity index 99% rename from tests/test_local_dream_repo_to_skill.py rename to tests/knowledge/test_local_dream_repo_to_skill.py index 425b9ed9d..76181236a 100644 --- a/tests/test_local_dream_repo_to_skill.py +++ b/tests/knowledge/test_local_dream_repo_to_skill.py @@ -18,7 +18,7 @@ from inferrsi.knowledge.skill_catalog import skill_metadata -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/local-dream" CASES = PROJECT / "tests/fixtures/repo_to_skill/local-dream/test-cases" SCRIPT = ROOT / "scripts/screen_declarations.py" diff --git a/tests/test_mistral_rs_repo_to_skill.py b/tests/knowledge/test_mistral_rs_repo_to_skill.py similarity index 99% rename from tests/test_mistral_rs_repo_to_skill.py rename to tests/knowledge/test_mistral_rs_repo_to_skill.py index dc5aa2678..144c79c00 100644 --- a/tests/test_mistral_rs_repo_to_skill.py +++ b/tests/knowledge/test_mistral_rs_repo_to_skill.py @@ -18,7 +18,7 @@ from inferrsi.knowledge.skill_catalog import skill_metadata -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/mistral-rs" CASES = PROJECT / "tests/fixtures/repo_to_skill/mistral-rs/test-cases" SCRIPTS = { diff --git a/tests/test_mlc_llm_repo_to_skill.py b/tests/knowledge/test_mlc_llm_repo_to_skill.py similarity index 99% rename from tests/test_mlc_llm_repo_to_skill.py rename to tests/knowledge/test_mlc_llm_repo_to_skill.py index 0e4229064..5686f9d1a 100644 --- a/tests/test_mlc_llm_repo_to_skill.py +++ b/tests/knowledge/test_mlc_llm_repo_to_skill.py @@ -19,7 +19,7 @@ from inferrsi.knowledge.skill_catalog import skill_metadata -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/mlc-llm" CASES = PROJECT / "tests/fixtures/repo_to_skill/mlc-llm/test-cases" SCRIPTS = { diff --git a/tests/knowledge/test_mlx_knowledge.py b/tests/knowledge/test_mlx_knowledge.py new file mode 100644 index 000000000..ded72bedd --- /dev/null +++ b/tests/knowledge/test_mlx_knowledge.py @@ -0,0 +1,62 @@ +from pathlib import Path + +import pytest + +from inferrsi.knowledge.catalog import get_knowledge, search_knowledge +from inferrsi.knowledge.knowledge_operations import KnowledgeReader +from inferrsi.knowledge.skill_catalog import skill_metadata, skill_resource + +LIBRARY = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" + + +@pytest.mark.parametrize( + ("skill", "owner", "commit", "resource", "marker"), + [ + ( + "lazy-evaluation-stream-lifetimes", "frameworks/mlx", + "bff10220c742907f0c68e55ff174aaea56f74e3d", "source-map.md", "TEST-SOURCE", + ), + ( + "generation-cache-lifecycle", "engines/mlx-lm", + "ab7f7048dc341ced2d84b1887eeb17d60b0d1b02", "cache-stop.md", "LRUPromptCache", + ), + ], + ids=["mlx", "mlx-lm"], +) +def test_mlx_candidate_preserves_source_state_and_owner_resources( + skill, owner, commit, resource, marker +): + metadata = skill_metadata(LIBRARY, skill) + assert metadata["status"] == "candidate" + assert metadata["empirical_validation"] == "not_run" + assert metadata["sources"][0]["commit"] == commit + path = skill_resource(LIBRARY, skill, f"references/{resource}") + assert path.is_relative_to(LIBRARY / "systems" / owner / skill) + assert marker in path.read_text(encoding="utf-8") + + +@pytest.mark.parametrize( + ("query", "identity", "resources", "marker"), + [ + ( + "mlx", "inferrsi.common.skills.lazy_evaluation_stream_lifetimes", + ("source-map.md", "execution-lifetime.md"), b"source-derived candidate", + ), + ( + "mlx-lm", "inferrsi.common.skills.generation_cache_lifecycle", + ("source-map.md", "generation-batch.md", "cache-stop.md", "validation.md"), + b"cooperative", + ), + ], + ids=["mlx", "mlx-lm"], +) +def test_mlx_packaged_guidance_is_discoverable_and_complete(query, identity, resources, marker): + record = get_knowledge(identity) + assert record in search_knowledge(query, repo="inferrsi", limit=100) + assert record["backend"] == "common" + assert record["verification"]["locally_verified"] is False + bundle = KnowledgeReader(skill_root=LIBRARY).read(identity) + assert bundle.metadata["kind"] == "knowledge" + for resource in resources: + assert any(name.endswith(f"references/{resource}") for name in bundle.content) + assert any(marker in content for content in bundle.content.values()) diff --git a/tests/test_mlx_swift_lm_repo_to_skill.py b/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py similarity index 99% rename from tests/test_mlx_swift_lm_repo_to_skill.py rename to tests/knowledge/test_mlx_swift_lm_repo_to_skill.py index ad02375d7..33ab20aea 100644 --- a/tests/test_mlx_swift_lm_repo_to_skill.py +++ b/tests/knowledge/test_mlx_swift_lm_repo_to_skill.py @@ -19,7 +19,7 @@ from inferrsi.knowledge.skill_catalog import skill_metadata -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/mlx-swift-lm" CASES = PROJECT / "tests/fixtures/repo_to_skill/mlx-swift-lm/test-cases" SOURCE_COMMIT = "3d066d3a0ffdc7e70c476a3d31488ea62dfdd0ac" diff --git a/tests/test_model_sol_analysis.py b/tests/knowledge/test_model_sol_analysis.py similarity index 99% rename from tests/test_model_sol_analysis.py rename to tests/knowledge/test_model_sol_analysis.py index 916ede5f8..dfa335ab8 100644 --- a/tests/test_model_sol_analysis.py +++ b/tests/knowledge/test_model_sol_analysis.py @@ -12,7 +12,7 @@ from inferrsi.knowledge.knowledge_operations import KnowledgeReader -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] LIBRARY = ROOT / "src/inferrsi/knowledge/data/skill_library" OWNER = LIBRARY / "playbooks/measurement/model-sol-analysis" CODE = compile((OWNER / "scripts/model_sol.py").read_text(encoding="utf-8"), "model_sol.py", "exec") diff --git a/tests/test_performance_ceiling.py b/tests/knowledge/test_performance_ceiling.py similarity index 99% rename from tests/test_performance_ceiling.py rename to tests/knowledge/test_performance_ceiling.py index 7f28fe298..1095d3451 100644 --- a/tests/test_performance_ceiling.py +++ b/tests/knowledge/test_performance_ceiling.py @@ -9,7 +9,7 @@ from inferrsi.knowledge.knowledge_operations import KnowledgeReader -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] OWNER = (ROOT / "src/inferrsi/knowledge/data/skill_library/playbooks/measurement" / "performance-ceiling-analysis") CODE = compile((OWNER / "scripts/roofline.py").read_text(encoding="utf-8"), "roofline.py", "exec") diff --git a/tests/test_project_maya_repo_to_skill.py b/tests/knowledge/test_project_maya_repo_to_skill.py similarity index 99% rename from tests/test_project_maya_repo_to_skill.py rename to tests/knowledge/test_project_maya_repo_to_skill.py index 3d0f8a380..a7226146f 100644 --- a/tests/test_project_maya_repo_to_skill.py +++ b/tests/knowledge/test_project_maya_repo_to_skill.py @@ -13,7 +13,7 @@ from inferrsi.knowledge.skill_catalog import skill_metadata -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/project-maya" CASES = PROJECT / "tests/fixtures/repo_to_skill/project-maya/test-cases" diff --git a/tests/test_pytorch_torchnpu_integration.py b/tests/knowledge/test_pytorch_torchnpu_integration.py similarity index 99% rename from tests/test_pytorch_torchnpu_integration.py rename to tests/knowledge/test_pytorch_torchnpu_integration.py index 4e76aeda8..74db92121 100644 --- a/tests/test_pytorch_torchnpu_integration.py +++ b/tests/knowledge/test_pytorch_torchnpu_integration.py @@ -13,7 +13,7 @@ from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.knowledge.skill_catalog import skill_metadata, skill_resource -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] LIBRARY = PROJECT / "src/inferrsi/knowledge/data/skill_library" GRAPHS = (("pytorch", "common"), ("torch-npu", "ascend")) diff --git a/tests/test_qwen3_tts_knowledge.py b/tests/knowledge/test_qwen3_tts_knowledge.py similarity index 100% rename from tests/test_qwen3_tts_knowledge.py rename to tests/knowledge/test_qwen3_tts_knowledge.py diff --git a/tests/test_raw_string_selection.py b/tests/knowledge/test_raw_string_selection.py similarity index 100% rename from tests/test_raw_string_selection.py rename to tests/knowledge/test_raw_string_selection.py diff --git a/tests/knowledge/test_repo_to_skill.py b/tests/knowledge/test_repo_to_skill.py new file mode 100644 index 000000000..3bf987f3a --- /dev/null +++ b/tests/knowledge/test_repo_to_skill.py @@ -0,0 +1,147 @@ +"""Validate portable repo-to-skill graphs and their offline helpers.""" + +import json +import re +import runpy +import subprocess +import sys +from pathlib import Path +from urllib.parse import unquote, urlsplit + +import pytest +import yaml + +from inferrsi.knowledge.skill_catalog import skill_metadata + +PROJECT = Path(__file__).resolve().parents[2] +LIBRARY = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines" +FIXTURES = PROJECT / "tests/fixtures/repo_to_skill" +ENGINES = ("dwarfstar", "lily", "splash") + + +def frontmatter(path): + text = path.read_text(encoding="utf-8") + header = text.split("---", 2)[1] + assert re.search(r'^description: ".+"$', header, re.MULTILINE) + value = yaml.safe_load(header) + assert value["name"] == path.parent.name + assert re.fullmatch(r"[a-z0-9][a-z0-9-]{0,63}", value["name"]) + assert value["license"] == "NO_LICENSE" + assert value["disable-model-invocation"] is True + assert value["metadata"]["disco-role"] == "operating" + return value + + +@pytest.mark.parametrize("name", ENGINES) +def test_runtime_graph_links_frontmatter_and_source_boundaries(name): + root = LIBRARY / name + skills = list(root.rglob("SKILL.md")) + assert len(skills) == 4 + for path in skills: + frontmatter(path) + for path in root.rglob("*.md"): + text = path.read_text(encoding="utf-8") + assert not any(value in text for value in ("/workspace/", "/home/agent/")) + for target in re.findall(r"\]\(([^)]+)\)", text): + link = urlsplit(target) + if link.scheme or link.netloc or not link.path: + continue + selected = (path.parent / unquote(link.path)).resolve() + assert selected.is_relative_to(root.resolve()), (path, target) + assert selected.exists(), (path, target) + assert not list(root.rglob("__pycache__")) + assert not list(root.rglob("*.pyc")) + metadata = skill_metadata(root.parent, root.name) + assert metadata["status"] == "candidate" + assert metadata["construction"]["native_import"] == "not-run" + assert "BLOCKED_REQUIRED_BACKEND" in " ".join(metadata["limitations"]) + + +@pytest.mark.parametrize("name", ENGINES) +def test_assertion_cases_resolve_their_expected_runtime_resources(name): + root, cases = LIBRARY / name, FIXTURES / name / "test-cases" + assertions = list(cases.rglob("assertions.json")) + assert len(assertions) >= 9 + assert len(list((cases / "integration").glob("*/assertions.json"))) == 2 + for skill in (root / "sub-skills").iterdir(): + assert len(list((cases / "sub-skills" / skill.name).glob("*/assertions.json"))) >= 2 + for path in assertions: + case = json.loads(path.read_text(encoding="utf-8")) + assert case["schema"] == "disco.usability-case.v1" + assert case["assertions"] and case["evidence_basis"] + assert (path.parent / "user_request.txt").read_text().strip() + assert (path.parent / "README.md").is_file() + for relative in case["expected_skill_files"]: + selected = (root / relative).resolve() + assert selected.is_relative_to(root.resolve()) and selected.is_file() + + +def test_dwarfstar_request_helper_is_offline_and_validates_its_small_contract(): + script = LIBRARY / "dwarfstar/scripts/request_template.py" + result = subprocess.run( + [sys.executable, str(script), "--model", "local-model", "--prompt", "Hello"], + check=True, capture_output=True, text=True, + ) + value = json.loads(result.stdout) + assert value == { + "model": "local-model", "messages": [{"role": "user", "content": "Hello"}], + "max_tokens": 64, "temperature": 0.0, "stream": False, + } + invalid = subprocess.run( + [sys.executable, str(script), "--model", "x", "--prompt", "y", "--max-tokens", "0"], + capture_output=True, text=True, + ) + assert invalid.returncode == 2 and "positive" in invalid.stderr + + +def test_lily_offline_helpers_are_screening_not_native_validation(): + root = LIBRARY / "lily/sub-skills" + config = runpy.run_path(str(root / "model-runtime/scripts/screen_config.py")) + text = dict(config["EXPECTED"]) + text.update(attn_output_gate=True, tie_word_embeddings=False, + layer_types=["full_attention" if i % 4 == 3 else "linear_attention" + for i in range(40)]) + result = config["screen_config"]({"model_type": "qwen3_5_moe", "text_config": text, + "quantization": {"bits": 4, "group_size": 64}}, 4096) + assert result["status"] == "passed_selected_rules" and result["screen_only"] + assert result["native_validation"] == "not_run" and result["unchecked"] + request = runpy.run_path(str(root / "serving-cache/scripts/request_template.py")) + assert request["validate"]({"model": request["MODEL_ID"], + "messages": [{"role": "user", "content": "Hello"}]}) + process = subprocess.run( + [sys.executable, str(root / "serving-cache/scripts/request_template.py"), + "--prompt", "Hello", "--max-tokens", "2"], + check=True, capture_output=True, text=True, + ) + assert json.loads(process.stdout)["max_tokens"] == 2 + auditor = runpy.run_path(str(root / "qualification/scripts/audit_benchmark_record.py")) + digest = 0xCBF29CE484222325 + for token in [1, 2]: + digest = ((digest ^ token) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF + record = { + "schema_version": 1, "meta": {"engine": "lily", "source_id": "a" * 40}, + "workload": {"gpu_timing_diagnostic": False, "decode_steps": 2, "prompt_len": 4}, + "results": {"prefill": {"wall_secs": 1, "tok_s": 4}, + "decode": {"wall_secs": 1, "tok_s": 2, "step_wall_secs": [0.5, 0.5], + "token_ids": [1, 2], "token_digest": f"{digest:016x}", + "gpu_passes": [], "lookahead_gpu_pass": None}}, + } + result = auditor["audit"](record, "a" * 40, 2) + assert result["record_consistent"] and "no native execution" in result["scope"] + + +def test_splash_offline_helpers_keep_syntax_and_statistics_separate_from_verdict(): + root = LIBRARY / "splash" + parser = runpy.run_path(str(root / "sub-skills/runtime-planning/scripts/parse_budget.py")) + assert parser["parse_budget"]("max-memory", "2.5G") == 2684354560 + assert parser["parse_budget"]("ple-memory", "off") == "off" + summarizer = runpy.run_path(str(root / "sub-skills/qualification/scripts/summarize_rounds.py")) + value = summarizer["summarize"]({"rounds": [[100], [90], [92], [102]]}) + assert value["baseline"] == 101 and value["candidate"] == 91 + assert "verdict" not in value and "descriptive" in value["scope"] + result = subprocess.run( + [sys.executable, str(root / "scripts/request_template.py"), + "--model", "local-model", "--prompt", "Hello", "--cache-salt", "scope"], + check=True, capture_output=True, text=True, + ) + assert json.loads(result.stdout)["cache_salt"] == "scope" diff --git a/tests/test_repository_packs_facade.py b/tests/knowledge/test_repository_packs_facade.py similarity index 98% rename from tests/test_repository_packs_facade.py rename to tests/knowledge/test_repository_packs_facade.py index c9d378cd2..cc8d06e30 100644 --- a/tests/test_repository_packs_facade.py +++ b/tests/knowledge/test_repository_packs_facade.py @@ -27,9 +27,9 @@ from inferrsi.apps.host import inspection from inferrsi.knowledge import catalog as knowledge_catalog from inferrsi.resources import repository_packs -from tests.test_contracts_package import IO_CONTROL, IO_PROBE +from tests.contracts.test_contracts_package import IO_CONTROL, IO_PROBE -SRC = Path(__file__).resolve().parents[1] / "src" +SRC = Path(__file__).resolve().parents[2] / "src" ROOT = SRC / "inferrsi" PACKS = ROOT / "harness" / "data" / "repo_packs" SEVEN = ("vllm", "vllm_omni", "afd_plugin", "vllm_rlt", "strata", "sglang", "sglang_omni") diff --git a/tests/test_research.py b/tests/knowledge/test_research.py similarity index 100% rename from tests/test_research.py rename to tests/knowledge/test_research.py diff --git a/tests/test_resource_migration.py b/tests/knowledge/test_resource_migration.py similarity index 98% rename from tests/test_resource_migration.py rename to tests/knowledge/test_resource_migration.py index 602935b1c..12de7fa40 100644 --- a/tests/test_resource_migration.py +++ b/tests/knowledge/test_resource_migration.py @@ -6,7 +6,7 @@ unchanged by the move. An installed wheel outside the checkout is covered by -``tests/test_knowledge_fresh_install.py`` and ``tests/check_installed.py``; under +``tests/knowledge/test_knowledge_fresh_install.py`` and ``tests/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. @@ -27,7 +27,7 @@ except ModuleNotFoundError: # Python 3.10: pytest supplies tomli. import tomli as tomllib -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] CHECKOUT = PROJECT / "src" / "inferrsi" KNOWLEDGE_DATA = CHECKOUT / "knowledge" / "data" HARNESS_DATA = CHECKOUT / "harness" / "data" diff --git a/tests/test_skill_catalog.py b/tests/knowledge/test_skill_catalog.py similarity index 99% rename from tests/test_skill_catalog.py rename to tests/knowledge/test_skill_catalog.py index 7cd3a86a6..b660c35a4 100644 --- a/tests/test_skill_catalog.py +++ b/tests/knowledge/test_skill_catalog.py @@ -16,7 +16,7 @@ skill_resource, ) -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] @pytest.mark.parametrize(("relative", "children"), [ diff --git a/tests/test_skill_coverage_view.py b/tests/knowledge/test_skill_coverage_view.py similarity index 99% rename from tests/test_skill_coverage_view.py rename to tests/knowledge/test_skill_coverage_view.py index 331af0e8a..d79362b8f 100644 --- a/tests/test_skill_coverage_view.py +++ b/tests/knowledge/test_skill_coverage_view.py @@ -6,7 +6,7 @@ from tools import build_skill_coverage as coverage -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] OUTPUT = PROJECT / coverage.OUTPUT LIBRARY = PROJECT / coverage.LIBRARY diff --git a/tests/test_skill_index.py b/tests/knowledge/test_skill_index.py similarity index 99% rename from tests/test_skill_index.py rename to tests/knowledge/test_skill_index.py index a49a274e2..82a2d942f 100644 --- a/tests/test_skill_index.py +++ b/tests/knowledge/test_skill_index.py @@ -14,7 +14,7 @@ from tools import build_skill_index as index_builder from tools.build_skill_index import DESTINATION, LIBRARY, build_index, render_index, source_inputs -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / LIBRARY diff --git a/tests/test_skill_library.py b/tests/knowledge/test_skill_library.py similarity index 99% rename from tests/test_skill_library.py rename to tests/knowledge/test_skill_library.py index 7ca2bf8dc..095b9f59a 100644 --- a/tests/test_skill_library.py +++ b/tests/knowledge/test_skill_library.py @@ -10,7 +10,7 @@ from inferrsi.apps.cli import main from inferrsi.knowledge.catalog import get_knowledge, knowledge_records, search_knowledge -PACKAGE = Path(__file__).resolve().parents[1] / "src/inferrsi" +PACKAGE = Path(__file__).resolve().parents[2] / "src/inferrsi" LIBRARY = PACKAGE / "knowledge/data/skill_library" REPOSITORIES = ("strata", "vllm", "sglang", "sglang_omni", "vllm_omni") diff --git a/tests/test_skill_library_readers.py b/tests/knowledge/test_skill_library_readers.py similarity index 99% rename from tests/test_skill_library_readers.py rename to tests/knowledge/test_skill_library_readers.py index c4fdcfee9..6b9d2cb1b 100644 --- a/tests/test_skill_library_readers.py +++ b/tests/knowledge/test_skill_library_readers.py @@ -208,7 +208,7 @@ def test_cli_defaults_to_installed_library_and_allows_custom_root(tmp_path, monk def test_package_catalog_and_reader_do_not_require_yaml(): - source = Path(__file__).resolve().parents[1] / "src" + source = Path(__file__).resolve().parents[2] / "src" environment = {**os.environ, "PYTHONPATH": str(source)} result = subprocess.run( [ diff --git a/tests/test_source_snapshot.py b/tests/knowledge/test_source_snapshot.py similarity index 99% rename from tests/test_source_snapshot.py rename to tests/knowledge/test_source_snapshot.py index 5f7f09e1f..f7bd4c430 100644 --- a/tests/test_source_snapshot.py +++ b/tests/knowledge/test_source_snapshot.py @@ -13,7 +13,7 @@ from tools import build_skill_index as index_builder from tools.build_skill_index import DESTINATION -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] GENERATED = PROJECT / DESTINATION REVISION = "a" * 40 # These fixtures hold their corpus at the recorded location, where the physical diff --git a/tests/test_vllm_ascend_rc_skill.py b/tests/knowledge/test_vllm_ascend_skills.py similarity index 67% rename from tests/test_vllm_ascend_rc_skill.py rename to tests/knowledge/test_vllm_ascend_skills.py index f9faf3441..7399fed58 100644 --- a/tests/test_vllm_ascend_rc_skill.py +++ b/tests/knowledge/test_vllm_ascend_skills.py @@ -1,3 +1,5 @@ +"""Packaged vLLM Ascend guidance, provenance, and history screening.""" + import json import re import runpy @@ -11,10 +13,80 @@ from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.knowledge.skill_catalog import skill_instructions, skill_metadata, skill_resource -LIBRARY = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library" +LIBRARY = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" NAME = "vllm-ascend" +@pytest.mark.parametrize( + ("query", "expected_skill_id"), + [ + # Query 1: ACLGraph capture/replay runtime contract + ( + "ACLGraph capture replay", + "inferrsi.ascend.skills.ascend_aclgraph_capture_replay", + ), + ( + "vLLM-Ascend ACLGraph", + "inferrsi.ascend.skills.ascend_aclgraph_capture_replay", + ), + # Query 2: Model adaptation and FP8 checkpoint onboarding + ( + "FP8 checkpoint", + "inferrsi.ascend.skills.ascend_model_adaptation", + ), + # Query 3: KV replication with Tensor Parallelism + ( + "KV replication TP", + "inferrsi.ascend.skills.ascend_model_adaptation", + ), + # Query 4: Multimodal feature validation + ( + "multimodal feature validation", + "inferrsi.ascend.skills.ascend_model_adaptation", + ), + ], +) +def test_batch1_skills_are_discoverable_for_representative_queries( + query, expected_skill_id +): + results = search_knowledge(query, repo="inferrsi", backend="ascend", limit=5) + skill_ids = [item["id"] for item in results] + assert expected_skill_id in skill_ids, ( + f"Query {query!r} expected {expected_skill_id} in {skill_ids}" + ) + + +@pytest.mark.parametrize( + ("skill", "notes_terms", "instruction_terms"), + [ + ( + "ascend-aclgraph-capture-replay", + ("8a8e1e05ecb64a30804c99c8f362909f9a0cb5bf", "acl_graph.py"), + ("cudagraph_capture_sizes", "ENPU"), + ), + ( + "ascend-model-adaptation", + ("bc8115ed7fdc7e500320b5de70742ef049b4c1a2", "Three-Tier Responsibility"), + ("--load-format dummy", "weight_scale_inv", "tp_size > num_key_value_heads"), + ), + ], + ids=["aclgraph-capture-replay", "model-adaptation"], +) +def test_distilled_skill_metadata_and_contracts(skill, notes_terms, instruction_terms): + metadata = skill_metadata(LIBRARY, skill) + assert metadata["status"] == "candidate" + assert metadata["empirical_validation"] == "not_run" + assert "references/source-notes.md" in metadata["provenance_readsets"] + + notes = skill_resource(LIBRARY, skill, "references/source-notes.md").read_text(encoding="utf-8") + for term in notes_terms: + assert term in notes + + instructions = skill_instructions(LIBRARY, skill) + for term in instruction_terms: + assert term in instructions + + @pytest.mark.parametrize(("query", "route"), [ ("v0.27.1rc1 plugin registration", "plugin-registration.md"), ("MiniMax-M3 FP8", "minimax-cache.md"), diff --git a/tests/test_vllm_ascend_source_anchors.py b/tests/knowledge/test_vllm_ascend_source_anchors.py similarity index 100% rename from tests/test_vllm_ascend_source_anchors.py rename to tests/knowledge/test_vllm_ascend_source_anchors.py diff --git a/tests/test_vllm_metal_repo_to_skill.py b/tests/knowledge/test_vllm_metal_repo_to_skill.py similarity index 99% rename from tests/test_vllm_metal_repo_to_skill.py rename to tests/knowledge/test_vllm_metal_repo_to_skill.py index 11add6a6e..56cb50ee2 100644 --- a/tests/test_vllm_metal_repo_to_skill.py +++ b/tests/knowledge/test_vllm_metal_repo_to_skill.py @@ -17,7 +17,7 @@ from inferrsi.knowledge.skill_catalog import skill_metadata -PROJECT = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[2] ROOT = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines/vllm-metal" CASES = PROJECT / "tests/fixtures/repo_to_skill/vllm-metal/test-cases" diff --git a/tests/repository/__init__.py b/tests/repository/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_architecture_anchors.py b/tests/repository/test_architecture_anchors.py similarity index 98% rename from tests/test_architecture_anchors.py rename to tests/repository/test_architecture_anchors.py index 984d451b5..2c10812a7 100644 --- a/tests/test_architecture_anchors.py +++ b/tests/repository/test_architecture_anchors.py @@ -8,7 +8,7 @@ from tools.check_pr_references import anchor_section -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] ARCHITECTURE = ROOT / "docs" / "architecture.md" CODE_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})([^\n]*)$") HEADING = re.compile(r"^#{1,6}[ \t]+([^\n]+)$") diff --git a/tests/test_architecture_closed_loop.py b/tests/repository/test_architecture_closed_loop.py similarity index 99% rename from tests/test_architecture_closed_loop.py rename to tests/repository/test_architecture_closed_loop.py index 682f9d464..2a567a4ee 100644 --- a/tests/test_architecture_closed_loop.py +++ b/tests/repository/test_architecture_closed_loop.py @@ -20,10 +20,10 @@ PackageKnowledgeRead, ) -LOOP = Path(__file__).with_name("architecture_closed_loop.py") -PORTS = Path(__file__).with_name("architecture_real_ports.py") -LAYOUT = Path(__file__).resolve().parents[1] / "docs" / "module-layout.md" -ROOT = Path(__file__).resolve().parents[1] +LOOP = Path(__file__).parents[1] / "architecture_closed_loop.py" +PORTS = Path(__file__).parents[1] / "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 # Harness runner, and Apps, Knowledge or Benchmark as packages. BANNED_FAMILIES = ( diff --git a/tests/test_campaign_plan_template.py b/tests/repository/test_campaign_plan_template.py similarity index 99% rename from tests/test_campaign_plan_template.py rename to tests/repository/test_campaign_plan_template.py index ae8152366..df64c1ca1 100644 --- a/tests/test_campaign_plan_template.py +++ b/tests/repository/test_campaign_plan_template.py @@ -12,7 +12,7 @@ import pytest -REPO_ROOT = Path(__file__).resolve().parents[1] +REPO_ROOT = Path(__file__).resolve().parents[2] PLAN_DIR = REPO_ROOT / "evidence" / "_template" / "plan" MARKDOWN = PLAN_DIR / "campaign-plan.md" MACHINE = PLAN_DIR / "campaign-plan.yaml" diff --git a/tests/test_check_labels.py b/tests/repository/test_check_labels.py similarity index 99% rename from tests/test_check_labels.py rename to tests/repository/test_check_labels.py index f5605b685..cbb83d3f2 100644 --- a/tests/test_check_labels.py +++ b/tests/repository/test_check_labels.py @@ -5,7 +5,7 @@ from tools import check_labels as check -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] MANIFEST = json.loads((ROOT / ".github/labels.json").read_text(encoding="utf-8")) EXTERNAL = json.loads((ROOT / ".github/external-labels.json").read_text(encoding="utf-8")) EXTERNAL_NAMES = {entry["name"] for entry in EXTERNAL} diff --git a/tests/test_evidence_archives.py b/tests/repository/test_evidence_archives.py similarity index 99% rename from tests/test_evidence_archives.py rename to tests/repository/test_evidence_archives.py index 09254df78..048b9ce38 100644 --- a/tests/test_evidence_archives.py +++ b/tests/repository/test_evidence_archives.py @@ -15,7 +15,7 @@ from tools.validate_evidence import budget_assets, validate_inventory from tools.verify_evidence_archive import main -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] def make_tar(path, entries): diff --git a/tests/test_evidence_inventory.py b/tests/repository/test_evidence_inventory.py similarity index 99% rename from tests/test_evidence_inventory.py rename to tests/repository/test_evidence_inventory.py index 824424ef8..475ab343d 100644 --- a/tests/test_evidence_inventory.py +++ b/tests/repository/test_evidence_inventory.py @@ -142,7 +142,7 @@ def test_external_archive_is_explicit_then_verified_when_available(bundle): def test_checked_in_inventory(): - repo = Path(__file__).resolve().parents[1] + repo = Path(__file__).resolve().parents[2] result = validate_inventory(repo) assert result["errors"] == [] assert len(result["bundles"]) == 26 diff --git a/tests/test_first_wave_isolation_policy.py b/tests/repository/test_first_wave_isolation_policy.py similarity index 100% rename from tests/test_first_wave_isolation_policy.py rename to tests/repository/test_first_wave_isolation_policy.py diff --git a/tests/test_frozen_bytes.py b/tests/repository/test_frozen_bytes.py similarity index 98% rename from tests/test_frozen_bytes.py rename to tests/repository/test_frozen_bytes.py index a7e10e6d8..d7aa4f9fc 100644 --- a/tests/test_frozen_bytes.py +++ b/tests/repository/test_frozen_bytes.py @@ -6,7 +6,7 @@ import pytest -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] def git(repo, *args): diff --git a/tests/test_legacy_run_forwarder_gate.py b/tests/repository/test_legacy_run_forwarder_gate.py similarity index 97% rename from tests/test_legacy_run_forwarder_gate.py rename to tests/repository/test_legacy_run_forwarder_gate.py index ad5e2e662..38fb11b66 100644 --- a/tests/test_legacy_run_forwarder_gate.py +++ b/tests/repository/test_legacy_run_forwarder_gate.py @@ -6,7 +6,7 @@ from tests import _gate_policy_support as support from tests._gate_policy_support import first_wave_report -from tests.test_first_wave_isolation_policy import CLEARED_TREE, EMPTY_ALLOWLIST, _report +from tests.repository.test_first_wave_isolation_policy import CLEARED_TREE, EMPTY_ALLOWLIST, _report # The exact targets that were registered before R1. RETIRED_FORWARDERS = { diff --git a/tests/test_module_boundaries.py b/tests/repository/test_module_boundaries.py similarity index 98% rename from tests/test_module_boundaries.py rename to tests/repository/test_module_boundaries.py index 418548dc5..9e338199e 100644 --- a/tests/test_module_boundaries.py +++ b/tests/repository/test_module_boundaries.py @@ -100,7 +100,7 @@ def test_cuda_qualification_accepts_campaign_supplied_count_and_sku(monkeypatch) def test_shared_layers_do_not_import_campaigns_or_reverse_dependencies(): - root = Path(__file__).resolve().parents[1] / "src/inferrsi" + root = Path(__file__).resolve().parents[2] / "src/inferrsi" # The Anthropic providers came from the retired model/ package and keep its rule: no # Harness import. Other integrations, such as Cannbot, are Apps code and may use Harness. for plane in ("apps/host", "apps/integrations/anthropic", "harness"): diff --git a/tests/test_package_root_inventory.py b/tests/repository/test_package_root_inventory.py similarity index 99% rename from tests/test_package_root_inventory.py rename to tests/repository/test_package_root_inventory.py index ac3b4136c..6f0177791 100644 --- a/tests/test_package_root_inventory.py +++ b/tests/repository/test_package_root_inventory.py @@ -13,7 +13,7 @@ import pytest -REPO = Path(__file__).resolve().parents[1] +REPO = Path(__file__).resolve().parents[2] PACKAGE = "src/inferrsi" # The 27 tracked root files before C1, minus the four that C1 moved into contracts/, # the two that C2 moved into resources/, contracts/ and apps/, the eleven that R1 diff --git a/tests/test_pr_references.py b/tests/repository/test_pr_references.py similarity index 99% rename from tests/test_pr_references.py rename to tests/repository/test_pr_references.py index 23802c3c3..7e3daf8ea 100644 --- a/tests/test_pr_references.py +++ b/tests/repository/test_pr_references.py @@ -5,7 +5,7 @@ from tools import check_pr_references as check -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] # Negated sentences from merged PR bodies that GitHub still treated as closing syntax. HISTORICAL = [ diff --git a/tests/test_release.py b/tests/repository/test_release.py similarity index 99% rename from tests/test_release.py rename to tests/repository/test_release.py index 712b0cf6e..50cdbc284 100644 --- a/tests/test_release.py +++ b/tests/repository/test_release.py @@ -62,7 +62,7 @@ def change_source(git): def test_wheel_version_discovery_ignores_nearer_nonrelease_tags(release_repo): git = release_repo - project = Path(__file__).resolve().parents[1] / "pyproject.toml" + project = Path(__file__).resolve().parents[2] / "pyproject.toml" with project.open("rb") as stream: scm = tomllib.load(stream)["tool"]["setuptools_scm"] command = shlex.split(scm["git_describe_command"]) diff --git a/tests/test_release_notes.py b/tests/repository/test_release_notes.py similarity index 100% rename from tests/test_release_notes.py rename to tests/repository/test_release_notes.py diff --git a/tests/test_release_publisher.py b/tests/repository/test_release_publisher.py similarity index 99% rename from tests/test_release_publisher.py rename to tests/repository/test_release_publisher.py index f50e353b3..d1da46b48 100644 --- a/tests/test_release_publisher.py +++ b/tests/repository/test_release_publisher.py @@ -10,7 +10,7 @@ import pytest import yaml -WORKFLOW = Path(__file__).resolve().parents[1] / ".github/workflows/release.yml" +WORKFLOW = Path(__file__).resolve().parents[2] / ".github/workflows/release.yml" COMMIT = "1" * 40 MOCK_GH = r'''#!/usr/bin/env python diff --git a/tests/test_smoke.py b/tests/repository/test_smoke.py similarity index 100% rename from tests/test_smoke.py rename to tests/repository/test_smoke.py diff --git a/tests/test_target_module_import_gate.py b/tests/repository/test_target_module_import_gate.py similarity index 99% rename from tests/test_target_module_import_gate.py rename to tests/repository/test_target_module_import_gate.py index 6b7d4ae55..d60d897b4 100644 --- a/tests/test_target_module_import_gate.py +++ b/tests/repository/test_target_module_import_gate.py @@ -549,7 +549,7 @@ def test_module_entry_rule_covers_no_other_shape_target_or_file(self) -> None: def test_layout_doc_states_the_same_limit(self) -> None: text = ( - Path(__file__).resolve().parents[1] / "docs" / "module-layout.md" + Path(__file__).resolve().parents[2] / "docs" / "module-layout.md" ).read_text(encoding="utf-8") self.assertIn("Isolation stays false", text) self.assertIn("Same-core imports are allowed", text) diff --git a/tests/test_template_layout.py b/tests/repository/test_template_layout.py similarity index 90% rename from tests/test_template_layout.py rename to tests/repository/test_template_layout.py index c51cb6107..4579d8c25 100644 --- a/tests/test_template_layout.py +++ b/tests/repository/test_template_layout.py @@ -2,7 +2,7 @@ from pathlib import Path from urllib.parse import unquote, urlsplit -REPO_ROOT = Path(__file__).resolve().parents[1] +REPO_ROOT = Path(__file__).resolve().parents[2] def test_evidence_template_segments() -> None: @@ -22,7 +22,7 @@ def test_maintained_documentation_links_resolve() -> None: documents = [REPO_ROOT / "README.md", REPO_ROOT / "AGENTS.md"] 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"] + documents += [REPO_ROOT / "evidence/README.md", REPO_ROOT / "tests/README.md"] for document in documents: for target in re.findall( r"\[[^\]]*\]\(([^\s)]+)\)", document.read_text(encoding="utf-8") diff --git a/tests/session_lock_probe.py b/tests/session_lock_probe.py index d8175213b..c6271da8b 100644 --- a/tests/session_lock_probe.py +++ b/tests/session_lock_probe.py @@ -1,6 +1,6 @@ """Hold a real optimization session's lock from a separate Harness process, then export it. -Run by tests/test_session_lock_across_processes.py once per interpreter: against the +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 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 diff --git a/tests/skill_eval/__init__.py b/tests/skill_eval/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/skill_eval/_budget_git_support.py b/tests/skill_eval/_budget_git_support.py new file mode 100644 index 000000000..9ae00ba2e --- /dev/null +++ b/tests/skill_eval/_budget_git_support.py @@ -0,0 +1,32 @@ +"""Git data objects shared by the PR and daily budget store fakes.""" + +import base64 +import copy +import hashlib +import json + + +class GitObjects: + def __init__(self): + self.objects = {} + + 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({ + "encoding": "base64", "size": len(raw), "content": base64.b64encode(raw).decode(), + }) + return self.put({ + "truncated": False, + "tree": [{"path": "ledger.json", "mode": "100644", "type": "blob", "sha": blob}], + }) + + def commit(self, tree, parents, **fields): + return self.put({"tree": {"sha": tree}, "parents": [{"sha": p} for p in parents], **fields}) diff --git a/tests/test_skill_eval_artifact_guidance.py b/tests/skill_eval/test_skill_eval_artifact_guidance.py similarity index 99% rename from tests/test_skill_eval_artifact_guidance.py rename to tests/skill_eval/test_skill_eval_artifact_guidance.py index 163ea2e7e..8b7c5e6b3 100644 --- a/tests/test_skill_eval_artifact_guidance.py +++ b/tests/skill_eval/test_skill_eval_artifact_guidance.py @@ -196,7 +196,7 @@ def test_comparison_preserves_deferred_capture_and_uses_independent_checks(): def test_existing_report_cli_integrates_missing_evidence_first_screen(tmp_path): - from tests.test_skill_eval_generation import prepared + from tests.skill_eval.test_skill_eval_generation import prepared from tools import skill_eval_compare as compare _, output, _ = prepared(tmp_path) diff --git a/tests/test_skill_eval_auto.py b/tests/skill_eval/test_skill_eval_auto.py similarity index 100% rename from tests/test_skill_eval_auto.py rename to tests/skill_eval/test_skill_eval_auto.py diff --git a/tests/test_skill_eval_auto_daily.py b/tests/skill_eval/test_skill_eval_auto_daily.py similarity index 100% rename from tests/test_skill_eval_auto_daily.py rename to tests/skill_eval/test_skill_eval_auto_daily.py diff --git a/tests/test_skill_eval_budget.py b/tests/skill_eval/test_skill_eval_budget.py similarity index 100% rename from tests/test_skill_eval_budget.py rename to tests/skill_eval/test_skill_eval_budget.py diff --git a/tests/test_skill_eval_budget_git.py b/tests/skill_eval/test_skill_eval_budget_git.py similarity index 93% rename from tests/test_skill_eval_budget_git.py rename to tests/skill_eval/test_skill_eval_budget_git.py index 959411bb2..5389a1bdb 100644 --- a/tests/test_skill_eval_budget_git.py +++ b/tests/skill_eval/test_skill_eval_budget_git.py @@ -1,13 +1,11 @@ """Credential-free Git-data API model; no remote writes/provider requests.""" -import base64 import copy -import hashlib -import json from dataclasses import replace import pytest +from tests.skill_eval._budget_git_support import GitObjects from tools import skill_eval_budget as budget from tools.skill_eval_budget_git import GitHubGitStore, LedgerAnchor @@ -19,11 +17,12 @@ def binding(number=1, amount=50_000_000): return budget.Binding(f"{number:064x}", f"run-{number}:attempt-1", amount) -class GitAPI: +class GitAPI(GitObjects): """Immutable objects plus non-force fast-forward reference updates.""" def __init__(self): - self.objects, self.calls = {}, [] + super().__init__() + self.calls = [] self.tip = None self.before_patch = None self.lose_response = False @@ -33,23 +32,10 @@ def __init__(self): self.genesis = self.append(ledger, parents=[]) self.anchor = LedgerAnchor(KEY, REF, self.genesis, self.genesis) - def put(self, value): - sha = hashlib.sha1(json.dumps(value, sort_keys=True).encode()).hexdigest() - self.objects[sha] = {**value, "sha": sha} - return sha - - def tree(self, content): - raw = content.encode() - blob = self.put({"encoding": "base64", "size": len(raw), - "content": base64.b64encode(raw).decode()}) - return self.put({"truncated": False, "tree": [{"path": "ledger.json", - "mode": "100644", "type": "blob", "sha": blob}]}) - def append(self, ledger, parents=None): tree = self.tree(budget.encode(ledger)) parents = [self.tip] if parents is None else parents - self.tip = self.put({"tree": {"sha": tree}, - "parents": [{"sha": p} for p in parents]}) + self.tip = self.commit(tree, parents) return self.tip def ref(self): @@ -64,16 +50,14 @@ def request(self, method, path, data=None): return {"id": self.repository_id} if path.startswith("/git/ref/"): return self.ref() - return copy.deepcopy(self.objects[path.rsplit("/", 1)[1]]) + 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.put({"tree": {"sha": data["tree"]}, - "parents": [{"sha": p} for p in data["parents"]], - "message": data["message"]})} + 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: diff --git a/tests/test_skill_eval_cloud_replay.py b/tests/skill_eval/test_skill_eval_cloud_replay.py similarity index 98% rename from tests/test_skill_eval_cloud_replay.py rename to tests/skill_eval/test_skill_eval_cloud_replay.py index 67021d456..e2ceda775 100644 --- a/tests/test_skill_eval_cloud_replay.py +++ b/tests/skill_eval/test_skill_eval_cloud_replay.py @@ -95,7 +95,7 @@ def test_no_arbitrary_ingress_url_and_no_redirect(): def test_workflow_inputs_not_interpolated_into_shell(): - root = Path(__file__).resolve().parents[1] + root = Path(__file__).resolve().parents[2] text = (root / ".github/workflows/skill-eval-cloud-replay.yml").read_text() workflow = yaml.safe_load(text) assert set(workflow[True]) == {"workflow_dispatch"} diff --git a/tests/test_skill_eval_compare.py b/tests/skill_eval/test_skill_eval_compare.py similarity index 100% rename from tests/test_skill_eval_compare.py rename to tests/skill_eval/test_skill_eval_compare.py diff --git a/tests/test_skill_eval_daily_budget.py b/tests/skill_eval/test_skill_eval_daily_budget.py similarity index 89% rename from tests/test_skill_eval_daily_budget.py rename to tests/skill_eval/test_skill_eval_daily_budget.py index 4569a1d46..5d70c7aeb 100644 --- a/tests/test_skill_eval_daily_budget.py +++ b/tests/skill_eval/test_skill_eval_daily_budget.py @@ -1,13 +1,10 @@ """Offline standard-library tests; no credentials, network, or provider calls.""" -import base64 -import copy -import hashlib -import json import unittest from dataclasses import replace from datetime import datetime, timezone +from tests.skill_eval._budget_git_support import GitObjects from tools import skill_eval_budget as b from tools.skill_eval_budget_git import DailyLedgerAnchor, GitHubDailyStore @@ -22,30 +19,17 @@ def binding(n, amount=200_000_000): return b.Binding(f"{n:064x}", f"{n}.1", amount) -class API: +class API(GitObjects): def __init__(self, ledger=None): - self.objects = {} + super().__init__() self.tip = None self.before_patch = None 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) - def put(self, value): - sha = hashlib.sha1(json.dumps(value, sort_keys=True).encode()).hexdigest() - self.objects[sha] = {**value, "sha": sha} - return sha - - def tree(self, content): - raw = content.encode() - blob = self.put({"encoding": "base64", "size": len(raw), - "content": base64.b64encode(raw).decode()}) - return self.put({"truncated": False, "tree": [{"path": "ledger.json", - "mode": "100644", "type": "blob", "sha": blob}]}) - def append(self, ledger, parents): - self.tip = self.put({"tree": {"sha": self.tree(b.encode_daily(ledger))}, - "parents": [{"sha": p} for p in parents]}) + self.tip = self.commit(self.tree(b.encode_daily(ledger)), parents) return self.tip def ref(self): @@ -59,13 +43,11 @@ def request(self, method, path, data=None): return {"id": 123} if path.startswith("/git/ref/"): return self.ref() - return copy.deepcopy(self.objects[path.rsplit("/", 1)[1]]) + return self.read_object(path) if path == "/git/trees": return {"sha": self.tree(data["tree"][0]["content"])} if path == "/git/commits": - return {"sha": self.put({"tree": {"sha": data["tree"]}, - "parents": [{"sha": p} for p in data["parents"]], - "message": data["message"]})} + 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: diff --git a/tests/test_skill_eval_deployment.py b/tests/skill_eval/test_skill_eval_deployment.py similarity index 100% rename from tests/test_skill_eval_deployment.py rename to tests/skill_eval/test_skill_eval_deployment.py diff --git a/tests/test_skill_eval_diagnostic.py b/tests/skill_eval/test_skill_eval_diagnostic.py similarity index 99% rename from tests/test_skill_eval_diagnostic.py rename to tests/skill_eval/test_skill_eval_diagnostic.py index 44734ebfc..ef14b0279 100644 --- a/tests/test_skill_eval_diagnostic.py +++ b/tests/skill_eval/test_skill_eval_diagnostic.py @@ -13,7 +13,7 @@ from tools import skill_eval_compare as compare CASES = json.loads( - (Path(__file__).parent / 'fixtures/skill_eval_diagnostic_cases.json').read_text()) + (Path(__file__).parents[1] / 'fixtures/skill_eval_diagnostic_cases.json').read_text()) # Independently authored expected responses: never emitted into model workspaces. ANSWERS = [ ('readiness', ['E2'], 'check_receive_completion'), diff --git a/tests/test_skill_eval_engineering.py b/tests/skill_eval/test_skill_eval_engineering.py similarity index 99% rename from tests/test_skill_eval_engineering.py rename to tests/skill_eval/test_skill_eval_engineering.py index c5cab4975..bbf5ba260 100644 --- a/tests/test_skill_eval_engineering.py +++ b/tests/skill_eval/test_skill_eval_engineering.py @@ -26,7 +26,7 @@ def test_old_and_canonical_script_entries_write_the_same_result(tmp_path, module task, output, result = (tmp_path / name for name in ("task.json", "output.json", "result.json")) task.write_text(json.dumps(TASK), encoding="utf-8") output.write_text("{}", encoding="utf-8") - source = Path(__file__).resolve().parents[1] / "src" + source = Path(__file__).resolve().parents[2] / "src" arguments = [str(source / (module.replace(".", "/") + ".py"))] if by_file else ["-m", module] environment = {**os.environ, "PYTHONPATH": str(source), "INFERRSI_RESULT_PATH": str(result)} executed = subprocess.run( @@ -39,7 +39,7 @@ def test_old_and_canonical_script_entries_write_the_same_result(tmp_path, module def test_starter_matches_frozen_fixture(): - fixture = Path(__file__).parent / "fixtures/skill_eval_engineering/parser.py" + fixture = Path(__file__).parents[1] / "fixtures/skill_eval_engineering/parser.py" assert fixture.read_text() == engineering.STARTER diff --git a/tests/test_skill_eval_feedback.py b/tests/skill_eval/test_skill_eval_feedback.py similarity index 99% rename from tests/test_skill_eval_feedback.py rename to tests/skill_eval/test_skill_eval_feedback.py index fa5a07d07..e25506943 100644 --- a/tests/test_skill_eval_feedback.py +++ b/tests/skill_eval/test_skill_eval_feedback.py @@ -13,7 +13,7 @@ from tools import skill_eval_feedback as feedback from tools import skill_eval_pr as integration -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] TASK_PATH = ROOT / 'tests/fixtures/skill-comparison/pr133-diagnostic-case05.json' TASK = json.loads(TASK_PATH.read_text())[0] OLD = dict(diagnosis='capacity', evidence=['E4'], next_check='inspect_allocator_accounting', diff --git a/tests/test_skill_eval_generation.py b/tests/skill_eval/test_skill_eval_generation.py similarity index 100% rename from tests/test_skill_eval_generation.py rename to tests/skill_eval/test_skill_eval_generation.py diff --git a/tests/test_skill_eval_historical_accounting.py b/tests/skill_eval/test_skill_eval_historical_accounting.py similarity index 100% rename from tests/test_skill_eval_historical_accounting.py rename to tests/skill_eval/test_skill_eval_historical_accounting.py diff --git a/tests/test_skill_eval_historical_job.py b/tests/skill_eval/test_skill_eval_historical_job.py similarity index 100% rename from tests/test_skill_eval_historical_job.py rename to tests/skill_eval/test_skill_eval_historical_job.py diff --git a/tests/test_skill_eval_local.py b/tests/skill_eval/test_skill_eval_local.py similarity index 65% rename from tests/test_skill_eval_local.py rename to tests/skill_eval/test_skill_eval_local.py index 7f64fd873..67cbc0dbc 100644 --- a/tests/test_skill_eval_local.py +++ b/tests/skill_eval/test_skill_eval_local.py @@ -1,5 +1,8 @@ -"""Local handoff software controls; fake grader results are not agent efficacy.""" +"""Local handoff CLI and API tests with synthetic inputs and verifier results.""" + import json +import shutil +import sys import pytest @@ -11,18 +14,26 @@ from tools import skill_eval_compare as compare from tools import skill_eval_local as local +CORRECT_CONTROL = "# hand-authored synthetic correct control; no model execution\n" -def prepared(tmp_path): + +def local_configuration(tmp_path, provenance): config_path, repo = configuration(tmp_path, ids=("parser",), repeats=1) config = json.loads(config_path.read_text()) config["adapter"] = engineering.ADAPTER write_json(config_path, config) - write_json(tmp_path / "cases.json", [{"id": "parser", "split": "development", - "request": engineering.REQUEST, - "provenance": "public reconstructed test fixture"}]) + write_json(tmp_path / "cases.json", [{ + "id": "parser", "split": "development", "request": engineering.REQUEST, + "provenance": provenance, + }]) + return config_path, repo, config["snapshots"]["candidate"]["git_revision"] + + +def prepared(tmp_path): + config_path, repo, head = local_configuration(tmp_path, "public reconstructed test fixture") output = tmp_path / "run" digest = compare.prepare(config_path, repo, output) - return output, digest, config["snapshots"]["candidate"]["git_revision"] + return output, digest, head def submission(tmp_path, output): @@ -313,3 +324,144 @@ def crlf_write_text(self, data, encoding=None, errors=None, newline=None): trial = result["pairs"][0]["baseline"] assert trial["evaluation_error"] == ("inputs_changed" if tamper else None) assert trial["verdict"] == ("INCONCLUSIVE" if tamper else "PASS") + + +def cli(monkeypatch, capsys, *args): + monkeypatch.setattr(sys, "argv", ["skill_eval_compare", *map(str, args)]) + compare.main() + stdout = capsys.readouterr().out + return json.loads(stdout) if stdout else None + + +def prepare_cli(tmp_path, monkeypatch, capsys): + # A routing regression must fail this test, never start the automatic client. + def forbidden_execute(*args, **kwargs): + pytest.fail("The manual CLI handoff must not launch an agent") + + monkeypatch.setattr(compare, "execute", forbidden_execute) + config_path, repo, head = local_configuration( + tmp_path, "synthetic CLI software control, not an agent trial" + ) + output = tmp_path / "run" + prepared = cli(monkeypatch, capsys, "prepare", "--output", output, + "--config", config_path, "--repo", repo) + assert prepared == {"plan_sha256": sha256(output / "plan/freeze.json")} + return output, prepared["plan_sha256"], head + + +def handoff_args(output, digest, head, role): + return ("execute", "--output", output, "--authorize", digest, + "--task-id", "parser", "--condition", role, "--repeat", "1", + "--current-head", head) + + +@pytest.mark.parametrize("sandbox_unavailable", [False, True]) +def test_cli_two_arm_capture_and_report_keep_synthetic_provenance( + tmp_path, monkeypatch, capsys, sandbox_unavailable): + output, digest, head = prepare_cli(tmp_path, monkeypatch, capsys) + verified_sources = [] + + def synthetic_verify(task, answer): + engineering.validate_task(task) + verified_sources.append(answer["artifact_source"]) + if sandbox_unavailable: + raise sandbox.SandboxUnavailable("synthetic unavailable-host control") + passed = answer["artifact_source"] == CORRECT_CONTROL + return {"passed": passed, "assertions": {"synthetic_cli_control": passed}} + + monkeypatch.setattr(artifact_check, "verify", synthetic_verify) + plan = compare.load_plan(output) + retained_sources = [] + for role in compare.ROLES: + workspace = tmp_path / role + args = handoff_args(output, digest, head, role) + cli(monkeypatch, capsys, *args, "--stage-local", workspace) + if role == "candidate": + (workspace / "parser.py").write_text(CORRECT_CONTROL, encoding="utf-8") + source = (workspace / "parser.py").read_bytes() + retained_sources.append(source.decode("utf-8")) + logs = tmp_path / (role + "-submission") + logs.mkdir() + metadata = { + "model": plan["model"], "environment": "synthetic CLI fixture", + "access": "hand-authored control; no actual agent or hardware run", + "resources": "no provider calls or charges; not model usage evidence", + "usage": None, "elapsed_seconds": 1.0, "agent_exit_code": 0, + "summary": "synthetic software control only: " + role, + } + write_json(logs / "execution.json", metadata) + (logs / "stdout.log").write_text(role + " synthetic author log\n", encoding="utf-8") + (logs / "stderr.log").write_bytes(b"") + cli(monkeypatch, capsys, *args, "--capture-local", workspace, + "--submission", logs) + entry = next(entry for entry in plan["schedule"] if entry["condition"] == role) + directory = compare.trial_directory(output, entry) + assert (directory / "parser.py").read_bytes() == source + assert json.loads((directory / "author-execution.json").read_text()) == metadata + for name in ("stdout.log", "stderr.log"): + assert (directory / "agent" / name).read_bytes() == (logs / name).read_bytes() + assert json.loads((directory / "receipt.json").read_text()) == { + "result_sha256": sha256(directory / "result.json")} + + retained = {p: p.read_bytes() for p in (output / "results").rglob("*") if p.is_file()} + with pytest.raises(ValueError, match="already started"): + cli(monkeypatch, capsys, *args, "--capture-local", workspace, "--submission", logs) + assert all(p.read_bytes() == value for p, value in retained.items()) + for role in compare.ROLES: + shutil.rmtree(tmp_path / role) + shutil.rmtree(tmp_path / (role + "-submission")) + # The report must use the retained closure, not the now-absent live workspaces. + before_replay = len(verified_sources) + assert cli(monkeypatch, capsys, "report", "--output", output) is None + result = json.loads((output / "report.json").read_text()) + assert retained == {p: p.read_bytes() for p in (output / "results").rglob("*") + if p.is_file()} + assert sorted(verified_sources[before_replay:]) == sorted(retained_sources) + assert result["status"]["execution_state"] == "author_reported_unverified" + assert "do not prove skill causality" in result["claim"] + pair = result["pairs"][0] + assert pair["comparability"] == "unverified_author_reported" + for role in compare.ROLES: + trial = pair[role] + assert trial["author_reported_execution"] is True + assert trial["observations"]["usage"] is None + assert "costs not independently verified" in trial["provenance"] + if sandbox_unavailable: + assert trial["verdict"] == "INCONCLUSIVE" + assert trial["artifact_verdict"] is None + assert trial["evaluation_error"] == "artifact_sandbox_unavailable" + else: + assert trial["artifact_verdict"] == ("PASS" if role == "candidate" else "FAIL") + assert trial["grader_trust"] == "reverified" + assert trial["artifact_checks"]["assertions"] == { + "synthetic_cli_control": role == "candidate"} + assert result["counts"]["artifact_improved"] == (0 if sandbox_unavailable else 1) + assert not (output / "results/start.json").exists() + assert "do not authorize merge" in (output / "report.md").read_text() + + +def test_cli_rejects_stale_head_and_incomplete_capture_before_writing( + tmp_path, monkeypatch, capsys): + output, digest, head = prepare_cli(tmp_path, monkeypatch, capsys) + workspace = tmp_path / "baseline" + args = handoff_args(output, digest, head, "baseline") + with pytest.raises(ValueError, match="head differs"): + cli(monkeypatch, capsys, *handoff_args(output, digest, "0" * 40, "baseline"), + "--stage-local", workspace) + assert not workspace.exists() + with pytest.raises(SystemExit) as error: + cli(monkeypatch, capsys, *args[:-2], "--stage-local", workspace) + assert error.value.code == 2 + assert "--current-head" in capsys.readouterr().err + assert not workspace.exists() + cli(monkeypatch, capsys, *args, "--stage-local", workspace) + before = {p: p.read_bytes() for p in output.rglob("*") if p.is_file()} + with pytest.raises(ValueError, match="head differs"): + cli(monkeypatch, capsys, *handoff_args(output, digest, "0" * 40, "baseline"), + "--capture-local", workspace, "--submission", tmp_path / "not-submitted") + assert {p: p.read_bytes() for p in output.rglob("*") if p.is_file()} == before + with pytest.raises(SystemExit) as error: + cli(monkeypatch, capsys, *args, "--capture-local", workspace) + assert error.value.code == 2 + assert "Capture requires --submission" in capsys.readouterr().err + assert {p: p.read_bytes() for p in output.rglob("*") if p.is_file()} == before diff --git a/tests/test_skill_eval_optional_dependencies.py b/tests/skill_eval/test_skill_eval_optional_dependencies.py similarity index 98% rename from tests/test_skill_eval_optional_dependencies.py rename to tests/skill_eval/test_skill_eval_optional_dependencies.py index c7ed2299f..abc429bcf 100644 --- a/tests/test_skill_eval_optional_dependencies.py +++ b/tests/skill_eval/test_skill_eval_optional_dependencies.py @@ -9,7 +9,7 @@ class OptionalSkillsDependencyTests(unittest.TestCase): def run_without_yaml(self, source): - root = Path(__file__).resolve().parents[1] + root = Path(__file__).resolve().parents[2] script = ( f"import sys; sys.path[:0] = {[str(root), str(root / 'src')]!r}\n" "sys.modules['yaml'] = None\n" diff --git a/tests/test_skill_eval_pipeline.py b/tests/skill_eval/test_skill_eval_pipeline.py similarity index 99% rename from tests/test_skill_eval_pipeline.py rename to tests/skill_eval/test_skill_eval_pipeline.py index 995c627c1..01c49f396 100644 --- a/tests/test_skill_eval_pipeline.py +++ b/tests/skill_eval/test_skill_eval_pipeline.py @@ -12,7 +12,7 @@ from inferrsi.apps.workflows.skill_evaluation import run_trial, summarize from tools import skill_eval_pilot -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] FIXTURES = ROOT / "tests/fixtures" DATA = json.loads((FIXTURES / "skill_eval_grading.json").read_text(encoding="utf-8")) diff --git a/tests/test_skill_eval_planned_guidance.py b/tests/skill_eval/test_skill_eval_planned_guidance.py similarity index 99% rename from tests/test_skill_eval_planned_guidance.py rename to tests/skill_eval/test_skill_eval_planned_guidance.py index c0973307f..2e9061e97 100644 --- a/tests/test_skill_eval_planned_guidance.py +++ b/tests/skill_eval/test_skill_eval_planned_guidance.py @@ -11,7 +11,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.test_skill_eval_pr_summary import visible +from tests.skill_eval.test_skill_eval_pr_summary import visible from tools import skill_eval_pr as pr diff --git a/tests/test_skill_eval_planning_boundaries.py b/tests/skill_eval/test_skill_eval_planning_boundaries.py similarity index 99% rename from tests/test_skill_eval_planning_boundaries.py rename to tests/skill_eval/test_skill_eval_planning_boundaries.py index 50f8905a0..c08325a60 100644 --- a/tests/test_skill_eval_planning_boundaries.py +++ b/tests/skill_eval/test_skill_eval_planning_boundaries.py @@ -10,7 +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 SimulatedGitHub, setup -from tests.test_skill_eval_pr import dispatch_event +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 diff --git a/tests/test_skill_eval_pr.py b/tests/skill_eval/test_skill_eval_pr.py similarity index 100% rename from tests/test_skill_eval_pr.py rename to tests/skill_eval/test_skill_eval_pr.py diff --git a/tests/test_skill_eval_pr_diagnostic.py b/tests/skill_eval/test_skill_eval_pr_diagnostic.py similarity index 97% rename from tests/test_skill_eval_pr_diagnostic.py rename to tests/skill_eval/test_skill_eval_pr_diagnostic.py index ed72ba2d9..a118a658b 100644 --- a/tests/test_skill_eval_pr_diagnostic.py +++ b/tests/skill_eval/test_skill_eval_pr_diagnostic.py @@ -7,7 +7,7 @@ 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.test_skill_eval_diagnostic import CASES, answer +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 diff --git a/tests/test_skill_eval_pr_http.py b/tests/skill_eval/test_skill_eval_pr_http.py similarity index 100% rename from tests/test_skill_eval_pr_http.py rename to tests/skill_eval/test_skill_eval_pr_http.py diff --git a/tests/test_skill_eval_pr_summary.py b/tests/skill_eval/test_skill_eval_pr_summary.py similarity index 100% rename from tests/test_skill_eval_pr_summary.py rename to tests/skill_eval/test_skill_eval_pr_summary.py diff --git a/tests/test_skill_eval_qualify.py b/tests/skill_eval/test_skill_eval_qualify.py similarity index 97% rename from tests/test_skill_eval_qualify.py rename to tests/skill_eval/test_skill_eval_qualify.py index f764add74..9c4aa1435 100644 --- a/tests/test_skill_eval_qualify.py +++ b/tests/skill_eval/test_skill_eval_qualify.py @@ -63,7 +63,7 @@ def test_control_mismatch_fails(change): def test_control_is_existing_reviewed_fixture(): - tree = ast.parse((qualify.ROOT / "tests/test_skill_eval_engineering.py").read_text()) + tree = ast.parse((qualify.ROOT / "tests/skill_eval/test_skill_eval_engineering.py").read_text()) source = next(ast.literal_eval(node.value) for node in tree.body if isinstance(node, ast.Assign) and any( isinstance(target, ast.Name) and target.id == "GOOD_ARTIFACT" diff --git a/tests/test_skill_eval_quarantine.py b/tests/skill_eval/test_skill_eval_quarantine.py similarity index 98% rename from tests/test_skill_eval_quarantine.py rename to tests/skill_eval/test_skill_eval_quarantine.py index 4ae0f5499..4eedc2323 100644 --- a/tests/test_skill_eval_quarantine.py +++ b/tests/skill_eval/test_skill_eval_quarantine.py @@ -5,7 +5,7 @@ from pathlib import Path from unittest.mock import Mock, patch -from tests.test_skill_eval_daily_budget import API, DAY, KEY, PR, binding +from tests.skill_eval.test_skill_eval_daily_budget import API, DAY, KEY, PR, binding from tools import skill_eval_budget as b from tools import skill_eval_quarantine as q from tools.skill_eval_budget_git import GitHubDailyStore diff --git a/tests/test_skill_eval_retained.py b/tests/skill_eval/test_skill_eval_retained.py similarity index 100% rename from tests/test_skill_eval_retained.py rename to tests/skill_eval/test_skill_eval_retained.py diff --git a/tests/test_skill_eval_retention.py b/tests/skill_eval/test_skill_eval_retention.py similarity index 98% rename from tests/test_skill_eval_retention.py rename to tests/skill_eval/test_skill_eval_retention.py index 2dd4840ab..40dd887d5 100644 --- a/tests/test_skill_eval_retention.py +++ b/tests/skill_eval/test_skill_eval_retention.py @@ -6,10 +6,10 @@ import pytest from inferrsi.apps.artifacts import write_json -from tests import test_skill_eval_auto as auto_tests from tests.fixtures.skill_eval_compare_support import FixedOutputClient from tests.fixtures.skill_eval_pr_support import SimulatedGitHub, approval, setup -from tests.test_skill_eval_pr import dispatch_event +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/test_skill_eval_review_guidance.py b/tests/skill_eval/test_skill_eval_review_guidance.py similarity index 100% rename from tests/test_skill_eval_review_guidance.py rename to tests/skill_eval/test_skill_eval_review_guidance.py diff --git a/tests/test_skill_eval_snapshot.py b/tests/skill_eval/test_skill_eval_snapshot.py similarity index 100% rename from tests/test_skill_eval_snapshot.py rename to tests/skill_eval/test_skill_eval_snapshot.py diff --git a/tests/test_skill_eval_verifier.py b/tests/skill_eval/test_skill_eval_verifier.py similarity index 98% rename from tests/test_skill_eval_verifier.py rename to tests/skill_eval/test_skill_eval_verifier.py index e52e19719..7bf75d880 100644 --- a/tests/test_skill_eval_verifier.py +++ b/tests/skill_eval/test_skill_eval_verifier.py @@ -7,7 +7,7 @@ from tools.skill_eval_verifier import verify FIXTURE = json.loads( - (Path(__file__).parent / "fixtures/skill_eval_grading.json").read_text(encoding="utf-8") + (Path(__file__).parents[1] / "fixtures/skill_eval_grading.json").read_text(encoding="utf-8") ) CASES = FIXTURE["cases"] diff --git a/tests/test_skill_evaluation.py b/tests/skill_eval/test_skill_evaluation.py similarity index 99% rename from tests/test_skill_evaluation.py rename to tests/skill_eval/test_skill_evaluation.py index 501a8d287..66ce942ec 100644 --- a/tests/test_skill_evaluation.py +++ b/tests/skill_eval/test_skill_evaluation.py @@ -11,7 +11,7 @@ from inferrsi.harness.skill_evaluation import CodexClient, toml_value, trace_metrics from inferrsi.knowledge.knowledge_operations import KnowledgeReader -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] def load_tool(name): diff --git a/tests/test_apps_generated_cli.py b/tests/test_apps_generated_cli.py deleted file mode 100644 index d6f2789be..000000000 --- a/tests/test_apps_generated_cli.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Exercise a generated candidate under a distinct, saved CLI evaluation attempt.""" - -import json -from pathlib import Path - -from inferrsi.apps.cli import main -from inferrsi.benchmark import cpu_smoke -from inferrsi.benchmark.workers import fixture_worker as worker -from inferrsi.harness import execution_service -from tests.test_apps_evaluate_cli import arguments, execute_request, save, target_config -from tests.test_apps_generation_plan import generation as generation -from tests.test_harness_generation_lineage import lineage as lineage -from tests.test_harness_generation_seal import cpu_generation as cpu_generation - - -def test_generated_candidate_through_saved_commands(lineage, tmp_path, capsys): - config = lineage["config"] - runtime = target_config({"target": lineage["evaluation_target"]}) - code = Path(worker.__file__) - protocol = cpu_smoke.protocol( - code.read_bytes(), control_domain=execution_service._CONTROL_DOMAIN, - ) - runtime["benchmark"] = { - "protocol": str(save(tmp_path, "protocol.json", protocol)), "worker_role": "worker-code", - "resources": {"worker-code": str(code), "baseline-code": str(code)}, - } - prepare = {"schema_version": 1, "request": cpu_smoke.default_request()} - assert main(arguments(tmp_path, "prepare", prepare, config, runtime, output="cli-prepare")) == 0 - request = execute_request(lineage) - request["prepared_ref"] = json.loads(capsys.readouterr().out)["prepared_ref"] - generation_ref = lineage["generated"]["record_ref"] - assert request["attempt"]["attempt_id"] != generation_ref["attempt_id"] - - assert main(arguments(tmp_path, "execute", request, config, runtime, output="cli-execute") - + ["--capture-evidence"]) == 0 - executed = json.loads(capsys.readouterr().out) - assert executed["execution"]["generation_record_ref"] == generation_ref - assert executed["record_ref"]["attempt_id"] == request["attempt"]["attempt_id"] - assessment = {"schema_version": 1, "record_ref": executed["record_ref"], - "primary_scope": "p1", "primary_claim_id": "C"} - assert main(arguments(tmp_path, "assess", assessment, config, output="cli-assess")) == 8 - assessed = json.loads(capsys.readouterr().out)["assessment"] - assert assessed["record_ref"] == executed["record_ref"] - assert [(item["claim_id"], item["verdict"]) for item in assessed["claims"]] == [ - ("F", "PASS"), ("C", "FAIL"), ("M", "PASS"), - ] diff --git a/tests/test_claim.py b/tests/test_claim.py deleted file mode 100644 index 9e65d460c..000000000 --- a/tests/test_claim.py +++ /dev/null @@ -1,20 +0,0 @@ -from inferrsi.contracts.claim import Verdict, claim_requires_pinned_shas, parse_verdict - - -def test_parse_verdict() -> None: - assert parse_verdict("pass") is Verdict.PASS - assert parse_verdict("FAIL") is Verdict.FAIL - - -def test_invalid_verdict() -> None: - try: - parse_verdict("MAYBE") - except ValueError as exc: - assert "INCONCLUSIVE" in str(exc) - else: - raise AssertionError("expected ValueError") - - -def test_pass_requires_pins() -> None: - assert claim_requires_pinned_shas(Verdict.PASS) is True - assert claim_requires_pinned_shas(Verdict.INCONCLUSIVE) is False diff --git a/tests/test_dashboard_candidate_events_ui.py b/tests/test_dashboard_candidate_events_ui.py deleted file mode 100644 index 268d6caed..000000000 --- a/tests/test_dashboard_candidate_events_ui.py +++ /dev/null @@ -1,65 +0,0 @@ -"""A bound agent event can be inspected without a caller-authored optimization trace.""" - -import shutil -import subprocess -from pathlib import Path - -import pytest - - -@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is needed for this UI regression") -def test_candidate_event_disclosure_and_live_elapsed(): - template = Path(__file__).parents[1] / "src/inferrsi/apps/views/template.html" - script = r""" -const fs=require('node:fs'),assert=require('node:assert/strict'); -const html=fs.readFileSync(process.argv[1],'utf8'); -const section=(a,b)=>html.slice(html.indexOf(' function '+a+'('), - html.indexOf(' function '+b+'(')); -const source=section('jumpToEvent','renderRoundInputs')+ - section('refreshElapsed','eventLabel')+section('eventLabel','stageFacts')+ - section('renderCandidateEvents','renderCandidate'); -const bound=[ - {source:'events',line:1,phase:'complete',details:{state:'completed'},refs:[]}, - {source:'agent_trace',line:1,type:'agent.tool',stage:'search',tool:'submit_candidate', - details:{count:3},refs:[{sha256:'a'.repeat(64)}]}]; -const row={candidate_id:'first',round:1,run_id:'run',events:bound,optimization_trace:null, - unlinked_agent_events:[{source:'agent_trace',line:2,details:{name:'UNBOUND_PAYLOAD'}}], - agent_trace_links:{unlinked:[2],mismatched:[3]},corrupt_event_sources:{events:[],agent_trace:[4]}}; -const node=(tag,text='')=>({tag,textContent:text,children:[],dataset:{},listeners:{},open:false, - get childElementCount(){return this.children.length}, - append(...nodes){this.children.push(...nodes)},setAttribute(){}, - addEventListener(name,fn){this.listeners[name]=fn},showModal(){this.open=true}}); -const all=n=>[n,...n.children.flatMap(all)]; -const panels=Object.fromEntries( - ['event-body','event-heading','event-record'].map(id=>[id,node(id)])); -const clockCell=node('td');clockCell.dataset.started='2026-01-01T00:00:00Z'; -const env={data:{candidates:[row]},selected:0,identity:()=>row.candidate_id,byId:id=>panels[id], - clear:n=>n.children=[],node,translated:s=>s,workNames:{},stageNames:{search:'Candidate search'}, - refText:ref=>ref.sha256,liveMode:true,serverTime:Date.parse('2026-01-01T00:00:07Z'), - document:{querySelectorAll:()=>[clockCell]},duration:s=>s+' s'}; -const api=new Function(...Object.keys(env),source+ - '\nreturn {renderCandidateEvents,refreshElapsed,jumpToEvent};')(...Object.values(env)); -const root=node('div'); -api.renderCandidateEvents(root,row); -const fold=root.children[0]; -assert.equal(fold.tag,'details');assert.equal(fold.open,false); -assert.equal(all(fold).filter(n=>n.tag==='button').length,0); -fold.open=true;fold.listeners.toggle(); -fold.listeners.toggle(); -const buttons=all(fold).filter(n=>n.tag==='button'); -assert.equal(buttons.length,2); -const button=buttons.find(b=>b.textContent.includes('submit_candidate')); -assert(button.textContent.includes('agent_trace:1'));button.listeners.click(); -assert(panels['event-record'].open);assert.equal(panels['event-heading'].textContent,'Tool call'); -const content=all(panels['event-body']).map(n=>n.textContent).join('\n'); -assert(content.includes('agent_trace:1') && content.includes('submit_candidate')); -assert(content.includes('"count": 3') && content.includes('a'.repeat(64))); -const labels=all(fold).map(n=>n.textContent).join('\n'); -for(const ref of ['agent_trace:2','agent_trace:3','agent_trace:4'])assert(labels.includes(ref)); -assert(!labels.includes('UNBOUND_PAYLOAD')); -panels['event-record'].open=false;api.jumpToEvent('agent_trace',2); -assert.equal(panels['event-record'].open,false); -api.refreshElapsed();assert.equal(clockCell.textContent,'Elapsed since start · 7 s'); -""" - subprocess.run([shutil.which("node"), "-e", script, str(template)], check=True, - capture_output=True, text=True) diff --git a/tests/test_engineering_benchmarks.py b/tests/test_engineering_benchmarks.py deleted file mode 100644 index affa25908..000000000 --- a/tests/test_engineering_benchmarks.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Discovery and normal entry points for the packaged NPU workloads.""" - -import json -import os -import subprocess -import sys -from pathlib import Path - -import pytest - -from inferrsi.apps.cli import main -from inferrsi.benchmark.registry import builtin_tasks, describe_task, task_resources -from inferrsi.harness import optimization_session - -EXPECTED = { - "moe-forward-npu": "moe-shared-ep2-npu-v1", - "qwen21-denoise-npu": "qwen21-denoise-npu-v1", - "qwen3-tts-npu": "qwen3-tts-npu-v2", -} - - -def test_cli_lists_the_three_packaged_workloads(capsys): - assert main(["benchmarks", "list"]) == 0 - assert json.loads(capsys.readouterr().out) == sorted(EXPECTED) - assert builtin_tasks() == sorted(EXPECTED) - - -def test_cli_lists_packaged_iterative_workloads(capsys): - assert main(["benchmarks", "list", "--iterative"]) == 0 - assert json.loads(capsys.readouterr().out) == ["moe-forward-npu", "qwen21-denoise-npu"] - - -def test_benchmark_list_help_documents_iterative(capsys): - with pytest.raises(SystemExit) as result: - main(["benchmarks", "list", "--help"]) - assert result.value.code == 0 - assert "--iterative" in capsys.readouterr().out - - -@pytest.mark.parametrize("name,task_id", EXPECTED.items()) -def test_cli_show_reads_the_relocated_manifest(name, task_id, capsys): - assert main(["benchmarks", "show", name]) == 0 - result = json.loads(capsys.readouterr().out) - assert result["package"] == name - assert result["manifest"]["id"] == task_id - assert result["manifest"]["backend"] == "ascend" - for resource in result["files"]: - assert task_resources(name).joinpath(resource).is_file() - assert {"task.json", "TASK.md", "baseline.py", "LICENSE"} <= set(result["files"]) - assert "benchmark.py" in result["files"] - - -def test_cwd_package_cannot_shadow_packaged_task(tmp_path, monkeypatch): - shadow = tmp_path / "qwen3-tts-npu" - shadow.mkdir() - (shadow / "task.json").write_text('{"id": "shadow"}', encoding="utf-8") - monkeypatch.chdir(tmp_path) - assert describe_task("qwen3-tts-npu")["manifest"]["id"] == EXPECTED["qwen3-tts-npu"] - - -@pytest.mark.parametrize("name", ["missing-task", "../qwen3-tts-npu"]) -def test_unknown_packages_are_rejected(name): - with pytest.raises(ValueError, match="Unknown engineering benchmark"): - task_resources(name) - - -def test_discovery_does_not_import_device_libraries(): - script = """ -import sys -from inferrsi.apps.cli import main -from inferrsi.benchmark.registry import builtin_tasks, describe_task -for name in builtin_tasks(): - describe_task(name) -assert main(["benchmarks", "list", "--iterative"]) == 0 -assert not {'torch', 'torch_npu', 'qwen_tts', 'vllm', 'vllm_omni'} & sys.modules.keys() -""" - subprocess.run([sys.executable, "-c", script], check=True, timeout=15) - - -@pytest.mark.parametrize("name", EXPECTED) -def test_packaged_task_entry_help_needs_no_npu(name): - result = subprocess.run( - [sys.executable, "-m", "inferrsi", "benchmarks", "run", name, "--help"], - capture_output=True, text=True, timeout=15, - ) - assert result.returncode == 0, result.stderr - assert "usage:" in result.stdout - markers = { - "moe-forward-npu": ("--pairs", "--candidate"), - "qwen21-denoise-npu": ("--candidate", "--check-only"), - "qwen3-tts-npu": ("prepare", "serve", "collect", "assess"), - } - assert all(marker in result.stdout for marker in markers[name]) - - -@pytest.mark.parametrize("name", EXPECTED) -@pytest.mark.parametrize("exit_code", [0, 1, 2]) -def test_generic_launcher_preserves_task_arguments_and_status(name, exit_code, monkeypatch): - arguments = ["--task-specific-flag", "value with spaces"] - monkeypatch.setattr(sys, "dont_write_bytecode", True) - - def call(command, *, env): - assert command == [ - sys.executable, str(Path(optimization_session.__file__).resolve()), - str(task_resources(name).joinpath("benchmark.py")), *arguments - ] - package = Path(env["PYTHONPATH"].split(os.pathsep)[0]) / "inferrsi" - assert (package / "apps" / "cli" / "__init__.py").is_file() - assert not (package / "cli.py").exists() - assert env["PYTHONDONTWRITEBYTECODE"] == "1" - return exit_code - - monkeypatch.setattr("subprocess.call", call) - assert main(["benchmarks", "run", name, *arguments]) == exit_code diff --git a/tests/test_harness_entry_code.py b/tests/test_harness_entry_code.py deleted file mode 100644 index 9af659f87..000000000 --- a/tests/test_harness_entry_code.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Actual entry-byte capture is separate from preparation declaration checks.""" - -from hashlib import sha256 - -import pytest - -from inferrsi.harness import entry_code - - -def test_capture_reads_actual_source_without_importing_or_executing_it(tmp_path): - root = tmp_path / "trusted" - root.mkdir() - source = b"raise RuntimeError('this worker must never be imported during binding')\n" - (root / "fixture_worker.py").write_bytes(source) - result = entry_code.capture_module(root, "fixture_worker", tmp_path / "captures") - assert result.path.read_bytes() == source - assert (result.sha256, result.size_bytes) == (sha256(source).hexdigest(), len(source)) - (root / "fixture_worker.py").write_bytes(b"changed after capture\n") - assert result.path.read_bytes() == source - - -@pytest.mark.parametrize("module", ["missing", "package.worker", "../outside", "worker.py"]) -def test_unresolvable_entry_has_no_actual_digest_or_capture(tmp_path, module): - with pytest.raises(entry_code.EntryUnavailable): - entry_code.capture_module(tmp_path, module, tmp_path / "captures") - assert not (tmp_path / "captures").exists() - - -def test_existing_snapshot_is_preserved_instead_of_replaced(tmp_path): - root = tmp_path / "trusted" - root.mkdir() - (root / "worker.py").write_bytes(b"new bytes") - captures = tmp_path / "captures" - captures.mkdir() - retained = captures / "worker.py" - retained.write_bytes(b"already retained") - with pytest.raises(entry_code.EntryCaptureError): - entry_code.capture_module(root, "worker", captures) - assert retained.read_bytes() == b"already retained" diff --git a/tests/test_lily_repo_to_skill.py b/tests/test_lily_repo_to_skill.py deleted file mode 100644 index 678d50904..000000000 --- a/tests/test_lily_repo_to_skill.py +++ /dev/null @@ -1,112 +0,0 @@ -"""Portable AREX graph structure, not unavailable engine/backend verification.""" - -import json -import re -import subprocess -import sys -from pathlib import Path -from urllib.parse import unquote, urlsplit - -import yaml - -from inferrsi.knowledge.skill_catalog import skill_metadata - -PROJECT = Path(__file__).resolve().parents[1] -LIBRARY = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines" -FIXTURES = PROJECT / "tests/fixtures/repo_to_skill" -GRAPHS = ("lily",) - - -def frontmatter(path): - text = path.read_text(encoding="utf-8") - header = text.split("---", 2)[1] - assert re.search(r'^description: ".+"$', header, re.MULTILINE) - value = yaml.safe_load(header) - assert value["name"] == path.parent.name - assert re.fullmatch(r"[a-z0-9][a-z0-9-]{0,63}", value["name"]) - assert value["license"] == "NO_LICENSE" - assert value["disable-model-invocation"] is True - assert value["metadata"]["disco-role"] == "operating" - return value - - -def test_arex_runtime_graph_links_frontmatter_and_source_boundaries(): - for name in GRAPHS: - root = LIBRARY / name - skills = list(root.rglob("SKILL.md")) - assert len(skills) == 4 - for path in skills: - frontmatter(path) - for path in root.rglob("*.md"): - text = path.read_text(encoding="utf-8") - assert not any(value in text for value in ("/workspace/", "/home/agent/")) - for target in re.findall(r"\]\(([^)]+)\)", text): - link = urlsplit(target) - if link.scheme or link.netloc or not link.path: - continue - selected = (path.parent / unquote(link.path)).resolve() - assert selected.is_relative_to(root.resolve()), (path, target) - assert selected.exists(), (path, target) - assert not list(root.rglob("__pycache__")) - assert not list(root.rglob("*.pyc")) - metadata = skill_metadata(root.parent, root.name) - assert metadata["status"] == "candidate" - assert metadata["construction"]["native_import"] == "not-run" - assert "BLOCKED_REQUIRED_BACKEND" in " ".join(metadata["limitations"]) - - -def test_arex_assertion_cases_resolve_their_expected_runtime_resources(): - for name in GRAPHS: - root, cases = LIBRARY / name, FIXTURES / name / "test-cases" - assertions = list(cases.rglob("assertions.json")) - assert len(assertions) >= 9 - assert len(list((cases / "integration").glob("*/assertions.json"))) == 2 - for skill in (root / "sub-skills").iterdir(): - assert len(list((cases / "sub-skills" / skill.name).glob("*/assertions.json"))) >= 2 - for path in assertions: - case = json.loads(path.read_text(encoding="utf-8")) - assert case["schema"] == "disco.usability-case.v1" - assert case["assertions"] and case["evidence_basis"] - assert (path.parent / "user_request.txt").read_text().strip() - assert (path.parent / "README.md").is_file() - for relative in case["expected_skill_files"]: - selected = (root / relative).resolve() - assert selected.is_relative_to(root.resolve()) and selected.is_file() - - -def test_lily_offline_helpers_are_screening_not_native_validation(): - import runpy - - root = LIBRARY / "lily/sub-skills" - config = runpy.run_path(str(root / "model-runtime/scripts/screen_config.py")) - text = dict(config["EXPECTED"]) - text.update(attn_output_gate=True, tie_word_embeddings=False, - layer_types=["full_attention" if i % 4 == 3 else "linear_attention" - for i in range(40)]) - result = config["screen_config"]({"model_type": "qwen3_5_moe", "text_config": text, - "quantization": {"bits": 4, "group_size": 64}}, 4096) - assert result["status"] == "passed_selected_rules" and result["screen_only"] - assert result["native_validation"] == "not_run" and result["unchecked"] - request = runpy.run_path(str(root / "serving-cache/scripts/request_template.py")) - assert request["validate"]({"model": request["MODEL_ID"], - "messages": [{"role": "user", "content": "Hello"}]}) - process = subprocess.run( - [sys.executable, str(root / "serving-cache/scripts/request_template.py"), - "--prompt", "Hello", "--max-tokens", "2"], - check=True, capture_output=True, text=True, - ) - assert json.loads(process.stdout)["max_tokens"] == 2 - auditor = runpy.run_path(str(root / "qualification/scripts/audit_benchmark_record.py")) - digest = 0xCBF29CE484222325 - for token in [1, 2]: - digest = ((digest ^ token) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF - record = { - "schema_version": 1, "meta": {"engine": "lily", "source_id": "a" * 40}, - "workload": {"gpu_timing_diagnostic": False, "decode_steps": 2, "prompt_len": 4}, - "results": {"prefill": {"wall_secs": 1, "tok_s": 4}, - "decode": {"wall_secs": 1, "tok_s": 2, "step_wall_secs": [0.5, 0.5], - "token_ids": [1, 2], "token_digest": f"{digest:016x}", - "gpu_passes": [], "lookahead_gpu_pass": None}}, - } - result = auditor["audit"](record, "a" * 40, 2) - assert result["record_consistent"] and "no native execution" in result["scope"] diff --git a/tests/test_mlx_knowledge.py b/tests/test_mlx_knowledge.py deleted file mode 100644 index 4f82a11cf..000000000 --- a/tests/test_mlx_knowledge.py +++ /dev/null @@ -1,33 +0,0 @@ -from pathlib import Path - -from inferrsi.knowledge.catalog import get_knowledge, search_knowledge -from inferrsi.knowledge.knowledge_operations import KnowledgeReader -from inferrsi.knowledge.skill_catalog import skill_metadata, skill_resource - -LIBRARY = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library" -SKILL = "lazy-evaluation-stream-lifetimes" -IDENTITY = "inferrsi.common.skills.lazy_evaluation_stream_lifetimes" - - -def test_mlx_candidate_preserves_source_state_and_owner_resources(): - metadata = skill_metadata(LIBRARY, SKILL) - assert metadata["status"] == "candidate" - assert metadata["empirical_validation"] == "not_run" - assert metadata["sources"][0]["commit"] == ( - "bff10220c742907f0c68e55ff174aaea56f74e3d" - ) - resource = skill_resource(LIBRARY, SKILL, "references/source-map.md") - assert resource.is_relative_to(LIBRARY / "systems/frameworks/mlx" / SKILL) - assert "TEST-SOURCE" in resource.read_text(encoding="utf-8") - - -def test_mlx_packaged_guidance_is_discoverable_and_complete(): - record = get_knowledge(IDENTITY) - assert record in search_knowledge("mlx", repo="inferrsi", limit=100) - assert record["backend"] == "common" - assert record["verification"]["locally_verified"] is False - bundle = KnowledgeReader(skill_root=LIBRARY).read(IDENTITY) - assert bundle.metadata["kind"] == "knowledge" - assert any(name.endswith("references/source-map.md") for name in bundle.content) - assert any(name.endswith("references/execution-lifetime.md") for name in bundle.content) - assert any(b"source-derived candidate" in content for content in bundle.content.values()) diff --git a/tests/test_mlx_lm_knowledge.py b/tests/test_mlx_lm_knowledge.py deleted file mode 100644 index 98de0846d..000000000 --- a/tests/test_mlx_lm_knowledge.py +++ /dev/null @@ -1,33 +0,0 @@ -from pathlib import Path - -from inferrsi.knowledge.catalog import get_knowledge, search_knowledge -from inferrsi.knowledge.knowledge_operations import KnowledgeReader -from inferrsi.knowledge.skill_catalog import skill_metadata, skill_resource - -LIBRARY = Path(__file__).resolve().parents[1] / "src/inferrsi/knowledge/data/skill_library" -SKILL = "generation-cache-lifecycle" -IDENTITY = "inferrsi.common.skills.generation_cache_lifecycle" - - -def test_mlx_lm_candidate_preserves_source_and_application_owner(): - metadata = skill_metadata(LIBRARY, SKILL) - assert metadata["status"] == "candidate" - assert metadata["empirical_validation"] == "not_run" - assert metadata["sources"][0]["commit"] == ( - "ab7f7048dc341ced2d84b1887eeb17d60b0d1b02" - ) - resource = skill_resource(LIBRARY, SKILL, "references/cache-stop.md") - assert resource.is_relative_to(LIBRARY / "systems/engines/mlx-lm" / SKILL) - assert "LRUPromptCache" in resource.read_text(encoding="utf-8") - - -def test_mlx_lm_packaged_guidance_keeps_resources_and_unverified_state(): - record = get_knowledge(IDENTITY) - assert record in search_knowledge("mlx-lm", repo="inferrsi", limit=100) - assert record["backend"] == "common" - assert record["verification"]["locally_verified"] is False - bundle = KnowledgeReader(skill_root=LIBRARY).read(IDENTITY) - assert bundle.metadata["kind"] == "knowledge" - for resource in ("source-map.md", "generation-batch.md", "cache-stop.md", "validation.md"): - assert any(name.endswith(f"references/{resource}") for name in bundle.content) - assert any(b"cooperative" in content for content in bundle.content.values()) diff --git a/tests/test_qwen21_validation_adapter.py b/tests/test_qwen21_validation_adapter.py deleted file mode 100644 index a09076788..000000000 --- a/tests/test_qwen21_validation_adapter.py +++ /dev/null @@ -1,34 +0,0 @@ -import importlib.util -import json -import tempfile -import unittest -from pathlib import Path - -path = Path(__file__).resolve().parents[1] / "examples/qwen21_turbo_validation_adapter.py" -spec = importlib.util.spec_from_file_location("qwen21_validation_adapter", path) -adapter = importlib.util.module_from_spec(spec) -spec.loader.exec_module(adapter) - - -class ValidationAdapterTests(unittest.TestCase): - def test_nested_runner_result_resolves_original_run_without_changing_output(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / "run.lock.json").write_text(json.dumps({"repetitions": 5})) - result = root / "validation/result.json" - env = adapter.validation_environment( - result, {"INFERRSI_RESULT_PATH": str(result), "CONTROL": "frozen"} - ) - self.assertEqual(env["INFERRSI_RESULT_PATH"], str(result)) - self.assertEqual(Path(env["OMNIRSI_RESULT_PATH"]).parent, root) - self.assertEqual(env["CONTROL"], "frozen") - self.assertFalse((root / "v4-root-adapter.json").exists()) - - def test_wrong_location_and_incomplete_cohort_are_rejected(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - with self.assertRaises(ValueError): - adapter.validation_environment(root / "result.json", {}) - (root / "run.lock.json").write_text(json.dumps({"repetitions": 4})) - with self.assertRaises(ValueError): - adapter.validation_environment(root / "validation/result.json", {}) diff --git a/tests/test_qwen_quality_compatibility.py b/tests/test_qwen_quality_compatibility.py deleted file mode 100644 index 178c66b9b..000000000 --- a/tests/test_qwen_quality_compatibility.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Current Qwen validation must agree with its frozen pre-cleanup implementation.""" - -import importlib.util -import sys -from pathlib import Path -from unittest.mock import patch - -import pytest - -ROOT = Path(__file__).resolve().parents[1] - - -def load_module(name, path): - spec = importlib.util.spec_from_file_location(name, path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -@pytest.mark.parametrize("change", ["identical", "rgb", "alpha"]) -def test_quality_gate_matches_frozen_snapshot(tmp_path, change): - np = pytest.importorskip("numpy") - Image = pytest.importorskip("PIL.Image") - pytest.importorskip("skimage.metrics") - legacy = ROOT / "tests/fixtures/legacy" - helper = load_module("legacy_artifact_helper", legacy / "ltx25_b300.py") - with patch.dict(sys.modules, {"ltx25_b300": helper}): - frozen = load_module("frozen_quality", legacy / "qwen21_turbo_quality.py") - current = load_module("current_quality", ROOT / "examples/qwen21_turbo_quality.py") - pixels = np.full((704, 1280, 4), 128, dtype=np.uint8) - reference = tmp_path / "reference.png" - candidate = tmp_path / "candidate.png" - Image.fromarray(pixels).save(reference) - if change == "rgb": - pixels[:, :, :3] = 0 - elif change == "alpha": - pixels[:, :, 3] = 0 - Image.fromarray(pixels).save(candidate) - ref = {"path": str(reference), "sha256": helper.sha256(reference)} - cand = {"path": str(candidate), "sha256": helper.sha256(candidate)} - actual = current.compare_images(cand, ref) - assert actual == frozen.compare_images(cand, ref) - assert actual["verdict"] == ("PASS" if change == "identical" else "FAIL") - assert current.lifecycle.digest({"images": [ref, cand]}) == helper.digest( - {"images": [ref, cand]} - ) - output = tmp_path / "current.json" - original = tmp_path / "frozen.json" - current.lifecycle.write_json(output, actual) - helper.write_json(original, actual) - assert output.read_bytes() == original.read_bytes() diff --git a/tests/test_repo_to_skill.py b/tests/test_repo_to_skill.py deleted file mode 100644 index b6a8b770c..000000000 --- a/tests/test_repo_to_skill.py +++ /dev/null @@ -1,92 +0,0 @@ -"""Portable AREX graph structure, not unavailable engine/backend verification.""" - -import json -import re -import subprocess -import sys -from pathlib import Path -from urllib.parse import unquote, urlsplit - -import yaml - -from inferrsi.knowledge.skill_catalog import skill_metadata - -PROJECT = Path(__file__).resolve().parents[1] -LIBRARY = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines" -FIXTURES = PROJECT / "tests/fixtures/repo_to_skill" -GRAPHS = ("dwarfstar",) - - -def frontmatter(path): - text = path.read_text(encoding="utf-8") - header = text.split("---", 2)[1] - assert re.search(r'^description: ".+"$', header, re.MULTILINE) - value = yaml.safe_load(header) - assert value["name"] == path.parent.name - assert re.fullmatch(r"[a-z0-9][a-z0-9-]{0,63}", value["name"]) - assert value["license"] == "NO_LICENSE" - assert value["disable-model-invocation"] is True - assert value["metadata"]["disco-role"] == "operating" - return value - - -def test_arex_runtime_graph_links_frontmatter_and_source_boundaries(): - for name in GRAPHS: - root = LIBRARY / name - skills = list(root.rglob("SKILL.md")) - assert len(skills) == 4 - for path in skills: - frontmatter(path) - for path in root.rglob("*.md"): - text = path.read_text(encoding="utf-8") - assert not any(value in text for value in ("/workspace/", "/home/agent/")) - for target in re.findall(r"\]\(([^)]+)\)", text): - link = urlsplit(target) - if link.scheme or link.netloc or not link.path: - continue - selected = (path.parent / unquote(link.path)).resolve() - assert selected.is_relative_to(root.resolve()), (path, target) - assert selected.exists(), (path, target) - assert not list(root.rglob("__pycache__")) - assert not list(root.rglob("*.pyc")) - metadata = skill_metadata(root.parent, root.name) - assert metadata["status"] == "candidate" - assert metadata["construction"]["native_import"] == "not-run" - assert "BLOCKED_REQUIRED_BACKEND" in " ".join(metadata["limitations"]) - - -def test_arex_assertion_cases_resolve_their_expected_runtime_resources(): - for name in GRAPHS: - root, cases = LIBRARY / name, FIXTURES / name / "test-cases" - assertions = list(cases.rglob("assertions.json")) - assert len(assertions) >= 9 - assert len(list((cases / "integration").glob("*/assertions.json"))) == 2 - for skill in (root / "sub-skills").iterdir(): - assert len(list((cases / "sub-skills" / skill.name).glob("*/assertions.json"))) >= 2 - for path in assertions: - case = json.loads(path.read_text(encoding="utf-8")) - assert case["schema"] == "disco.usability-case.v1" - assert case["assertions"] and case["evidence_basis"] - assert (path.parent / "user_request.txt").read_text().strip() - assert (path.parent / "README.md").is_file() - for relative in case["expected_skill_files"]: - selected = (root / relative).resolve() - assert selected.is_relative_to(root.resolve()) and selected.is_file() - - -def test_dwarfstar_request_helper_is_offline_and_validates_its_small_contract(): - script = LIBRARY / "dwarfstar/scripts/request_template.py" - result = subprocess.run( - [sys.executable, str(script), "--model", "local-model", "--prompt", "Hello"], - check=True, capture_output=True, text=True, - ) - value = json.loads(result.stdout) - assert value == { - "model": "local-model", "messages": [{"role": "user", "content": "Hello"}], - "max_tokens": 64, "temperature": 0.0, "stream": False, - } - invalid = subprocess.run( - [sys.executable, str(script), "--model", "x", "--prompt", "y", "--max-tokens", "0"], - capture_output=True, text=True, - ) - assert invalid.returncode == 2 and "positive" in invalid.stderr diff --git a/tests/test_sias_layout.py b/tests/test_sias_layout.py deleted file mode 100644 index 141f6ac2f..000000000 --- a/tests/test_sias_layout.py +++ /dev/null @@ -1,13 +0,0 @@ -import importlib - - -def test_sias_subpackages_import() -> None: - importlib.import_module("inferrsi.harness") - importlib.import_module("inferrsi.apps.host") - importlib.import_module("inferrsi.apps.integrations.anthropic") - - -def test_harness_exports_verdict() -> None: - from inferrsi.harness import Verdict - - assert Verdict.PASS.value == "PASS" diff --git a/tests/test_skill_eval_local_cli.py b/tests/test_skill_eval_local_cli.py deleted file mode 100644 index a0366c8c5..000000000 --- a/tests/test_skill_eval_local_cli.py +++ /dev/null @@ -1,168 +0,0 @@ -"""CLI handoff controls, not a local-agent run or evidence of skill efficacy. - -Exercise the real argument parser/dispatch and retained files. The verifier is -an explicitly synthetic seam: these tests certify neither sandbox isolation nor -the behavior of a model-produced parser. No agent, provider or hardware runs. -""" - -import json -import shutil -import sys - -import pytest - -from inferrsi.apps.artifacts import sha256, write_json -from inferrsi.apps.workflows import skill_eval_engineering as artifact_check -from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox as sandbox -from tests.fixtures.skill_eval_compare_support import configuration -from tools import skill_eval_compare as compare - -CORRECT_CONTROL = "# hand-authored synthetic correct control; no model execution\n" - - -def cli(monkeypatch, capsys, *args): - monkeypatch.setattr(sys, "argv", ["skill_eval_compare", *map(str, args)]) - compare.main() - stdout = capsys.readouterr().out - return json.loads(stdout) if stdout else None - - -def prepare_cli(tmp_path, monkeypatch, capsys): - # A routing regression must fail this test, never start the automatic client. - def forbidden_execute(*args, **kwargs): - pytest.fail("The manual CLI handoff must not launch an agent") - - monkeypatch.setattr(compare, "execute", forbidden_execute) - config_path, repo = configuration(tmp_path, ids=("parser",), repeats=1) - config = json.loads(config_path.read_text()) - config["adapter"] = engineering.ADAPTER - write_json(config_path, config) - write_json(tmp_path / "cases.json", [{ - "id": "parser", "split": "development", "request": engineering.REQUEST, - "provenance": "synthetic CLI software control, not an agent trial", - }]) - output = tmp_path / "run" - prepared = cli(monkeypatch, capsys, "prepare", "--output", output, - "--config", config_path, "--repo", repo) - assert prepared == {"plan_sha256": sha256(output / "plan/freeze.json")} - head = config["snapshots"]["candidate"]["git_revision"] - return output, prepared["plan_sha256"], head - - -def handoff_args(output, digest, head, role): - return ("execute", "--output", output, "--authorize", digest, - "--task-id", "parser", "--condition", role, "--repeat", "1", - "--current-head", head) - - -@pytest.mark.parametrize("sandbox_unavailable", [False, True]) -def test_cli_two_arm_capture_and_report_keep_synthetic_provenance( - tmp_path, monkeypatch, capsys, sandbox_unavailable): - output, digest, head = prepare_cli(tmp_path, monkeypatch, capsys) - verified_sources = [] - - def synthetic_verify(task, answer): - engineering.validate_task(task) - verified_sources.append(answer["artifact_source"]) - if sandbox_unavailable: - raise sandbox.SandboxUnavailable("synthetic unavailable-host control") - passed = answer["artifact_source"] == CORRECT_CONTROL - return {"passed": passed, "assertions": {"synthetic_cli_control": passed}} - - monkeypatch.setattr(artifact_check, "verify", synthetic_verify) - plan = compare.load_plan(output) - retained_sources = [] - for role in compare.ROLES: - workspace = tmp_path / role - args = handoff_args(output, digest, head, role) - cli(monkeypatch, capsys, *args, "--stage-local", workspace) - if role == "candidate": - (workspace / "parser.py").write_text(CORRECT_CONTROL, encoding="utf-8") - source = (workspace / "parser.py").read_bytes() - retained_sources.append(source.decode("utf-8")) - logs = tmp_path / (role + "-submission") - logs.mkdir() - metadata = { - "model": plan["model"], "environment": "synthetic CLI fixture", - "access": "hand-authored control; no actual agent or hardware run", - "resources": "no provider calls or charges; not model usage evidence", - "usage": None, "elapsed_seconds": 1.0, "agent_exit_code": 0, - "summary": "synthetic software control only: " + role, - } - write_json(logs / "execution.json", metadata) - (logs / "stdout.log").write_text(role + " synthetic author log\n", encoding="utf-8") - (logs / "stderr.log").write_bytes(b"") - cli(monkeypatch, capsys, *args, "--capture-local", workspace, - "--submission", logs) - entry = next(entry for entry in plan["schedule"] if entry["condition"] == role) - directory = compare.trial_directory(output, entry) - assert (directory / "parser.py").read_bytes() == source - assert json.loads((directory / "author-execution.json").read_text()) == metadata - for name in ("stdout.log", "stderr.log"): - assert (directory / "agent" / name).read_bytes() == (logs / name).read_bytes() - assert json.loads((directory / "receipt.json").read_text()) == { - "result_sha256": sha256(directory / "result.json")} - - retained = {p: p.read_bytes() for p in (output / "results").rglob("*") if p.is_file()} - with pytest.raises(ValueError, match="already started"): - cli(monkeypatch, capsys, *args, "--capture-local", workspace, "--submission", logs) - assert all(p.read_bytes() == value for p, value in retained.items()) - for role in compare.ROLES: - shutil.rmtree(tmp_path / role) - shutil.rmtree(tmp_path / (role + "-submission")) - # The report must use the retained closure, not the now-absent live workspaces. - before_replay = len(verified_sources) - assert cli(monkeypatch, capsys, "report", "--output", output) is None - result = json.loads((output / "report.json").read_text()) - assert retained == {p: p.read_bytes() for p in (output / "results").rglob("*") - if p.is_file()} - assert sorted(verified_sources[before_replay:]) == sorted(retained_sources) - assert result["status"]["execution_state"] == "author_reported_unverified" - assert "do not prove skill causality" in result["claim"] - pair = result["pairs"][0] - assert pair["comparability"] == "unverified_author_reported" - for role in compare.ROLES: - trial = pair[role] - assert trial["author_reported_execution"] is True - assert trial["observations"]["usage"] is None - assert "costs not independently verified" in trial["provenance"] - if sandbox_unavailable: - assert trial["verdict"] == "INCONCLUSIVE" - assert trial["artifact_verdict"] is None - assert trial["evaluation_error"] == "artifact_sandbox_unavailable" - else: - assert trial["artifact_verdict"] == ("PASS" if role == "candidate" else "FAIL") - assert trial["grader_trust"] == "reverified" - assert trial["artifact_checks"]["assertions"] == { - "synthetic_cli_control": role == "candidate"} - assert result["counts"]["artifact_improved"] == (0 if sandbox_unavailable else 1) - assert not (output / "results/start.json").exists() - assert "do not authorize merge" in (output / "report.md").read_text() - - -def test_cli_rejects_stale_head_and_incomplete_capture_before_writing( - tmp_path, monkeypatch, capsys): - output, digest, head = prepare_cli(tmp_path, monkeypatch, capsys) - workspace = tmp_path / "baseline" - args = handoff_args(output, digest, head, "baseline") - with pytest.raises(ValueError, match="head differs"): - cli(monkeypatch, capsys, *handoff_args(output, digest, "0" * 40, "baseline"), - "--stage-local", workspace) - assert not workspace.exists() - with pytest.raises(SystemExit) as error: - cli(monkeypatch, capsys, *args[:-2], "--stage-local", workspace) - assert error.value.code == 2 - assert "--current-head" in capsys.readouterr().err - assert not workspace.exists() - cli(monkeypatch, capsys, *args, "--stage-local", workspace) - before = {p: p.read_bytes() for p in output.rglob("*") if p.is_file()} - with pytest.raises(ValueError, match="head differs"): - cli(monkeypatch, capsys, *handoff_args(output, digest, "0" * 40, "baseline"), - "--capture-local", workspace, "--submission", tmp_path / "not-submitted") - assert {p: p.read_bytes() for p in output.rglob("*") if p.is_file()} == before - with pytest.raises(SystemExit) as error: - cli(monkeypatch, capsys, *args, "--capture-local", workspace) - assert error.value.code == 2 - assert "Capture requires --submission" in capsys.readouterr().err - assert {p: p.read_bytes() for p in output.rglob("*") if p.is_file()} == before diff --git a/tests/test_splash_repo_to_skill.py b/tests/test_splash_repo_to_skill.py deleted file mode 100644 index 161b5e5ff..000000000 --- a/tests/test_splash_repo_to_skill.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Portable AREX graph structure, not unavailable engine/backend verification.""" - -import json -import re -import subprocess -import sys -from pathlib import Path -from urllib.parse import unquote, urlsplit - -import yaml - -from inferrsi.knowledge.skill_catalog import skill_metadata - -PROJECT = Path(__file__).resolve().parents[1] -LIBRARY = PROJECT / "src/inferrsi/knowledge/data/skill_library/systems/engines" -FIXTURES = PROJECT / "tests/fixtures/repo_to_skill" -GRAPHS = ("splash",) - - -def frontmatter(path): - text = path.read_text(encoding="utf-8") - header = text.split("---", 2)[1] - assert re.search(r'^description: ".+"$', header, re.MULTILINE) - value = yaml.safe_load(header) - assert value["name"] == path.parent.name - assert re.fullmatch(r"[a-z0-9][a-z0-9-]{0,63}", value["name"]) - assert value["license"] == "NO_LICENSE" - assert value["disable-model-invocation"] is True - assert value["metadata"]["disco-role"] == "operating" - return value - - -def test_arex_runtime_graph_links_frontmatter_and_source_boundaries(): - for name in GRAPHS: - root = LIBRARY / name - skills = list(root.rglob("SKILL.md")) - assert len(skills) == 4 - for path in skills: - frontmatter(path) - for path in root.rglob("*.md"): - text = path.read_text(encoding="utf-8") - assert not any(value in text for value in ("/workspace/", "/home/agent/")) - for target in re.findall(r"\]\(([^)]+)\)", text): - link = urlsplit(target) - if link.scheme or link.netloc or not link.path: - continue - selected = (path.parent / unquote(link.path)).resolve() - assert selected.is_relative_to(root.resolve()), (path, target) - assert selected.exists(), (path, target) - assert not list(root.rglob("__pycache__")) - assert not list(root.rglob("*.pyc")) - metadata = skill_metadata(root.parent, root.name) - assert metadata["status"] == "candidate" - assert metadata["construction"]["native_import"] == "not-run" - assert "BLOCKED_REQUIRED_BACKEND" in " ".join(metadata["limitations"]) - - -def test_arex_assertion_cases_resolve_their_expected_runtime_resources(): - for name in GRAPHS: - root, cases = LIBRARY / name, FIXTURES / name / "test-cases" - assertions = list(cases.rglob("assertions.json")) - assert len(assertions) >= 9 - assert len(list((cases / "integration").glob("*/assertions.json"))) == 2 - for skill in (root / "sub-skills").iterdir(): - assert len(list((cases / "sub-skills" / skill.name).glob("*/assertions.json"))) >= 2 - for path in assertions: - case = json.loads(path.read_text(encoding="utf-8")) - assert case["schema"] == "disco.usability-case.v1" - assert case["assertions"] and case["evidence_basis"] - assert (path.parent / "user_request.txt").read_text().strip() - assert (path.parent / "README.md").is_file() - for relative in case["expected_skill_files"]: - selected = (root / relative).resolve() - assert selected.is_relative_to(root.resolve()) and selected.is_file() - - -def test_splash_offline_helpers_keep_syntax_and_statistics_separate_from_verdict(): - import runpy - - root = LIBRARY / "splash" - parser = runpy.run_path(str(root / "sub-skills/runtime-planning/scripts/parse_budget.py")) - assert parser["parse_budget"]("max-memory", "2.5G") == 2684354560 - assert parser["parse_budget"]("ple-memory", "off") == "off" - summarizer = runpy.run_path(str(root / "sub-skills/qualification/scripts/summarize_rounds.py")) - value = summarizer["summarize"]({"rounds": [[100], [90], [92], [102]]}) - assert value["baseline"] == 101 and value["candidate"] == 91 - assert "verdict" not in value and "descriptive" in value["scope"] - result = subprocess.run( - [sys.executable, str(root / "scripts/request_template.py"), - "--model", "local-model", "--prompt", "Hello", "--cache-salt", "scope"], - check=True, capture_output=True, text=True, - ) - assert json.loads(result.stdout)["cache_salt"] == "scope" diff --git a/tests/test_trial_check_reports.py b/tests/test_trial_check_reports.py deleted file mode 100644 index 856e4c3de..000000000 --- a/tests/test_trial_check_reports.py +++ /dev/null @@ -1,81 +0,0 @@ -"""Reports must obey the evaluator's trial checks before plotting either input.""" - -import json - -import pytest - -from inferrsi.apps.legacy.evaluation import evaluate -from inferrsi.apps.legacy.reporting import write_report -from inferrsi.apps.views.summary_chart import SpecError, spec_from_evaluation -from inferrsi.contracts import RunSpec - - -def evaluated_pair(checks, side="candidate"): - spec = RunSpec(repo=".", repetitions=1, required_trial_checks=("evidence.closed",)) - arms = { - label: [{"status": "completed", "metric": value, - "trial_checks": {"evidence.closed": True}}] - for label, value in (("baseline", 100), ("candidate", 80)) - } - arms[side][0]["trial_checks"] = checks - return evaluate(spec, arms["baseline"], arms["candidate"], - {"status": "completed"}, {"verified": True}) - - -def persist_report(directory, evaluation): - (directory / "evaluation.json").write_text(json.dumps(evaluation), encoding="utf-8") - return write_report(directory).read_text(encoding="utf-8") - - -@pytest.mark.parametrize("campaign", [False, True]) -@pytest.mark.parametrize("side", ["baseline", "candidate"]) -@pytest.mark.parametrize("checks", [ - {}, {"evidence.closed": False}, {"evidence.closed": "true"}, {"evidence.closed": True}, -], ids=["missing", "false", "not-boolean", "qualified"]) -def test_trial_evidence_controls_report_chart(tmp_path, checks, side, campaign): - historical = json.dumps(spec_from_evaluation(evaluated_pair({"evidence.closed": True}))) - specification = tmp_path / "summary-chart.json" - if campaign: - specification.write_text(historical, encoding="utf-8") - - result = evaluated_pair(checks, side) - html = persist_report(tmp_path, result) - svg = tmp_path / "summary-chart.svg" - if checks.get("evidence.closed") is True: - assert result["verdict"] == "PASS" - assert "0.80×" in html - assert "0.80×" in svg.read_text(encoding="utf-8") - else: - assert result["verdict"] == "INCONCLUSIVE" - assert result["improvement_pct"] is None - assert "raw measurements" in html - assert "required trial checks" in html - assert " num_key_value_heads" in inst