File size: 29,057 Bytes
899047c
 
 
857d4f1
2602733
899047c
 
 
5b755c5
 
 
 
 
 
899047c
 
 
 
 
 
 
 
 
 
 
 
 
 
9dcf6ec
899047c
9dcf6ec
899047c
 
 
2602733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899047c
2602733
320fa63
 
0298d14
ea9c9dc
 
 
 
 
 
 
0298d14
 
 
 
 
 
 
9dcf6ec
320fa63
0298d14
899047c
 
 
 
 
 
 
 
 
 
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899047c
 
 
 
 
 
ae55cea
 
ea9c9dc
ae55cea
 
 
 
 
 
 
 
 
9fe0434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899047c
 
 
 
 
 
 
 
 
 
 
2602733
5b755c5
 
 
 
2602733
5b755c5
 
 
 
899047c
 
 
 
 
 
 
 
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899047c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f75ebd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899047c
 
5b755c5
320fa63
 
 
 
 
 
 
 
 
 
 
 
ae55cea
9dcf6ec
0298d14
 
 
 
 
320fa63
ae55cea
320fa63
6431675
 
 
9dcf6ec
6431675
 
 
 
 
 
 
 
 
 
 
 
 
 
9dcf6ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6431675
5b755c5
320fa63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b755c5
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
ea9c9dc
ae55cea
 
9fe0434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b755c5
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
 
9fe0434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f75ebd
 
 
857d4f1
 
 
 
 
 
 
2f75ebd
 
 
 
 
 
 
 
 
 
 
857d4f1
 
2f75ebd
 
 
 
 
5b755c5
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
5b755c5
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
5b755c5
2602733
5b755c5
 
 
 
 
 
 
 
2602733
5b755c5
2602733
5b755c5
9fe0434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b755c5
899047c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b755c5
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b755c5
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b755c5
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b755c5
ae55cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899047c
 
 
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
from __future__ import annotations

from dataclasses import dataclass
import itertools
import json
import unittest
from unittest.mock import patch

from tron.env import TronEnvironment
from tron.executor import CommandExecutor, CommandResult
from tron.models import BenchmarkConfig, ServiceProbe
from tron.observations import collect_observations
from tron.sampler import sample_scenario
from tron.scenario_catalog import load_catalog


@dataclass
class StubCommandResult:
    command: str
    return_code: int
    stdout: str
    stderr: str
    rejected: bool = False
    timed_out: bool = False
    action_cost: float = 0.0


class StubExecutor:
    def __init__(self, runtime_override_names: str = "") -> None:
        self.commands: list[str] = []
        self.runtime_override_names = runtime_override_names

    def run(self, command: str, timeout: float = 20.0) -> StubCommandResult:
        self.commands.append(command)
        combined_summary = json.dumps(
            {
                "items": [
                    {
                        "kind": "Pod",
                        "metadata": {"name": "nginx-123"},
                        "spec": {"containers": [{}, {}]},
                        "status": {
                            "phase": "Running",
                            "containerStatuses": [{"ready": True}, {"ready": True}],
                        },
                    },
                    {
                        "kind": "Pod",
                        "metadata": {"name": "redis-123"},
                        "spec": {"containers": [{}]},
                        "status": {
                            "phase": "Running",
                            "containerStatuses": [{"ready": True}],
                        },
                    },
                    {
                        "kind": "Service",
                        "metadata": {"name": "nginx"},
                        "spec": {"type": "ClusterIP"},
                    },
                    {
                        "kind": "Service",
                        "metadata": {"name": "redis"},
                        "spec": {"type": "ClusterIP"},
                    },
                    {
                        "kind": "Deployment",
                        "metadata": {"name": "nginx"},
                        "spec": {"replicas": 1},
                        "status": {"availableReplicas": 1},
                    },
                    {
                        "kind": "Deployment",
                        "metadata": {"name": "redis"},
                        "spec": {"replicas": 1},
                        "status": {"availableReplicas": 1},
                    },
                    {
                        "kind": "Endpoints",
                        "metadata": {"name": "nginx"},
                        "subsets": [{"addresses": [{"ip": "10.0.0.1"}], "ports": [{"port": 8080}]}],
                    },
                    {
                        "kind": "Endpoints",
                        "metadata": {"name": "redis"},
                        "subsets": [{"addresses": [{"ip": "10.0.0.2"}], "ports": [{"port": 6379}]}],
                    },
                ]
            }
        )
        mapping = {
            "kubectl -n tron get pods,services,deployments,endpoints -o json": combined_summary,
            "CLUSTER_NAME=tron-lab INGRESS_HOST=tron.localhost INGRESS_PORT=8080 NAMESPACE=tron bash ./cleanup.sh": "",
            "CLUSTER_NAME=tron-lab INGRESS_HOST=tron.localhost INGRESS_PORT=8080 NAMESPACE=tron bash ./setup.sh": "",
            "kubectl apply --validate=false -f manifests/namespace.yaml": "namespace/tron unchanged",
            (
                "kubectl -n tron apply --validate=false "
                "-f manifests/configmap.yaml "
                "-f manifests/redis.yaml "
                "-f manifests/nginx.yaml "
                "-f manifests/ingress.yaml "
                "-f manifests/networkpolicy-base.yaml"
            ): (
                "configmap/app-config unchanged\n"
                "deployment.apps/redis unchanged\n"
                "deployment.apps/nginx unchanged\n"
                "service/nginx unchanged\n"
                "service/redis unchanged"
            ),
            "kubectl -n tron get deployment nginx -o jsonpath='{.spec.template.spec.containers[*].env[*].name}'": self.runtime_override_names,
            "kubectl -n tron rollout status deployment/nginx --timeout=120s": "",
            "kubectl -n tron rollout status deployment/redis --timeout=120s": "",
        }
        return StubCommandResult(command=command, return_code=0, stdout=mapping.get(command, ""), stderr="")

    def run_argv(self, argv: list[str], timeout: float = 20.0) -> StubCommandResult:
        return StubCommandResult(command=" ".join(argv), return_code=0, stdout="", stderr="")

    def execute_action(self, command: str, timeout: float = 20.0) -> StubCommandResult:
        self.commands.append(command)
        if command.startswith("kubectl exec"):
            return StubCommandResult(command=command, return_code=0, stdout="ok", stderr="", action_cost=-0.02)
        if command == "kubectl -n tron get networkpolicy -o yaml":
            return StubCommandResult(
                command=command,
                return_code=0,
                stdout="apiVersion: v1\nitems:\n- kind: NetworkPolicy\n  metadata:\n    name: deny-nginx-egress",
                stderr="",
                action_cost=0.0,
            )
        if "REDIS_HOST" in command:
            return StubCommandResult(
                command=command,
                return_code=0,
                stdout="redis-stale",
                stderr="",
                action_cost=0.0,
            )
        return StubCommandResult(command=command, return_code=0, stdout="ok", stderr="", action_cost=0.0)

    def is_mutating(self, command: str) -> bool:
        return command.startswith("kubectl apply") or command.startswith("kubectl rollout restart")


class FailingRestoreExecutor(StubExecutor):
    def run(self, command: str, timeout: float = 20.0) -> StubCommandResult:
        if command.startswith("kubectl -n tron apply --validate=false ") and "manifests/nginx.yaml" in command:
            return StubCommandResult(
                command=command,
                return_code=1,
                stdout="",
                stderr="mock nginx apply failure",
            )
        return super().run(command, timeout=timeout)


class MissingClusterExecutor(StubExecutor):
    def __init__(self) -> None:
        super().__init__()
        self.failed_restore = False

    def run(self, command: str, timeout: float = 20.0) -> StubCommandResult:
        if command == "kubectl apply --validate=false -f manifests/namespace.yaml" and not self.failed_restore:
            self.failed_restore = True
            self.commands.append(command)
            return StubCommandResult(
                command=command,
                return_code=1,
                stdout="",
                stderr=(
                    'E0407 23:22:58.734202 memcache.go:265] "Unhandled Error" '
                    'err="couldn\'t get current server API group list: '
                    'Get \\"https://0.0.0.0:59961/api?timeout=32s\\": '
                    'dial tcp 0.0.0.0:59961: connect: connection refused"'
                ),
            )
        return super().run(command, timeout=timeout)


class StubIncidentEngine:
    def __init__(self) -> None:
        self.injected: list[str] = []

    def inject(self, instance) -> list[str]:
        self.injected = instance.rendered_inject_commands
        return self.injected

    def verify_activation(self, instance):
        return []

    def verify_cluster_clues(self, instance, clue_checks=None):
        return []


class MissingClueIncidentEngine(StubIncidentEngine):
    def verify_cluster_clues(self, instance, clue_checks=None):
        from tron.models import CheckResult

        return [CheckResult(name="cluster-clue", ok=False, details="missing pod-side signal")]


class ExecutorTests(unittest.TestCase):
    def test_executor_rejects_non_kubectl_commands(self) -> None:
        executor = CommandExecutor(cwd=".")
        result = executor.execute_action("bash -lc 'echo nope'")
        self.assertTrue(result.rejected)
        self.assertIn("only kubectl and curl", result.stderr)

    def test_executor_rejects_kubectl_edit(self) -> None:
        executor = CommandExecutor(cwd=".")
        result = executor.execute_action("kubectl -n tron edit deployment nginx")
        self.assertTrue(result.rejected)
        self.assertIn("kubectl edit is not allowed", result.stderr)

    def test_executor_rejects_kubectl_scale(self) -> None:
        executor = CommandExecutor(cwd=".")
        result = executor.execute_action("kubectl -n tron scale deployment/nginx --replicas=0")
        self.assertTrue(result.rejected)
        self.assertIn("kubectl scale is not allowed", result.stderr)

    def test_executor_rejects_direct_replicaset_mutation(self) -> None:
        executor = CommandExecutor(cwd=".")
        result = executor.execute_action("kubectl -n tron patch rs nginx-123 -p '{\"spec\":{\"replicas\":0}}'")
        self.assertTrue(result.rejected)
        self.assertIn("ReplicaSet mutation", result.stderr)

    def test_executor_assigns_destructive_action_cost(self) -> None:
        executor = CommandExecutor(cwd=".")
        self.assertEqual(executor.action_cost("kubectl delete pod nginx"), -0.30)
        self.assertEqual(executor.action_cost("kubectl get pods -n tron"), 0.0)


class ObservationTests(unittest.TestCase):
    def test_default_observation_is_tiered(self) -> None:
        instance = sample_scenario(load_catalog(), seed=17, scenario_id="bad-rollout-wrong-redis-host")
        observation = collect_observations(
            executor=StubExecutor(),
            config=BenchmarkConfig(),
            instance=instance,
            step_number=2,
            last_action="kubectl get pods -n tron",
            last_reward=0.0,
            service_probe=ServiceProbe(
                health_status="ok",
                data_status="error",
                http_status=503,
                latency_ms=240,
                score=0.7,
            ),
        )
        self.assertEqual(observation.step_number, 2)
        self.assertEqual(observation.service_probe.score, 0.7)
        self.assertIn("nginx-123", observation.cluster_summary.pods)
        self.assertTrue(observation.recent_change_hint)

    def test_fast_reset_can_skip_cluster_summary_collection(self) -> None:
        instance = sample_scenario(load_catalog(), seed=17, scenario_id="bad-rollout-wrong-redis-host")
        executor = StubExecutor()
        observation = collect_observations(
            executor=executor,
            config=BenchmarkConfig(skip_reset_cluster_summary=True),
            instance=instance,
            step_number=0,
            last_action=None,
            last_reward=0.0,
            service_probe=ServiceProbe(
                health_status="unreachable",
                data_status="unreachable",
                http_status=None,
                latency_ms=None,
                score=0.0,
            ),
            include_cluster_summary=False,
        )

        self.assertEqual(observation.cluster_summary.pods, "omitted during fast reset")
        self.assertNotIn(
            "kubectl -n tron get pods,services,deployments,endpoints -o json",
            executor.commands,
        )


class EnvironmentLoopTests(unittest.TestCase):
    @patch("tron.env.probe_service")
    def test_reset_uses_in_cluster_restore_by_default(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("ok", "error", 503, 250, 0.7)
        executor = StubExecutor()
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=executor,
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        env.reset(scenario_id="bad-rollout-wrong-redis-host", seed=17)

        self.assertIn("kubectl apply --validate=false -f manifests/namespace.yaml", executor.commands)
        self.assertIn(
            "kubectl -n tron get deployment nginx -o jsonpath='{.spec.template.spec.containers[*].env[*].name}'",
            executor.commands,
        )
        self.assertNotIn("kubectl -n tron set env deployment/nginx REDIS_HOST-", executor.commands)
        self.assertNotIn("kubectl -n tron rollout status deployment/nginx --timeout=120s", executor.commands)
        self.assertNotIn("CLUSTER_NAME=tron-lab INGRESS_HOST=tron.localhost INGRESS_PORT=8080 NAMESPACE=tron bash ./cleanup.sh", executor.commands)
        self.assertNotIn("CLUSTER_NAME=tron-lab INGRESS_HOST=tron.localhost INGRESS_PORT=8080 NAMESPACE=tron bash ./setup.sh", executor.commands)

    @patch("tron.env.probe_service")
    def test_reset_cleans_runtime_override_after_prior_mutation(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("ok", "error", 503, 250, 0.7)
        executor = StubExecutor(runtime_override_names="REDIS_HOST")
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=executor,
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )
        env._needs_runtime_override_cleanup = True

        env.reset(scenario_id="bad-rollout-wrong-redis-host", seed=17)

        self.assertIn(
            "kubectl -n tron get deployment nginx -o jsonpath='{.spec.template.spec.containers[*].env[*].name}'",
            executor.commands,
        )
        self.assertIn("kubectl -n tron set env deployment/nginx REDIS_HOST-", executor.commands)

    @patch("tron.env.probe_service")
    def test_reset_cleans_stale_runtime_override_even_without_prior_local_mutation(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("ok", "error", 503, 250, 0.7)
        executor = StubExecutor(runtime_override_names="REDIS_HOST")
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=executor,
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        env.reset(scenario_id="service-selector-mismatch", seed=17)

        self.assertIn(
            "kubectl -n tron get deployment nginx -o jsonpath='{.spec.template.spec.containers[*].env[*].name}'",
            executor.commands,
        )
        self.assertIn("kubectl -n tron set env deployment/nginx REDIS_HOST-", executor.commands)

    @patch("tron.env.probe_service")
    def test_reset_hard_reset_recreates_cluster(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("ok", "error", 503, 250, 0.7)
        executor = StubExecutor()
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=executor,
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        env.reset(scenario_id="bad-rollout-wrong-redis-host", seed=17, hard_reset=True)

        self.assertIn("CLUSTER_NAME=tron-lab INGRESS_HOST=tron.localhost INGRESS_PORT=8080 NAMESPACE=tron bash ./cleanup.sh", executor.commands)
        self.assertIn("CLUSTER_NAME=tron-lab INGRESS_HOST=tron.localhost INGRESS_PORT=8080 NAMESPACE=tron bash ./setup.sh", executor.commands)

    @patch("tron.env.probe_service")
    def test_reset_reports_exact_restore_command_on_failure(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("ok", "error", 503, 250, 0.7)
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=FailingRestoreExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        with self.assertRaises(RuntimeError) as ctx:
            env.reset(scenario_id="bad-rollout-wrong-redis-host", seed=17)

        self.assertIn("baseline restore failed", str(ctx.exception))
        self.assertIn("manifests/nginx.yaml", str(ctx.exception))
        self.assertIn("mock nginx apply failure", str(ctx.exception))

    @patch("tron.env.probe_service")
    def test_reset_falls_back_to_hard_reset_when_cluster_is_unreachable(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("ok", "error", 503, 250, 0.7)
        executor = MissingClusterExecutor()
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=executor,
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        env.reset(scenario_id="bad-rollout-wrong-redis-host", seed=17)

        self.assertIn("kubectl apply --validate=false -f manifests/namespace.yaml", executor.commands)
        self.assertIn(
            "CLUSTER_NAME=tron-lab INGRESS_HOST=tron.localhost INGRESS_PORT=8080 NAMESPACE=tron bash ./cleanup.sh",
            executor.commands,
        )
        self.assertIn(
            "CLUSTER_NAME=tron-lab INGRESS_HOST=tron.localhost INGRESS_PORT=8080 NAMESPACE=tron bash ./setup.sh",
            executor.commands,
        )

    @patch("tron.env.probe_service")
    def test_reset_raises_when_resource_incident_is_not_externally_visible(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("ok", "ok", 200, 90, 1.0)
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0, trusted_timeout_seconds=0.01),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        with self.assertRaises(RuntimeError) as ctx:
            env.reset(scenario_id="cpu-limits-too-low", seed=17)

        self.assertIn("scenario did not become externally visible", str(ctx.exception))

    @patch("tron.env.probe_service")
    @patch("tron.env.time.sleep", return_value=None)
    def test_reset_waits_past_transient_health_failure_for_steady_state(self, _sleep_mock, probe_service_mock) -> None:
        probe_service_mock.side_effect = [
            ServiceProbe("error", "error", 503, 250, 0.4),
            ServiceProbe("ok", "error", 503, 250, 0.7),
        ]
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.1),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        observation = env.reset(scenario_id="bad-rollout-wrong-redis-host", seed=17)

        self.assertEqual(observation.service_probe.health_status, "ok")
        self.assertEqual(observation.service_probe.data_status, "error")

    @patch("tron.env.probe_service")
    @patch("tron.env.time.sleep", return_value=None)
    def test_reset_fast_profile_shortens_transient_wait_window(self, _sleep_mock, probe_service_mock) -> None:
        probe_service_mock.side_effect = itertools.chain(
            [
                ServiceProbe("unreachable", "unreachable", None, None, 0.0),
                ServiceProbe("unreachable", "unreachable", None, None, 0.0),
            ],
            itertools.repeat(ServiceProbe("unreachable", "unreachable", None, None, 0.0)),
        )
        env = TronEnvironment(
            BenchmarkConfig(
                max_agent_steps=4,
                mutation_settle_seconds=0.1,
                transient_probe_wait_seconds=0.1,
            ),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        mock_times = itertools.chain([0.0, 0.0, 0.0], (0.1 * value for value in itertools.count(1)))
        with patch("tron.env.time.time", side_effect=mock_times):
            observation = env.reset(scenario_id="deployment-scaled-to-zero", seed=17)

        self.assertEqual(observation.service_probe.health_status, "unreachable")
        self.assertEqual(probe_service_mock.call_count, 2)

    @patch("tron.env.probe_service")
    def test_reset_allows_non_degrading_probe_scenario(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("ok", "ok", 200, 90, 1.0)
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        observation = env.reset(scenario_id="readiness-probe-too-permissive", seed=17)

        self.assertEqual(observation.service_probe.score, 1.0)

    @patch("tron.env.probe_service")
    def test_reset_allows_unreachable_scaled_to_zero_incident(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("unreachable", "unreachable", None, None, 0.0)
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )

        observation = env.reset(scenario_id="deployment-scaled-to-zero", seed=17)

        self.assertEqual(observation.service_probe.score, 0.0)

    @patch("tron.env.probe_service")
    def test_reset_reuses_duplicate_cluster_clue_checks(self, probe_service_mock) -> None:
        probe_service_mock.return_value = ServiceProbe("ok", "error", 503, 250, 0.7)
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=MissingClueIncidentEngine(),
        )

        observation = env.reset(scenario_id="bad-rollout-wrong-redis-host", seed=17)

        self.assertEqual(observation.service_probe.score, 0.7)

    @patch("tron.env.probe_service")
    @patch("tron.env.time.sleep", return_value=None)
    def test_rollout_status_waits_briefly_for_blackbox_recovery(self, _sleep_mock, probe_service_mock) -> None:
        instance = sample_scenario(load_catalog(), seed=17, scenario_id="bad-rollout-wrong-redis-host")
        probe_service_mock.side_effect = [
            ServiceProbe("ok", "error", 503, 250, 0.7),
            ServiceProbe("ok", "ok", 200, 90, 1.0),
        ]
        executor = StubExecutor()
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.1),
            executor=executor,
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )
        env.current_instance = instance
        env.current_observation = collect_observations(
            executor=executor,
            config=env.config,
            instance=instance,
            step_number=0,
            last_action=None,
            last_reward=0.0,
            service_probe=ServiceProbe("ok", "error", 503, 250, 0.7),
        )
        env.current_service_score = env.current_observation.service_probe.score

        transition = env.step("kubectl -n tron rollout status deployment/nginx --timeout=120s")

        self.assertTrue(transition.done)
        self.assertEqual(transition.service_score, 1.0)
        self.assertEqual(transition.observation.service_probe.data_status, "ok")

    @patch("tron.env.probe_service")
    def test_step_updates_reward_and_completion(self, probe_service_mock) -> None:
        instance = sample_scenario(load_catalog(), seed=17, scenario_id="bad-rollout-wrong-redis-host")
        probe_service_mock.side_effect = [
            ServiceProbe("ok", "error", 503, 250, 0.7),
            ServiceProbe("ok", "ok", 200, 90, 1.0),
        ]
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )
        env.current_instance = instance
        env.current_observation = env.observe(instance)
        env.current_service_score = env.current_observation.service_probe.score

        transition = env.step("kubectl get pods -n tron")

        self.assertEqual(transition.reward, 0.3)
        self.assertTrue(transition.done)
        self.assertEqual(env.step_number, 1)
        self.assertEqual(env.steps[0].command, "kubectl get pods -n tron")

    @patch("tron.env.probe_service")
    def test_discriminating_read_bonus_applies_for_networkpolicy_read(self, probe_service_mock) -> None:
        instance = sample_scenario(load_catalog(), seed=13, scenario_id="networkpolicy-blocks-nginx-to-redis")
        probe_service_mock.side_effect = [
            ServiceProbe("ok", "timeout", 200, 3000, 0.7),
            ServiceProbe("ok", "timeout", 200, 3000, 0.7),
        ]
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )
        env.current_instance = instance
        env.current_observation = env.observe(instance)
        env.current_service_score = env.current_observation.service_probe.score

        transition = env.step("kubectl -n tron get networkpolicy -o yaml")

        self.assertEqual(transition.reward, 0.02)

    @patch("tron.env.probe_service")
    def test_repeated_no_effect_restart_gets_penalty(self, probe_service_mock) -> None:
        instance = sample_scenario(load_catalog(), seed=17, scenario_id="bad-rollout-wrong-redis-host")
        probe_service_mock.side_effect = [
            ServiceProbe("ok", "error", 503, 250, 0.7),
            ServiceProbe("ok", "error", 503, 250, 0.7),
            ServiceProbe("ok", "error", 503, 250, 0.7),
        ]
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )
        env.current_instance = instance
        env.current_observation = env.observe(instance)
        env.current_service_score = env.current_observation.service_probe.score

        first = env.step("kubectl -n tron rollout restart deployment/nginx")
        second = env.step("kubectl -n tron rollout restart deployment/nginx")

        self.assertEqual(first.reward, 0.0)
        self.assertEqual(second.reward, -0.05)

    @patch("tron.env.probe_service")
    def test_third_no_effect_restart_gets_stronger_penalty(self, probe_service_mock) -> None:
        instance = sample_scenario(load_catalog(), seed=17, scenario_id="bad-rollout-wrong-redis-host")
        probe_service_mock.side_effect = [
            ServiceProbe("ok", "error", 503, 250, 0.7),
            ServiceProbe("ok", "error", 503, 250, 0.7),
            ServiceProbe("ok", "error", 503, 250, 0.7),
            ServiceProbe("ok", "error", 503, 250, 0.7),
        ]
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=5, mutation_settle_seconds=0.0),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )
        env.current_instance = instance
        env.current_observation = env.observe(instance)
        env.current_service_score = env.current_observation.service_probe.score

        env.step("kubectl -n tron rollout restart deployment/nginx")
        second = env.step("kubectl -n tron rollout restart deployment/nginx")
        third = env.step("kubectl -n tron rollout restart deployment/nginx")

        self.assertEqual(second.reward, -0.05)
        self.assertEqual(third.reward, -0.1)

    @patch("tron.env.probe_service")
    def test_live_runtime_read_gets_bonus(self, probe_service_mock) -> None:
        instance = sample_scenario(load_catalog(), seed=17, scenario_id="bad-rollout-wrong-redis-host")
        probe_service_mock.side_effect = [
            ServiceProbe("ok", "error", 503, 250, 0.7),
            ServiceProbe("ok", "error", 503, 250, 0.7),
        ]
        env = TronEnvironment(
            BenchmarkConfig(max_agent_steps=4, mutation_settle_seconds=0.0),
            executor=StubExecutor(),
            catalog=load_catalog(),
            incident_engine=StubIncidentEngine(),
        )
        env.current_instance = instance
        env.current_observation = env.observe(instance)
        env.current_service_score = env.current_observation.service_probe.score

        transition = env.step(
            "kubectl -n tron get pods -l app=nginx -o jsonpath='{.items[*].spec.containers[*].env[?(@.name==\"REDIS_HOST\")].value}'"
        )

        self.assertEqual(transition.reward, 0.03)


if __name__ == "__main__":
    unittest.main()