This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathtest_remote_function.py
More file actions
3232 lines (2706 loc) · 119 KB
/
test_remote_function.py
File metadata and controls
3232 lines (2706 loc) · 119 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 2023 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.
from datetime import datetime
import importlib.util
import inspect
import math # must keep this at top level to test udf referring global import
import os.path
import shutil
import tempfile
import textwrap
import warnings
import google.api_core.exceptions
from google.cloud import bigquery, functions_v2, storage
import pandas
import pytest
import test_utils.prefixer
import bigframes
import bigframes.dataframe
import bigframes.dtypes
import bigframes.exceptions
import bigframes.functions._utils as bff_utils
import bigframes.pandas as bpd
import bigframes.series
from bigframes.testing.utils import (
assert_pandas_df_equal,
cleanup_function_assets,
delete_cloud_function,
get_cloud_functions,
)
# NOTE: Keep this import at the top level to test global var behavior with
# remote functions
_team_pi = "Team Pi"
_team_euler = "Team Euler"
def make_uniq_udf(udf):
"""Transform a udf to another with same behavior but a unique name.
Use this to test remote functions with reuse=True, in which case parallel
instances of the same tests may evaluate same named cloud functions and BQ
remote functions, therefore interacting with each other and causing unwanted
failures. With this method one can transform a udf into another with the
same behavior but a different name which will remain unique for the
lifetime of one test instance.
"""
prefixer = test_utils.prefixer.Prefixer(udf.__name__, "")
udf_uniq_name = prefixer.create_prefix()
udf_file_name = f"{udf_uniq_name}.py"
# We are not using `tempfile.TemporaryDirectory()` because we want to keep
# the temp code around, otherwise `inspect.getsource()` complains.
tmpdir = tempfile.mkdtemp()
udf_file_path = os.path.join(tmpdir, udf_file_name)
with open(udf_file_path, "w") as f:
# TODO(shobs): Find a better way of modifying the udf, maybe regex?
source_key = f"def {udf.__name__}"
target_key = f"def {udf_uniq_name}"
source_code = textwrap.dedent(inspect.getsource(udf))
target_code = source_code.replace(source_key, target_key, 1)
f.write(target_code)
spec = importlib.util.spec_from_file_location(udf_file_name, udf_file_path)
assert (spec is not None) and (spec.loader is not None)
module = importlib.util.module_from_spec(spec)
# exec_module fills the module object with all the functions, classes, and
# variables defined in the module file.
spec.loader.exec_module(module)
udf_uniq = getattr(module, udf_uniq_name)
return udf_uniq, tmpdir
@pytest.fixture(scope="module")
def bq_cf_connection() -> str:
"""Pre-created BQ connection in the test project in US location, used to
invoke cloud function.
$ bq show --connection --location=us --project_id=PROJECT_ID bigframes-rf-conn
"""
return "bigframes-rf-conn"
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_binop(session, scalars_dfs, dataset_id, bq_cf_connection):
try:
def func(x, y):
return x * abs(y % 4)
remote_func = session.remote_function(
# Make sure that the input/output types can be used positionally.
# This avoids the worst of the breaking change from 1.x to 2.x.
[str, int],
str,
dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)(func)
scalars_df, scalars_pandas_df = scalars_dfs
scalars_df = scalars_df.dropna()
scalars_pandas_df = scalars_pandas_df.dropna()
bf_result = (
scalars_df["string_col"]
.combine(scalars_df["int64_col"], remote_func)
.to_pandas()
)
pd_result = scalars_pandas_df["string_col"].combine(
scalars_pandas_df["int64_col"], func
)
pandas.testing.assert_series_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
remote_func, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_binop_array_output(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
def func(x, y):
return [len(x), abs(y % 4)]
remote_func = session.remote_function(
# Make sure that the input/output types can be used positionally.
# This avoids the worst of the breaking change from 1.x to 2.x.
[str, int],
list[int],
dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)(func)
scalars_df, scalars_pandas_df = scalars_dfs
scalars_df = scalars_df.dropna()
scalars_pandas_df = scalars_pandas_df.dropna()
bf_result = (
scalars_df["string_col"]
.combine(scalars_df["int64_col"], remote_func)
.to_pandas()
)
pd_result = scalars_pandas_df["string_col"].combine(
scalars_pandas_df["int64_col"], func
)
pandas.testing.assert_series_equal(bf_result, pd_result, check_dtype=False)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
remote_func, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_decorator_with_bigframes_series(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
@session.remote_function(
# Make sure that the input/output types can be used positionally.
# This avoids the worst of the breaking change from 1.x to 2.x.
[int],
int,
dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)
def square(x):
return x * x
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_col"]
bf_int64_col_filter = bf_int64_col.notnull()
bf_int64_col_filtered = bf_int64_col[bf_int64_col_filter]
bf_result_col = bf_int64_col_filtered.apply(square)
bf_result = (
bf_int64_col_filtered.to_frame().assign(result=bf_result_col).to_pandas()
)
pd_int64_col = scalars_pandas_df["int64_col"]
pd_int64_col_filter = pd_int64_col.notnull()
pd_int64_col_filtered = pd_int64_col[pd_int64_col_filter]
pd_result_col = pd_int64_col_filtered.apply(lambda x: x * x)
# TODO(shobs): Figure why pandas .apply() changes the dtype, i.e.
# pd_int64_col_filtered.dtype is Int64Dtype()
# pd_int64_col_filtered.apply(lambda x: x * x).dtype is int64.
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.Int64Dtype())
pd_result = pd_int64_col_filtered.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(square, session.bqclient, session.cloudfunctionsclient)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_explicit_with_bigframes_series(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
def add_one(x):
return x + 1
remote_add_one = session.remote_function(
# Make sure that the input/output types can be used positionally.
# This avoids the worst of the breaking change from 1.x to 2.x.
[int],
int,
dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)(add_one)
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_col"]
bf_int64_col_filter = bf_int64_col.notnull()
bf_int64_col_filtered = bf_int64_col[bf_int64_col_filter]
bf_result_col = bf_int64_col_filtered.apply(remote_add_one)
bf_result = (
bf_int64_col_filtered.to_frame().assign(result=bf_result_col).to_pandas()
)
pd_int64_col = scalars_pandas_df["int64_col"]
pd_int64_col_filter = pd_int64_col.notnull()
pd_int64_col_filtered = pd_int64_col[pd_int64_col_filter]
pd_result_col = pd_int64_col_filtered.apply(add_one)
# TODO(shobs): Figure why pandas .apply() changes the dtype, e.g.
# pd_int64_col_filtered.dtype is Int64Dtype()
# pd_int64_col_filtered.apply(lambda x: x).dtype is int64.
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.Int64Dtype())
pd_result = pd_int64_col_filtered.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
remote_add_one, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.parametrize(
("input_types"),
[
pytest.param([int], id="list-of-int"),
pytest.param(int, id="int"),
],
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_input_types(session, scalars_dfs, input_types):
try:
def add_one(x):
return x + 1
remote_add_one = session.remote_function(
# Make sure that the input/output types can be used positionally.
# This avoids the worst of the breaking change from 1.x to 2.x.
input_types,
int,
reuse=False,
cloud_function_service_account="default",
)(add_one)
assert remote_add_one.input_dtypes == (bigframes.dtypes.INT_DTYPE,)
scalars_df, scalars_pandas_df = scalars_dfs
bf_result = scalars_df.int64_too.map(remote_add_one).to_pandas()
pd_result = scalars_pandas_df.int64_too.map(add_one)
pandas.testing.assert_series_equal(bf_result, pd_result, check_dtype=False)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
remote_add_one, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_explicit_dataset_not_created(
session,
scalars_dfs,
dataset_id_not_created,
bq_cf_connection,
):
try:
@session.remote_function(
# Make sure that the input/output types can be used positionally.
# This avoids the worst of the breaking change from 1.x to 2.x.
[int],
int,
dataset=dataset_id_not_created,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)
def square(x):
return x * x
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_col"]
bf_int64_col_filter = bf_int64_col.notnull()
bf_int64_col_filtered = bf_int64_col[bf_int64_col_filter]
bf_result_col = bf_int64_col_filtered.apply(square)
bf_result = (
bf_int64_col_filtered.to_frame().assign(result=bf_result_col).to_pandas()
)
pd_int64_col = scalars_pandas_df["int64_col"]
pd_int64_col_filter = pd_int64_col.notnull()
pd_int64_col_filtered = pd_int64_col[pd_int64_col_filter]
pd_result_col = pd_int64_col_filtered.apply(lambda x: x * x)
# TODO(shobs): Figure why pandas .apply() changes the dtype, i.e.
# pd_int64_col_filtered.dtype is Int64Dtype()
# pd_int64_col_filtered.apply(lambda x: x * x).dtype is int64.
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.Int64Dtype())
pd_result = pd_int64_col_filtered.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(square, session.bqclient, session.cloudfunctionsclient)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_udf_referring_outside_var(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
POSITIVE_SIGN = 1
NEGATIVE_SIGN = -1
NO_SIGN = 0
def sign(num):
if num > 0:
return POSITIVE_SIGN
elif num < 0:
return NEGATIVE_SIGN
return NO_SIGN
remote_sign = session.remote_function(
# Make sure that the input/output types can be used positionally.
# This avoids the worst of the breaking change from 1.x to 2.x.
[int],
int,
dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)(sign)
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_col"]
bf_int64_col_filter = bf_int64_col.notnull()
bf_int64_col_filtered = bf_int64_col[bf_int64_col_filter]
bf_result_col = bf_int64_col_filtered.apply(remote_sign)
bf_result = (
bf_int64_col_filtered.to_frame().assign(result=bf_result_col).to_pandas()
)
pd_int64_col = scalars_pandas_df["int64_col"]
pd_int64_col_filter = pd_int64_col.notnull()
pd_int64_col_filtered = pd_int64_col[pd_int64_col_filter]
pd_result_col = pd_int64_col_filtered.apply(sign)
# TODO(shobs): Figure why pandas .apply() changes the dtype, e.g.
# pd_int64_col_filtered.dtype is Int64Dtype()
# pd_int64_col_filtered.apply(lambda x: x).dtype is int64.
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.Int64Dtype())
pd_result = pd_int64_col_filtered.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
remote_sign, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_udf_referring_outside_import(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
import math as mymath
def circumference(radius):
return 2 * mymath.pi * radius
remote_circumference = session.remote_function(
# Make sure that the input/output types can be used positionally.
# This avoids the worst of the breaking change from 1.x to 2.x.
[float],
float,
dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)(circumference)
scalars_df, scalars_pandas_df = scalars_dfs
bf_float64_col = scalars_df["float64_col"]
bf_float64_col_filter = bf_float64_col.notnull()
bf_float64_col_filtered = bf_float64_col[bf_float64_col_filter]
bf_result_col = bf_float64_col_filtered.apply(remote_circumference)
bf_result = (
bf_float64_col_filtered.to_frame().assign(result=bf_result_col).to_pandas()
)
pd_float64_col = scalars_pandas_df["float64_col"]
pd_float64_col_filter = pd_float64_col.notnull()
pd_float64_col_filtered = pd_float64_col[pd_float64_col_filter]
pd_result_col = pd_float64_col_filtered.apply(circumference)
# TODO(shobs): Figure why pandas .apply() changes the dtype, e.g.
# pd_float64_col_filtered.dtype is Float64Dtype()
# pd_float64_col_filtered.apply(lambda x: x).dtype is float64.
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.Float64Dtype())
pd_result = pd_float64_col_filtered.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
remote_circumference, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_udf_referring_global_var_and_import(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
def find_team(num):
boundary = (math.pi + math.e) / 2
if num >= boundary:
return _team_euler
return _team_pi
remote_find_team = session.remote_function(
input_types=[float],
output_type=str,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)(find_team)
scalars_df, scalars_pandas_df = scalars_dfs
bf_float64_col = scalars_df["float64_col"]
bf_float64_col_filter = bf_float64_col.notnull()
bf_float64_col_filtered = bf_float64_col[bf_float64_col_filter]
bf_result_col = bf_float64_col_filtered.apply(remote_find_team)
bf_result = (
bf_float64_col_filtered.to_frame().assign(result=bf_result_col).to_pandas()
)
pd_float64_col = scalars_pandas_df["float64_col"]
pd_float64_col_filter = pd_float64_col.notnull()
pd_float64_col_filtered = pd_float64_col[pd_float64_col_filter]
pd_result_col = pd_float64_col_filtered.apply(find_team)
# TODO(shobs): Figure if the dtype mismatch is by design:
# bf_result.dtype: string[pyarrow]
# pd_result.dtype: dtype('O').
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.StringDtype(storage="pyarrow"))
pd_result = pd_float64_col_filtered.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
remote_find_team, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_restore_with_bigframes_series(
session,
scalars_dfs,
dataset_id,
bq_cf_connection,
):
try:
def add_one(x):
return x + 1
# Make a unique udf
add_one_uniq, add_one_uniq_dir = make_uniq_udf(add_one)
# Expected cloud function name for the unique udf
package_requirements = bff_utils.get_updated_package_requirements()
add_one_uniq_hash = bff_utils.get_hash(add_one_uniq, package_requirements)
add_one_uniq_cf_name = bff_utils.get_cloud_function_name(
add_one_uniq_hash, session.session_id
)
# There should be no cloud function yet for the unique udf
cloud_functions = list(
get_cloud_functions(
session.cloudfunctionsclient,
session.bqclient.project,
session.bqclient.location,
name=add_one_uniq_cf_name,
)
)
assert len(cloud_functions) == 0
# The first time both the cloud function and the bq remote function don't
# exist and would be created
remote_add_one = session.remote_function(
input_types=[int],
output_type=int,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
reuse=True,
cloud_function_service_account="default",
)(add_one_uniq)
# There should have been excactly one cloud function created at this point
cloud_functions = list(
get_cloud_functions(
session.cloudfunctionsclient,
session.bqclient.project,
session.bqclient.location,
name=add_one_uniq_cf_name,
)
)
assert len(cloud_functions) == 1
# We will test this twice
def inner_test():
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_col"]
bf_int64_col_filter = bf_int64_col.notnull()
bf_int64_col_filtered = bf_int64_col[bf_int64_col_filter]
bf_result_col = bf_int64_col_filtered.apply(remote_add_one)
bf_result = (
bf_int64_col_filtered.to_frame()
.assign(result=bf_result_col)
.to_pandas()
)
pd_int64_col = scalars_pandas_df["int64_col"]
pd_int64_col_filter = pd_int64_col.notnull()
pd_int64_col_filtered = pd_int64_col[pd_int64_col_filter]
pd_result_col = pd_int64_col_filtered.apply(add_one_uniq)
# TODO(shobs): Figure why pandas .apply() changes the dtype, i.e.
# pd_int64_col_filtered.dtype is Int64Dtype()
# pd_int64_col_filtered.apply(lambda x: x * x).dtype is int64.
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.Int64Dtype())
pd_result = pd_int64_col_filtered.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
# Test that the remote function works as expected
inner_test()
# Let's delete the cloud function while not touching the bq remote function
delete_operation = delete_cloud_function(
session.cloudfunctionsclient, cloud_functions[0].name
)
delete_operation.result()
assert delete_operation.done()
# There should be no cloud functions at this point for the uniq udf
cloud_functions = list(
get_cloud_functions(
session.cloudfunctionsclient,
session.bqclient.project,
session.bqclient.location,
name=add_one_uniq_cf_name,
)
)
assert len(cloud_functions) == 0
# The second time bigframes detects that the required cloud function doesn't
# exist even though the remote function exists, and goes ahead and recreates
# the cloud function
remote_add_one = session.remote_function(
input_types=[int],
output_type=int,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
reuse=True,
cloud_function_service_account="default",
)(add_one_uniq)
# There should be excactly one cloud function again
cloud_functions = list(
get_cloud_functions(
session.cloudfunctionsclient,
session.bqclient.project,
session.bqclient.location,
name=add_one_uniq_cf_name,
)
)
assert len(cloud_functions) == 1
# Test again after the cloud function is restored that the remote function
# works as expected
inner_test()
# clean up the temp code
shutil.rmtree(add_one_uniq_dir)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
remote_add_one, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_udf_mask_default_value(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
def is_odd(num):
flag = False
try:
flag = num % 2 == 1
except TypeError:
pass
return flag
is_odd_remote = session.remote_function(
input_types=[int],
output_type=bool,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)(is_odd)
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_col"]
bf_result_col = bf_int64_col.mask(is_odd_remote)
bf_result = bf_int64_col.to_frame().assign(result=bf_result_col).to_pandas()
pd_int64_col = scalars_pandas_df["int64_col"]
pd_result_col = pd_int64_col.mask(is_odd)
pd_result = pd_int64_col.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
is_odd_remote, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_udf_mask_custom_value(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
def is_odd(num):
flag = False
try:
flag = num % 2 == 1
except TypeError:
pass
return flag
is_odd_remote = session.remote_function(
input_types=[int],
output_type=bool,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)(is_odd)
scalars_df, scalars_pandas_df = scalars_dfs
# TODO(shobs): Revisit this test when NA handling of pandas' Series.mask is
# fixed https://github.com/pandas-dev/pandas/issues/52955,
# for now filter out the nulls and test the rest
bf_int64_col = scalars_df["int64_col"]
bf_result_col = bf_int64_col[bf_int64_col.notnull()].mask(is_odd_remote, -1)
bf_result = bf_int64_col.to_frame().assign(result=bf_result_col).to_pandas()
pd_int64_col = scalars_pandas_df["int64_col"]
pd_result_col = pd_int64_col[pd_int64_col.notnull()].mask(is_odd, -1)
pd_result = pd_int64_col.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
is_odd_remote, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_udf_lambda(session, scalars_dfs, dataset_id, bq_cf_connection):
try:
add_one_lambda = lambda x: x + 1 # noqa: E731
add_one_lambda_remote = session.remote_function(
input_types=[int],
output_type=int,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
cloud_function_service_account="default",
)(add_one_lambda)
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_col"]
bf_int64_col_filter = bf_int64_col.notnull()
bf_int64_col_filtered = bf_int64_col[bf_int64_col_filter]
bf_result_col = bf_int64_col_filtered.apply(add_one_lambda_remote)
bf_result = (
bf_int64_col_filtered.to_frame().assign(result=bf_result_col).to_pandas()
)
pd_int64_col = scalars_pandas_df["int64_col"]
pd_int64_col_filter = pd_int64_col.notnull()
pd_int64_col_filtered = pd_int64_col[pd_int64_col_filter]
pd_result_col = pd_int64_col_filtered.apply(add_one_lambda)
# TODO(shobs): Figure why pandas .apply() changes the dtype, i.e.
# pd_int64_col_filtered.dtype is Int64Dtype()
# pd_int64_col_filtered.apply(lambda x: x).dtype is int64.
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.Int64Dtype())
pd_result = pd_int64_col_filtered.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
add_one_lambda_remote, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_with_explicit_name(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
def square(x):
return x * x
prefixer = test_utils.prefixer.Prefixer(square.__name__, "")
rf_name = prefixer.create_prefix()
expected_remote_function = f"{dataset_id}.{rf_name}"
# Initially the expected BQ remote function should not exist
with pytest.raises(google.api_core.exceptions.NotFound):
session.bqclient.get_routine(expected_remote_function)
# Create the remote function with the name provided explicitly
square_remote = session.remote_function(
input_types=[int],
output_type=int,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
name=rf_name,
cloud_function_service_account="default",
)(square)
# The remote function should reflect the explicitly provided name
assert square_remote.bigframes_remote_function == expected_remote_function
assert square_remote.bigframes_bigquery_function == expected_remote_function
# Now the expected BQ remote function should exist
session.bqclient.get_routine(expected_remote_function)
# The behavior of the created remote function should be as expected
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_too"]
bf_result_col = bf_int64_col.apply(square_remote)
bf_result = bf_int64_col.to_frame().assign(result=bf_result_col).to_pandas()
pd_int64_col = scalars_pandas_df["int64_too"]
pd_result_col = pd_int64_col.apply(square)
# TODO(shobs): Figure why pandas .apply() changes the dtype, i.e.
# pd_int64_col.dtype is Int64Dtype()
# pd_int64_col.apply(square).dtype is int64.
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.Int64Dtype())
pd_result = pd_int64_col.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
square_remote, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_with_external_package_dependencies(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
# The return type hint in this function's signature has conflict. The
# `output_type` argument from remote_function decorator takes precedence
# and will be used instead.
def pd_np_foo(x) -> None:
import numpy as mynp
import pandas as mypd
return mypd.Series([x, mynp.sqrt(mynp.abs(x))]).sum()
with warnings.catch_warnings(record=True) as record:
# Create the remote function with the name provided explicitly
pd_np_foo_remote = session.remote_function(
input_types=[int],
output_type=float,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
reuse=False,
packages=["numpy", "pandas >= 2.0.0"],
cloud_function_service_account="default",
)(pd_np_foo)
input_type_warning = "Conflicting input types detected"
assert not any(input_type_warning in str(warning.message) for warning in record)
return_type_warning = "Conflicting return type detected"
assert any(return_type_warning in str(warning.message) for warning in record)
# The behavior of the created remote function should be as expected
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_too"]
bf_result_col = bf_int64_col.apply(pd_np_foo_remote)
bf_result = bf_int64_col.to_frame().assign(result=bf_result_col).to_pandas()
pd_int64_col = scalars_pandas_df["int64_too"]
pd_result_col = pd_int64_col.apply(pd_np_foo)
pd_result = pd_int64_col.to_frame().assign(result=pd_result_col)
# pandas result is non-nullable type float64, make it Float64 before
# comparing for the purpose of this test
pd_result.result = pd_result.result.astype(pandas.Float64Dtype())
assert_pandas_df_equal(bf_result, pd_result)
finally:
# clean up the gcp assets created for the remote function
cleanup_function_assets(
pd_np_foo_remote, session.bqclient, session.cloudfunctionsclient
)
@pytest.mark.flaky(retries=2, delay=120)
def test_remote_function_with_explicit_name_reuse(
session, scalars_dfs, dataset_id, bq_cf_connection
):
try:
dirs_to_cleanup = []
# Define a user code
def square(x):
return x * x
# Make it a unique udf
square_uniq, square_uniq_dir = make_uniq_udf(square)
dirs_to_cleanup.append(square_uniq_dir)
# Define a common routine which accepts a remote function and the
# corresponding user defined function and tests that bigframes bahavior
# on the former is in parity with the pandas behaviour on the latter
def test_internal(rf, udf):
# The behavior of the created remote function should be as expected
scalars_df, scalars_pandas_df = scalars_dfs
bf_int64_col = scalars_df["int64_too"]
bf_result_col = bf_int64_col.apply(rf)
bf_result = bf_int64_col.to_frame().assign(result=bf_result_col).to_pandas()
pd_int64_col = scalars_pandas_df["int64_too"]
pd_result_col = pd_int64_col.apply(udf)
# TODO(shobs): Figure why pandas .apply() changes the dtype, i.e.
# pd_int64_col.dtype is Int64Dtype()
# pd_int64_col.apply(square).dtype is int64.
# For this test let's force the pandas dtype to be same as bigframes' dtype.
pd_result_col = pd_result_col.astype(pandas.Int64Dtype())
pd_result = pd_int64_col.to_frame().assign(result=pd_result_col)
assert_pandas_df_equal(bf_result, pd_result)
# Create an explicit name for the remote function
prefixer = test_utils.prefixer.Prefixer("foo", "")
rf_name = prefixer.create_prefix()
expected_remote_function = f"{dataset_id}.{rf_name}"
# Initially the expected BQ remote function should not exist
with pytest.raises(google.api_core.exceptions.NotFound):
session.bqclient.get_routine(expected_remote_function)
# Create a new remote function with the name provided explicitly
square_remote1 = session.remote_function(
input_types=[int],
output_type=int,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
name=rf_name,
cloud_function_service_account="default",
)(square_uniq)
# The remote function should reflect the explicitly provided name
assert square_remote1.bigframes_remote_function == expected_remote_function
assert square_remote1.bigframes_bigquery_function == expected_remote_function
# Now the expected BQ remote function should exist
routine = session.bqclient.get_routine(expected_remote_function)
square_remote1_created = routine.created
square_remote1_cf_updated = session.cloudfunctionsclient.get_function(
name=square_remote1.bigframes_cloud_function
).update_time
# Test pandas parity with square udf
test_internal(square_remote1, square)
# Now Create another remote function with the same name provided
# explicitly. Since reuse is True by default, the previously created
# remote function with the same name will be reused.
square_remote2 = session.remote_function(
input_types=[int],
output_type=int,
dataset=dataset_id,
bigquery_connection=bq_cf_connection,
name=rf_name,
cloud_function_service_account="default",
)(square_uniq)
# The new remote function should still reflect the explicitly provided name
assert square_remote2.bigframes_remote_function == expected_remote_function
assert square_remote2.bigframes_bigquery_function == expected_remote_function
# The expected BQ remote function should still exist
routine = session.bqclient.get_routine(expected_remote_function)
square_remote2_created = routine.created
square_remote2_cf_updated = session.cloudfunctionsclient.get_function(
name=square_remote2.bigframes_cloud_function
).update_time
# The new remote function should reflect that the previous BQ remote
# function and the cloud function were reused instead of creating anew
assert square_remote2_created == square_remote1_created
assert (
square_remote2.bigframes_cloud_function
== square_remote1.bigframes_cloud_function
)
assert square_remote2_cf_updated == square_remote1_cf_updated
# Test again that the new remote function is actually same as the
# previous remote function
test_internal(square_remote2, square)