-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_live_artifacts.py
More file actions
2976 lines (2345 loc) · 102 KB
/
Copy pathtest_live_artifacts.py
File metadata and controls
2976 lines (2345 loc) · 102 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
import base64
import json
import subprocess
from dataclasses import replace
from types import SimpleNamespace
import pytest
from sentinel.circuit_breaker import CircuitBreaker
from sentinel.config import SentinelSettings
from sentinel.errors import ToolErrorKind, ToolExecutionError
from sentinel.live_clients import (
GenericAlertClient,
KubernetesClient,
_created_within,
_deployment_selector,
_replica_set_revisions,
_replica_sets_owned_by,
)
from sentinel.models import InvestigationState, RemediationReadinessReport
from sentinel.orchestrator import SentinelOrchestrator
from sentinel.rate_limiters import InMemoryRateLimitBackend, SharedRateLimiter
from sentinel.real_tools import (
LIVE_TOOL_HANDLERS,
LiveToolRouter,
_dashboard,
_evidence_from_live_result,
_github_blame,
_github_commits,
_github_contents,
_github_deployments,
_github_issue,
_github_pr,
_github_runbook,
_github_status,
_logs,
_k8s_drain,
_k8s_job,
_k8s_patch,
_k8s_rollback,
_k8s_restart,
_k8s_scale,
_pagerduty_close,
_pagerduty_oncall,
_rollback_targets,
_slack_channel,
_slack_post,
_slack_schedule,
)
from sentinel.time_windows import repository_payload
def test_live_github_pr_handler_infers_recent_pr_instead_of_defaulting_to_one():
router = LiveToolRouter(_StubClients())
result = _github_pr(router, {"service": "checkout-service"})
assert result["pull_request"]["number"] == 231
assert _StubClients.github.requested_pull_request == 231
assert _StubClients.github.requested_pull_request != 1
def test_live_github_pr_handler_infers_pr_from_incident_window_commit_sha():
clients = _StubPrCorrelationClients(
commits=[{"sha": "sha-window", "commit": {"message": "Deploy checkout change"}}],
pull_requests=[
{"number": 999, "merge_commit_sha": "sha-other"},
{"number": 456, "merge_commit_sha": "sha-window"},
],
)
router = LiveToolRouter(clients)
result = _github_pr(
router,
{
"service": "checkout-service",
"time_window": "2024-01-15T02:42:00Z",
"time_window_end": "2024-01-15T03:27:00Z",
},
)
assert result["pull_request"]["number"] == 456
assert clients.github.requested_pull_request == 456
assert clients.github.pull_request_kwargs == {"state": "closed", "per_page": 20}
assert clients.github.commit_kwargs == {
"per_page": 10,
"since": "2024-01-15T02:42:00Z",
"until": "2024-01-15T03:27:00Z",
}
def test_live_github_pr_handler_confirms_pr_by_paginated_pr_commits():
clients = _StubPrCorrelationClients(
commits=[{"sha": "sha-window", "commit": {"message": "Deploy checkout change"}}],
pull_requests=[
{"number": 999, "merge_commit_sha": "sha-other"},
{"number": 456, "merge_commit_sha": "sha-not-window"},
],
pull_request_commits={
999: [{"sha": "sha-other"}],
456: [{"sha": "sha-window"}],
},
)
router = LiveToolRouter(clients)
result = _github_pr(router, {"service": "checkout-service"})
assert result["pull_request"]["number"] == 456
assert clients.github.requested_pull_request_commits == [999, 456]
assert clients.github.requested_pull_request == 456
def test_live_github_pr_handler_rejects_uncorrelated_recent_pr():
clients = _StubPrCorrelationClients(
commits=[{"sha": "sha-window", "commit": {"message": "Deploy checkout change"}}],
pull_requests=[{"number": 999, "merge_commit_sha": "sha-other"}],
)
router = LiveToolRouter(clients)
with pytest.raises(ToolExecutionError) as exc:
_github_pr(router, {"service": "checkout-service"})
assert exc.value.kind == ToolErrorKind.PERMANENT
assert "No incident-window pull request" in str(exc.value)
def test_live_github_pr_handler_rejects_unconfirmed_commit_message_pr_reference():
clients = _StubPrCorrelationClients(
commits=[
{
"sha": "sha-window",
"commit": {"message": "Merge pull request #999 from example/unrelated"},
}
],
pull_requests=[],
)
router = LiveToolRouter(clients)
with pytest.raises(ToolExecutionError) as exc:
_github_pr(router, {"service": "checkout-service"})
assert exc.value.kind == ToolErrorKind.PERMANENT
assert "No incident-window pull request" in str(exc.value)
assert clients.github.requested_pull_request == 999
assert clients.github.pull_request_kwargs == {"state": "closed", "per_page": 20}
def test_live_github_pr_handler_rejects_invalid_explicit_pr_before_network():
clients = _StubPrCorrelationClients(commits=[], pull_requests=[])
router = LiveToolRouter(clients)
with pytest.raises(ToolExecutionError) as exc:
_github_pr(router, {"pr": "not-a-number"})
assert exc.value.kind == ToolErrorKind.PERMANENT
assert "positive integer" in str(exc.value)
assert clients.github.commit_kwargs is None
assert clients.github.pull_request_kwargs is None
assert clients.github.requested_pull_request is None
def test_live_github_commit_handler_honors_incident_time_window():
clients = _StubTimeWindowClients()
router = LiveToolRouter(clients)
result = _github_commits(
router,
{
"service": "checkout-service",
"path": "checkout/payment.py",
"time_window": "2024-01-15T02:42:00Z",
"time_window_end": "2024-01-15T03:27:00Z",
},
)
assert result["commits"] == [{"sha": "windowed"}]
assert clients.github.commit_kwargs == {
"path": "checkout/payment.py",
"since": "2024-01-15T02:42:00Z",
"until": "2024-01-15T03:27:00Z",
}
def test_live_github_deployment_handler_honors_incident_time_window():
clients = _StubTimeWindowClients()
router = LiveToolRouter(clients)
result = _github_deployments(
router,
{
"service": "checkout-service",
"time_window": "2024-01-15T02:42:00Z",
"time_window_end": "2024-01-15T03:27:00Z",
},
)
assert result["deployments"] == [{"sha": "deploy-windowed"}]
assert clients.github.deployment_kwargs == {
"since": "2024-01-15T02:42:00Z",
"until": "2024-01-15T03:27:00Z",
}
def test_live_repository_payload_carries_collected_ref_and_pull_request():
state = InvestigationState(
incident_id="PD-LIVE",
scenario_name="live",
affected_services=["checkout-service"],
service_priority=["checkout-service"],
)
state.artifacts.update(
{
"repo_window": "2024-01-15T02:42:00Z",
"repo_window_end": "2024-01-15T03:27:00Z",
"deployment_ref": "sha-deploy",
"commit_sha": "sha-commit",
"pull_request": 456,
}
)
payload = repository_payload(state, "checkout-service")
assert payload == {
"service": "checkout-service",
"time_window": "2024-01-15T02:42:00Z",
"time_window_end": "2024-01-15T03:27:00Z",
"ref": "sha-deploy",
"pull_request": 456,
}
def test_live_github_status_handler_infers_incident_window_commit_when_ref_missing():
clients = _StubStatusClients(commits=[{"sha": "sha-window"}])
router = LiveToolRouter(clients)
result = _github_status(
router,
{
"service": "checkout-service",
"time_window": "2024-01-15T02:42:00Z",
"time_window_end": "2024-01-15T03:27:00Z",
},
)
assert result["ref"] == "sha-window"
assert result["ref_source"] == "incident_window_commit"
assert result["status"] == {"sha": "sha-window", "state": "success"}
assert result["check_runs"] == {"total_count": 1, "check_runs": [{"name": "tests"}]}
assert clients.github.commit_kwargs == {
"per_page": 1,
"since": "2024-01-15T02:42:00Z",
"until": "2024-01-15T03:27:00Z",
}
assert clients.github.requested_statuses == ["sha-window"]
assert clients.github.requested_check_runs == ["sha-window"]
def test_live_github_status_handler_uses_explicit_sha_for_status_and_checks():
clients = _StubStatusClients()
router = LiveToolRouter(clients)
result = _github_status(router, {"sha": "sha-live"})
assert result == {
"ref": "sha-live",
"ref_source": "payload",
"status": {"sha": "sha-live", "state": "success"},
"check_runs": {"total_count": 1, "check_runs": [{"name": "tests"}]},
}
assert clients.github.requested_statuses == ["sha-live"]
assert clients.github.requested_check_runs == ["sha-live"]
def test_live_github_content_handler_falls_back_across_real_repo_candidates():
clients = _StubContentsClients(
{
"deployment.yml": ToolExecutionError(ToolErrorKind.PERMANENT, "github request failed 404: not found"),
"deployment.yaml": {"name": "deployment.yaml", "sha": "sha-deploy"},
}
)
router = LiveToolRouter(clients)
handler = _github_contents(["deployment.yml", "deployment.yaml", "Dockerfile"])
result = handler(router, {"service": "checkout-service", "ref": "main"})
assert result == {
"path": "deployment.yaml",
"content": {"name": "deployment.yaml", "sha": "sha-deploy"},
}
assert clients.github.requested == [
("deployment.yml", "main"),
("deployment.yaml", "main"),
]
def test_live_github_content_handler_keeps_explicit_paths_strict():
clients = _StubContentsClients(
{
"custom/deploy.yaml": ToolExecutionError(
ToolErrorKind.PERMANENT,
"github request failed 404: not found",
),
"deployment.yaml": {"name": "deployment.yaml", "sha": "sha-deploy"},
}
)
router = LiveToolRouter(clients)
handler = _github_contents(["deployment.yml", "deployment.yaml"])
with pytest.raises(ToolExecutionError) as exc:
handler(router, {"path": "custom/deploy.yaml", "ref": "main"})
assert exc.value.kind == ToolErrorKind.PERMANENT
assert clients.github.requested == [("custom/deploy.yaml", "main")]
def test_live_github_content_handler_surfaces_non_missing_provider_errors():
clients = _StubContentsClients(
{
"deployment.yml": ToolExecutionError(
ToolErrorKind.RATE_LIMITED,
"github rate limited",
retryable=True,
),
"deployment.yaml": {"name": "deployment.yaml", "sha": "sha-deploy"},
}
)
router = LiveToolRouter(clients)
handler = _github_contents(["deployment.yml", "deployment.yaml"])
with pytest.raises(ToolExecutionError) as exc:
handler(router, {})
assert exc.value.kind == ToolErrorKind.RATE_LIMITED
assert clients.github.requested == [("deployment.yml", None)]
def test_live_feature_flags_return_not_configured_when_no_candidate_file_exists():
clients = _StubContentsClients({})
router = LiveToolRouter(clients)
result = LIVE_TOOL_HANDLERS["repo.get_feature_flags"](router, {"service": "checkout-service", "ref": "main"})
assert result["provider"] == "github"
assert result["path"] is None
assert result["content"] is None
assert result["configured"] is False
assert result["absent_kind"] == "feature_flags_not_configured"
assert ("feature-flags.yml", "main") in clients.github.requested
assert (".launchdarkly.json", "main") in clients.github.requested
def test_live_github_blame_handler_infers_path_from_correlated_pr_files():
clients = _StubPrCorrelationClients(
commits=[{"sha": "sha-window", "commit": {"message": "Merge pull request #456 from checkout/fix"}}],
pull_requests=[],
pull_request_commits={456: [{"sha": "sha-window", "commit": {"message": "Deploy checkout fix"}}]},
)
router = LiveToolRouter(clients)
result = _github_blame(
router,
{
"service": "checkout-service",
"time_window": "2024-01-15T02:42:00Z",
"time_window_end": "2024-01-15T03:27:00Z",
},
)
assert result["path"] == "checkout/payment.py"
assert result["path_source"] == "pull_request_files"
assert result["commits"] == [{"sha": "sha-window", "commit": {"message": "Merge pull request #456 from checkout/fix"}}]
assert clients.github.requested_pull_request == 456
def test_live_github_blame_handler_queries_commits_for_explicit_file_path():
clients = _StubTimeWindowClients()
router = LiveToolRouter(clients)
result = _github_blame(
router,
{
"service": "checkout-service",
"file": "checkout/payment.py",
"line": "84",
"time_window": "2024-01-15T02:42:00Z",
"time_window_end": "2024-01-15T03:27:00Z",
},
)
assert result["path"] == "checkout/payment.py"
assert result["line"] == 84
assert result["blame_source"] == "github_commits_for_path"
assert result["path_source"] == "payload"
assert result["commits"] == [{"sha": "windowed"}]
assert clients.github.commit_kwargs == {
"path": "checkout/payment.py",
"per_page": 5,
"since": "2024-01-15T02:42:00Z",
"until": "2024-01-15T03:27:00Z",
}
def test_live_github_blame_handler_rejects_invalid_line_payload():
router = LiveToolRouter(_StubTimeWindowClients())
try:
_github_blame(router, {"path": "checkout/payment.py", "line": "zero"})
except ToolExecutionError as exc:
assert exc.kind == ToolErrorKind.PERMANENT
assert exc.retryable is False
assert "line to be a positive integer" in str(exc)
else:
raise AssertionError("expected invalid blame line to fail closed")
def test_live_deployment_timestamp_filter_keeps_only_incident_window_items():
assert _created_within(
{"created_at": "2024-01-15T03:00:00Z"},
since="2024-01-15T02:42:00Z",
until="2024-01-15T03:27:00Z",
)
assert not _created_within(
{"created_at": "2024-01-15T01:00:00Z"},
since="2024-01-15T02:42:00Z",
until="2024-01-15T03:27:00Z",
)
def test_live_dashboard_handler_requires_explicit_dashboard_id():
clients = _StubDashboardClients()
router = LiveToolRouter(clients)
try:
_dashboard(router, {"service": "checkout-service"})
except ToolExecutionError as exc:
assert exc.kind == ToolErrorKind.PERMANENT
assert exc.retryable is False
assert "requires an explicit dashboard_id" in str(exc)
else:
raise AssertionError("expected dashboard lookup without dashboard_id to fail closed")
assert clients.datadog.requested_dashboard is None
def test_live_dashboard_handler_uses_explicit_dashboard_id():
clients = _StubDashboardClients()
router = LiveToolRouter(clients)
result = _dashboard(router, {"dashboard_id": "dash-payments-overview"})
assert result == {"id": "dash-payments-overview", "title": "Payments overview", "provider": "datadog"}
assert clients.datadog.requested_dashboard == "dash-payments-overview"
@pytest.mark.parametrize(
"tool_name",
[
"observe.fetch_service_logs",
"observe.query_metrics_range",
"observe.get_distributed_traces",
"observe.check_pod_health",
"observe.get_error_rate_timeseries",
"observe.fetch_apm_data",
"observe.read_queue_depth",
"observe.check_db_slow_queries",
"observe.get_network_latency",
"observe.fetch_cdn_logs",
"observe.read_flame_graph",
"observe.check_uptime_history",
"observe.get_memory_cpu_usage",
"observe.fetch_alerting_rules",
"repo.get_rollback_targets",
],
)
def test_live_service_scoped_read_handlers_require_explicit_service_before_provider_call(tool_name):
clients = _NoNetworkClients()
router = LiveToolRouter(clients)
with pytest.raises(ToolExecutionError) as exc:
LIVE_TOOL_HANDLERS[tool_name](router, {})
assert exc.value.kind == ToolErrorKind.PERMANENT
assert "requires an explicit service or affected_service" in str(exc.value)
assert clients.provider_calls == []
def test_live_service_scoped_read_handlers_accept_affected_service_payload():
clients = _RecordingDatadogClients()
router = LiveToolRouter(clients)
result = _logs(
router,
{
"affected_service": "checkout-service",
"time_window": "2024-01-15T02:42:00Z",
"time_window_end": "2024-01-15T03:27:00Z",
},
)
assert result["events"] == [{"id": "log-1"}]
assert clients.datadog.searches == [
(
"service:checkout-service",
"2024-01-15T02:42:00Z",
"2024-01-15T03:27:00Z",
)
]
def test_generic_alert_client_uses_shared_reliability_envelope():
backend = InMemoryRateLimitBackend()
rate_limiter = SharedRateLimiter(backend, limit=1, window_seconds=60)
circuit_breaker = CircuitBreaker("generic_webhook", failure_threshold=1)
client = GenericAlertClient(
SimpleNamespace(approver_id="eng-oncall"),
rate_limiter=rate_limiter,
circuit_breaker=circuit_breaker,
)
result = client.on_call_context("FREE-1")
assert result["provider"] == "generic_webhook"
assert result["incident"]["id"] == "FREE-1"
assert result["oncalls"][0]["user"]["id"] == "eng-oncall"
with pytest.raises(ToolExecutionError) as exc:
client.on_call_context("FREE-2")
assert exc.value.kind == ToolErrorKind.RATE_LIMITED
assert exc.value.retryable is True
assert circuit_breaker.state.value == "closed"
def test_live_slack_channel_artifact_routes_later_comms_payloads():
orchestrator = SentinelOrchestrator()
state = InvestigationState(
incident_id="PD-LIVE",
scenario_name="live",
affected_services=["checkout-service"],
service_priority=["checkout-service"],
)
orchestrator._collect_artifacts_from_result(
state,
{"channel": {"id": "C-live-incident", "name": "inc-pd-live-checkout"}},
)
payload = orchestrator._comms_payload(
state,
"checkout-service",
{"message": "SENTINEL is investigating."},
)
assert state.artifacts["slack_channel_id"] == "C-live-incident"
assert state.artifacts["slack_channel_name"] == "inc-pd-live-checkout"
assert payload["channel"] == "C-live-incident"
def test_live_slack_channel_handler_requires_explicit_channel_name():
router = LiveToolRouter(_StubSlackClients())
try:
_slack_channel(router, {"service": "checkout-service"})
except ToolExecutionError as exc:
assert exc.kind == ToolErrorKind.PERMANENT
assert exc.retryable is False
assert "requires an explicit channel_name" in str(exc)
else:
raise AssertionError("expected missing channel_name to fail closed")
def test_live_slack_channel_handler_creates_explicit_channel_name():
clients = _StubSlackClients()
router = LiveToolRouter(clients)
result = _slack_channel(router, {"channel_name": "inc-pd-live-checkout"})
assert result == {"channel": {"id": "C-live", "name": "inc-pd-live-checkout"}}
assert clients.slack.channels == ["inc-pd-live-checkout"]
def test_live_slack_channel_handler_returns_discord_channel_receipt_when_slack_is_disabled():
router = LiveToolRouter(_StubDiscordFallbackClients())
result = _slack_channel(router, {"channel_name": "inc-free-alert-checkout"})
assert result == {
"provider": "discord",
"channel": {"id": "discord-webhook", "name": "inc-free-alert-checkout"},
"created": False,
"reused": True,
}
def test_live_pagerduty_oncall_handler_includes_incident_when_id_is_present():
clients = _StubPagerDutyClients()
router = LiveToolRouter(clients)
result = _pagerduty_oncall(router, {"incident_id": "PD-LIVE-123"})
assert result["incident"]["id"] == "PD-LIVE-123"
assert result["incident"]["status"] == "triggered"
assert result["oncalls"] == [{"user": {"id": "U-oncall"}}]
assert result["escalation_policy_ids"] == ["EP-live"]
assert result["oncall_scope"] == "incident_escalation_policy"
assert clients.pagerduty.requested_incident == "PD-LIVE-123"
assert clients.pagerduty.requested_oncall_policy_ids == ["EP-live"]
def test_live_pagerduty_oncall_handler_does_not_broaden_when_incident_policy_has_no_oncall():
clients = _StubPagerDutyClients(
policy_oncalls={("EP-empty",): []},
incident_policy_id="EP-empty",
)
router = LiveToolRouter(clients)
result = _pagerduty_oncall(router, {"incident_id": "PD-LIVE-123"})
assert result["escalation_policy_ids"] == ["EP-empty"]
assert result["oncall_scope"] == "incident_escalation_policy"
assert result["oncalls"] == []
assert clients.pagerduty.requested_oncall_policy_ids == ["EP-empty"]
def test_live_pagerduty_oncall_empty_incident_policy_yields_empty_live_evidence():
clients = _StubPagerDutyClients(
policy_oncalls={("EP-empty",): []},
incident_policy_id="EP-empty",
)
router = LiveToolRouter(clients)
result = _pagerduty_oncall(router, {"incident_id": "PD-LIVE-123", "service": "checkout-service"})
evidence = _evidence_from_live_result(
"comms.page_oncall_engineer",
{"incident_id": "PD-LIVE-123", "service": "checkout-service"},
result,
)
assert evidence[0].provenance == "live_empty::comms.page_oncall_engineer"
assert "no provider-confirming records" in evidence[0].claim
def test_live_pagerduty_oncall_handler_does_not_use_account_oncall_without_incident_policy():
clients = _StubPagerDutyClients(incident_policy_id=None)
router = LiveToolRouter(clients)
result = _pagerduty_oncall(router, {"incident_id": "PD-LIVE-123"})
assert result["escalation_policy_ids"] == []
assert result["oncall_scope"] == "unconfirmed_incident_escalation_policy"
assert result["oncalls"] == []
assert clients.pagerduty.requested_oncall_policy_ids is None
def test_live_pagerduty_oncall_unconfirmed_incident_policy_yields_empty_live_evidence():
clients = _StubPagerDutyClients(incident_policy_id=None)
router = LiveToolRouter(clients)
result = _pagerduty_oncall(router, {"incident_id": "PD-LIVE-123", "service": "checkout-service"})
evidence = _evidence_from_live_result(
"comms.page_oncall_engineer",
{"incident_id": "PD-LIVE-123", "service": "checkout-service"},
result,
)
assert evidence[0].provenance == "live_empty::comms.page_oncall_engineer"
assert "no provider-confirming records" in evidence[0].claim
def test_live_pagerduty_oncall_confirmed_incident_policy_yields_live_evidence():
clients = _StubPagerDutyClients()
router = LiveToolRouter(clients)
result = _pagerduty_oncall(router, {"incident_id": "PD-LIVE-123", "service": "checkout-service"})
evidence = _evidence_from_live_result(
"comms.page_oncall_engineer",
{"incident_id": "PD-LIVE-123", "service": "checkout-service"},
result,
)
assert evidence[0].provenance == "live::comms.page_oncall_engineer"
assert "observed 1 provider item" in evidence[0].claim
def test_loki_live_evidence_counts_log_entries_not_streams():
evidence = _evidence_from_live_result(
"observe.fetch_service_logs",
{"service": "checkout-service"},
{
"provider": "loki",
"events": [
{
"stream": {"service": "checkout-service"},
"values": [
["1717425600000000000", "first checkout log"],
["1717425601000000000", "second checkout log"],
],
}
],
"streams": [
{
"stream": {"service": "checkout-service"},
"values": [
["1717425600000000000", "first checkout log"],
["1717425601000000000", "second checkout log"],
],
}
],
},
)
assert evidence[0].provenance == "live::observe.fetch_service_logs"
assert "observed 2 provider item" in evidence[0].claim
def test_loki_empty_streams_yield_empty_live_evidence():
evidence = _evidence_from_live_result(
"observe.fetch_service_logs",
{"service": "checkout-service"},
{
"provider": "loki",
"events": [{"stream": {"service": "checkout-service"}, "values": []}],
"streams": [{"stream": {"service": "checkout-service"}, "values": []}],
},
)
assert evidence[0].provenance == "live_empty::observe.fetch_service_logs"
assert "no provider-confirming records" in evidence[0].claim
def test_live_pagerduty_close_handler_requires_explicit_incident_id():
router = LiveToolRouter(_StubPagerDutyClients())
try:
_pagerduty_close(router, {"requester_email": "oncall@example.com"})
except ToolExecutionError as exc:
assert exc.kind == ToolErrorKind.PERMANENT
assert exc.retryable is False
assert "requires an explicit incident_id" in str(exc)
else:
raise AssertionError("expected close incident without incident_id to fail closed")
def test_live_pagerduty_close_handler_trims_explicit_incident_id():
clients = _StubPagerDutyClients()
router = LiveToolRouter(clients)
result = _pagerduty_close(
router,
{"incident_id": " PD-LIVE-123 ", "requester_email": "oncall@example.com"},
)
assert result["incident"]["id"] == "PD-LIVE-123"
assert result["incident"]["status"] == "resolved"
assert clients.pagerduty.updated_incident == ("PD-LIVE-123", "resolved", "oncall@example.com")
def test_live_pagerduty_artifacts_are_collected_from_context_result():
orchestrator = SentinelOrchestrator()
state = InvestigationState(
incident_id="PD-LIVE",
scenario_name="live",
affected_services=["checkout-service"],
service_priority=["checkout-service"],
)
orchestrator._collect_artifacts_from_result(
state,
{
"incident": {
"id": "PD-LIVE",
"status": "triggered",
"urgency": "high",
"html_url": "https://example.pagerduty.com/incidents/PD-LIVE",
},
"escalation_policy_ids": ["EP-live"],
"oncall_scope": "incident_escalation_policy",
"oncalls": [{"user": {"id": "U-oncall", "summary": "On Call"}}],
},
)
assert state.artifacts["pagerduty_incident_status"] == "triggered"
assert state.artifacts["pagerduty_incident_urgency"] == "high"
assert state.artifacts["pagerduty_incident_url"].endswith("/PD-LIVE")
assert state.artifacts["pagerduty_escalation_policy_ids"] == ["EP-live"]
assert state.artifacts["pagerduty_oncall_scope"] == "incident_escalation_policy"
assert state.artifacts["pagerduty_oncall_user"] == "U-oncall"
def test_live_account_scoped_pagerduty_oncalls_do_not_authorize_remediation():
orchestrator = SentinelOrchestrator()
state = InvestigationState(
incident_id="PD-LIVE",
scenario_name="live",
affected_services=["checkout-service"],
service_priority=["checkout-service"],
)
orchestrator._collect_artifacts_from_result(
state,
{
"oncall_scope": "account",
"oncalls": [{"user": {"id": "U-account-oncall"}}],
},
)
assert state.artifacts["pagerduty_oncall_scope"] == "account"
assert "pagerduty_oncall_user" not in state.artifacts
def test_live_pagerduty_oncall_summary_without_user_id_does_not_authorize_remediation():
orchestrator = SentinelOrchestrator()
state = InvestigationState(
incident_id="PD-LIVE",
scenario_name="live",
affected_services=["checkout-service"],
service_priority=["checkout-service"],
)
orchestrator._collect_artifacts_from_result(
state,
{
"oncall_scope": "incident_escalation_policy",
"oncalls": [{"user": {"summary": "On Call"}}],
},
)
assert state.artifacts["pagerduty_oncall_scope"] == "incident_escalation_policy"
assert "pagerduty_oncall_user" not in state.artifacts
def test_live_paged_user_shortcut_does_not_authorize_remediation():
orchestrator = SentinelOrchestrator()
state = InvestigationState(
incident_id="PD-LIVE",
scenario_name="live",
affected_services=["checkout-service"],
service_priority=["checkout-service"],
)
orchestrator._collect_artifacts_from_result(
state,
{"paged_user": "legacy-shortcut"},
)
assert "pagerduty_oncall_user" not in state.artifacts
def test_live_slack_post_handler_requires_explicit_message_payload():
router = LiveToolRouter(_StubSlackClients())
try:
_slack_post(router, {"channel": "C-live"})
except ToolExecutionError as exc:
assert exc.kind == ToolErrorKind.PERMANENT
assert exc.retryable is False
assert "requires an explicit message or text" in str(exc)
else:
raise AssertionError("expected missing Slack message payload to fail closed")
def test_live_slack_post_handler_sends_explicit_text_payload():
clients = _StubSlackClients()
router = LiveToolRouter(clients)
result = _slack_post(router, {"text": " SENTINEL is investigating. ", "channel": "C-live"})
assert result == {
"provider": "slack",
"channel": "C-live",
"ts": "1717425600.000100",
"text": "SENTINEL is investigating.",
}
assert clients.slack.posts == [("SENTINEL is investigating.", "C-live")]
def test_live_slack_post_handler_falls_back_to_discord_webhook():
clients = _StubDiscordFallbackClients()
router = LiveToolRouter(clients)
result = _slack_post(router, {"message": " SENTINEL is investigating. "})
assert result == {
"ok": True,
"provider": "discord",
"content": "SENTINEL is investigating.",
"id": "discord-message-id",
}
assert clients.discord.posts == ["SENTINEL is investigating."]
def test_discord_live_evidence_requires_confirmed_message_id():
evidence = _evidence_from_live_result(
"comms.post_to_slack",
{"service": "checkout-service"},
{
"provider": "discord",
"content": "SENTINEL is investigating.",
},
)
assert evidence[0].provenance == "live_empty::comms.post_to_slack"
assert "no provider-confirming records" in evidence[0].claim
def test_discord_live_evidence_counts_confirmed_message_id():
evidence = _evidence_from_live_result(
"comms.post_to_slack",
{"service": "checkout-service"},
{
"provider": "discord",
"id": "discord-message-id",
"content": "SENTINEL is investigating.",
},
)
assert evidence[0].provenance == "live::comms.post_to_slack"
assert "observed 1 provider item" in evidence[0].claim
def test_live_slack_post_handler_fails_closed_when_slack_and_discord_are_missing():
router = LiveToolRouter(_DiscordMissingClients())
with pytest.raises(ToolExecutionError) as exc:
_slack_post(router, {"message": "SENTINEL is investigating."})
assert exc.value.kind == ToolErrorKind.AUTHORIZATION
assert exc.value.retryable is False
assert "SLACK_BOT_TOKEN is missing and DISCORD_WEBHOOK_URL is not configured" in str(exc.value)
def test_live_status_page_update_is_out_of_scope_for_v1_without_slack_fallback():
clients = _StubSlackClients()
router = LiveToolRouter(clients)
with pytest.raises(ToolExecutionError) as exc:
LIVE_TOOL_HANDLERS["comms.update_status_page"](
router,
{"service": "checkout-service", "message": "Customer-facing update"},
)
assert exc.value.kind == ToolErrorKind.PERMANENT
assert exc.value.retryable is False
assert "out of scope" in str(exc.value)
assert "external customer communication" in str(exc.value)
assert clients.slack.posts == []
@pytest.mark.parametrize(
"tool_name",
[
"infra.scale_replicas",
"infra.toggle_feature_flag",
"infra.flush_cache",
"infra.update_rate_limit",
"infra.drain_node",
"infra.redeploy_service",
"infra.modify_env_config",
"infra.open_circuit_breaker",
"infra.run_migration",
"comms.close_incident",
],
)
def test_live_non_rollback_mutations_are_out_of_scope_for_v1(tool_name):
router = LiveToolRouter(object())
with pytest.raises(ToolExecutionError) as exc:
LIVE_TOOL_HANDLERS[tool_name](router, {"service": "checkout-service"})
assert exc.value.kind == ToolErrorKind.PERMANENT
assert exc.value.retryable is False
assert "out of scope" in str(exc.value)
def test_live_add_database_index_executes_supported_sqlite_index(monkeypatch, tmp_path):
monkeypatch.setenv("SENTINEL_SLOW_QUERY_DB_PATH", str(tmp_path / "slow-query.db"))
monkeypatch.setenv("SENTINEL_PUSH_SLOW_QUERY_LOGS_TO_LOKI", "false")
router = LiveToolRouter(object())
result = LIVE_TOOL_HANDLERS["infra.add_database_index"](
router,
{"service": "payment-service", "table": "orders", "column": "user_id"},
)
assert result["provider"] == "sqlite"
assert result["status"] == "executed"
assert result["verified"] is True
assert result["index"] == "idx_orders_user_id"
assert result["verification_query"]["index_present"] is True
def test_live_add_database_index_rejects_unscoped_index_target(monkeypatch, tmp_path):
monkeypatch.setenv("SENTINEL_SLOW_QUERY_DB_PATH", str(tmp_path / "slow-query.db"))
router = LiveToolRouter(object())
with pytest.raises(ToolExecutionError) as exc:
LIVE_TOOL_HANDLERS["infra.add_database_index"](
router,
{"service": "payment-service", "table": "customers", "column": "email"},
)