-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathtest_shared_pipeline.py
More file actions
934 lines (827 loc) · 32.9 KB
/
test_shared_pipeline.py
File metadata and controls
934 lines (827 loc) · 32.9 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
import io
import json
import os
import pathlib
import tempfile
import time
import unittest
import zipfile
import gzip
import pandas as pd
from feldera import Pipeline
from feldera.enums import CompletionTokenStatus, PipelineFieldSelector, PipelineStatus
from feldera.rest.errors import FelderaAPIError
from feldera.runtime_config import RuntimeConfig
from tests import TEST_CLIENT, enterprise_only
from tests.shared_test_pipeline import SharedTestPipeline
from tests.platform.helper import http_request, API_PREFIX
from feldera.testutils import (
FELDERA_TEST_NUM_WORKERS,
FELDERA_TEST_NUM_HOSTS,
)
from .helper import wait_for_condition
class TestPipeline(SharedTestPipeline):
result = None
def test_create_pipeline(self):
"""
CREATE TABLE tbl(id INT) WITH ('materialized' = 'true', 'connectors' = '[{
"name": "d1",
"paused": true,
"transport": {
"name": "datagen",
"config": {
"plan": [{
"limit": 10,
"rate": 1
}]
}
}
}]');
CREATE MATERIALIZED VIEW v0 AS SELECT * FROM tbl;
CREATE MATERIALIZED VIEW "V0" AS SELECT * FROM tbl WHERE id % 2 <> 0;
CREATE MATERIALIZED VIEW "DATE" AS SELECT * FROM tbl WHERE id % 2 = 0;
"""
pass
def __test_push_to_pipeline(self, data, format, array):
self.pipeline.start()
TEST_CLIENT.push_to_pipeline(
pipeline_name=self.pipeline.name,
table_name="tbl",
format=format,
array=array,
data=data,
)
def test_push_to_pipeline_json(self):
data = [
{"id": 1},
{"id": 2},
{"id": 3},
]
self.__test_push_to_pipeline(data, format="json", array=True)
def test_push_to_pipeline_csv0(self):
data = "1\n2\n"
self.__test_push_to_pipeline(data, format="csv", array=False)
def test_list_pipelines(self):
pipelines = TEST_CLIENT.pipelines()
assert len(pipelines) > 0
assert self.pipeline.name in [p.name for p in pipelines]
def test_get_pipeline(self):
p = TEST_CLIENT.get_pipeline(self.pipeline.name, PipelineFieldSelector.ALL)
assert self.pipeline.name == p.name
def test_get_pipeline_config(self):
config = TEST_CLIENT.get_runtime_config(self.pipeline.name)
assert config is not None
def test_get_pipeline_stats(self):
self.pipeline.start()
stats = TEST_CLIENT.get_pipeline_stats(self.pipeline.name)
assert stats is not None
assert stats.get("global_metrics") is not None
assert stats.get("inputs") is not None
assert stats.get("outputs") is not None
def test_case_sensitive_views_listen(self):
self.pipeline.start_paused()
all_stream = self.pipeline.listen("v0")
odd_stream = self.pipeline.listen("V0")
even_stream = self.pipeline.listen("DATE")
self.pipeline.resume()
self.pipeline.input_json("tbl", [{"id": i} for i in range(10)])
self.pipeline.wait_for_idle()
all = all_stream.to_dict()
odd = odd_stream.to_dict()
even = even_stream.to_dict()
expected_all = list(self.pipeline.query("select * from v0"))
expected_odd = list(self.pipeline.query('select * from "V0"'))
expected_even = list(self.pipeline.query('select * from "DATE"'))
def extract_ids(x):
return sorted(i["id"] for i in x)
assert extract_ids(all) == extract_ids(expected_all)
assert extract_ids(odd) == extract_ids(expected_odd)
assert extract_ids(even) == extract_ids(expected_even)
def test_adhoc_query_text(self):
data = "1\n2\n"
self.pipeline.start()
TEST_CLIENT.push_to_pipeline(self.pipeline.name, "tbl", "csv", data)
resp = TEST_CLIENT.query_as_text(
self.pipeline.name, "SELECT * FROM tbl ORDER BY id"
)
expected = [
"""+----+
| id |
+----+
| 1 |
| 2 |
+----+"""
]
got = "\n".join(resp)
assert got in expected
def test_adhoc_query_hash(self):
data = "1\n2\n"
self.pipeline.start()
TEST_CLIENT.push_to_pipeline(self.pipeline.name, "tbl", "csv", data)
resp = TEST_CLIENT.query_as_hash(
self.pipeline.name, "SELECT * FROM tbl ORDER BY id"
)
assert (
resp == "0B021466CA428474EF16F899D0F841D7338C168C063DA5DB43666D1AB3081558"
)
def test_adhoc_query_parquet(self):
data = "1\n2\n"
self.pipeline.start()
TEST_CLIENT.push_to_pipeline(self.pipeline.name, "tbl", "csv", data)
file = self.pipeline.name.split("-")[0]
TEST_CLIENT.query_as_parquet(self.pipeline.name, "SELECT * FROM tbl", file)
path = pathlib.Path(file + ".parquet")
assert path.stat().st_size > 0
os.remove(path)
def test_adhoc_query_json(self):
data = "1\n2\n"
self.pipeline.start()
TEST_CLIENT.push_to_pipeline(self.pipeline.name, "tbl", "csv", data)
resp = TEST_CLIENT.query_as_json(self.pipeline.name, "SELECT * FROM tbl")
expected = [{"id": 2}, {"id": 1}]
got = list(resp)
self.assertCountEqual(got, expected)
def test_local(self):
"""
CREATE TABLE students (
name STRING,
id INT
);
CREATE TABLE grades (
student_id INT,
science INT,
maths INT,
art INT
);
CREATE MATERIALIZED VIEW average_scores AS
SELECT name, ((science + maths + art) / 3) as average
FROM students JOIN grades on id = student_id
ORDER BY average DESC;
"""
df_students = pd.read_csv("tests/assets/students.csv")
df_grades = pd.read_csv("tests/assets/grades.csv")
self.pipeline.start_paused()
out = self.pipeline.listen("average_scores")
self.pipeline.resume()
self.pipeline.input_pandas("students", df_students)
self.pipeline.input_pandas("grades", df_grades)
self.pipeline.wait_for_idle()
df = out.to_pandas()
assert df.shape[0] == 100
self.pipeline.stop(force=True)
def test_pipeline_get(self):
df_students = pd.read_csv("tests/assets/students.csv")
df_grades = pd.read_csv("tests/assets/grades.csv")
self.pipeline.start_paused()
out = self.pipeline.listen("average_scores")
self.pipeline.resume()
self.pipeline.input_pandas("students", df_students)
self.pipeline.input_pandas("grades", df_grades)
self.pipeline.wait_for_idle()
df = out.to_pandas()
assert df.shape[0] == 100
self.pipeline.stop(force=True)
def test_local_listen_after_start(self):
df_students = pd.read_csv("tests/assets/students.csv")
df_grades = pd.read_csv("tests/assets/grades.csv")
self.pipeline.start()
out = self.pipeline.listen("average_scores")
self.pipeline.input_pandas("students", df_students)
self.pipeline.input_pandas("grades", df_grades)
self.pipeline.wait_for_idle()
df = out.to_pandas()
assert df.shape[0] == 100
self.pipeline.stop(force=True)
def test_foreach_chunk(self):
def callback(df: pd.DataFrame, seq_no: int):
print(f"\nSeq No: {seq_no}, DF size: {df.shape[0]}\n")
df_students = pd.read_csv("tests/assets/students.csv")
df_grades = pd.read_csv("tests/assets/grades.csv")
self.pipeline.start_paused()
self.pipeline.foreach_chunk("average_scores", callback)
self.pipeline.resume()
self.pipeline.input_pandas("students", df_students)
self.pipeline.input_pandas("grades", df_grades)
self.pipeline.wait_for_idle()
self.pipeline.stop(force=True)
def test_df_without_columns(self):
df = pd.DataFrame([(1, "a"), (2, "b"), (3, "c")])
self.pipeline.start()
with self.assertRaises(ValueError):
self.pipeline.input_pandas("students", df)
self.pipeline.stop(force=True)
def test_variant(self):
"""
-- Ingest JSON as string; output it as VARIANT.
CREATE TABLE json_table (json VARCHAR) with ('materialized' = 'true');
CREATE MATERIALIZED VIEW json_view AS SELECT PARSE_JSON(json) AS json FROM json_table;
CREATE MATERIALIZED VIEW json_string_view AS SELECT TO_JSON(json) AS json FROM json_view;
CREATE MATERIALIZED VIEW average_view AS SELECT
CAST(json['name'] AS VARCHAR) as name,
((CAST(json['scores'][1] AS DECIMAL(8, 2)) + CAST(json['scores'][2] AS DECIMAL(8, 2))) / 2) as average
FROM json_view;
-- Ingest JSON as variant; extract strongly typed columns from it.
CREATE TABLE variant_table(val VARIANT) with ('materialized' = 'true');
CREATE MATERIALIZED VIEW typed_view AS SELECT
CAST(val['name'] AS VARCHAR) as name,
CAST(val['scores'] AS DECIMAL ARRAY) as scores
FROM variant_table;
"""
from decimal import Decimal
# Input as JSON strings
input_strings = [
{"json": '{"name":"Bob","scores":[8,10]}'},
{"json": '{"name":"Dunce","scores":[3,4]}'},
{"json": '{"name":"John","scores":[9,10]}'},
]
# Input as VARIANT
input_json = [
{"val": {"name": "Bob", "scores": [8, 10]}},
{"val": {"name": "Dunce", "scores": [3, 4]}},
{"val": {"name": "John", "scores": [9, 10]}},
]
# Expected outputs
expected_strings = [{**j, "insert_delete": 1} for j in input_strings]
expected_average = [
{"name": "Bob", "average": Decimal(9)},
{"name": "Dunce", "average": Decimal(3.5)},
{"name": "John", "average": Decimal(9.5)},
]
for datum in expected_average:
datum["insert_delete"] = 1 # Add insert_delete marker
expected_typed = [
{"name": "Bob", "scores": [8, 10]},
{"name": "Dunce", "scores": [3, 4]},
{"name": "John", "scores": [9, 10]},
]
for datum in expected_typed:
datum["insert_delete"] = 1
expected_variant = [
{"json": {"name": "Bob", "scores": [8, 10]}, "insert_delete": 1},
{"json": {"name": "Dunce", "scores": [3, 4]}, "insert_delete": 1},
{"json": {"name": "John", "scores": [9, 10]}, "insert_delete": 1},
]
# Set up listeners for all output views
self.pipeline.start_paused()
variant_out = self.pipeline.listen("json_view")
json_out = self.pipeline.listen("json_string_view")
average_out = self.pipeline.listen("average_view")
typed_out = self.pipeline.listen("typed_view")
self.pipeline.resume()
# Feed JSON as strings, receive output from `average_view` and `json_view`
self.pipeline.input_json("json_table", input_strings)
self.pipeline.wait_for_idle()
assert expected_average == average_out.to_dict()
assert expected_variant == variant_out.to_dict()
assert expected_strings == json_out.to_dict()
# Feed VARIANT, read strongly typed columns. Since output columns have the same
# shape as inputs, output and input should be identical.
self.pipeline.input_json("variant_table", input_json)
assert expected_typed == typed_out.to_dict()
self.pipeline.stop(True)
def test_issue2142(self):
self.pipeline.start_paused()
data = [{"id": None}, {"id": 1}]
out = self.pipeline.listen("v0")
self.pipeline.resume()
self.pipeline.input_json("tbl", data=data)
self.pipeline.wait_for_idle()
out_data = out.to_dict()
expected = []
for d in data:
row = dict(d)
row["insert_delete"] = 1
expected.append(row)
assert out_data == expected
self.pipeline.stop(force=True)
def test_failed_pipeline_stop(self):
"""
CREATE VIEW id_plus_one AS SELECT id + 1 FROM tbl;
"""
self.pipeline.start()
data = [{"id": 2147483647}]
self.pipeline.input_json("tbl", data, wait=False)
wait_for_condition(
"pipeline stops with deployment error after worker panic",
lambda: self.pipeline.status() == PipelineStatus.STOPPED
and len(self.pipeline.deployment_error()) > 0,
timeout_s=20.0,
poll_interval_s=1.0,
)
self.pipeline.stop(force=True)
def test_adhoc_execute(self):
self.pipeline.start()
self.pipeline.execute("INSERT INTO tbl VALUES (1), (2);")
self.pipeline.wait_for_idle()
resp = self.pipeline.query("SELECT * FROM tbl;")
got = list(resp)
expected = [{"id": 1}, {"id": 2}]
self.pipeline.stop(force=True)
self.assertCountEqual(got, expected)
def test_input_json0(self):
data = {"insert": {"id": 1}}
self.pipeline.start_paused()
out = self.pipeline.listen("v0")
self.pipeline.resume()
self.pipeline.input_json("tbl", data, update_format="insert_delete")
self.pipeline.wait_for_idle()
out_data = out.to_dict()
expected = [dict(data["insert"], insert_delete=1)]
assert out_data == expected
self.pipeline.stop(force=True)
def test_input_json1(self):
data = [{"id": 1}, {"id": 2}]
self.pipeline.start_paused()
out = self.pipeline.listen("v0")
self.pipeline.resume()
self.pipeline.input_json("tbl", data)
self.pipeline.wait_for_idle()
out_data = out.to_dict()
expected = [dict(row, insert_delete=1) for row in data]
assert out_data == expected
self.pipeline.stop(force=True)
@enterprise_only
def test_suspend(self):
data = {"insert": {"id": 1}}
self.pipeline.start_paused()
out = self.pipeline.listen("v0")
self.pipeline.resume()
self.pipeline.input_json("tbl", data, update_format="insert_delete")
self.pipeline.wait_for_idle()
out_data = out.to_dict()
expected = [dict(data["insert"], insert_delete=1)]
assert out_data == expected
self.pipeline.stop(force=False)
def test_timestamp_pandas(self):
"""
CREATE TABLE tbl_timestamp (
id INT,
name STRING,
birthdate TIMESTAMP
);
CREATE VIEW v_timestamp AS SELECT * FROM tbl_timestamp;
"""
df = pd.DataFrame(
{
"id": [1, 2, 3],
"name": ["a", "b", "c"],
"birthdate": [
pd.Timestamp.now(),
pd.Timestamp.now(),
pd.Timestamp.now(),
],
}
)
self.pipeline.start_paused()
out = self.pipeline.listen("v_timestamp")
self.pipeline.resume()
self.pipeline.input_pandas("tbl_timestamp", df)
self.pipeline.wait_for_idle()
df_out = out.to_pandas()
assert df_out.shape[0] == 3
self.pipeline.stop(force=True)
def test_pandas_binary(self):
"""
CREATE TABLE tbl_binary (c1 VARBINARY);
CREATE VIEW v_binary AS SELECT SUBSTRING(c1 FROM 2) as c1 FROM tbl_binary;
"""
data = [{"c1": [12, 34, 56]}]
expected_data = [{"c1": [34, 56], "insert_delete": 1}]
self.pipeline.start_paused()
out = self.pipeline.listen("v_binary")
self.pipeline.resume()
self.pipeline.input_json("tbl_binary", data=data)
self.pipeline.wait_for_idle()
got = out.to_dict()
assert expected_data == got
self.pipeline.stop(force=True)
def test_pandas_decimal(self):
"""
CREATE TABLE tbl_decimal (c1 DECIMAL(5, 2));
CREATE VIEW v_decimal AS SELECT c1 + 2.75::DECIMAL(5, 2) as c1 FROM tbl_decimal;
"""
from decimal import Decimal
data = [{"c1": 2.25}]
expected = [{"c1": Decimal("5.00"), "insert_delete": 1}]
self.pipeline.start_paused()
out = self.pipeline.listen("v_decimal")
self.pipeline.resume()
self.pipeline.input_json("tbl_decimal", data=data)
self.pipeline.wait_for_idle()
got = out.to_dict()
assert expected == got
self.pipeline.stop(force=True)
def test_pandas_array(self):
"""
CREATE TABLE tbl_array (c1 INT ARRAY);
CREATE VIEW v_array AS SELECT c1 FROM tbl_array;
"""
data = [{"c1": [1, 2, 3]}]
self.pipeline.start_paused()
out = self.pipeline.listen("v_array")
self.pipeline.resume()
self.pipeline.input_json("tbl_array", data=data)
self.pipeline.wait_for_idle()
got = out.to_dict()
expected = [{"c1": [1, 2, 3], "insert_delete": 1}]
assert got == expected
self.pipeline.stop(force=True)
def test_pandas_struct(self):
"""
CREATE TYPE s_struct AS (
f1 INT,
f2 STRING
);
CREATE TABLE tbl_struct (c1 s_struct);
CREATE VIEW v_struct AS SELECT c1 FROM tbl_struct;
"""
data = [{"c1": {"f1": 1, "f2": "a"}}]
self.pipeline.start_paused()
out = self.pipeline.listen("v_struct")
self.pipeline.resume()
self.pipeline.input_json("tbl_struct", data)
self.pipeline.wait_for_idle()
got = out.to_dict()
expected = [{"c1": {"f1": 1, "f2": "a"}, "insert_delete": 1}]
assert got == expected
self.pipeline.stop(force=True)
def test_pandas_date_time_timestamp(self):
"""
CREATE TABLE tbl_datetime (c1 DATE, c2 TIME, c3 TIMESTAMP);
CREATE VIEW v_datetime AS SELECT c1, c2, c3 FROM tbl_datetime;
"""
from pandas import Timedelta, Timestamp
data = [{"c1": "2022-01-01", "c2": "12:00:00", "c3": "2022-01-01 12:00:00"}]
expected = [
{
"c1": Timestamp("2022-01-01 00:00:00"),
"c2": Timedelta("0 days 12:00:00"),
"c3": Timestamp("2022-01-01 12:00:00"),
"insert_delete": 1,
}
]
self.pipeline.start_paused()
out = self.pipeline.listen("v_datetime")
self.pipeline.resume()
self.pipeline.input_json("tbl_datetime", data)
self.pipeline.wait_for_idle()
got = out.to_dict()
assert expected == got
self.pipeline.stop(force=True)
def test_pandas_simple(self):
"""
CREATE TABLE tbl_simple (
c0 BOOLEAN, c1 TINYINT, c2 SMALLINT, c3 INT, c4 BIGINT, c5 REAL, c6 DOUBLE, c7 VARCHAR, c8 CHAR
);
CREATE VIEW v_simple AS SELECT * FROM tbl_simple;
"""
data = [
{
"c0": True,
"c1": 1,
"c2": 2,
"c3": 3,
"c4": 4,
"c5": 5.0,
"c6": 6.0,
"c7": "seven",
"c8": "c",
}
]
self.pipeline.start_paused()
out = self.pipeline.listen("v_simple")
self.pipeline.resume()
self.pipeline.input_json("tbl_simple", data)
self.pipeline.wait_for_idle()
got = out.to_dict()
expected = []
for d in data:
row = dict(d)
row["insert_delete"] = 1
expected.append(row)
assert got == expected
self.pipeline.stop(force=True)
def test_pandas_map(self):
"""
CREATE TABLE tbl_map (c1 MAP<STRING, INT>);
CREATE VIEW v_map AS SELECT c1 FROM tbl_map;
"""
data = [{"c1": {"a": 1, "b": 2}}]
expected = [{"c1": {"a": 1, "b": 2}, "insert_delete": 1}]
self.pipeline.start_paused()
out = self.pipeline.listen("v_map")
self.pipeline.resume()
self.pipeline.input_json("tbl_map", data)
self.pipeline.wait_for_idle()
got = out.to_dict()
assert expected == got
self.pipeline.stop(force=True)
# Second round: single dict
self.pipeline.start_paused()
out = self.pipeline.listen("v_map")
self.pipeline.resume()
self.pipeline.input_json("tbl_map", {"c1": {"a": 1, "b": 2}})
self.pipeline.wait_for_idle()
got = out.to_dict()
assert expected == got
self.pipeline.stop(force=True)
def test_uuid(self):
"""
CREATE TABLE tbl_uuid(c0 UUID);
CREATE MATERIALIZED VIEW v_uuid AS SELECT c0 FROM tbl_uuid;
"""
import uuid
data = [{"c0": uuid.uuid4()}]
self.pipeline.start_paused()
out = self.pipeline.listen("v_uuid")
self.pipeline.resume()
self.pipeline.input_json("tbl_uuid", data)
self.pipeline.wait_for_idle()
got = out.to_dict()
# Compare only the UUID values
got_uuids = sorted([row["c0"] for row in got])
expected_uuids = sorted([row["c0"] for row in data])
assert got_uuids == expected_uuids
self.pipeline.stop(force=True)
def test_issue3754(self):
"""
CREATE TABLE tbl_map_issue3754(m_var MAP<VARCHAR, VARCHAR>);
CREATE MATERIALIZED VIEW v_map_issue3754 AS SELECT * FROM tbl_map_issue3754;
"""
self.pipeline.start()
with self.assertRaises(ValueError):
data = {"insert": {"m_var": {None: 1}}}
TEST_CLIENT.push_to_pipeline(
self.pipeline.name, "tbl_map_issue3754", "insert_delete", [data]
)
with self.assertRaises(ValueError):
data = {"delete": {"m_var": {None: 1}}}
TEST_CLIENT.push_to_pipeline(
self.pipeline.name, "tbl_map_issue3754", "insert_delete", [data]
)
with self.assertRaises(ValueError):
data = {"m_var": {None: 1}}
TEST_CLIENT.push_to_pipeline(
self.pipeline.name, "tbl_map_issue3754", "raw", [data]
)
with self.assertRaises(ValueError):
data = {"m_var": {None: 1}}
self.pipeline.input_json("tbl_map_issue3754", [data])
self.pipeline.stop(force=True)
def test_pipeline_resource_config(self):
from feldera.runtime_config import Resources, RuntimeConfig
config = {
"cpu_cores_max": 3,
"cpu_cores_min": 2,
"memory_mb_max": 500,
"memory_mb_min": 300,
"storage_mb_max": None,
"storage_class": None,
"namespace": None,
"service_account_name": None,
}
resources = Resources(config)
self.pipeline.set_runtime_config(
RuntimeConfig(
workers=FELDERA_TEST_NUM_WORKERS,
hosts=FELDERA_TEST_NUM_HOSTS,
resources=resources,
)
)
self.pipeline.start()
got = TEST_CLIENT.get_pipeline(
self.pipeline.name, PipelineFieldSelector.ALL
).runtime_config["resources"]
assert got == config
def test_support_bundle(self):
self.pipeline.start()
# Test getting support bundle as bytes (all collections enabled)
support_bundle_bytes = self.pipeline.support_bundle()
assert isinstance(support_bundle_bytes, bytes)
assert len(support_bundle_bytes) > 0
# Test that it's a valid ZIP file
try:
with zipfile.ZipFile(io.BytesIO(support_bundle_bytes), "r") as zip_file:
# Check that the ZIP file contains some files
file_list = zip_file.namelist()
assert any("circuit_profile.json" in item for item in file_list)
assert len(file_list) > 0
except zipfile.BadZipFile:
self.fail("Support bundle is not a valid ZIP file")
# Test saving to file
with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as temp_file:
temp_path = temp_file.name
try:
# Test saving with explicit path
self.pipeline.support_bundle(output_path=temp_path)
# Verify the file was created and is a valid ZIP
assert os.path.exists(temp_path)
with zipfile.ZipFile(temp_path, "r") as zip_file:
file_list = zip_file.namelist()
assert len(file_list) > 0
finally:
# Clean up
if os.path.exists(temp_path):
os.unlink(temp_path)
def test_support_bundle_with_selectors(self):
self.pipeline.start()
# Test with all collections disabled
support_bundle_bytes = self.pipeline.support_bundle(
circuit_profile=False,
heap_profile=False,
metrics=False,
logs=False,
stats=False,
pipeline_config=False,
system_config=False,
dataflow_graph=False,
)
assert isinstance(support_bundle_bytes, bytes)
assert len(support_bundle_bytes) > 0
# Verify it's a valid ZIP file
with zipfile.ZipFile(io.BytesIO(support_bundle_bytes), "r") as zip_file:
file_list = zip_file.namelist()
# Should only contain manifest.txt when all collections are disabled
assert len(file_list) == 1
assert "manifest.txt" in file_list
# Test with partial collections enabled
support_bundle_bytes = self.pipeline.support_bundle(
circuit_profile=True,
heap_profile=False,
metrics=True,
logs=False,
stats=True,
pipeline_config=False,
system_config=True,
)
assert isinstance(support_bundle_bytes, bytes)
assert len(support_bundle_bytes) > 0
# Verify it's a valid ZIP file
with zipfile.ZipFile(io.BytesIO(support_bundle_bytes), "r") as zip_file:
file_list = zip_file.namelist()
assert len(file_list) >= 2
assert "manifest.txt" in file_list
def test_url_encoding_ingress_egress_table_name(self):
"""
CREATE TABLE "t1#a1" (
c1 TEXT NOT NULL
) WITH ('materialized' = 'true');
"""
# Test egress with URL encoding - listen directly to table with special characters
self.pipeline.start_paused()
out = self.pipeline.listen("t1#a1")
# Test ingress with URL encoding
self.pipeline.resume()
data = [{"c1": "test_value"}]
# Test pushing data to table with special characters in name
TEST_CLIENT.push_to_pipeline(
pipeline_name=self.pipeline.name,
table_name="t1#a1",
format="json",
array=True,
data=data,
)
# Verify data was inserted correctly via query
result = list(self.pipeline.query('SELECT * FROM "t1#a1"'))
expected = [{"c1": "test_value"}]
self.assertCountEqual(result, expected)
# Insert another value to test egress
additional_data = [{"c1": "test_value_2"}]
TEST_CLIENT.push_to_pipeline(
pipeline_name=self.pipeline.name,
table_name="t1#a1",
format="json",
array=True,
data=additional_data,
)
# Verify egress data includes both values with insert_delete markers
egress_result = out.to_dict()
expected_egress = [
{"c1": "test_value", "insert_delete": 1},
{"c1": "test_value_2", "insert_delete": 1},
]
self.assertCountEqual(egress_result, expected_egress)
def test_listen_non_existent_view_paused(self):
self.pipeline.start_paused()
with self.assertRaises(ValueError):
self.pipeline.listen("FrodoBagginsInMordor")
def test_listen_non_existent_view_running(self):
self.pipeline.start()
with self.assertRaises(ValueError):
self.pipeline.listen("FrodoBagginsInMordor")
def test_pipelines(self):
assert self.pipeline.name in [p.name for p in Pipeline.all(TEST_CLIENT)]
# Give this test a different name than the one in platform/test_completion_tokens.
def test_completion_tokens_sdk(self):
self.pipeline.start()
self.pipeline.resume_connector("tbl", "d1")
token = self.pipeline.generate_completion_token("tbl", "d1")
self.pipeline.wait_for_token(token)
assert (
self.pipeline.completion_token_status(token)
== CompletionTokenStatus.COMPLETE
)
@enterprise_only
def test_samply_profile(self):
self.pipeline.set_runtime_config(
RuntimeConfig(dev_tweaks={"profiling": "samply"})
)
self.pipeline.start()
duration = 5
self.pipeline.start_samply_profile(duration)
time.sleep(duration)
timeout = time.monotonic() + 5
samply_profile_bytes = None
while time.monotonic() < timeout:
try:
samply_profile_bytes = self.pipeline.get_samply_profile()
if samply_profile_bytes:
break
time.sleep(0.1)
except FelderaAPIError as e:
if e.status_code == 500:
raise
assert isinstance(samply_profile_bytes, bytes)
assert len(samply_profile_bytes) > 0
# Verify it's a valid GZIP file
try:
with gzip.GzipFile(fileobj=io.BytesIO(samply_profile_bytes)) as gz:
# Try reading a small chunk to verify it's a valid gzip
chunk = gz.read(10)
assert len(chunk) > 0
except OSError:
self.fail("Samply profile is not a valid GZIP file")
# Verify /circuit_profile returns a valid ZIP via the streaming proxy
# (Transfer-Encoding: chunked, Content-Encoding: identity since ZIP
# is already compressed).
def test_circuit_profile_streaming(self):
self.pipeline.start()
resp = http_request(
"GET",
f"{API_PREFIX}/pipelines/{self.pipeline.name}/circuit_profile",
timeout=120,
)
assert resp.status_code == 200, (
f"Expected 200, got {resp.status_code}: {resp.text[:200]}"
)
# Response must be a valid ZIP archive
try:
with zipfile.ZipFile(io.BytesIO(resp.content), "r") as zf:
assert len(zf.namelist()) > 0, "ZIP is empty"
except zipfile.BadZipFile:
self.fail("circuit_profile did not return a valid ZIP")
# ZIP is already compressed; Content-Encoding should be identity
ce = resp.headers.get("content-encoding", "identity")
assert ce == "identity", (
f"Expected Content-Encoding: identity for ZIP, got {ce}"
)
# Confirm the streaming proxy is used (not the buffered path, which
# would set Content-Length instead of Transfer-Encoding: chunked).
assert resp.headers.get("transfer-encoding") == "chunked", (
"Expected Transfer-Encoding: chunked (streaming proxy)"
)
# Verify /circuit_json_profile streams valid JSON via the streaming proxy
# (Transfer-Encoding: chunked) and that the gzip compression round-trip
# is transparent (compressed and uncompressed responses yield the same data).
def test_circuit_json_profile_streaming(self):
self.pipeline.start()
# Request with gzip — the pipeline compresses and the streaming
# proxy passes the compressed bytes through. `requests`
# auto-decompresses, so resp.content is plain JSON.
resp_gzip = http_request(
"GET",
f"{API_PREFIX}/pipelines/{self.pipeline.name}/circuit_json_profile",
headers={"Accept-Encoding": "gzip"},
timeout=120,
)
assert resp_gzip.status_code == 200, (
f"Expected 200, got {resp_gzip.status_code}: {resp_gzip.text[:200]}"
)
try:
data_gzip = resp_gzip.json()
except json.JSONDecodeError:
self.fail("circuit_json_profile (gzip) did not return valid JSON")
assert isinstance(data_gzip, (dict, list))
# Confirm the streaming proxy is used (not the buffered path, which
# would set Content-Length instead of Transfer-Encoding: chunked).
assert resp_gzip.headers.get("transfer-encoding") == "chunked", (
"Expected Transfer-Encoding: chunked (streaming proxy)"
)
# Request without compression
resp_plain = http_request(
"GET",
f"{API_PREFIX}/pipelines/{self.pipeline.name}/circuit_json_profile",
headers={"Accept-Encoding": "identity"},
timeout=120,
)
assert resp_plain.status_code == 200
try:
data_plain = resp_plain.json()
except json.JSONDecodeError:
self.fail("circuit_json_profile (identity) did not return valid JSON")
# Both should return the same profile data
assert data_gzip == data_plain, (
"Compressed and uncompressed responses returned different data"
)
if __name__ == "__main__":
unittest.main()