-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_main.py
More file actions
2731 lines (2218 loc) · 100 KB
/
Copy pathtest_main.py
File metadata and controls
2731 lines (2218 loc) · 100 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
"""Tests for main loop logic."""
from __future__ import annotations
from unittest.mock import MagicMock, call, patch
import pyarrow as pa
import pytest
from viaduck import metrics
from viaduck.apply import (
_apply_changes,
_build_delete_filter,
_resolve_conflicts,
_write_with_retry,
append_only,
)
from viaduck.main import (
_derive_dest_status,
_fmt_duration,
_group_by_cursor,
_initial_snapshot_id,
_poll_cycle,
_resolve_preimages,
_scan_progress_suffix,
_seed_new_destinations,
_start_progress_heartbeat,
)
from viaduck.router import RoutingError
def setup_module():
metrics.init("test")
# ---------------------------------------------------------------------------
# _group_by_cursor
# ---------------------------------------------------------------------------
def test_group_by_cursor_all_same():
cursors = {"a": 10, "b": 10, "c": 10}
groups = _group_by_cursor(cursors, ["a", "b", "c"])
assert groups == {10: ["a", "b", "c"]}
def test_group_by_cursor_mixed():
cursors = {"a": 10, "b": 5, "c": 10}
groups = _group_by_cursor(cursors, ["a", "b", "c"])
assert groups == {10: ["a", "c"], 5: ["b"]}
def test_group_by_cursor_missing_defaults_to_zero():
cursors = {"a": 10}
groups = _group_by_cursor(cursors, ["a", "b"])
assert groups == {10: ["a"], 0: ["b"]}
def test_group_by_cursor_empty():
groups = _group_by_cursor({}, [])
assert groups == {}
# ---------------------------------------------------------------------------
# _write_with_retry
# ---------------------------------------------------------------------------
def test_write_with_retry_success_first_attempt():
pool = MagicMock()
mock_catalog = MagicMock()
mock_table = MagicMock()
pool.get.return_value = (mock_catalog, mock_table)
called = {}
def op(catalog, table):
called["catalog"] = catalog
called["table"] = table
_write_with_retry(pool, "dest-1", op)
assert called["catalog"] is mock_catalog
assert called["table"] is mock_table
def test_write_with_retry_retries_on_failure():
pool = MagicMock()
mock_catalog = MagicMock()
mock_table = MagicMock()
pool.get.return_value = (mock_catalog, mock_table)
attempts = {"count": 0}
def op(catalog, table):
attempts["count"] += 1
if attempts["count"] == 1:
raise Exception("fail")
with patch("viaduck.apply.time.sleep"):
_write_with_retry(pool, "dest-1", op)
assert attempts["count"] == 2
pool.evict.assert_called_once_with("dest-1")
def test_write_with_retry_exhausted():
pool = MagicMock()
pool.get.return_value = (MagicMock(), MagicMock())
def op(catalog, table):
raise Exception("persistent failure")
with patch("viaduck.apply.time.sleep"):
with pytest.raises(Exception, match="persistent failure"):
_write_with_retry(pool, "dest-1", op)
def test_write_with_retry_logs_exception_message():
"""Retry should log the actual exception message."""
pool = MagicMock()
pool.get.return_value = (MagicMock(), MagicMock())
attempts = {"count": 0}
def op(catalog, table):
attempts["count"] += 1
if attempts["count"] == 1:
raise ConnectionError("connection refused")
with patch("viaduck.apply.time.sleep"), patch("viaduck.apply.log") as mock_log:
_write_with_retry(pool, "dest-1", op)
warning_call = mock_log.warning.call_args
assert "connection refused" in str(warning_call)
# ---------------------------------------------------------------------------
# _poll_cycle helpers
# ---------------------------------------------------------------------------
def _make_cfg(dest_ids_and_rvs: list[tuple[str, str]]):
"""Create a mock config with given (dest_id, routing_value) pairs."""
cfg = MagicMock()
dests = []
for did, rv in dest_ids_and_rvs:
d = MagicMock()
d.id = did
d.routing_value = rv
dests.append(d)
cfg.destinations = dests
cfg.poll.cdc_chunk_snapshots = 100
def by_id(dest_id):
for d in dests:
if d.id == dest_id:
return d
raise KeyError(dest_id)
cfg.destination_by_id = by_id
return cfg
# ---------------------------------------------------------------------------
# _poll_cycle (buffered delivery: reads + routing land in the DeliveryManager;
# writes are worker-side and covered by tests/unit/test_delivery.py)
# ---------------------------------------------------------------------------
def _make_delivery(positions: dict[str, int]):
"""Mock DeliveryManager: position map + status snapshot for all dests."""
from viaduck.delivery import DestDeliveryStatus
delivery = MagicMock()
delivery.positions.return_value = dict(positions)
delivery.read_plan.return_value = {d: (snap, 0) for d, snap in positions.items()}
delivery.should_pause_reads.return_value = False
delivery.maybe_flush.return_value = 0
delivery.status_snapshot.return_value = {
d: DestDeliveryStatus(
flushed_snapshot=snap,
position_snapshot=snap,
rows_replicated=0,
last_error=None,
buffer_rows=0,
buffer_age_s=0.0,
flushing=False,
)
for d, snap in positions.items()
}
return delivery
def test_poll_cycle_no_snapshots():
"""If source has no snapshots, no reads happen — but triggers are still
evaluated (position-only persists may be due)."""
delivery = _make_delivery({})
router = MagicMock()
cfg = _make_cfg([])
with patch("viaduck.main.source.current_snapshot_id", return_value=None):
_poll_cycle(MagicMock(), delivery, MagicMock(), router, cfg, [], {}, key_columns=[], mode="append_only")
delivery.read_plan.assert_not_called()
delivery.maybe_flush.assert_called_once()
def test_poll_cycle_all_caught_up():
"""If every position is at the current snapshot, no CDC reads occur."""
delivery = _make_delivery({"dest-1": 10})
router = MagicMock()
cfg = _make_cfg([("dest-1", "quacksworth")])
with patch("viaduck.main.source.current_snapshot_id", return_value=10):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1"],
{"quacksworth": "dest-1"},
key_columns=[],
mode="append_only",
)
router.build_filter_expr.assert_not_called()
delivery.buffer.assert_not_called()
delivery.maybe_flush.assert_called_once()
def test_poll_cycle_routes_and_buffers():
"""Read CDC, route, buffer (BufferRead) — no synchronous writes."""
delivery = _make_delivery({"dest-1": 5})
router = MagicMock()
cfg = _make_cfg([("dest-1", "quacksworth")])
arrow_data = pa.table({"company": ["quacksworth", "quacksworth"], "value": [10, 20]})
router.build_filter_expr.return_value = "company IN ('quacksworth')"
router.split_and_count.return_value = ({"quacksworth": arrow_data}, 0)
with (
patch("viaduck.main.source.current_snapshot_id", return_value=10),
patch("viaduck.main.source.read_cdc", return_value=arrow_data),
):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1"],
{"quacksworth": "dest-1"},
key_columns=[],
mode="append_only",
)
delivery.buffer.assert_called_once_with("dest-1", arrow_data, 10, epoch=0)
delivery.advance_position.assert_not_called()
assert delivery.maybe_flush.call_count == 2 # once per chunk + once at end of cycle
def test_poll_cycle_empty_changeset_advances_positions():
"""An empty CDC range advances in-memory positions (no PG write)."""
delivery = _make_delivery({"dest-1": 5, "dest-2": 5})
router = MagicMock()
cfg = _make_cfg([("dest-1", "a"), ("dest-2", "b")])
empty = pa.table({"company": pa.array([], type=pa.string())})
with (
patch("viaduck.main.source.current_snapshot_id", return_value=10),
patch("viaduck.main.source.read_cdc", return_value=empty),
):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1", "dest-2"],
{"a": "dest-1", "b": "dest-2"},
key_columns=[],
mode="append_only",
)
assert delivery.advance_position.call_count == 2
delivery.advance_position.assert_any_call("dest-1", 10, epoch=0)
delivery.advance_position.assert_any_call("dest-2", 10, epoch=0)
delivery.buffer.assert_not_called()
assert delivery.maybe_flush.call_count == 2 # once per chunk + once at end of cycle
def test_poll_cycle_routing_error_breaks_gracefully():
"""A routing failure stops reads for the cycle without buffering."""
delivery = _make_delivery({"dest-1": 5})
router = MagicMock()
cfg = _make_cfg([("dest-1", "quacksworth")])
arrow_data = pa.table({"other": ["x"]})
router.split_and_count.side_effect = RoutingError("routing field missing")
with (
patch("viaduck.main.source.current_snapshot_id", return_value=10),
patch("viaduck.main.source.read_cdc", return_value=arrow_data),
):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1"],
{"quacksworth": "dest-1"},
key_columns=[],
mode="append_only",
)
delivery.buffer.assert_not_called()
assert delivery.maybe_flush.call_count == 1 # routing error skips per-chunk flush
def test_poll_cycle_chunks_large_range():
"""Range larger than cdc_chunk_snapshots is split into multiple reads."""
delivery = _make_delivery({"dest-1": 0})
router = MagicMock()
cfg = _make_cfg([("dest-1", "quacksworth")])
cfg.poll.cdc_chunk_snapshots = 5 # positions 0→5, 5→10
arrow_data = pa.table({"company": ["quacksworth"], "value": [1]})
router.build_filter_expr.return_value = None
router.split_and_count.return_value = ({"quacksworth": arrow_data}, 0)
read_calls = []
def fake_read_cdc(src_table, *, after_snapshot, end_snapshot, filter_expr=None):
read_calls.append((after_snapshot, end_snapshot))
return arrow_data
with (
patch("viaduck.main.source.current_snapshot_id", return_value=10),
patch("viaduck.main.source.read_cdc", side_effect=fake_read_cdc),
):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1"],
{"quacksworth": "dest-1"},
key_columns=[],
mode="append_only",
)
assert read_calls == [(0, 5), (5, 10)], f"expected two chunk reads, got {read_calls}"
# cursor advances to chunk_end (5, then 10), not directly to 10 in one shot
buffer_calls = delivery.buffer.call_args_list
assert len(buffer_calls) == 2
assert buffer_calls[0] == call("dest-1", arrow_data, 5, epoch=0)
assert buffer_calls[1] == call("dest-1", arrow_data, 10, epoch=0)
delivery.advance_position.assert_not_called()
assert delivery.maybe_flush.call_count == 3 # once per chunk (×2) + once at end of cycle
def test_poll_cycle_chunk_end_not_current_id():
"""buffer() and advance_position() receive chunk_end, not current_id."""
delivery = _make_delivery({"dest-1": 0, "dest-2": 0})
router = MagicMock()
cfg = _make_cfg([("dest-1", "a"), ("dest-2", "b")])
cfg.poll.cdc_chunk_snapshots = 3 # chunks: 0→3, 3→6, 6→7
row_a = pa.table({"company": ["a"]})
empty = pa.table({"company": pa.array([], type=pa.string())})
call_count = [0]
def fake_read(src_table, *, after_snapshot, end_snapshot, filter_expr=None):
call_count[0] += 1
return row_a if call_count[0] == 1 else empty
router.build_filter_expr.return_value = None
router.split_and_count.return_value = ({"a": row_a}, 0)
with (
patch("viaduck.main.source.current_snapshot_id", return_value=7),
patch("viaduck.main.source.read_cdc", side_effect=fake_read),
):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1", "dest-2"],
{"a": "dest-1", "b": "dest-2"},
key_columns=[],
mode="append_only",
)
# First chunk (0→3): dest-1 buffered at 3, dest-2 advanced to 3
delivery.buffer.assert_any_call("dest-1", row_a, 3, epoch=0)
delivery.advance_position.assert_any_call("dest-2", 3, epoch=0)
# Chunks 3→6 and 6→7: empty, both advanced through to 7
delivery.advance_position.assert_any_call("dest-1", 7, epoch=0)
delivery.advance_position.assert_any_call("dest-2", 7, epoch=0)
assert delivery.maybe_flush.call_count == 4 # once per chunk (×3) + once at end of cycle
def test_poll_cycle_multi_chunk_all_empty_flushes_per_chunk():
"""Multi-chunk catch-up where every chunk is empty still flushes and advances per chunk."""
delivery = _make_delivery({"dest-1": 0})
router = MagicMock()
cfg = _make_cfg([("dest-1", "quacksworth")])
cfg.poll.cdc_chunk_snapshots = 5 # two chunks: 0→5, 5→10
empty = pa.table({"company": pa.array([], type=pa.string())})
with (
patch("viaduck.main.source.current_snapshot_id", return_value=10),
patch("viaduck.main.source.read_cdc", return_value=empty),
):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1"],
{"quacksworth": "dest-1"},
key_columns=[],
mode="append_only",
)
# cursor advanced to each chunk_end incrementally, not directly to 10
assert delivery.advance_position.call_count == 2
delivery.advance_position.assert_any_call("dest-1", 5, epoch=0)
delivery.advance_position.assert_any_call("dest-1", 10, epoch=0)
delivery.buffer.assert_not_called()
assert delivery.maybe_flush.call_count == 3 # once per chunk (×2) + once at end of cycle
def test_poll_cycle_advances_no_data_destinations():
"""Destinations in the group with no routed rows advance positions."""
delivery = _make_delivery({"dest-1": 5, "dest-2": 5})
router = MagicMock()
cfg = _make_cfg([("dest-1", "a"), ("dest-2", "b")])
arrow_data = pa.table({"company": ["a"], "value": [1]})
router.split_and_count.return_value = ({"a": arrow_data}, 0)
with (
patch("viaduck.main.source.current_snapshot_id", return_value=10),
patch("viaduck.main.source.read_cdc", return_value=arrow_data),
):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1", "dest-2"],
{"a": "dest-1", "b": "dest-2"},
key_columns=[],
mode="append_only",
)
delivery.buffer.assert_called_once_with("dest-1", arrow_data, 10, epoch=0)
delivery.advance_position.assert_called_once_with("dest-2", 10, epoch=0)
assert delivery.maybe_flush.call_count == 2 # once per chunk + once at end of cycle
def test_poll_cycle_pauses_reads_at_watermark():
"""When the global buffer watermark is hit with all flushes in flight,
the cycle skips reads but still evaluates triggers."""
delivery = _make_delivery({"dest-1": 5})
delivery.should_pause_reads.return_value = True
router = MagicMock()
cfg = _make_cfg([("dest-1", "quacksworth")])
with patch("viaduck.main.source.current_snapshot_id", return_value=10):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1"],
{"quacksworth": "dest-1"},
key_columns=[],
mode="append_only",
)
delivery.read_plan.assert_not_called()
delivery.maybe_flush.assert_called_once()
def test_poll_cycle_mid_chunk_watermark_flushes_completed_chunks():
"""Watermark firing mid-loop only skips future chunks; completed chunks already flushed."""
delivery = _make_delivery({"dest-1": 0})
router = MagicMock()
cfg = _make_cfg([("dest-1", "quacksworth")])
cfg.poll.cdc_chunk_snapshots = 5 # chunks: 0→5 (completes), 5→10 (paused by watermark)
empty = pa.table({"company": pa.array([], type=pa.string())})
router.build_filter_expr.return_value = None
# outer check: False; inner chunk-1 check: False; inner chunk-2 check: True (pause)
delivery.should_pause_reads.side_effect = [False, False, True]
with (
patch("viaduck.main.source.current_snapshot_id", return_value=10),
patch("viaduck.main.source.read_cdc", return_value=empty),
):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1"],
{"quacksworth": "dest-1"},
key_columns=[],
mode="append_only",
)
# chunk 0→5 completed: cursor advanced and flushed
delivery.advance_position.assert_called_once_with("dest-1", 5, epoch=0)
# chunk 5→10 was never read (watermark break)
assert delivery.maybe_flush.call_count == 2 # once after chunk 0→5 + once at end of cycle
def test_poll_cycle_snapshot_at_zero():
"""Source snapshot 0 with positions at 0: nothing to read, triggers run."""
delivery = _make_delivery({"dest-1": 0})
router = MagicMock()
cfg = _make_cfg([("dest-1", "quacksworth")])
with patch("viaduck.main.source.current_snapshot_id", return_value=0):
_poll_cycle(
MagicMock(),
delivery,
MagicMock(),
router,
cfg,
["dest-1"],
{"quacksworth": "dest-1"},
key_columns=[],
mode="append_only",
)
router.build_filter_expr.assert_not_called()
delivery.maybe_flush.assert_called_once()
# ---------------------------------------------------------------------------
# _resolve_preimages
# ---------------------------------------------------------------------------
def _cdc_table(rows, routing_field="company"):
"""Build a pyarrow table with CDC metadata columns from list of dicts."""
if not rows:
return pa.table(
{
routing_field: pa.array([], type=pa.string()),
"value": pa.array([], type=pa.int64()),
"change_type": pa.array([], type=pa.string()),
"snapshot_id": pa.array([], type=pa.int64()),
"rowid": pa.array([], type=pa.int64()),
}
)
cols = {}
for key in rows[0]:
cols[key] = [r[key] for r in rows]
return pa.table(cols)
def test_resolve_preimages_same_tenant_drops():
"""Preimage with same routing value as postimage should be dropped."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "update_preimage", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 2, "change_type": "update_postimage", "snapshot_id": 1, "rowid": 100},
]
)
result = _resolve_preimages(batch, "company", ["value"])
assert result.num_rows == 1
assert result.column("change_type")[0].as_py() == "update_postimage"
def test_resolve_preimages_cross_tenant_converts_to_delete():
"""Different routing values: preimage becomes delete. Metric incremented."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "update_preimage", "snapshot_id": 1, "rowid": 100},
{"company": "beta", "value": 2, "change_type": "update_postimage", "snapshot_id": 1, "rowid": 100},
]
)
with patch("viaduck.main.metrics.cdc_routing_mutations_total") as mock_metric:
result = _resolve_preimages(batch, "company", ["value"])
assert result.num_rows == 2
types = result.column("change_type").to_pylist()
assert types[0] == "delete"
assert types[1] == "update_postimage"
mock_metric.inc.assert_called_once()
def test_resolve_preimages_orphaned_converts_to_delete():
"""Preimage with no matching postimage becomes delete. Metric incremented."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "update_preimage", "snapshot_id": 1, "rowid": 100},
{"company": "beta", "value": 2, "change_type": "insert", "snapshot_id": 1, "rowid": 200},
]
)
with patch("viaduck.main.metrics.cdc_orphaned_preimages_total") as mock_metric:
result = _resolve_preimages(batch, "company", ["value"])
assert result.num_rows == 2
types = result.column("change_type").to_pylist()
assert types[0] == "delete"
assert types[1] == "insert"
mock_metric.inc.assert_called_once()
def test_resolve_preimages_no_preimages():
"""Batch with no preimages should pass through unchanged."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "beta", "value": 2, "change_type": "delete", "snapshot_id": 1, "rowid": 200},
]
)
result = _resolve_preimages(batch, "company", ["value"])
assert result.num_rows == 2
assert result.column("change_type").to_pylist() == ["insert", "delete"]
def test_resolve_preimages_mixed_same_and_cross():
"""Mix of same-tenant and cross-tenant updates."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "update_preimage", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 2, "change_type": "update_postimage", "snapshot_id": 1, "rowid": 100},
{"company": "old", "value": 3, "change_type": "update_preimage", "snapshot_id": 1, "rowid": 200},
{"company": "new", "value": 4, "change_type": "update_postimage", "snapshot_id": 1, "rowid": 200},
]
)
result = _resolve_preimages(batch, "company", ["value"])
# Same-tenant (rowid=100): preimage dropped -> postimage only
# Cross-tenant (rowid=200): preimage -> delete, postimage kept
assert result.num_rows == 3
types = result.column("change_type").to_pylist()
assert types == ["update_postimage", "delete", "update_postimage"]
def test_resolve_preimages_preserves_non_update_rows():
"""Inserts and deletes pass through unmodified."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "beta", "value": 2, "change_type": "delete", "snapshot_id": 1, "rowid": 200},
]
)
result = _resolve_preimages(batch, "company", ["value"])
assert result.num_rows == 2
assert result.column("change_type").to_pylist() == ["insert", "delete"]
assert result.column("value").to_pylist() == [1, 2]
def test_resolve_preimages_validates_key_columns_exist():
"""Missing key column should raise RoutingError."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
]
)
with pytest.raises(RoutingError, match="Key column 'missing_col' not found"):
_resolve_preimages(batch, "company", ["missing_col"])
# ---------------------------------------------------------------------------
# _resolve_conflicts
# ---------------------------------------------------------------------------
def test_resolve_conflicts_insert_delete_keeps_tombstone():
"""Same rowid insert + delete: the insert drops, the delete SURVIVES
(tombstone). Against a destination that never saw the insert it is an
idempotent no-op; against one that did (commit/cursor-gap replay) it
is the only event that can remove the phantom. Both metrics fire."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 1, "change_type": "delete", "snapshot_id": 1, "rowid": 100},
]
)
with (
patch("viaduck.main.metrics.cdc_conflicts_resolved_total") as mock_conflicts,
patch("viaduck.main.metrics.cdc_tombstones_emitted_total") as mock_tombstones,
):
result = _resolve_conflicts(batch)
assert result.column("change_type").to_pylist() == ["delete"]
assert result.column("rowid").to_pylist() == [100]
mock_conflicts.inc.assert_called_once_with(1)
mock_tombstones.inc.assert_called_once_with(1)
def test_resolve_conflicts_update_delete_keeps_delete():
"""Same rowid postimage + delete: postimage dropped, delete kept."""
batch = _cdc_table(
[
{"company": "acme", "value": 2, "change_type": "update_postimage", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 1, "change_type": "delete", "snapshot_id": 1, "rowid": 100},
]
)
result = _resolve_conflicts(batch)
assert result.num_rows == 1
assert result.column("change_type")[0].as_py() == "delete"
def test_resolve_conflicts_no_conflicts():
"""No overlapping rowids: unchanged."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "beta", "value": 2, "change_type": "insert", "snapshot_id": 1, "rowid": 200},
]
)
result = _resolve_conflicts(batch)
assert result.num_rows == 2
def test_resolve_conflicts_mixed_pairs_and_plain():
"""A paired rowid keeps only its tombstone delete; unrelated rows pass."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 1, "change_type": "delete", "snapshot_id": 1, "rowid": 100},
{"company": "beta", "value": 2, "change_type": "insert", "snapshot_id": 1, "rowid": 200},
]
)
result = _resolve_conflicts(batch)
by_rowid = dict(zip(result.column("rowid").to_pylist(), result.column("change_type").to_pylist()))
assert by_rowid == {100: "delete", 200: "insert"}
def test_resolve_conflicts_empty_batch():
"""Empty batch should return empty."""
batch = _cdc_table([])
result = _resolve_conflicts(batch)
assert result.num_rows == 0
def test_resolve_conflicts_insert_update_delete_sequence():
"""Same rowid: insert + postimage + delete. Insert and postimage drop;
the delete survives as the tombstone (matches spec Phase2)."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 2, "change_type": "update_postimage", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 1, "change_type": "delete", "snapshot_id": 1, "rowid": 100},
]
)
result = _resolve_conflicts(batch)
assert result.column("change_type").to_pylist() == ["delete"]
def test_resolve_conflicts_duplicate_keys_last_wins():
"""Multiple inserts for same rowid: verify no crash."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 2, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
]
)
# No crash expected, both rows preserved (no delete to trigger cancellation)
result = _resolve_conflicts(batch)
assert result.num_rows == 2
def test_resolve_conflicts_same_key_different_rowid_no_cancel():
"""Same key_columns value but different rowid should NOT cancel."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 1, "change_type": "delete", "snapshot_id": 1, "rowid": 200},
]
)
result = _resolve_conflicts(batch)
# Different rowids, no cancellation
assert result.num_rows == 2
def test_resolve_conflicts_uses_rowid_not_just_key():
"""Explicit test that rowid is used for matching, not key column values."""
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 1, "change_type": "delete", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 300},
]
)
result = _resolve_conflicts(batch)
# rowid 100: insert drops, tombstone delete survives. rowid 300: insert preserved.
by_rowid = dict(zip(result.column("rowid").to_pylist(), result.column("change_type").to_pylist()))
assert by_rowid == {100: "delete", 300: "insert"}
def test_resolve_conflicts_insert_postimage_same_rowid_drops_insert():
"""Same rowid with insert + update_postimage: drop the insert, keep postimage.
Repro for the flaky CI failure in tests/integration::test_full_cdc_update_round_trip.
When the source's table_changes range covers an INSERT and a later same-rowid
UPDATE (because the upsert reused the rowid rather than delete+insert), Phase 1
drops the same-tenant preimage, leaving INSERT(rowid=R, value=old) and
UPDATE_POSTIMAGE(rowid=R, value=new) for the same key. Phase 3 _apply_changes
feeds both rows into a single tbl.upsert(join_cols=...) — which has undefined
ordering for duplicate join keys, so the older value can win non-deterministically.
Phase 2 must collapse this pair: the postimage represents the newer state.
"""
batch = _cdc_table(
[
{"company": "acme", "value": 10, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 999, "change_type": "update_postimage", "snapshot_id": 2, "rowid": 100},
]
)
result = _resolve_conflicts(batch)
assert result.num_rows == 1
assert result.column("change_type")[0].as_py() == "update_postimage"
assert result.column("value")[0].as_py() == 999
# ---------------------------------------------------------------------------
# _build_delete_filter
# ---------------------------------------------------------------------------
def test_build_delete_filter_single_key():
"""Single key column with multiple values produces IN expression."""
rows = pa.table(
{
"id": [1, 2, 3],
"change_type": ["delete", "delete", "delete"],
"snapshot_id": [1, 1, 1],
"rowid": [10, 20, 30],
}
)
sql = _build_delete_filter(rows, ["id"])
assert "IN" in sql
assert "1" in sql
assert "2" in sql
assert "3" in sql
def test_build_delete_filter_composite_key():
"""Composite key produces OR(AND(...), AND(...))."""
rows = pa.table(
{
"a": [1, 2],
"b": ["x", "y"],
"change_type": ["delete", "delete"],
"snapshot_id": [1, 1],
"rowid": [10, 20],
}
)
sql = _build_delete_filter(rows, ["a", "b"])
assert "OR" in sql or "AND" in sql
def test_build_delete_filter_single_row():
"""Single row produces simple equality."""
rows = pa.table(
{
"id": [42],
"change_type": ["delete"],
"snapshot_id": [1],
"rowid": [10],
}
)
sql = _build_delete_filter(rows, ["id"])
assert "42" in sql
def test_build_delete_filter_null_in_key():
"""NULL value in key should use IS NULL."""
rows = pa.table(
{
"id": pa.array([None, 1], type=pa.int64()),
"change_type": ["delete", "delete"],
"snapshot_id": [1, 1],
"rowid": [10, 20],
}
)
sql = _build_delete_filter(rows, ["id"])
assert "NULL" in sql.upper()
def test_build_delete_filter_all_null_composite_key():
"""All NULLs in composite key."""
rows = pa.table(
{
"a": pa.array([None], type=pa.int64()),
"b": pa.array([None], type=pa.string()),
"change_type": ["delete"],
"snapshot_id": [1],
"rowid": [10],
}
)
sql = _build_delete_filter(rows, ["a", "b"])
assert "NULL" in sql.upper()
def test_build_delete_filter_composite_key_partial_null_column():
"""Composite key where only one column has nulls — exercises col_has_nulls short-circuit."""
rows = pa.table(
{
"a": pa.array([None, 2], type=pa.int64()), # has nulls
"b": pa.array(["x", "y"], type=pa.string()), # no nulls
"change_type": ["delete", "delete"],
"snapshot_id": [1, 2],
"rowid": [10, 20],
}
)
sql = _build_delete_filter(rows, ["a", "b"])
# First row: a IS NULL AND b = 'x'
# Second row: a = 2 AND b = 'y'
assert "NULL" in sql.upper()
assert "2" in sql
assert "x" in sql
assert "y" in sql
def test_build_delete_filter_mixed_null_and_values():
"""Mix of NULL and non-NULL for single key column."""
rows = pa.table(
{
"id": pa.array([None, 5, None, 7], type=pa.int64()),
"change_type": ["delete"] * 4,
"snapshot_id": [1] * 4,
"rowid": [10, 20, 30, 40],
}
)
sql = _build_delete_filter(rows, ["id"])
assert "NULL" in sql.upper()
assert "IN" in sql or "5" in sql
def test_build_delete_filter_missing_key_column_raises():
"""Missing key column should raise RoutingError."""
rows = pa.table(
{
"id": [1],
"change_type": ["delete"],
"snapshot_id": [1],
"rowid": [10],
}
)
with pytest.raises(RoutingError, match="Key column 'missing' not found"):
_build_delete_filter(rows, ["missing"])
# ---------------------------------------------------------------------------
# _apply_changes
# ---------------------------------------------------------------------------
def _mock_catalog_and_table():
"""Create mock catalog with transaction context manager and table."""
catalog = MagicMock()
dest_table = MagicMock()
dest_table.identifier = "test_table"
txn = MagicMock()
txn_table = MagicMock()
# Mock upsert to return UpsertResult-like object
upsert_result = MagicMock()
upsert_result.rows_updated = 0
upsert_result.rows_inserted = 0
txn_table.upsert.return_value = upsert_result
txn.load_table.return_value = txn_table
catalog.begin_transaction.return_value.__enter__ = MagicMock(return_value=txn)
catalog.begin_transaction.return_value.__exit__ = MagicMock(return_value=False)
return catalog, dest_table, txn, txn_table
def test_apply_changes_inserts_only():
"""Only inserts: upsert called, no delete.
These _apply_changes tests key on "value" (unique per fixture row), not
"company" (constant): with a realistic key, duplicate-key rows collapse
via Winner(k) and the pass-through counts asserted here would change.
Same-key behavior is covered by the Winner(k) tests below."""
catalog, dest_table, txn, txn_table = _mock_catalog_and_table()
batch = _cdc_table(
[
{"company": "acme", "value": 1, "change_type": "insert", "snapshot_id": 1, "rowid": 100},
{"company": "acme", "value": 2, "change_type": "insert", "snapshot_id": 1, "rowid": 200},
]
)
counts = _apply_changes(catalog, dest_table, batch, ["value"])
assert counts["upserted"] == 2
assert counts["deleted"] == 0
txn_table.upsert.assert_called_once()