Repository navigation
Expand file tree
/
Copy pathconftest.py
More file actions
1777 lines (1556 loc) · 86.6 KB
/
Copy pathconftest.py
File metadata and controls
1777 lines (1556 loc) · 86.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Repo-root pytest configuration: the host-mutation floor.
``test/conftest.py`` holds the bulk of the suite's isolation, but it only applies
to ``test/``. ``[tool:pytest] testpaths`` also collects ``transfer`` and
``src/kiro_crew/apps/builtins`` (~108 test modules that ship inside the package,
next to the code they cover), and those get no ``test/conftest.py`` fixtures at
all -- only this file, plus that app's own ``tests/conftest.py`` where one exists.
Anything that must hold for EVERY test therefore has to live here, at the
rootdir, which is the one conftest pytest applies to every testpath.
Only the HOST-MUTATION FLOOR belongs in this file, plus the two Determinism-contract
pieces described below: the guards that must hold for a test collected from any
testpath, because what they protect is the developer's machine rather than the
correctness of one suite. Everything that is
merely suite-specific isolation stays in ``test/conftest.py``.
The floor has nine parts, and each one exists because the "remember to isolate
this" contract failed at least once:
* **Git auto maintenance.** ``GIT_CONFIG_GLOBAL`` points at a session-owned file
that turns ``maintenance.auto`` and ``gc.auto`` off, and the same keys are
appended through ``GIT_CONFIG_COUNT``. A fixture commit otherwise leaves a
detached ``git maintenance run --auto`` adding and removing lock files under
``.git``, and a test that copied or walked that repo right after saw a file
vanish (issue #20310). See ``test/git_maintenance_helpers.py``. The git
location variables (``GIT_DIR``, ``GIT_INDEX_FILE``, ``GIT_WORK_TREE``, ...)
are removed as well: a suite started from a git hook inherits them, and a
fixture repo's ``git add`` would then stage into the operator's real index.
* **Services.** ``$XDG_CONFIG_HOME`` is redirected and the stdlib spawn funnels
refuse a ``systemctl``/``launchctl`` invocation carrying a mutating verb, so no
test can reconfigure or restart the operator's real gateway (issue #1722).
* **The data home.** ``KIROCREW_HOME`` is pinned per test, and the ``~/.kiro``
paths that production binds at IMPORT time (which the env var cannot reach) are
pinned with it. Without this, the ~108 test modules that ship inside the package
under ``src/kiro_crew/apps/builtins/*/tests/`` -- which see this conftest and no
other -- write the operator's live ``~/.kiro/crew`` the moment they touch
``config_dir()``. ``KIROCREW_WORKSPACE`` is pinned alongside it for the same
reason: ``workspace_root()`` is a SEPARATE default from ``config_dir()`` (it
falls back to ``~/workplace/kirocrew-workspace``, not under the data home at
all), so pinning only ``KIROCREW_HOME`` leaves it resolving to the operator's
real ``~/workplace`` the moment a test reaches an agent working directory.
* **Credential environment.** Recognised fixed credentials and validated
``JIRA_TOKEN_<HEX>`` keys are restored after every test, so a fabricated
``.env`` cannot silently override the next test's credentials in the same
worker.
* **The inherited shell environment.** The entries ``name_grant`` refuses as
inherited preloads are removed for each test's duration and restored
afterwards: the ``_ENV_PRELOAD_VARS`` names (``BASH_ENV``, ``ENV``, ...) and
exported bash functions (``BASH_FUNC_*`` keys, or the legacy bare-name
spelling whose value starts with ``() {``). RHEL-family hosts export ``which``
as a function from ``/etc/profile.d/which2.sh``, and that refusal is checked
before every narrower code, so 79 of 163 name-grant tests observed the wrong
refusal on those hosts while Ubuntu CI stayed green (issue #8395).
* **The agent-spec home.** ``kiro_agents_dir()`` is a LAZY resolver, so neither of
the two above reaches it, and a test that reaches the spec write path rewrites
the machine-wide ``<kiro home>/agents/kirocrew.json`` -- the file that decides
which MCP servers the operator's real agent has (issue #4912). The per-module
override seams are pinned instead of ``KIRO_HOME``, which cannot be pinned
without overriding ~35 tests' own ``Path.home()`` isolation.
* **The system temp directory.** ``tempfile``'s base is redirected to a per-run
directory for the whole process, so a bare ``mkdtemp()`` whose cleanup is missing
or skipped leaves its directory somewhere this run owns and removes, instead of
accumulating in the shared temp root forever. What was left behind is REPORTED
first, so the leak is a red rather than silent inode consumption. On macOS the
base is additionally moved to ``/tmp`` -- the prefix Linux and CI already use --
because the launchd per-user temp dir is long enough to break an AF_UNIX bind and
random enough to read as a credential. See :data:`conftest_floor_tmp._SHORT_TMP_BASE`.
* **The sandbox mount-source sweep.** The periodic janitor's candidate roots
(the operator's real ``/run/user/$UID`` and ``/dev/shm``) and its /proc pin
scan are both pinned to inert stand-ins -- the roots to an empty directory,
the scan to fail-closed -- so no test deletes real orphaned bind-mount
sources from the developer's machine or depends on host process state.
* **The repository checkout.** The run fails when it ends with residue anywhere in
the checkout, which is how a subprocess spawned without ``cwd=`` announces
itself.
One consequence of living at the rootdir: the module name ``conftest`` is now
resolvable from the repository root as well as from ``test/``, and 11 test modules
import helpers by bare name (``from conftest import requires_git``). Under pytest's
default ``prepend`` import mode each test module's own directory goes on
``sys.path`` first, so those imports still bind to ``test/conftest.py`` -- but the
name IS shadowed, so switching to ``--import-mode=importlib`` would need those
imports made explicit first. The visible effect today is that isort now classifies
``conftest`` as first-party (a root-level module is inside its default
``src_paths``), which is why this change also reorders that import in the modules
that use it.
Why this floor exists (issue #1722): a test asserting that a staged cutover can
be *cancelled* rewrote the operator's real ``kirocrew-gateway.service`` drop-in
to point at its own pytest temp dir. pytest deleted the temp dir at the end of
the run; the drop-in survived, so systemd looped on ``203/EXEC`` — 548 failed
starts over 25 minutes. The test never intended to touch the host: it called the
real ``_make_live()`` because that function was the subject under test, and two
of that function's seams (the drop-in path and the subprocess layer) were left
for each test to remember to stub.
The fixtures below remove that "remember to" from the contract. None of them
changes the behaviour of a test that already isolates itself correctly: every one
sets a value a test can still override, and a test that sets its own
``KIROCREW_HOME`` or its own temp dir keeps winning.
Besides the floor, this file carries the two pieces of the Determinism contract
(``docs/system-specs/common/testing-conventions.md``) that every testpath needs and
that no test can import from ``test/``: the opt-in ``manual_clock``, ``seeded_rng``
and ``local_tz`` fixtures (requested by name, never autouse), and the per-test
publication of the running test's timeout to
``kiro_crew.testing.wait.runner_timeout_secs``, so a wait helper's default deadline is
half of the timeout pytest-timeout enforces on that test.
Imports at MODULE level are stdlib + pytest only, on purpose: a rootdir conftest is
imported before every collection, so pulling ``kiro_crew`` in here would make the
whole suite depend on import-time side effects of the package under test. The
fixtures that do need ``kiro_crew`` import it in their own body, which runs at test
setup -- by which point the test module has already imported the package anyway --
and tolerate an ImportError so a partial checkout cannot break collection.
"""
from __future__ import annotations
import asyncio
import contextlib
import gc
import importlib
import importlib.util
import linecache
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import warnings
import _pytest.outcomes
import _pytest.runner
import pytest
# ── ACP frame recorder switch (rootdir floor) ───────────────────────────────
# ``kiro_crew.acp._frame_record`` starts its writer thread at IMPORT time when
# ``KIROCREW_ACP_RECORD_FRAMES`` is set, and ``acp.client`` (hence the dashboard
# server, the session handle, the Slack handler, ...) imports it transitively. An
# operator running the suite with a live recording configured would otherwise
# have every collected test module's fake frames appended to their real corpus
# file -- from ANY testpath, including the ~108 modules under
# ``src/kiro_crew/apps/builtins/*/tests/`` that never see ``test/conftest.py``.
# Cleared here, at rootdir-conftest import, which precedes every test module's
# first ``kiro_crew`` import; tests that need the switch set it themselves
# through monkeypatch.
os.environ.pop("KIROCREW_ACP_RECORD_FRAMES", None)
@pytest.fixture
def _floor_monkeypatch():
"""The isolation floor's OWN ``MonkeyPatch`` -- never the shared ``monkeypatch``.
Every floor fixture below patches through this instance instead of the
``monkeypatch`` fixture a test also receives. The two are undone
independently, and that is the point: ``monkeypatch.undo()`` reverts EVERY
record on the instance it is called on, so a test that called it mid-way to
drop one of its own patches -- ~90 sites do, to restore a function before a
final assertion -- also dropped the floor's ``KIROCREW_HOME`` pin, and
whatever ran after that resolved the OPERATOR's real data home. Five full
runs on a developer machine left ``~/.kiro/crew/trash/session-storage.lock``
(``test_session_storage`` ran ``empty_trash()`` against the real trash) and
``~/.kiro/crew/inbound-spool/refused.jsonl.lock`` behind this way.
A test that pins something itself still wins: its ``monkeypatch`` is set up
after the floor and torn down before it, so its value overrides during the
test and the floor's value is what gets put back first, then the original.
"""
mp = pytest.MonkeyPatch()
# In-process CLI calls clear the sandbox markers and publish the UTF-8
# process contract. Preserve the worker's exact outer environment for the
# next test, including absent and explicitly empty values.
cli_process_environment = {
name: os.environ.get(name)
for name in (
"KIROCREW_SANDBOX_ACTIVE",
"KIROCREW_SANDBOX_LEVEL",
"PYTHONUTF8",
"PYTHONIOENCODING",
)
}
try:
yield mp
finally:
mp.undo()
for name, value in cli_process_environment.items():
if value is None:
os.environ.pop(name, None)
else:
os.environ[name] = value
@pytest.fixture
def monkeypatch(_floor_monkeypatch):
"""pytest's own ``monkeypatch``, re-declared to order it AFTER the floor.
Body-identical to ``_pytest.monkeypatch.monkeypatch``; the only change is the
dependency on ``_floor_monkeypatch``, which is what GUARANTEES the order the
docstring above relies on: the floor is set up before the test's ``monkeypatch``
and torn down after it, whatever autouse fixture in whatever conftest happens to
request ``monkeypatch`` first. A test's ``setenv("KIROCREW_HOME", ...)`` therefore
records the pinned value, restores it on the test's undo, and the floor's undo then
restores the operator's. A test cannot tell the difference otherwise: same type,
same scope, same undo semantics for everything IT patched.
``test_host_isolation_floor.py::TestTheDataHomeIsPinnedForEveryTestpath`` pins it.
"""
mp = pytest.MonkeyPatch()
yield mp
mp.undo()
# ── the floor's own modules ───────────────────────────────────────────────────
#
# Most of the floor is defined in plain modules beside the suite, ``test/conftest_floor_*.py``,
# and bound here by name, because pytest registers fixtures and hooks from THIS module's
# namespace. They are loaded by file path: ``test/`` is off ``sys.path`` while this file runs,
# and tests also execute this file by path under other names. A loaded part is reused, so every
# copy of this file shares one module object per part. No bytecode is written for them, since
# this runs before ``pytest_configure`` moves bytecode off the checkout.
_FLOOR_PARTS = (
"conftest_floor_home",
"conftest_floor_tmp",
"conftest_floor_configure",
"conftest_floor_services",
"conftest_floor_seams",
"conftest_floor_restores",
"conftest_floor_determinism",
"conftest_floor_reporting",
"conftest_floor_git",
)
def _load_floor_part(stem: str):
"""Load ``test/<stem>.py`` once per process, registered in ``sys.modules`` as *stem*."""
module = sys.modules.get(stem)
if module is not None:
return module
path = pathlib.Path(__file__).resolve().parent / "test" / f"{stem}.py"
spec = importlib.util.spec_from_file_location(stem, path)
assert spec is not None and spec.loader is not None, path
module = importlib.util.module_from_spec(spec)
sys.modules[stem] = module
dont_write_bytecode, sys.dont_write_bytecode = sys.dont_write_bytecode, True
try:
spec.loader.exec_module(module)
except BaseException:
del sys.modules[stem]
raise
finally:
sys.dont_write_bytecode = dont_write_bytecode
return module
for _stem in _FLOOR_PARTS:
_load_floor_part(_stem)
# Once-per-run redirects pytest_configure installs, and the warning trim.
from conftest_floor_configure import ( # noqa: E402,F401 -- bound for pytest and for tests
_AsyncFixtureScanGate,
_gate_pytest_asyncio_fixture_scan,
_pin_crew_log_off_for_the_process,
_put_the_tree_under_test_first_on_child_paths,
_redirect_bytecode_cache,
_redirect_hypothesis_database,
pytest_warning_recorded,
)
# Determinism fixtures and the report-only floors' detectors.
from conftest_floor_determinism import ( # noqa: E402,F401 -- bound for pytest and for tests
_HOOKED_EVENTS,
_NET_STRICT_ENV,
_PACKAGE_TABLE,
_PKG_ATTR_STRICT_ENV,
_POOL_STATE,
_TMP_AUDITED_EVENTS,
_TZ_STATE,
OffLoopbackNetworkRefused,
_another_run_member,
_AuditState,
_bind_unbound_kiro_crew_modules,
_classify_kill_target,
_kill_finding,
_network_finding,
_PackageTable,
_pool_activity,
_process_zone,
_runner_timeout_secs,
local_tz,
manual_clock,
pytest_report_header,
seeded_rng,
)
# Git auto maintenance off and git's location variables removed for every test.
from conftest_floor_git import ( # noqa: E402,F401 -- bound for pytest and for tests
_GIT_MAINTENANCE,
_git_global_config,
_git_location_unset,
_git_maintenance_off,
_git_maintenance_off_entries,
_git_vars_to_strip,
_load_git_maintenance_helpers,
)
# Data home: the import-time floor and the per-test home, SEL and ~/.kiro pins.
from conftest_floor_home import ( # noqa: E402,F401 -- bound for pytest and for tests
_AGENT_SPEC_HOOKS,
_HOME_PIN_ARMED,
_REAL_DATA_HOMES,
_REAL_KIRO_HOME_AT_START,
_SHARED_KIRO_PATHS,
_TMP_ROOT_PREFIX,
_agent_spec_seam_modules,
_breadcrumb_guard,
_isolate_agent_spec_home,
_isolate_kiro_sessions_dir,
_isolate_kirocrew_home,
_isolate_sel_default_dir,
_isolate_shared_kiro_paths,
_isolate_subagents_dir,
_isolation_dirs,
_isolation_root,
_refuse_a_real_data_home,
_refuse_a_resolved_real_default_home,
_resolved_real_default_home,
_tmp_root_prefix_for_run,
sel_private_root,
unpinned_agent_spec_home,
unpinned_kiro_sessions_dir,
)
# Collection-time marks, the teardown timer stop, and the CI annotations.
from conftest_floor_reporting import ( # noqa: E402,F401 -- bound for pytest and for tests
_MAX_ANNOTATED_FAILURES,
MAX_NODEID_CHARS,
_base_nodeid,
_failure_reason,
_gha_escape,
_refuse_oversized_nodeids,
_report_location,
_root_can_create_real_symlink,
_ungrouped_nodeid,
on_self_hosted_runner,
pytest_collection_modifyitems,
pytest_runtest_makereport,
)
# Teardown joins and the globals put back after every test.
from conftest_floor_restores import ( # noqa: E402,F401 -- bound for pytest and for tests
_EMBED_EVICTOR_THREAD,
_EXECUTOR_JOIN_SECS,
_TELEMETRY_CONSENT_THREAD,
_cancel_session_tree_checkpoints,
_drain_windows_proactor_finalizers,
_join_install_receipt_workers,
_join_test_loop_executor,
_live_embed_evictors,
_live_telemetry_consent_workers,
_no_leaked_embed_evictor,
_no_leaked_telemetry_exporter,
_restore_hooks_integration_globals,
_restore_log_queue_listener,
_restore_log_record_factory,
_restore_logger_levels,
_resume_crew_log_eager_fold,
_retire_crew_log_eager_fold,
)
# Host seams and process singletons pinned for every test.
from conftest_floor_seams import ( # noqa: E402,F401 -- bound for pytest and for tests
_isolate_agent_state_sidecar,
_isolate_kiro_cli_sign_in_store,
_isolate_launchd_paths,
_isolate_pre_exec_stops,
_isolate_sandbox_mount_source_roots,
_isolate_xdg_config_home,
_no_central_policy_fetch,
_no_credential_env_residue,
_no_default_builtin_skills_sync,
_no_model_download,
_pin_agent_state_sidecar,
_pin_kill_and_reap_group_probe,
_reset_member_eventlog_singleton,
_reset_platform_context,
_sandbox_mount_source_root,
_xdg_config_root,
sandbox_sweep_original,
)
# Host services: the mutation guard and the systemd user session.
from conftest_floor_services import ( # noqa: E402,F401 -- bound for pytest and for tests
_ALWAYS_REFUSED,
_HOST_SERVICE_EXEC_ALLOWED_MODULES,
_SERVICE_MANAGERS,
_block_host_service_mutation,
_fail_on_refused_real_reclaim_write,
_no_real_cgroup_reclaim_write,
_no_systemd_user_session,
_refusal_reason,
real_user_session,
)
# Temp directories: run naming, the tempfile redirect, the residue report.
from conftest_floor_tmp import ( # noqa: E402,F401 -- bound for pytest and for tests
_SHORT_TMP_ROOT_ENV,
_TMP_ENV_VARS,
_TMP_PER_TEST,
_TMP_PER_TEST_ENV,
_TMP_RESIDUE_STRICT_ENV,
_create_tmp_root,
_prefer_short_tmp_base,
_redirect_tempfile_base,
_remove_tree,
_stop_git_discovery_above_the_temp_roots,
_tmp_residue,
_tmp_residue_report,
)
# Defined by conftest_floor_tmp only in per-test mode.
if _TMP_PER_TEST:
from conftest_floor_tmp import _isolate_tempfile_base_per_test # noqa: E402,F401
@pytest.fixture(autouse=True)
def _scrub_inherited_preload_env(_floor_monkeypatch):
"""Hide the entries ``name_grant`` refuses as inherited preloads, then restore them.
RHEL-family distributions (Amazon Linux 2023, RHEL, CentOS Stream, Fedora) ship
``/etc/profile.d/which2.sh``, which exports ``which`` as a shell function -- so
``BASH_FUNC_which%%`` sits in ``os.environ`` of any login shell before pytest even
starts. ``name_grant._inherited_preload()`` fires its AMBIGUOUS_ENV refusal on
exactly that shape, and that refusal is checked before every narrower code, so on
such a host 79 of the 163 tests in ``test/test_name_grant.py`` observed
``inherited_env_can_redefine_programs`` instead of the code they assert, while
Ubuntu CI (no ``which2.sh``) stayed green (issue #8395). The detector's OTHER half
is host state just as easily: a login profile exporting ``BASH_ENV``, or a
container image setting ``ENV``, reproduces the same failure shape with no
``which2.sh`` anywhere. The PRODUCT behaviour is correct -- an inherited preload
genuinely can redefine a program the agent runs -- the gap was that this floor
pins the data home, the credential env and the temp base, but not the environment
the run inherited.
The predicate is IMPORTED from ``name_grant`` rather than restated, so the scrub
and the detector cannot drift apart, and it mirrors BOTH halves the detector
checks: the ``_ENV_PRELOAD_VARS`` names (matched truthy, exactly as the detector's
``os.environ.get(var)`` reads them -- an empty value triggers no refusal and is
left alone), and the exported-function pair (the ``BASH_FUNC_`` key prefix, plus
the legacy bare-name spelling whose value starts with ``() {``). It is also
deliberately no WIDER than that predicate: this is not a general "no exported
functions" floor -- how wide the detector should be is ``name_grant``'s design
question, and the scrub merely mirrors its answer. The import is deliberately
UNGUARDED, like ``_no_credential_env_residue``'s: an ImportError escape hatch
would disarm the scrub silently on a broken checkout and hand back the exact
79-failure pattern this fixture exists to remove, as a wall of wrong refusal
codes instead of one clear error.
The removals use the private host-floor stack. A shared ``monkeypatch.undo()``
cannot restore an inherited preload during the test. The public ``monkeypatch``
fixture depends on ``_floor_monkeypatch``, so its stack unwinds first at teardown:
an override of the SAME inherited key first reverts to "absent", and only then
does this fixture's ``delenv`` record restore the inherited value. Reversing
those steps would delete the restored host value and leak the scrub into the
next test. ``test_name_grant.py::TestInheritedHostEnvironment``
pins exactly that same-key case, and
``test_host_isolation_floor_restores.py::TestInheritedShellEnvironmentIsScrubbed`` drives
one real cycle of this fixture directly.
The deliberate AMBIGUOUS_ENV tests lose nothing: they construct their entries
inside the test body, after the scrub. The teardown sweep below is the
``_no_credential_env_residue`` half of the contract: a matching entry still
present at teardown is either a raw ``os.environ`` write (no undo record --
swept here, stays gone) or a monkeypatch-managed one (its undo re-deletes
tolerantly or restores what it recorded), so nothing this fixture scrubbed and
nothing a test leaked survives past the test on this worker.
"""
monkeypatch = _floor_monkeypatch
from kiro_crew.name_grant import (
_BASH_FUNC_KEY_PREFIX,
_BASH_FUNC_VALUE_PREFIX,
_ENV_PRELOAD_VARS,
)
def _is_inherited_preload(key: str, value: str) -> bool:
if key in _ENV_PRELOAD_VARS:
return bool(value)
return key.startswith(_BASH_FUNC_KEY_PREFIX) or value.startswith(_BASH_FUNC_VALUE_PREFIX)
for key in [k for k, v in os.environ.items() if _is_inherited_preload(k, v)]:
monkeypatch.delenv(key)
try:
yield
finally:
for key in [k for k, v in os.environ.items() if _is_inherited_preload(k, v)]:
os.environ.pop(key, None)
# ── the process working directory is shared state too ─────────────────
#: The working directory pytest started in, captured once. Restoring to THIS rather than
#: to a per-test snapshot is both simpler and more correct: it is the only value that is
#: certain to still exist, and it is where every test expects to begin.
_SESSION_CWD: str | None = None
#: Tests between ``linecache`` clears. Measured on a 1,266-test slice: 500 saves
#: 22.8 MiB and 100 saves 28.0 MiB, with no measurable difference in wall time, so the
#: CPU side of this trade is flat enough to take the memory. The cache is per-process,
#: so under ``-n auto`` each worker clears on its own count.
_LINECACHE_CLEAR_EVERY = 100
_TESTS_SINCE_LINECACHE_CLEAR = 0
#: How many objects ``pytest_collection_finish`` moved into the permanent generation.
#: ``None`` until it has run, which is what distinguishes "this hook did its job" from
#: the few hundred objects the interpreter had already frozen on its own.
_FROZEN_AT_COLLECTION: int | None = None
#: Module nodeids whose COLLECTION built the process-global metrics recorder.
#:
#: Filled by :func:`pytest_make_collect_report`, asserted empty by
#: ``test_host_isolation_floor.py::TestNoMetricIsEmittedAtImport``. A metric emitted
#: while a test module is being imported (a default argument evaluated at
#: definition time, a module constant built through a factory that counts itself)
#: runs ``get_recorder()`` before any test's pins exist. The recorder's first build
#: reads the OPERATOR's real config; with ``telemetry.enabled`` there, it starts a
#: ``PeriodicExportingMetricReader`` whose exporter is bound to the real
#: ``~/.kiro/crew/metrics`` and which exports every minute for the life of the xdist
#: worker. The per-test exporter-leak guard cannot see it (the thread predates every
#: test), and the per-test ``KIROCREW_TELEMETRY=0`` pin cannot reach it (it is already
#: built). The third full-run audit found four worker pids writing the operator's
#: metrics dir on every run from exactly one such default argument.
IMPORT_TIME_METRIC_EMITTERS: list[str] = []
def _metrics_provider_module():
return sys.modules.get("kiro_crew.metrics.provider")
def _pin_telemetry_off_for_the_process() -> None:
"""``KIROCREW_TELEMETRY=0`` from process start, not just from each test's setup.
The per-test pin (``_no_model_download``) covers the test body; this covers the
stretch BEFORE the first test (conftest imports and the collection of every
module), which is where an import-time metric emission builds the recorder. With
the env pin in force the build is a no-op recorder that reads no config and starts
no thread, so even an emitter this guard has not yet named cannot reach the host.
Tests that exercise telemetry delete the variable themselves, as they already did.
"""
os.environ["KIROCREW_TELEMETRY"] = "0"
@pytest.hookimpl(hookwrapper=True)
def pytest_make_collect_report(collector):
"""Name the module whose import built the metrics recorder, and undo it.
The detection is ``metrics.provider._ever_built`` flipping across one module's
collection: the flag is set by every build, including the no-op one the env pin
above turns it into, so an emitter is caught whether or not it reached the host.
``reset_for_testing()`` then drops what was built (stopping an exporter thread if
one exists), so the next module starts clean and the attribution stays per-module.
Fail the collection report on the detecting worker: file shards do not all
collect the test that asserts the record, and xdist forwards collection errors
to the controller even when that worker executes no tests.
"""
provider = _metrics_provider_module()
built_before = bool(provider is not None and getattr(provider, "_ever_built", False))
outcome = yield
if not isinstance(collector, pytest.Module):
return
provider = _metrics_provider_module()
if provider is None or not getattr(provider, "_ever_built", False):
return
if built_before:
# Built before this module was reached, by a conftest import. Named as such
# rather than blamed on whichever module happened to be first.
IMPORT_TIME_METRIC_EMITTERS.append(f"conftest import (before {collector.nodeid})")
else:
IMPORT_TIME_METRIC_EMITTERS.append(collector.nodeid)
with contextlib.suppress(Exception):
provider.reset_for_testing()
report = outcome.get_result()
if not report.failed:
report.outcome = "failed"
report.longrepr = (
f"Import-time metric emission: {IMPORT_TIME_METRIC_EMITTERS[-1]}. "
"Build the value inside the test or fixture instead."
)
def pytest_configure(config: pytest.Config) -> None:
"""Record the working directory pytest started in, before any test can move it."""
_refuse_a_real_data_home()
_pin_telemetry_off_for_the_process()
_pin_crew_log_off_for_the_process()
_prefer_short_tmp_base()
_install_short_tmp_root()
_redirect_hypothesis_database()
_redirect_bytecode_cache()
_install_determinism_audit_hook()
_put_the_tree_under_test_first_on_child_paths()
_gate_pytest_asyncio_fixture_scan()
global _SESSION_CWD
try:
_SESSION_CWD = os.getcwd()
except OSError: # pragma: no cover - pytest could not have started here
_SESSION_CWD = str(_REPO_ROOT)
def pytest_collection_finish(session: pytest.Session) -> None:
"""Move the collected item tree out of the garbage collector's reach.
Collecting every testpath leaves roughly three million objects alive, and they
are alive for the rest of the run by design -- the item tree, its fixture closures,
the rewritten assertion code. The garbage collector does not know that, so every
full pass walks all of them looking for cycles it will never find. Worse, on the
interpreters this suite supports the full collection is scheduled from a measure of
how much long-lived material exists, so that static population also DELAYS
collection: a test's own cyclic garbage waits longer before anything reclaims it.
(The exact scheduling differs across 3.10-3.13 -- 3.13 replaced the generational
threshold with an incremental collector -- but the static set is unscanned either
way, which is the part this depends on.)
``gc.freeze()`` moves everything currently tracked into a permanent generation that
is never scanned. Measured over 3,798 test executions: full passes went 1 -> 3 and
the objects they reclaimed went 61,604 -> 423,380, a 6.9x improvement in how much
cyclic garbage is actually collected during a run.
The end-RSS effect is small on its own (-3.5 MiB) because freed memory stays in the
allocator's arena rather than returning to the OS. What it buys is that the garbage
is reclaimed at all, which is why it is worth keeping despite the modest number.
Placed at collection finish, not at configure: before collection there is nothing
worth freezing, and after the first test the population is no longer purely static.
Freezing is safe here for the same reason it helps -- these objects were going to
live for the whole session anyway. Verified rather than assumed: live tracked objects
at session end are slightly FEWER with the freeze than without (3,221,373 vs
3,235,522), uncollectable stays 0, and the frozen count itself falls during the run,
so refcount reclamation still works inside the permanent generation. Only cyclic
garbage created BEFORE the freeze could leak, and collection creates none.
It also helps the sandbox's ``fork``-based probes rather than hurting them: this is
the documented pre-fork optimization, and the 16 sandbox suites pass identically
with and without it.
Records the delta rather than leaving the effect to be inferred from
``gc.get_freeze_count()``: the interpreter already has a few hundred objects frozen
before this runs, so a bare "is anything frozen" assertion passes with this hook
deleted.
"""
global _FROZEN_AT_COLLECTION
gc.collect()
before = gc.get_freeze_count()
gc.freeze()
_FROZEN_AT_COLLECTION = gc.get_freeze_count() - before
def pytest_runtest_logfinish(nodeid: str, location) -> None:
"""Periodically drop ``linecache``'s copy of every source file that was read.
``linecache`` keeps the full TEXT of every file it is asked for, and nothing evicts
it, so a worker accumulates source it will not look at again. Measured on a
1,266-test slice: 90 files / 0.8 MiB after collection, growing to 170 files /
11.4 MiB by the end of the run, and the ceiling is the 27.7 MiB of text in ``src``.
The fillers are ``inspect.getsource`` (used by 128 test modules) and traceback
rendering, one module at a time -- NOT the source-scanning guard tests, which read
with ``Path.read_text()`` and add no linecache entries at all. The biggest single
entries are simply the biggest modules (``dashboard/chat_runner.py`` at 408 KiB,
``slack/gateway.py`` at 388 KiB).
This is the one of the three retention guards that pays on an ORDINARY slice rather
than on a particular file, and it grows with the run: measured over 12,660 test
executions, end RSS 1025 -> 924 MiB (-101 MiB, -10%), with the repeat-visit slope
falling from 19.6 to 12.4 MiB per 1,000 tests.
``logfinish`` rather than teardown for tidiness, not safety: a failure report is
unaffected either way. ``report.longrepr`` is a string already rendered at
``pytest_runtest_makereport``, and ``inspect.findsource`` calls
``linecache.checkcache()`` before ``getlines``, so a cleared or stale entry is
simply re-read. Verified by running a two-failure file with no clearing, clearing at
teardown, and clearing here: the ``FAILURES`` sections are byte-identical.
Every N tests rather than every test because the cache is also what makes the next
traceback cheap. The interval is a memory/CPU trade with a very flat CPU side --
clearing 5x more often buys another ~5 MiB at no measurable time cost.
"""
global _TESTS_SINCE_LINECACHE_CLEAR
_TESTS_SINCE_LINECACHE_CLEAR += 1
if _TESTS_SINCE_LINECACHE_CLEAR >= _LINECACHE_CLEAR_EVERY:
_TESTS_SINCE_LINECACHE_CLEAR = 0
linecache.clearcache()
def pytest_xdist_auto_num_workers(config: pytest.Config) -> int | None:
"""Budget ``-n auto`` by memory and by what other runs on this host hold.
Registered HERE, at the rootdir, because a budget that only covers ``test/``
is absent from ``transfer`` and from the in-package app suites -- and absent
reads exactly like "decided not to clamp", so the gap is silent. Over-spawning
workers takes the whole machine down, which makes this a host-protection
concern and puts it on the same floor as the rest of them.
The policy lives in :mod:`xdist_budget`; this is only the registration.
Imported in-body to keep this file's module-level imports stdlib + pytest, and
returning ``None`` on an ImportError hands the decision back to xdist's own
default rather than breaking startup on a partial checkout.
"""
try:
import xdist_budget
except ImportError: # pragma: no cover - partial checkout
return None
return xdist_budget.resolve_workers()
def _join_telemetry_consent_worker() -> "BaseException | None":
"""Join the metrics provider's consent-recheck worker before this test's pins lift.
``metrics.provider.get_recorder()`` is on the path of ordinary production code
(``skills``, ``session``, ``context``, ``hooks`` and the metric helpers all call
it), and once per ``_CONSENT_RECHECK_SECS`` the call hands a consent re-read to a
daemon thread. That thread runs ``KiroCrewConfig.load()``, which reaches
``config_dir()``, which honours ``KIROCREW_HOME`` *at call time* and ``mkdir``s
the data home it names. The recorder is process-global and nothing resets it
between tests, so the test that schedules the worker is rarely the test whose
home it creates: the read lands a few milliseconds later, under the NEXT test's
pin, and that test sees its own data home appear underneath it from a thread it
never started. The same lazy-resolving-worker shape as the receipt writer
:func:`_join_install_receipt_workers` joins, one module over.
MEASURED, replaying one Windows CI shard's file list with a probe on every
``os.mkdir`` of a per-test home: the only off-main-thread creator of a home that
was not the running test's own was this thread. The symptom it produced on CI was
``test_pathres_loop_starvation.py::test_the_inline_anchors_are_the_bounded_anchors``:
the test builds the sensitive-target set twice and compares, and on Windows
``os.path.realpath`` keeps its ``\\\\?\\`` prefix when the directory above a
not-yet-existing anchor is created between its two lookups -- so the first build
carried ``\\\\?\\...\\<n>-kirocrew-home\\diag`` (``diag`` being the first anchor under
the crew home) and the second did not.
Same place and same reason as :func:`_join_install_receipt_workers`: the
``tryfirst`` teardown hook runs before any fixture unwinds, so the pins still hold
and the worker's read lands in the home of the test that scheduled it. The module
is found by thread name rather than imported, so a run that never builds a
recorder pays one ``threading.enumerate``. Bounded by ``_EXECUTOR_JOIN_SECS``; a
worker still alive past it is RETURNED as the failure to raise after the
hookwrapper's ``yield`` (see :func:`_retire_crew_log_eager_fold` for why it is not
raised here), because a consent read that does not finish in ten seconds is a
wedged config read, and the next test would otherwise start with a live thread
able to create its home at any moment.
"""
workers = _live_telemetry_consent_workers()
if not workers:
return None
deadline = time.monotonic() + _EXECUTOR_JOIN_SECS
for worker in workers:
worker.join(max(0.0, deadline - time.monotonic()))
still_alive = [t.name for t in workers if t.is_alive()]
if not still_alive:
return None
return AssertionError(
f"a telemetry consent-recheck worker {still_alive} is still running "
f"{_EXECUTOR_JOIN_SECS:.0f}s after this test ended; its config read would land "
"under the next test's KIROCREW_HOME. See conftest._join_telemetry_consent_worker."
)
# Durations and phases pytest_runtest_logreport has already seen for the item whose
# runtest protocol is in flight, keyed by node id. The escape guard uses both to
# preserve one report per phase and to charge only time no logged report covers.
_escape_logged_reports: dict[str, tuple[float, set[str]]] = {}
@pytest.hookimpl(tryfirst=True)
def pytest_runtest_logreport(report):
"""Track logged phases and durations for the in-flight escape guard."""
logged = _escape_logged_reports.get(report.nodeid)
if logged is not None:
duration, phases = logged
_escape_logged_reports[report.nodeid] = (
duration + max(report.duration, 0.0),
phases | {report.when},
)
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_protocol(item, nextitem):
"""Turn a ``Failed`` that escapes the runtest protocol into that test's failure.
Every ``pytest.fail`` raised inside setup, call or teardown is caught by
``CallInfo.from_call`` and becomes a report. The one that is NOT is
pytest-timeout's: with ``timeout_func_only`` off, its SIGALRM handler can fire
anywhere in the protocol -- while pytest is rendering a failure report, between
phases -- and ``pytest.fail("Timeout >120.0s")`` then propagates out of
``pytest_runtest_protocol`` with no report logged. Under xdist that is fatal
to the whole session, not the test: ``xdist.remote`` sends
``runtest_protocol_complete`` only when this hook RETURNS, so the controller
either takes the worker's traceback as an INTERNALERROR or, when the worker
goes on to finish, trips ``dsession.worker_workerfinished``'s
``assert not crashitem`` for the still-assigned item. Either way one slow
test on an overloaded runner erases the shard's results.
Outermost wrapper (``tryfirst``), so it sees what every inner wrapper --
pytest-timeout's own included, which has already cancelled its timer by the
time the outcome reaches here -- let through. Only ``Failed`` is repaired: an
``Exit`` escaping here is ``pytest.exit`` doing its job.
The invariant is one report per phase. The earliest of setup and call without a
logged report carries the escape, and teardown always runs unless it already
logged. This leaves three branches: no call report synthesizes the earliest
missing setup/call report, a call report without teardown puts the escape on the
teardown report, and a logged teardown emits nothing extra.
The teardown ``makereport`` hook disarms pytest-timeout before teardown report
logging starts. All timed phases are complete there, so serialization and
``logfinish`` cannot create another timer escape. A logged teardown therefore
reached the controller before branch three can be entered. An alarm in the setup
or call logreport chain after this tracker runs but before xdist sends the report
can still leave that original phase absent on the controller. The synthesized
failure or teardown error makes that item fail loudly rather than pass green.
``_escape_logged_reports`` records phases and durations at the start of each
logreport chain. ``pytest-split`` sums report durations by node id, so a
synthesized report owns only protocol time not charged to a logged phase. A
normal call keeps its elapsed time, while the replacement teardown owns only
teardown time. The hook then returns normally so xdist completes the item.
Teardown is required because live fixtures left on ``SetupState`` break the next
item on the worker. A clean teardown receives the escaped failure. Its own error
wins when teardown fails. Control-flow exceptions keep pytest's normal reraise
and interactive handling.
"""
protocol_start_perf = time.perf_counter()
_escape_logged_reports[item.nodeid] = (0.0, set())
try:
outcome = yield
finally:
already_logged, logged_phases = _escape_logged_reports.pop(item.nodeid, (0.0, set()))
protocol_stop = time.time()
protocol_duration = time.perf_counter() - protocol_start_perf
excinfo = outcome.excinfo
if excinfo is None or not isinstance(excinfo[1], _pytest.outcomes.Failed):
return
escaped = excinfo[1]
if "call" not in logged_phases:
carrier = next(phase for phase in ("setup", "call") if phase not in logged_phases)
def _reraise():
raise escaped
call = _pytest.runner.CallInfo.from_call(_reraise, carrier)
call.duration = max(protocol_duration - already_logged, 0.0)
call.stop = protocol_stop
call.start = protocol_stop - call.duration
report = item.ihook.pytest_runtest_makereport(item=item, call=call)
item.ihook.pytest_runtest_logreport(report=report)
_pytest.runner.call_and_report(item, "teardown", log=True, nextitem=nextitem)
elif "teardown" not in logged_phases:
call = _pytest.runner.CallInfo.from_call(
lambda: item.ihook.pytest_runtest_teardown(item=item, nextitem=nextitem),
"teardown",
reraise=_pytest.runner.get_reraise_exceptions(item.config),
)
if call.excinfo is None:
call = _pytest.runner.CallInfo(
None,
pytest.ExceptionInfo.from_exc_info(excinfo),
start=call.start,
stop=call.stop,
duration=call.duration,
when="teardown",
_ispytest=True,
)
report = item.ihook.pytest_runtest_makereport(item=item, call=call)
item.ihook.pytest_runtest_logreport(report=report)
if _pytest.runner.check_interactive_exception(call, report):
item.ihook.pytest_exception_interact(node=item, call=call, report=report)
item.ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
outcome.force_result(True)
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_teardown(item, nextitem):
"""Put the process working directory back, BEFORE any fixture teardown runs.
A ``tryfirst`` HOOKWRAPPER: everything before the ``yield`` runs before any other
teardown impl (so before any fixture unwinds), and the one thing after it (the
verdict of ``_refuse_a_resolved_real_default_home``) runs after every fixture has
been torn down. That split is load-bearing: the check must READ its evidence before
the test's ``monkeypatch`` restores the global, but it must RAISE only once the
floor has unwound, because an exception raised before the default teardown impl
skips fixture finalization for the whole item and leaves every pin in place for
the rest of the worker (1,245 downstream errors when it was first tried).
The CWD is per-PROCESS, so under xdist one test's ``os.chdir`` silently becomes every
later test's starting directory on that worker. That was survivable while the
directory it pointed at outlived the run. It is not survivable now: with
``tmp_path_retention_policy = failed`` pytest removes a passing test's ``tmp_path`` at
that test's own teardown, so a test that chdirs into ``tmp_path`` and does not come
back leaves the worker sitting in a DELETED directory -- and then ``Path.cwd()`` raises
``FileNotFoundError`` in every later test that reaches it, including deep inside
production code (``taskrunner.TaskRunner.__init__`` does ``work_dir or Path.cwd()``).
Measured instance and its numbers:
``docs/system-specs/common/testing-conventions.md`` § Rules. It reads as "the suite is
flaky" -- many files, each passing in isolation -- rather than as one missing line.
**A ``tryfirst`` teardown hook rather than an autouse fixture, and the difference is
load-bearing on Windows.** A fixture here would be an OUTER one (the rootdir conftest
is set up before the test's own fixtures), so it would tear down LAST -- after
``tmp_path`` cleanup had already tried to remove a directory the process was still
sitting in. Windows refuses to delete a process's current working directory, so the
cleanup fails there. Making the fixture depend on ``tmp_path`` would invert the order,
but at the price of allocating a directory for every test in the suite, which is
exactly the per-test cost this change removed elsewhere. A ``tryfirst`` hookimpl runs
before the default ``pytest_runtest_teardown``, which is what performs fixture
finalization -- so the CWD is restored before ANY teardown, at no per-test cost.
Restoring rather than failing is deliberate. The damage a leaked CWD does is to OTHER
tests, so the floor's job is to stop it propagating; naming every offender is a
separate cleanup, and one a red suite would not help with. A test that wants to change
directory for its own duration keeps working, and ``monkeypatch.chdir`` (which reverts
itself, and whose undo lands on the same value) remains the right tool inside a test.
"""
_join_install_receipt_workers()
_join_test_loop_executor(item)
# LAST, and the order is load-bearing: everything above cancels tasks, joins executor
# jobs and drains the crew-log writer, and the ``finally`` blocks that run as they
# unwind APPEND -- which reaches ``note_commit``, and an enqueue after a stop starts a
# fresh daemon nothing holds a handle to. Stopping the worker once its producers are
# quiescent is what makes the stop final.
wedged_eager_fold = _retire_crew_log_eager_fold()
# After the fold worker is stopped: it is the fold that arms these, so a write armed
# by its last entries is cancelled here rather than re-armed after the cancel.
_cancel_session_tree_checkpoints()
# After every step above: a cancelled task's ``finally`` or a drained writer can
# itself call ``get_recorder()`` and schedule a consent re-read, and a worker
# scheduled by teardown must still be joined under this test's pins.
wedged_consent_worker = _join_telemetry_consent_worker()
resolved_real_home = (
_resolved_real_default_home() if item.stash.get(_HOME_PIN_ARMED, False) else None
)
_restore_session_cwd()
yield
_publish_runner_timeout(None)
try:
refused_network = _determinism_floors_end(item)
except Exception as exc: # noqa: BLE001 - a floor bug must not skip the checks below
refused_network = None
warnings.warn(f"[determinism floors] end-of-test check failed: {exc!r}", stacklevel=1)
if resolved_real_home is not None:
_refuse_a_resolved_real_default_home(resolved_real_home)
if wedged_eager_fold is not None:
# Reported AFTER the yield for the reason on _retire_crew_log_eager_fold: fixture
# finalization has run by here, so failing the test costs nothing but the failure.
raise wedged_eager_fold
if wedged_consent_worker is not None:
raise wedged_consent_worker
if refused_network is not None:
raise refused_network
def _restore_session_cwd() -> None:
if _SESSION_CWD is None: # pragma: no cover - configure always runs first
return
try:
if os.getcwd() == _SESSION_CWD:
return
except OSError:
# The CWD was deleted under us, so the comparison itself raises. Getting back to a
# real directory is the whole point, so fall through and do it unconditionally.
pass
try:
os.chdir(_SESSION_CWD)
except OSError: # pragma: no cover - the starting directory would have to be gone
pass
# ── the sandbox probe cache is warm for every test, in every testpath ──
#: The verdict this worker's ONE real probe produced, so a later test that finds the
#: cache cold can be handed the same answer instead of paying another probe. ``None``
#: means "not established" -- either the probe has not run yet, or it came back
#: transient and left nothing to cache.
_probe_verdict: str | None = None
_probe_attempted = False
#: The session's own ``time.monotonic``, ``time.sleep`` and ``asyncio.sleep``, taken in
#: ``pytest_sessionstart`` (after every plugin's configure, before any test can patch
#: them): what :func:`_publish_runner_timeout` hands back to ``kiro_crew.testing.wait``.
_WAIT_CLOCKS: tuple | None = None
def _publish_runner_timeout(seconds: float | None) -> None: