-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathtest_context_graph.py
More file actions
2151 lines (1938 loc) · 71.1 KB
/
test_context_graph.py
File metadata and controls
2151 lines (1938 loc) · 71.1 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
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the context_graph module."""
from datetime import datetime
from datetime import timezone
from unittest.mock import MagicMock
from unittest.mock import patch
import pytest
from bigquery_agent_analytics.context_graph import BizNode
from bigquery_agent_analytics.context_graph import Candidate
from bigquery_agent_analytics.context_graph import ContextGraphConfig
from bigquery_agent_analytics.context_graph import ContextGraphManager
from bigquery_agent_analytics.context_graph import DecisionPoint
from bigquery_agent_analytics.context_graph import WorldChangeAlert
from bigquery_agent_analytics.context_graph import WorldChangeReport
# ------------------------------------------------------------------ #
# Data Model Tests #
# ------------------------------------------------------------------ #
class TestBizNode:
"""Tests for BizNode dataclass."""
def test_creation(self):
node = BizNode(
span_id="span-1",
session_id="sess-1",
node_type="Product",
node_value="Yahoo Homepage",
)
assert node.node_type == "Product"
assert node.node_value == "Yahoo Homepage"
assert node.confidence == 1.0
assert node.metadata == {}
def test_with_confidence(self):
node = BizNode(
span_id="span-1",
session_id="sess-1",
node_type="Targeting",
node_value="Millennials",
confidence=0.92,
metadata={"source": "brief"},
)
assert node.confidence == 0.92
assert node.metadata["source"] == "brief"
class TestWorldChangeAlert:
"""Tests for WorldChangeAlert model."""
def test_creation(self):
alert = WorldChangeAlert(
biz_node="Yahoo Homepage",
original_state="Product: Yahoo Homepage",
current_state="unavailable",
drift_type="inventory_depleted",
severity=0.9,
)
assert alert.biz_node == "Yahoo Homepage"
assert alert.drift_type == "inventory_depleted"
assert alert.severity == 0.9
assert alert.recommendation == "Review before approving."
class TestWorldChangeReport:
"""Tests for WorldChangeReport model."""
def test_safe_report(self):
report = WorldChangeReport(
session_id="sess-1",
total_entities_checked=5,
stale_entities=0,
is_safe_to_approve=True,
)
assert report.is_safe_to_approve
assert report.stale_entities == 0
assert "Safe to approve : True" in report.summary()
def test_unsafe_report(self):
alert = WorldChangeAlert(
biz_node="Yahoo Homepage",
original_state="Product: Yahoo Homepage",
current_state="sold_out",
drift_type="inventory_depleted",
severity=0.95,
)
report = WorldChangeReport(
session_id="sess-1",
alerts=[alert],
total_entities_checked=3,
stale_entities=1,
is_safe_to_approve=False,
)
assert not report.is_safe_to_approve
assert report.stale_entities == 1
summary = report.summary()
assert "inventory_depleted" in summary
assert "Yahoo Homepage" in summary
def test_summary_format(self):
report = WorldChangeReport(
session_id="sess-42",
total_entities_checked=10,
stale_entities=2,
is_safe_to_approve=False,
alerts=[
WorldChangeAlert(
biz_node="Product A",
original_state="available",
current_state="depleted",
drift_type="unavailable",
severity=0.8,
),
WorldChangeAlert(
biz_node="Product B",
original_state="$50",
current_state="$75",
drift_type="price_changed",
severity=0.6,
),
],
)
summary = report.summary()
assert "sess-42" in summary
assert "Entities checked : 10" in summary
assert "Stale entities : 2" in summary
assert "Product A" in summary
assert "Product B" in summary
class TestContextGraphConfig:
"""Tests for ContextGraphConfig model."""
def test_defaults(self):
config = ContextGraphConfig()
assert config.biz_nodes_table == "extracted_biz_nodes"
assert config.cross_links_table == "context_cross_links"
assert config.graph_name == "agent_context_graph"
assert config.max_hops == 20
assert "Product" in config.entity_types
def test_custom_config(self):
config = ContextGraphConfig(
graph_name="adcp_graph",
entity_types=["Ad", "Inventory"],
max_hops=10,
)
assert config.graph_name == "adcp_graph"
assert config.entity_types == ["Ad", "Inventory"]
assert config.max_hops == 10
# ------------------------------------------------------------------ #
# ContextGraphManager Tests #
# ------------------------------------------------------------------ #
class TestContextGraphManager:
"""Tests for ContextGraphManager."""
def _make_manager(self, mock_client=None):
return ContextGraphManager(
project_id="test-project",
dataset_id="test_dataset",
table_id="agent_events",
client=mock_client or MagicMock(),
)
def test_resolve_endpoint_short_name(self):
mgr = self._make_manager()
ep = mgr._resolve_endpoint()
assert ep == (
"https://aiplatform.googleapis.com/v1/projects/"
"test-project/locations/global/publishers/google/"
"models/gemini-2.5-flash"
)
def test_resolve_endpoint_full_url(self):
mgr = self._make_manager()
mgr.config = ContextGraphConfig(
endpoint="https://aiplatform.googleapis.com/v1/projects/p/locations/global/publishers/google/models/gemini-3-flash-preview"
)
ep = mgr._resolve_endpoint()
assert ep.startswith("https://")
assert "gemini-3-flash-preview" in ep
def test_resolve_endpoint_rejects_legacy_ref(self):
mgr = self._make_manager()
mgr.config = ContextGraphConfig(endpoint="my-project.my_dataset.my_model")
with pytest.raises(ValueError, match="Legacy BQ ML"):
mgr._resolve_endpoint()
def test_get_property_graph_ddl(self):
mgr = self._make_manager()
ddl = mgr.get_property_graph_ddl()
assert "CREATE OR REPLACE PROPERTY GRAPH" in ddl
assert "test-project" in ddl
assert "test_dataset" in ddl
assert "agent_events" in ddl
assert "TechNode" in ddl
assert "BizNode" in ddl
assert "Caused" in ddl
assert "Evaluated" in ddl
# P1: composite keys
assert "KEY (biz_node_id)" in ddl
assert "KEY (link_id)" in ddl
def test_get_property_graph_ddl_custom_name(self):
mgr = self._make_manager()
ddl = mgr.get_property_graph_ddl(graph_name="my_graph")
assert "my_graph" in ddl
def test_get_reasoning_chain_gql(self):
mgr = self._make_manager()
gql = mgr.get_reasoning_chain_gql(
decision_event_type="HITL_CONFIRMATION_REQUEST_COMPLETED",
biz_entity="Yahoo Homepage",
)
assert "GRAPH" in gql
assert "MATCH" in gql
assert "Caused" in gql
assert "Evaluated" in gql
# P2: biz_entity is parameterized, not interpolated
assert "@biz_entity" in gql
assert "Yahoo Homepage" not in gql
def test_get_reasoning_chain_gql_no_entity(self):
mgr = self._make_manager()
gql = mgr.get_reasoning_chain_gql(
decision_event_type="AGENT_COMPLETED",
)
assert "GRAPH" in gql
assert "@biz_entity" not in gql
def test_get_causal_chain_gql(self):
mgr = self._make_manager()
gql = mgr.get_causal_chain_gql(session_id="sess-1")
assert "GRAPH" in gql
assert "MATCH" in gql
assert "USER_MESSAGE_RECEIVED" in gql
def test_create_property_graph_success(self):
mock_client = MagicMock()
mock_job = MagicMock()
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
result = mgr.create_property_graph()
assert result is True
mock_client.query.assert_called_once()
mock_job.result.assert_called_once()
def test_create_property_graph_failure(self):
mock_client = MagicMock()
mock_client.query.side_effect = Exception("BigQuery error")
mgr = self._make_manager(mock_client)
result = mgr.create_property_graph()
assert result is False
def test_store_biz_nodes_empty(self):
mgr = self._make_manager()
assert mgr.store_biz_nodes([]) is True
def test_store_biz_nodes_success(self):
mock_client = MagicMock()
mock_query_job = MagicMock()
mock_client.query.return_value = mock_query_job
mock_load_job = MagicMock()
mock_client.load_table_from_json.return_value = mock_load_job
mgr = self._make_manager(mock_client)
nodes = [
BizNode(
span_id="s1",
session_id="sess-1",
node_type="Product",
node_value="Homepage",
),
]
result = mgr.store_biz_nodes(nodes)
assert result is True
mock_client.load_table_from_json.assert_called_once()
# Streaming insert path must NOT be used — that's the buffered
# write path that breaks rerun idempotency.
mock_client.insert_rows_json.assert_not_called()
def test_store_biz_nodes_insert_error(self):
mock_client = MagicMock()
mock_query_job = MagicMock()
mock_client.query.return_value = mock_query_job
# Load job raises — surfaces as False from store_biz_nodes.
mock_client.load_table_from_json.side_effect = Exception("load failed")
mgr = self._make_manager(mock_client)
nodes = [
BizNode(
span_id="s1",
session_id="sess-1",
node_type="Product",
node_value="Homepage",
),
]
result = mgr.store_biz_nodes(nodes)
assert result is False
def test_store_biz_nodes_dedupes_by_biz_node_id_and_uses_load_job(self):
"""The BizNode KEY in the property graph is biz_node_id, so the
backing table must have at most one row per id. ``store_biz_nodes``
dedupes (last-wins) before insert AND writes via a load job, not
via the streaming-insert API.
The streaming insert path was the source of the duplicate-key
rerun bug (PR #99 follow-up): its buffer is invisible to DML
DELETE for ~30 minutes, so a re-run within that window would
add duplicates against rows the DELETE could not evict. Load
jobs write to managed storage, so the DELETE in the same Python
session sees the rows.
"""
mock_client = MagicMock()
mock_query_job = MagicMock()
mock_client.query.return_value = mock_query_job
mock_load_job = MagicMock()
mock_client.load_table_from_json.return_value = mock_load_job
mgr = self._make_manager(mock_client)
nodes = [
BizNode(
span_id="s1",
session_id="sess-1",
node_type="Product",
node_value="Homepage",
confidence=0.5,
),
BizNode(
span_id="s1",
session_id="sess-1",
node_type="Product",
node_value="Homepage",
confidence=0.9, # later — should win
),
BizNode(
span_id="s2",
session_id="sess-1",
node_type="Product",
node_value="Other",
),
]
assert mgr.store_biz_nodes(nodes) is True
mock_client.insert_rows_json.assert_not_called()
args, _ = mock_client.load_table_from_json.call_args
loaded_rows = args[0]
biz_ids = [r["biz_node_id"] for r in loaded_rows]
assert len(biz_ids) == len(
set(biz_ids)
), f"load_table_from_json received duplicate biz_node_id keys: {biz_ids}"
dup_row = next(
r for r in loaded_rows if r["biz_node_id"] == "s1:Product:Homepage"
)
assert dup_row["confidence"] == 0.9
def test_store_biz_nodes_is_rerun_idempotent_via_session_delete(self):
"""Calling store_biz_nodes twice with the same nodes must not
duplicate biz_node_id rows.
The append-only load-job path is not idempotent on its own —
the BizNode KEY (biz_node_id) graph contract would be violated.
store_biz_nodes() therefore issues a DELETE FROM ... WHERE
session_id IN UNNEST(@session_ids) before the load, so the
second call evicts the first call's rows before appending.
"""
mock_client = MagicMock()
mock_query_job = MagicMock()
mock_client.query.return_value = mock_query_job
mock_load_job = MagicMock()
mock_client.load_table_from_json.return_value = mock_load_job
mgr = self._make_manager(mock_client)
nodes = [
BizNode(
span_id="s1",
session_id="sess-1",
node_type="Product",
node_value="Homepage",
),
]
assert mgr.store_biz_nodes(nodes) is True
# Capture all query() calls — the per-session DELETE is one of
# them (the other being the table-create DDL).
delete_calls_run_1 = [
c
for c in mock_client.query.call_args_list
if "DELETE FROM" in c[0][0]
and self._make_manager().config.biz_nodes_table in c[0][0]
]
assert len(delete_calls_run_1) == 1, (
"store_biz_nodes should issue exactly one biz_nodes DELETE"
" before its load on each call; got"
f" {len(delete_calls_run_1)}"
)
# Re-invoke. The second call must also DELETE before load.
assert mgr.store_biz_nodes(nodes) is True
delete_calls_total = [
c
for c in mock_client.query.call_args_list
if "DELETE FROM" in c[0][0]
and self._make_manager().config.biz_nodes_table in c[0][0]
]
assert len(delete_calls_total) == 2, (
"second store_biz_nodes call must also DELETE for idempotency;"
f" total observed: {len(delete_calls_total)}"
)
# Both load-job calls must have happened — but both with the
# same single deduped row (the second one repeats the first).
assert mock_client.load_table_from_json.call_count == 2
def test_detect_world_changes_no_drift(self):
mock_client = MagicMock()
mock_job = MagicMock()
mock_job.result.return_value = []
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
report = mgr.detect_world_changes(session_id="sess-1")
assert report.is_safe_to_approve
assert report.stale_entities == 0
assert len(report.alerts) == 0
def test_detect_world_changes_with_drift(self):
mock_client = MagicMock()
mock_job = MagicMock()
# Simulate returned biz nodes with evaluated_at timestamps
mock_job.result.return_value = [
{
"span_id": "s1",
"node_type": "Product",
"node_value": "Yahoo Homepage",
"confidence": 0.95,
"evaluated_at": datetime(2025, 6, 1, 12, 0, tzinfo=timezone.utc),
},
{
"span_id": "s2",
"node_type": "Targeting",
"node_value": "Millennials",
"confidence": 0.90,
"evaluated_at": datetime(2025, 6, 1, 12, 1, tzinfo=timezone.utc),
},
]
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
def check_state(node):
# Verify evaluated_at timestamp is passed through
assert node.evaluated_at is not None
if node.node_value == "Yahoo Homepage":
return {
"available": False,
"current_value": "sold_out",
"drift_type": "inventory_depleted",
"severity": 0.95,
}
return {"available": True, "current_value": node.node_value}
report = mgr.detect_world_changes(
session_id="sess-1",
current_state_fn=check_state,
)
assert not report.is_safe_to_approve
assert report.stale_entities == 1
assert len(report.alerts) == 1
assert report.alerts[0].biz_node == "Yahoo Homepage"
assert report.alerts[0].drift_type == "inventory_depleted"
def test_detect_world_changes_fn_exception(self):
mock_client = MagicMock()
mock_job = MagicMock()
mock_job.result.return_value = [
{
"span_id": "s1",
"node_type": "Product",
"node_value": "Test",
"confidence": 1.0,
"evaluated_at": datetime(2025, 6, 1, 12, 0, tzinfo=timezone.utc),
},
]
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
def bad_fn(node):
raise RuntimeError("API failure")
report = mgr.detect_world_changes(
session_id="sess-1",
current_state_fn=bad_fn,
)
# Fail-closed: callback failure → not safe to approve
assert not report.is_safe_to_approve
assert report.check_failed is True
def test_detect_world_changes_query_failure_is_fail_closed(self):
mock_client = MagicMock()
mock_client.query.side_effect = Exception("BigQuery unavailable")
mgr = self._make_manager(mock_client)
report = mgr.detect_world_changes(session_id="sess-1")
assert not report.is_safe_to_approve
assert report.check_failed is True
assert "CHECK FAILED" in report.summary()
def test_create_cross_links_success(self):
mock_client = MagicMock()
mock_job = MagicMock()
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
result = mgr.create_cross_links(["sess-1"])
assert result is True
# create table + delete old links + insert new links
assert mock_client.query.call_count == 3
def test_create_cross_links_failure(self):
mock_client = MagicMock()
mock_client.query.side_effect = Exception("fail")
mgr = self._make_manager(mock_client)
result = mgr.create_cross_links(["sess-1"])
assert result is False
def test_build_context_graph(self):
mock_client = MagicMock()
mock_job = MagicMock()
mock_job.result.return_value = []
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
results = mgr.build_context_graph(
session_ids=["sess-1"],
use_ai_generate=False,
)
assert "biz_nodes_count" in results
assert "cross_links_created" in results
assert "property_graph_created" in results
def test_explain_decision_failure(self):
mock_client = MagicMock()
mock_client.query.side_effect = Exception("GQL error")
mgr = self._make_manager(mock_client)
result = mgr.explain_decision(
biz_entity="Yahoo Homepage",
)
assert result == []
def test_traverse_causal_chain_failure(self):
mock_client = MagicMock()
mock_client.query.side_effect = Exception("GQL error")
mgr = self._make_manager(mock_client)
result = mgr.traverse_causal_chain(session_id="sess-1")
assert result == []
def test_extract_query_uses_prompt_only_extraction(self):
"""Biz-node extraction relies on prompt-shaped JSON output, not on
AI.GENERATE's ``output_schema`` parameter.
Background: the current BigQuery AI.GENERATE parser rejects the
JSON-Schema strings the SDK previously passed via ``output_schema``
(it now expects a SQL-style column list like ``'foo STRING'``).
The SDK instead asks the model in-prompt to return a JSON array
and parses the response with markdown-fence stripping +
``JSON_EXTRACT_ARRAY``.
"""
self._make_manager()
from bigquery_agent_analytics.context_graph import _EXTRACT_BIZ_NODES_QUERY
# No output_schema kwarg in the AI.GENERATE call.
assert "output_schema =>" not in _EXTRACT_BIZ_NODES_QUERY
# Prompt enumerates the field contract.
assert "entity_type" in _EXTRACT_BIZ_NODES_QUERY
assert "entity_value" in _EXTRACT_BIZ_NODES_QUERY
assert "confidence" in _EXTRACT_BIZ_NODES_QUERY
# Markdown-fence stripping + JSON_EXTRACT_ARRAY parse pipeline.
assert "JSON_EXTRACT_ARRAY" in _EXTRACT_BIZ_NODES_QUERY
assert "REGEXP_REPLACE" in _EXTRACT_BIZ_NODES_QUERY
def test_property_graph_ddl_has_artifact_uri(self):
mgr = self._make_manager()
ddl = mgr.get_property_graph_ddl()
assert "artifact_uri" in ddl
def test_property_graph_ddl_evaluated_has_properties(self):
mgr = self._make_manager()
ddl = mgr.get_property_graph_ddl()
assert "link_type" in ddl
assert "created_at" in ddl
def test_reconstruct_trace_gql_success(self):
mock_client = MagicMock()
mock_job = MagicMock()
mock_job.result.return_value = [
{
"parent_span_id": "s1",
"parent_event_type": "USER_MESSAGE_RECEIVED",
"parent_agent": "root",
"parent_timestamp": datetime(
2025, 6, 1, 12, 0, tzinfo=timezone.utc
),
"session_id": "sess-1",
"parent_invocation_id": "inv-1",
"parent_content": {},
"parent_latency_ms": None,
"parent_status": "OK",
"parent_error_message": None,
"child_span_id": "s2",
"child_event_type": "LLM_REQUEST",
"child_agent": "root",
"child_timestamp": datetime(2025, 6, 1, 12, 1, tzinfo=timezone.utc),
"child_invocation_id": "inv-1",
"child_content": {},
"child_latency_ms": 500,
"child_status": "OK",
"child_error_message": None,
},
]
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
rows = mgr.reconstruct_trace_gql(session_id="sess-1")
assert len(rows) == 1
assert rows[0]["parent_span_id"] == "s1"
assert rows[0]["child_span_id"] == "s2"
def test_reconstruct_trace_gql_failure(self):
mock_client = MagicMock()
mock_client.query.side_effect = Exception("GQL error")
mgr = self._make_manager(mock_client)
result = mgr.reconstruct_trace_gql(session_id="sess-1")
assert result == []
def test_biz_node_has_evaluated_at_and_artifact_uri(self):
node = BizNode(
span_id="s1",
session_id="sess-1",
node_type="Product",
node_value="Yahoo Homepage",
evaluated_at=datetime(2025, 6, 1, 12, 0, tzinfo=timezone.utc),
artifact_uri="gs://bucket/path/file.json",
)
assert node.evaluated_at is not None
assert node.artifact_uri == "gs://bucket/path/file.json"
def test_detect_world_changes_passes_evaluated_at(self):
mock_client = MagicMock()
mock_job = MagicMock()
eval_time = datetime(2025, 6, 1, 12, 0, tzinfo=timezone.utc)
mock_job.result.return_value = [
{
"span_id": "s1",
"node_type": "Product",
"node_value": "Test",
"confidence": 1.0,
"evaluated_at": eval_time,
},
]
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
received_timestamps = []
def check_fn(node):
received_timestamps.append(node.evaluated_at)
return {"available": True, "current_value": node.node_value}
mgr.detect_world_changes(
session_id="sess-1",
current_state_fn=check_fn,
)
assert len(received_timestamps) == 1
assert received_timestamps[0] == eval_time
def test_get_biz_nodes_returns_artifact_uri(self):
mock_client = MagicMock()
mock_job = MagicMock()
mock_job.result.return_value = [
{
"biz_node_id": "s1:Product:Yahoo",
"span_id": "s1",
"session_id": "sess-1",
"node_type": "Product",
"node_value": "Yahoo",
"confidence": 0.95,
"artifact_uri": "gs://bucket/output.json",
},
]
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
nodes = mgr.get_biz_nodes_for_session("sess-1")
assert len(nodes) == 1
assert nodes[0].artifact_uri == "gs://bucket/output.json"
def test_read_biz_nodes_returns_artifact_uri(self):
mock_client = MagicMock()
mock_job = MagicMock()
mock_job.result.return_value = [
{
"span_id": "s1",
"session_id": "sess-1",
"node_type": "Product",
"node_value": "Yahoo",
"confidence": 0.95,
"artifact_uri": "gs://bucket/file.pdf",
},
]
mock_client.query.return_value = mock_job
mgr = self._make_manager(mock_client)
nodes = mgr._read_biz_nodes(["sess-1"])
assert len(nodes) == 1
assert nodes[0].artifact_uri == "gs://bucket/file.pdf"
def test_cross_link_id_uses_biz_node_id(self):
from bigquery_agent_analytics.context_graph import _INSERT_CROSS_LINKS_QUERY
assert "b.biz_node_id AS link_id" in _INSERT_CROSS_LINKS_QUERY
def test_merge_deletes_stale_biz_nodes(self):
from bigquery_agent_analytics.context_graph import _EXTRACT_BIZ_NODES_QUERY
assert "WHEN NOT MATCHED BY SOURCE" in _EXTRACT_BIZ_NODES_QUERY
assert "DELETE" in _EXTRACT_BIZ_NODES_QUERY
def test_store_biz_nodes_persists_artifact_uri(self):
mock_client = MagicMock()
mock_query_job = MagicMock()
mock_client.query.return_value = mock_query_job
mock_load_job = MagicMock()
mock_client.load_table_from_json.return_value = mock_load_job
mgr = self._make_manager(mock_client)
nodes = [
BizNode(
span_id="s1",
session_id="sess-1",
node_type="Product",
node_value="Homepage",
artifact_uri="gs://bucket/artifact.json",
),
]
result = mgr.store_biz_nodes(nodes)
assert result is True
call_args = mock_client.load_table_from_json.call_args
loaded_rows = call_args[0][0]
assert loaded_rows[0]["artifact_uri"] == "gs://bucket/artifact.json"
def test_create_cross_links_fails_on_real_delete_error(self):
mock_client = MagicMock()
# First call (create table) succeeds, second (delete) fails
mock_job_ok = MagicMock()
mock_job_ok.result.return_value = None
call_count = {"n": 0}
def side_effect(*args, **kwargs):
call_count["n"] += 1
if call_count["n"] == 2:
raise Exception("Permission denied")
return mock_job_ok
mock_client.query.side_effect = side_effect
mgr = self._make_manager(mock_client)
result = mgr.create_cross_links(["sess-1"])
assert result is False
def test_create_cross_links_ignores_not_found_delete(self):
mock_client = MagicMock()
mock_job_ok = MagicMock()
mock_job_ok.result.return_value = None
call_count = {"n": 0}
def side_effect(*args, **kwargs):
call_count["n"] += 1
if call_count["n"] == 2:
raise Exception("Table not found: cross_links")
return mock_job_ok
mock_client.query.side_effect = side_effect
mgr = self._make_manager(mock_client)
result = mgr.create_cross_links(["sess-1"])
assert result is True
# ------------------------------------------------------------------ #
# Decision Semantics Data Model Tests #
# ------------------------------------------------------------------ #
class TestDecisionPoint:
"""Tests for DecisionPoint dataclass."""
def test_creation(self):
dp = DecisionPoint(
decision_id="dp-1",
session_id="sess-1",
span_id="span-5",
decision_type="audience_selection",
description="Select target audience for Nike campaign",
)
assert dp.decision_id == "dp-1"
assert dp.decision_type == "audience_selection"
assert dp.description == "Select target audience for Nike campaign"
assert dp.metadata == {}
def test_defaults(self):
dp = DecisionPoint(
decision_id="dp-1",
session_id="sess-1",
span_id="span-1",
decision_type="placement",
)
assert dp.description == ""
assert dp.timestamp is None
assert dp.metadata == {}
class TestCandidate:
"""Tests for Candidate dataclass."""
def test_selected_candidate(self):
c = Candidate(
candidate_id="c-1",
decision_id="dp-1",
session_id="sess-1",
name="Athletes 18-35",
score=0.91,
status="SELECTED",
)
assert c.name == "Athletes 18-35"
assert c.score == 0.91
assert c.status == "SELECTED"
assert c.rejection_rationale is None
def test_dropped_candidate(self):
c = Candidate(
candidate_id="c-2",
decision_id="dp-1",
session_id="sess-1",
name="Fitness Enthusiasts",
score=0.78,
status="DROPPED",
rejection_rationale="Budget constraint: $50K insufficient for reach",
)
assert c.status == "DROPPED"
assert "Budget constraint" in c.rejection_rationale
def test_defaults(self):
c = Candidate(
candidate_id="c-1",
decision_id="dp-1",
session_id="sess-1",
name="Test",
)
assert c.score == 0.0
assert c.status == "SELECTED"
assert c.rejection_rationale is None
assert c.properties == {}
# ------------------------------------------------------------------ #
# Decision Semantics Manager Tests #
# ------------------------------------------------------------------ #
class TestDecisionSemantics:
"""Tests for Decision Semantics extension methods."""
def _make_manager(self, mock_client=None):
return ContextGraphManager(
project_id="test-project",
dataset_id="test_dataset",
table_id="agent_events",
client=mock_client or MagicMock(),
)
def test_config_has_decision_tables(self):
config = ContextGraphConfig()
assert config.decision_points_table == "decision_points"
assert config.candidates_table == "candidates"
assert config.made_decision_edges_table == "made_decision_edges"
assert config.candidate_edges_table == "candidate_edges"
def test_config_custom_decision_tables(self):
config = ContextGraphConfig(
decision_points_table="my_decisions",
candidates_table="my_candidates",
made_decision_edges_table="my_md_edges",
candidate_edges_table="my_cand_edges",
)
assert config.decision_points_table == "my_decisions"
assert config.candidates_table == "my_candidates"
assert config.made_decision_edges_table == "my_md_edges"
assert config.candidate_edges_table == "my_cand_edges"
def test_store_decision_points_empty(self):
mgr = self._make_manager()
assert mgr.store_decision_points([], []) is True
def test_store_decision_points_success(self):
mock_client = MagicMock()
mock_query_job = MagicMock()
mock_client.query.return_value = mock_query_job
mock_load_job = MagicMock()
mock_client.load_table_from_json.return_value = mock_load_job
mgr = self._make_manager(mock_client)
dps = [
DecisionPoint(
decision_id="dp-1",
session_id="sess-1",
span_id="s5",
decision_type="audience_selection",
description="Select audience",
),
]
candidates = [
Candidate(
candidate_id="c-1",
decision_id="dp-1",
session_id="sess-1",
name="Athletes 18-35",
score=0.91,
status="SELECTED",
),
Candidate(
candidate_id="c-2",
decision_id="dp-1",
session_id="sess-1",
name="Fitness Enthusiasts",
score=0.78,
status="DROPPED",
rejection_rationale="Budget constraint",
),
]
result = mgr.store_decision_points(dps, candidates)
assert result is True
# Two load jobs (one for decision_points, one for candidates).
assert mock_client.load_table_from_json.call_count == 2
# Streaming insert path must not be used.
mock_client.insert_rows_json.assert_not_called()
def test_store_decision_points_dedupes_by_id_and_uses_load_job(self):
"""The DecisionPoint and CandidateNode KEYs in the property
graph are decision_id and candidate_id; the backing tables must
have at most one row per id. ``store_decision_points`` dedupes
(last-wins) before insert AND writes via load jobs, not via the
streaming-insert API.
Both halves are needed: the in-Python dedupe handles the
in-batch duplicate case (AI.GENERATE returning overlapping
items in a single extraction), and the load-job path handles
the cross-batch / rerun case (a prior ``DELETE`` is invisible
to the next streaming insert because of the ~30 minute legacy
streaming buffer; load jobs write to managed storage so the
DELETE in the same Python session sees the rows).
"""
mock_client = MagicMock()
mock_query_job = MagicMock()
mock_client.query.return_value = mock_query_job
mock_load_job = MagicMock()
mock_client.load_table_from_json.return_value = mock_load_job
mgr = self._make_manager(mock_client)
dps = [
DecisionPoint(
decision_id="dp-1",
session_id="sess-1",
span_id="s5",
decision_type="audience_selection",
description="first",
),