Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

perf(ci): rebalance unit test shards

cyhff93b25a2963
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index a0dd14f93..b86bca0e0 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -83,21 +83,20 @@ jobs:
unit-test-shards:
name: unit-tests (${{ matrix.shard }}/${{ matrix.shard-total }})
runs-on: ubuntu-latest
- needs: build-linux-artifacts
strategy:
fail-fast: false
matrix:
- shard: [0, 1, 2, 3]
- shard-total: [4]
+ shard: [0, 1, 2, 3, 4, 5]
+ shard-total: [6]
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
- # hatchling force-includes ui/dist into the (editable) install, so it must
- # exist before `pip install -e .`.
- - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5
- with:
- name: ui-dist-linux
- path: ui/dist
+ # Editable installs require the force-included directory, but unit tests
+ # build their own UI fixtures and do not need the production bundle.
+ - name: Prepare minimal UI asset placeholder
+ run: |
+ mkdir -p ui/dist
+ printf '%s\n' '<!doctype html><html><body></body></html>' > ui/dist/index.html
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
with:
diff --git a/scripts/ci_unit_test_shards.py b/scripts/ci_unit_test_shards.py
new file mode 100644
index 000000000..72e5d440b
--- /dev/null
+++ b/scripts/ci_unit_test_shards.py
@@ -0,0 +1,122 @@
+"""Plan isolated unit-test files across CI shards by measured duration."""
+
+from __future__ import annotations
+
+import json
+import re
+import statistics
+import sys
+from pathlib import Path
+from typing import Iterable, Mapping
+
+DEFAULT_TEST_ROOT = Path("tests")
+DEFAULT_TIMINGS_PATH = Path("scripts/ci_unit_test_timings.json")
+
+
+def discover_unit_test_files(root: Path = DEFAULT_TEST_ROOT) -> list[Path]:
+ """Return deterministic unit-test files, excluding Docker-backed e2e tests."""
+ return sorted(
+ path
+ for path in root.rglob("test_*.py")
+ if "tests/e2e/" not in path.as_posix()
+ )
+
+
+def structural_weight(path: Path) -> int:
+ """Estimate a new file's cost before it has a timing sample."""
+ text = path.read_text(encoding="utf-8", errors="ignore")
+ line_count = text.count("\n") + 1
+ test_count = len(re.findall(r"^\s*(?:async\s+def|def)\s+test_", text, re.MULTILINE))
+ class_count = len(re.findall(r"^\s*class\s+Test", text, re.MULTILINE))
+ return max(1, line_count + (test_count * 20) + (class_count * 60))
+
+
+def load_timings(path: Path = DEFAULT_TIMINGS_PATH) -> dict[str, float]:
+ """Load a timing snapshot, tolerating a missing or stale local snapshot."""
+ if not path.is_file():
+ return {}
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ durations = payload.get("durations_seconds", payload) if isinstance(payload, dict) else {}
+ if not isinstance(durations, dict):
+ return {}
+ result: dict[str, float] = {}
+ for file_path, duration in durations.items():
+ if not isinstance(file_path, str) or isinstance(duration, bool):
+ continue
+ try:
+ value = float(duration)
+ except (TypeError, ValueError):
+ continue
+ if value >= 0:
+ result[file_path] = max(1.0, value)
+ return result
+
+
+def _timing_scale(files: Iterable[Path], timings: Mapping[str, float]) -> float:
+ ratios = [
+ timings[path.as_posix()] / structural_weight(path)
+ for path in files
+ if path.as_posix() in timings
+ ]
+ return statistics.median(ratios) if ratios else 1.0
+
+
+def plan_shards(
+ files: Iterable[Path],
+ shard_total: int,
+ timings: Mapping[str, float] | None = None,
+) -> list[tuple[float, list[Path]]]:
+ """Assign the heaviest remaining file to the lightest shard (LPT)."""
+ if shard_total < 1:
+ raise ValueError("shard_total must be at least 1")
+ file_list = sorted(files)
+ timing_map = timings or {}
+ scale = _timing_scale(file_list, timing_map)
+ weighted_files = []
+ for path in file_list:
+ key = path.as_posix()
+ weight = timing_map.get(key, structural_weight(path) * scale)
+ weighted_files.append((max(1.0, float(weight)), path))
+
+ shards: list[tuple[float, list[Path]]] = [(0.0, []) for _ in range(shard_total)]
+ for weight, path in sorted(weighted_files, key=lambda item: (-item[0], item[1].as_posix())):
+ target = min(
+ range(shard_total),
+ key=lambda index: (shards[index][0], len(shards[index][1]), index),
+ )
+ total, selected = shards[target]
+ shards[target] = (total + weight, [*selected, path])
+ return shards
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = list(argv if argv is not None else sys.argv[1:])
+ if len(args) != 2 or any(not value.isdigit() for value in args):
+ print("Usage: ci_unit_test_shards.py SHARD_INDEX SHARD_TOTAL", file=sys.stderr)
+ return 2
+ shard_index, shard_total = (int(value) for value in args)
+ if shard_total < 1 or shard_index >= shard_total:
+ print("Shard index must be less than a positive shard total.", file=sys.stderr)
+ return 2
+
+ files = discover_unit_test_files()
+ timings = load_timings()
+ shards = plan_shards(files, shard_total, timings)
+ selected = sorted(shards[shard_index][1])
+ print(
+ f"Planned {len(files)} unit test file(s) across {shard_total} shard(s); "
+ f"shard {shard_index} has {len(selected)} file(s), "
+ f"estimated weight {shards[shard_index][0]:.0f}s "
+ f"({len(timings)} historical timing samples).",
+ file=sys.stderr,
+ )
+ for path in selected:
+ print(path.as_posix())
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/ci_unit_test_timings.json b/scripts/ci_unit_test_timings.json
new file mode 100644
index 000000000..f2cf8eb74
--- /dev/null
+++ b/scripts/ci_unit_test_timings.json
@@ -0,0 +1,296 @@
+{
+ "schema_version": 1,
+ "source": "GitHub Actions run 31034359265 (d2077a91e8)",
+ "durations_seconds": {
+ "tests/scenarios/auth_setup/test_auth_setup_scenarios.py": 11,
+ "tests/scenarios/message_delivery/test_message_delivery_scenarios.py": 7,
+ "tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py": 3,
+ "tests/scenarios/model_hub/test_model_hub_migration_scenarios.py": 8,
+ "tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py": 2,
+ "tests/test_agent_activity_service.py": 7,
+ "tests/test_agent_auth_service.py": 3,
+ "tests/test_agent_backend_alive.py": 3,
+ "tests/test_agent_backend_catalog.py": 2,
+ "tests/test_agent_graph_service.py": 4,
+ "tests/test_agent_initiated_turn_fsm.py": 2,
+ "tests/test_agent_run_target.py": 4,
+ "tests/test_agent_service.py": 3,
+ "tests/test_agent_silent_result.py": 2,
+ "tests/test_agent_steering.py": 14,
+ "tests/test_agent_stop_settlement.py": 2,
+ "tests/test_agent_tool_policy.py": 3,
+ "tests/test_agents_graph_route.py": 4,
+ "tests/test_api_key_masking.py": 2,
+ "tests/test_api_runtime_refresh.py": 2,
+ "tests/test_api_save_config_merge.py": 18,
+ "tests/test_async_bridge.py": 1,
+ "tests/test_audio_asr.py": 3,
+ "tests/test_auth_pipeline.py": 2,
+ "tests/test_avault_agent.py": 2,
+ "tests/test_backend_failure.py": 2,
+ "tests/test_backend_model_catalog.py": 2,
+ "tests/test_backend_restart.py": 3,
+ "tests/test_background_work_banner.py": 8,
+ "tests/test_bind_code_api.py": 2,
+ "tests/test_bind_security.py": 2,
+ "tests/test_caller_context.py": 2,
+ "tests/test_chat_discovery.py": 21,
+ "tests/test_claude_agent_initiated_turn.py": 2,
+ "tests/test_claude_agent_sessions.py": 3,
+ "tests/test_claude_cli_path.py": 4,
+ "tests/test_claude_container_sandbox.py": 2,
+ "tests/test_claude_model_catalog.py": 2,
+ "tests/test_claude_process_reaper.py": 2,
+ "tests/test_claude_reasoning_options.py": 2,
+ "tests/test_claude_receiver_result_settle.py": 2,
+ "tests/test_claude_sdk_compat.py": 3,
+ "tests/test_claude_subprocess_env.py": 2,
+ "tests/test_claude_token_usage.py": 2,
+ "tests/test_cli_agent_models.py": 3,
+ "tests/test_cli_agent_run_schema.py": 10,
+ "tests/test_cli_definition_read_projection.py": 5,
+ "tests/test_cli_pagination.py": 8,
+ "tests/test_cli_screenshot_command.py": 2,
+ "tests/test_cli_setup_status.py": 1,
+ "tests/test_cli_task_command.py": 48,
+ "tests/test_cli_watch_command.py": 25,
+ "tests/test_cloudflare_network.py": 2,
+ "tests/test_codex_agent.py": 3,
+ "tests/test_codex_api_auth.py": 2,
+ "tests/test_codex_config.py": 2,
+ "tests/test_codex_event_handler.py": 2,
+ "tests/test_codex_process_match.py": 2,
+ "tests/test_codex_session.py": 2,
+ "tests/test_codex_token_usage.py": 2,
+ "tests/test_codex_transport.py": 2,
+ "tests/test_codex_turn_state.py": 2,
+ "tests/test_command_handler_user_names.py": 2,
+ "tests/test_command_runner.py": 6,
+ "tests/test_conftest_auth_home_isolation.py": 1,
+ "tests/test_controller_ack.py": 2,
+ "tests/test_controller_agent_status.py": 3,
+ "tests/test_controller_config_reload.py": 2,
+ "tests/test_controller_dispatch_loop.py": 3,
+ "tests/test_controller_idle_cleanup.py": 2,
+ "tests/test_controller_im_ready.py": 3,
+ "tests/test_controller_model_hub_gate.py": 2,
+ "tests/test_controller_platform_reconcile.py": 8,
+ "tests/test_controller_vibe_agent_routing.py": 2,
+ "tests/test_core_services_dispatch.py": 2,
+ "tests/test_core_services_sessions.py": 7,
+ "tests/test_core_services_settings.py": 3,
+ "tests/test_delete_channel_scope.py": 2,
+ "tests/test_delivery_state_matrix.py": 2,
+ "tests/test_dependency_network.py": 2,
+ "tests/test_dev_state_migration_guard.py": 2,
+ "tests/test_discord_api_retry.py": 2,
+ "tests/test_discord_guild_settings.py": 6,
+ "tests/test_discord_model_picker.py": 2,
+ "tests/test_discord_reply_anchor.py": 3,
+ "tests/test_discord_runtime.py": 3,
+ "tests/test_discovered_chats.py": 2,
+ "tests/test_dispatcher_stream_chunk.py": 2,
+ "tests/test_dock_api.py": 10,
+ "tests/test_docker_entrypoint_supervisor.py": 16,
+ "tests/test_feishu_event_dispatcher.py": 1,
+ "tests/test_feishu_hot_stop.py": 11,
+ "tests/test_feishu_post_messages.py": 2,
+ "tests/test_feishu_routing_card.py": 1,
+ "tests/test_feishu_status_bubble_footer.py": 10,
+ "tests/test_file_browser_backend.py": 3,
+ "tests/test_file_search.py": 2,
+ "tests/test_git_binary.py": 2,
+ "tests/test_git_runtime_release_guard.py": 2,
+ "tests/test_git_runtime.py": 1,
+ "tests/test_github_wait_common.py": 2,
+ "tests/test_global_agents_md.py": 1,
+ "tests/test_harness_definition_lifecycle.py": 17,
+ "tests/test_harness_failure_visibility.py": 102,
+ "tests/test_harness_health_projection.py": 5,
+ "tests/test_harness_payload_enrichment.py": 3,
+ "tests/test_harness_run_projection.py": 4,
+ "tests/test_harness_skill_guidance.py": 2,
+ "tests/test_i18n_backend_keys.py": 2,
+ "tests/test_i18n_key_parity.py": 1,
+ "tests/test_im_base_auth.py": 2,
+ "tests/test_im_post_send_bookkeeping.py": 6,
+ "tests/test_im_proxy_unification.py": 2,
+ "tests/test_inbox_bridge.py": 2,
+ "tests/test_inbox_events.py": 3,
+ "tests/test_incus_regression_supervisor.py": 2,
+ "tests/test_incus_regression.py": 2,
+ "tests/test_incus_tenant_scaffold.py": 2,
+ "tests/test_install_script.py": 3,
+ "tests/test_internal_client.py": 2,
+ "tests/test_internal_server.py": 24,
+ "tests/test_local_deps.py": 11,
+ "tests/test_macos_session_diagnostics.py": 3,
+ "tests/test_managed_runtime.py": 1,
+ "tests/test_message_context_helpers.py": 2,
+ "tests/test_message_delivery_authority.py": 12,
+ "tests/test_message_dispatcher_file_uploads.py": 3,
+ "tests/test_message_dispatcher_platform_limits.py": 2,
+ "tests/test_message_dispatcher_result_fallback.py": 2,
+ "tests/test_message_dispatcher_scheduled.py": 7,
+ "tests/test_message_dispatcher_status_bubble.py": 2,
+ "tests/test_message_handler_attachments.py": 2,
+ "tests/test_message_handler_auth_setup.py": 2,
+ "tests/test_message_handler_harness_echo.py": 2,
+ "tests/test_message_handler_missing_agent.py": 3,
+ "tests/test_message_handler_typing.py": 3,
+ "tests/test_message_handler_user_info.py": 2,
+ "tests/test_message_mirror.py": 4,
+ "tests/test_message_priority_cutover.py": 2,
+ "tests/test_message_search.py": 4,
+ "tests/test_message_type_catalog.py": 2,
+ "tests/test_message_type_python_consumers.py": 2,
+ "tests/test_messages_service.py": 7,
+ "tests/test_model_hub_api.py": 3,
+ "tests/test_model_hub_config.py": 3,
+ "tests/test_model_hub_injection.py": 3,
+ "tests/test_model_hub_l3.py": 3,
+ "tests/test_model_hub_oauth.py": 2,
+ "tests/test_model_hub_resolution.py": 3,
+ "tests/test_model_hub_runtime.py": 6,
+ "tests/test_multi_platform_runtime.py": 11,
+ "tests/test_native_session_providers.py": 2,
+ "tests/test_opencode_caller_context.py": 2,
+ "tests/test_opencode_client_manager.py": 1,
+ "tests/test_opencode_config_reconciler.py": 2,
+ "tests/test_opencode_default_provider_routing.py": 3,
+ "tests/test_opencode_provider_base_url.py": 2,
+ "tests/test_opencode_provider_catalog_coercion.py": 2,
+ "tests/test_opencode_provider_keys_reader.py": 2,
+ "tests/test_opencode_restore_polls.py": 3,
+ "tests/test_opencode_server.py": 3,
+ "tests/test_opencode_session_manager.py": 2,
+ "tests/test_origin_links.py": 2,
+ "tests/test_pagination.py": 1,
+ "tests/test_platform_registry.py": 2,
+ "tests/test_prepare_regression.py": 2,
+ "tests/test_process_diagnostics.py": 1,
+ "tests/test_process_isolation.py": 2,
+ "tests/test_processing_indicator_reaction.py": 2,
+ "tests/test_project_agents_md.py": 2,
+ "tests/test_projects_service.py": 4,
+ "tests/test_pypi_shim.py": 2,
+ "tests/test_queued_message_writer_policy.py": 3,
+ "tests/test_read_only_query_vault_denylist.py": 2,
+ "tests/test_read_only_query.py": 2,
+ "tests/test_regression_script.py": 2,
+ "tests/test_remote_access_vibe_cloud.py": 6,
+ "tests/test_reply_enhancer_platform.py": 2,
+ "tests/test_reply_enhancer_secret_requests.py": 2,
+ "tests/test_reserved_native_session_id.py": 2,
+ "tests/test_resource_governance.py": 2,
+ "tests/test_restart_supervisor.py": 2,
+ "tests/test_result_message_token_field.py": 2,
+ "tests/test_resume_session.py": 3,
+ "tests/test_routing_modal_selection.py": 2,
+ "tests/test_running_agents_service.py": 2,
+ "tests/test_runtime_activation.py": 3,
+ "tests/test_runtime_commands.py": 2,
+ "tests/test_runtime_log_sink.py": 3,
+ "tests/test_runtime_ownership.py": 8,
+ "tests/test_runtime_recovery.py": 4,
+ "tests/test_runtime_scope_bootstrap.py": 2,
+ "tests/test_runtime_service_lock.py": 2,
+ "tests/test_runtime_work_supervisor.py": 2,
+ "tests/test_save_opencode_provider_auth.py": 12,
+ "tests/test_scheduled_command_task_integration.py": 5,
+ "tests/test_scheduled_tasks.py": 131,
+ "tests/test_sentry_integration.py": 3,
+ "tests/test_service_logging_handlers.py": 3,
+ "tests/test_session_activities.py": 5,
+ "tests/test_session_archive.py": 4,
+ "tests/test_session_cli.py": 7,
+ "tests/test_session_delivery_fsm.py": 21,
+ "tests/test_session_fork.py": 15,
+ "tests/test_session_handler_base_id.py": 2,
+ "tests/test_session_route_writer_policy.py": 2,
+ "tests/test_session_titles.py": 2,
+ "tests/test_settings_disk_fallback.py": 4,
+ "tests/test_settings_handler.py": 2,
+ "tests/test_show_git_turn_entrypoints.py": 3,
+ "tests/test_show_git.py": 4,
+ "tests/test_show_pages_admin_api.py": 4,
+ "tests/test_show_pages.py": 10,
+ "tests/test_show_runtime_manifest_packaging.py": 1,
+ "tests/test_show_runtime_manifest.py": 2,
+ "tests/test_show_runtime_orphan_sweep.py": 2,
+ "tests/test_show_session_events.py": 7,
+ "tests/test_skills_service.py": 2,
+ "tests/test_slack_app_mention_empty.py": 1,
+ "tests/test_slack_dm_mentions.py": 2,
+ "tests/test_slack_markdown_footer.py": 2,
+ "tests/test_sqlite_sessions_store.py": 29,
+ "tests/test_sqlite_settings_store.py": 20,
+ "tests/test_sqlite_state_migration.py": 36,
+ "tests/test_sqlite_state_startup.py": 2,
+ "tests/test_sse_broker.py": 2,
+ "tests/test_state_backups.py": 5,
+ "tests/test_status_bubble_footer_render.py": 2,
+ "tests/test_status_bubble_indicator.py": 3,
+ "tests/test_status_bubble_settings.py": 2,
+ "tests/test_subagent_router.py": 2,
+ "tests/test_telegram_bot.py": 9,
+ "tests/test_telegram_formatter.py": 2,
+ "tests/test_telegram_proxy.py": 2,
+ "tests/test_terminal_backend.py": 2,
+ "tests/test_test_failure_classifier.py": 3,
+ "tests/test_tmux_runtime.py": 1,
+ "tests/test_tunnel_quality.py": 2,
+ "tests/test_tunnel_recovery.py": 4,
+ "tests/test_ui_api.py": 24,
+ "tests/test_ui_remote_access_auth.py": 9,
+ "tests/test_ui_server_fastapi.py": 15,
+ "tests/test_ui_server_install.py": 3,
+ "tests/test_ui_server_logs.py": 3,
+ "tests/test_ui_server_mutation_protection.py": 8,
+ "tests/test_ui_server_reload.py": 3,
+ "tests/test_ui_server_skills_routes.py": 3,
+ "tests/test_ui_server_voice_telemetry.py": 2,
+ "tests/test_ui_server_voice_transcription.py": 2,
+ "tests/test_ui_session_stream.py": 9,
+ "tests/test_ui_show_pages.py": 289,
+ "tests/test_update_checker_platforms.py": 29,
+ "tests/test_upgrade_flow.py": 2,
+ "tests/test_user_platform_scope.py": 4,
+ "tests/test_v2_compat_platforms.py": 2,
+ "tests/test_v2_config_platform_registry.py": 2,
+ "tests/test_v2_paths.py": 2,
+ "tests/test_v2_sessions.py": 10,
+ "tests/test_vault_addresses.py": 1,
+ "tests/test_vault_api.py": 82,
+ "tests/test_vault_cli.py": 65,
+ "tests/test_vault_crypto.py": 2,
+ "tests/test_vault_export_inject.py": 11,
+ "tests/test_vault_fetch.py": 16,
+ "tests/test_vault_protected_format.py": 2,
+ "tests/test_vault_request_callbacks.py": 4,
+ "tests/test_vault_request_im_notifications.py": 3,
+ "tests/test_vault_rest.py": 9,
+ "tests/test_vault_schema.py": 2,
+ "tests/test_vault_service.py": 5,
+ "tests/test_version_identity.py": 2,
+ "tests/test_vibe_agent_archive.py": 23,
+ "tests/test_vibe_agent_model_prefill.py": 6,
+ "tests/test_vibe_cli.py": 4,
+ "tests/test_wait_for_github_action_runs.py": 1,
+ "tests/test_wait_for_github_issue_activity.py": 2,
+ "tests/test_wait_for_github_pr_activity.py": 2,
+ "tests/test_watch_worker.py": 3,
+ "tests/test_watches.py": 28,
+ "tests/test_web_oauth_flow.py": 2,
+ "tests/test_web_push_notifications.py": 3,
+ "tests/test_web_push_service.py": 5,
+ "tests/test_wechat_auth.py": 3,
+ "tests/test_wechat_bot.py": 4,
+ "tests/test_wechat_cdn.py": 2,
+ "tests/test_workbench_media.py": 6,
+ "tests/test_workbench_only_runtime.py": 4,
+ "tests/test_workbench_prefs_api.py": 4,
+ "tests/test_workbench_session_defaults.py": 3,
+ "tests/test_workspace_system_session.py": 4
+ }
+}
diff --git a/scripts/ci_unit_tests.sh b/scripts/ci_unit_tests.sh
index 3e81ecff0..ea891851c 100755
--- a/scripts/ci_unit_tests.sh
+++ b/scripts/ci_unit_tests.sh
@@ -12,8 +12,8 @@
#
# CI may pass a shard index and total shard count to split the file list across
# multiple runners while preserving the one-process-per-file isolation. Shards
-# are assigned by a deterministic file-size/test-count heuristic instead of by
-# sorted-list modulo so large test modules are spread more evenly.
+# use the checked-in per-file timing snapshot when available and fall back to a
+# deterministic file-size/test-count estimate for new or missing files.
#
# Excludes ``tests/e2e`` (Docker) and the ``integration`` marker (Docker +
# platform tokens) — those run in dedicated jobs. ``-p no:randomly`` keeps a
@@ -63,62 +63,7 @@ fi
PYTEST=("$PYTHON_BIN" -m pytest)
select_unit_test_files() {
- "$PYTHON_BIN" - "$SHARD_INDEX" "$SHARD_TOTAL" <<'PY'
-from __future__ import annotations
-
-import re
-import sys
-from pathlib import Path
-
-shard_index = int(sys.argv[1])
-shard_total = int(sys.argv[2])
-
-files = sorted(
- path
- for path in Path("tests").rglob("test_*.py")
- if "tests/e2e/" not in path.as_posix()
-)
-
-
-def estimate_weight(path: Path) -> int:
- text = path.read_text(encoding="utf-8", errors="ignore")
- line_count = text.count("\n") + 1
- test_count = len(re.findall(r"^\s*(?:async\s+def|def)\s+test_", text, re.MULTILINE))
- class_count = len(re.findall(r"^\s*class\s+Test", text, re.MULTILINE))
- return max(1, line_count + (test_count * 20) + (class_count * 60))
-
-
-weighted_files = [(estimate_weight(path), path.as_posix()) for path in files]
-shards: list[dict[str, object]] = [
- {"weight": 0, "files": []}
- for _ in range(shard_total)
-]
-
-for weight, file_path in sorted(weighted_files, key=lambda item: (-item[0], item[1])):
- target = min(
- range(shard_total),
- key=lambda index: (
- shards[index]["weight"],
- len(shards[index]["files"]), # type: ignore[arg-type]
- index,
- ),
- )
- shards[target]["weight"] = int(shards[target]["weight"]) + weight
- shard_files = shards[target]["files"]
- assert isinstance(shard_files, list)
- shard_files.append(file_path)
-
-selected_files = sorted(shards[shard_index]["files"])
-print(
- "Planned "
- f"{len(files)} unit test file(s) across {shard_total} shard(s); "
- f"shard {shard_index} has {len(selected_files)} file(s), "
- f"estimated weight {shards[shard_index]['weight']}.",
- file=sys.stderr,
-)
-for file_path in selected_files:
- print(file_path)
-PY
+ "$PYTHON_BIN" scripts/ci_unit_test_shards.py "$SHARD_INDEX" "$SHARD_TOTAL"
}
failed=""
diff --git a/tests/conftest.py b/tests/conftest.py
index a67aa029c..ce72b10c3 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -83,8 +83,13 @@ def _module_uses_default_sqlite_state(request: pytest.FixtureRequest) -> bool:
def _is_default_sqlite_call(node: ast.Call) -> bool:
- function_name = node.func.id if isinstance(node.func, ast.Name) else None
- if function_name == "get_sqlite_state_path":
+ if isinstance(node.func, ast.Name):
+ function_name = node.func.id
+ elif isinstance(node.func, ast.Attribute):
+ function_name = node.func.attr
+ else:
+ function_name = None
+ if function_name in {"get_sqlite_state_path", "_vault_engine", "_open_vault_engine"}:
return True
if function_name not in {"ensure_sqlite_state", "create_sqlite_engine"}:
return False
diff --git a/tests/test_ci_unit_test_shards.py b/tests/test_ci_unit_test_shards.py
new file mode 100644
index 000000000..82df57474
--- /dev/null
+++ b/tests/test_ci_unit_test_shards.py
@@ -0,0 +1,56 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from scripts.ci_unit_test_shards import load_timings, plan_shards
+
+
+def _test_file(root: Path, name: str, *, tests: int = 1, lines: int = 1) -> Path:
+ path = root / name
+ path.write_text(
+ ("def test_case():\n pass\n" * tests) + ("# filler\n" * lines),
+ encoding="utf-8",
+ )
+ return path
+
+
+def test_plan_shards_balances_measured_durations(tmp_path: Path) -> None:
+ files = [_test_file(tmp_path, f"test_{name}.py") for name in "abcd"]
+ timings = {path.as_posix(): duration for path, duration in zip(files, [10, 9, 8, 7])}
+
+ shards = plan_shards(files, 2, timings)
+
+ assert [total for total, _ in shards] == [17, 17]
+ assert {path for _, selected in shards for path in selected} == set(files)
+
+
+def test_plan_shards_uses_structural_fallback_for_new_files(tmp_path: Path) -> None:
+ measured = _test_file(tmp_path, "test_measured.py", tests=1, lines=1)
+ new = _test_file(tmp_path, "test_new.py", tests=1, lines=4)
+
+ shards = plan_shards(
+ [measured, new],
+ 2,
+ {measured.as_posix(): 10},
+ )
+
+ assert sorted(path for _, selected in shards for path in selected) == [measured, new]
+ assert all(total > 0 for total, _ in shards)
+
+
+def test_load_timings_ignores_malformed_values(tmp_path: Path) -> None:
+ path = tmp_path / "timings.json"
+ path.write_text(
+ '{"durations_seconds": {"tests/test_ok.py": 3, "tests/test_bad.py": "x", "tests/test_bool.py": true}}',
+ encoding="utf-8",
+ )
+
+ assert load_timings(path) == {"tests/test_ok.py": 3.0}
+
+
[email protected]("shard_total", [0, -1])
+def test_plan_shards_rejects_invalid_shard_total(tmp_path: Path, shard_total: int) -> None:
+ with pytest.raises(ValueError, match="shard_total"):
+ plan_shards([_test_file(tmp_path, "test_one.py")], shard_total)
diff --git a/tests/test_conftest_auth_home_isolation.py b/tests/test_conftest_auth_home_isolation.py
index 3a4d7089d..a41a0275c 100644
--- a/tests/test_conftest_auth_home_isolation.py
+++ b/tests/test_conftest_auth_home_isolation.py
@@ -14,16 +14,34 @@ that tests must never mutate live user state.
from __future__ import annotations
-import os
+import ast
import json
+import os
import subprocess
import sys
from pathlib import Path
-from tests.conftest import REAL_USER_HOME
+import pytest
+
+from tests.conftest import REAL_USER_HOME, _is_default_sqlite_call
from vibe import claude_config, codex_config, opencode_config
+ ("source", "expected"),
+ [
+ ("api._vault_engine()", True),
+ ("cli._open_vault_engine()", True),
+ ("config_paths.get_sqlite_state_path()", True),
+ ("storage.ensure_sqlite_state()", True),
+ ("storage.ensure_sqlite_state(db_path=path)", False),
+ ],
+)
+def test_sqlite_default_state_detector_handles_indirect_calls(source: str, expected: bool) -> None:
+ call = next(node for node in ast.walk(ast.parse(source)) if isinstance(node, ast.Call))
+ assert _is_default_sqlite_call(call) is expected
+
+
def test_backend_credential_homes_are_isolated_from_real_home() -> None:
codex_home = codex_config.get_codex_home()
claude_home = claude_config.get_claude_home()