forked from sirius-db/sirius
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsirius_extension.cpp
More file actions
1086 lines (951 loc) · 43 KB
/
sirius_extension.cpp
File metadata and controls
1086 lines (951 loc) · 43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2025, Sirius Contributors.
*
* 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.
*/
#include "duckdb/main/database.hpp"
#define DUCKDB_EXTENSION_MAIN
#include "config.hpp"
// Forward-declare CUDA profiler API functions (linked via libcudart).
extern "C" int cudaProfilerStart();
extern "C" int cudaProfilerStop();
#include "data/sirius_converter_registry.hpp"
#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp"
#include "duckdb/common/assert.hpp"
#include "duckdb/execution/column_binding_resolver.hpp"
#include "duckdb/function/table_function.hpp"
#include "duckdb/main/client_context.hpp"
#include "duckdb/main/config.hpp"
#include "duckdb/main/connection.hpp"
#include "duckdb/main/extension_callback_manager.hpp"
#include "duckdb/main/prepared_statement_data.hpp"
#include "duckdb/main/query_result.hpp"
#include "duckdb/main/relation.hpp"
#include "duckdb/optimizer/optimizer.hpp"
#include "duckdb/parser/parsed_data/create_table_function_info.hpp"
#include "duckdb/parser/parser.hpp"
#include "duckdb/planner/planner.hpp"
#include "planner/sirius_physical_plan_generator.hpp"
// #include "from_substrait.hpp"
#include "gpu_buffer_manager.hpp"
#ifdef SIRIUS_ENABLE_LEGACY
#include "gpu_context.hpp"
#include "gpu_physical_plan_generator.hpp"
#endif
#include "duckdb/main/connection_manager.hpp"
#include "log/logging.hpp"
#include "sirius_context.hpp"
#include "sirius_extension.hpp"
#include "sirius_interface.hpp"
#include "util/segfault_backtrace.hpp"
#include <cstdlib>
namespace duckdb {
const std::string PINNED_MEMORY_PARAM_KEY = "pinned_memory_size";
bool SiriusExtension::buffer_is_initialized = false;
struct SiriusTableFunctionData : public TableFunctionData {
SiriusTableFunctionData() = default;
shared_ptr<::sirius::sirius_prepared_statement_data> gpu_prepared;
unique_ptr<QueryResult> res;
unique_ptr<Connection> conn;
unique_ptr<::sirius::sirius_interface> sirius_iface;
string query;
bool enable_optimizer;
bool finished = false;
bool plan_error = false;
//! Original options from the connection
ClientConfig original_config;
set<OptimizerType> original_disabled_optimizers;
void PrepareConnection(ClientContext& context)
{
// First collect original options
original_config = context.config;
original_disabled_optimizers = DBConfig::GetConfig(context).options.disabled_optimizers;
// The user might want to disable the optimizer of the new connection
context.config.enable_optimizer = enable_optimizer;
// We want for sure to disable the internal compression optimizations.
// These are DuckDB specific, no other system implements these. Also,
// respect the user's settings if they chose to disable any specific optimizers.
//
// The InClauseRewriter optimization converts large `IN` clauses to a
// "mark join" against a `ColumnDataCollection`, which may not make
// sense in other systems and would complicate the conversion to Substrait.
set<OptimizerType> disabled_optimizers =
DBConfig::GetConfig(context).options.disabled_optimizers;
disabled_optimizers.insert(OptimizerType::IN_CLAUSE);
disabled_optimizers.insert(OptimizerType::COMPRESSED_MATERIALIZATION);
// STATISTICS_PROPAGATION is now enabled: cpu_source_task handles the
// COLUMN_DATA_SCAN / EXPRESSION_GET / DUMMY_SCAN sources that this
// optimizer produces (e.g. folding count(*), MIN, MAX to constants).
#ifdef DEBUG
disabled_optimizers.insert(OptimizerType::COLUMN_LIFETIME);
#endif
// disabled_optimizers.insert(OptimizerType::MATERIALIZED_CTE);
// If error(varchar) gets implemented in substrait this can be removed
// context.config.scalar_subquery_error_on_multiple_rows = false;
DBConfig::GetConfig(context).options.disabled_optimizers = disabled_optimizers;
}
// Reset configuration
void CleanupConnection(ClientContext& context) const
{
DBConfig::GetConfig(context).options.disabled_optimizers = original_disabled_optimizers;
context.config = original_config;
}
unique_ptr<LogicalOperator> ExtractPlan(ClientContext& context)
{
PrepareConnection(context);
unique_ptr<LogicalOperator> plan;
try {
Parser parser(context.GetParserOptions());
parser.ParseQuery(query);
Planner planner(context);
planner.CreatePlan(std::move(parser.statements[0]));
D_ASSERT(planner.plan);
plan = std::move(planner.plan);
if (context.config.enable_optimizer) {
Optimizer optimizer(*planner.binder, context);
plan = optimizer.Optimize(std::move(plan));
}
// After optimization, refresh types before column binding resolution
// to ensure types are consistent (some optimizers may have set stale types)
plan->ResolveOperatorTypes();
ColumnBindingResolver resolver;
ColumnBindingResolver::Verify(*plan);
resolver.VisitOperator(*plan);
} catch (...) {
CleanupConnection(context);
throw;
}
CleanupConnection(context);
return plan;
}
};
#ifdef SIRIUS_ENABLE_LEGACY
struct GPUTableFunctionData : public TableFunctionData {
GPUTableFunctionData() = default;
shared_ptr<Relation> plan;
shared_ptr<GPUPreparedStatementData> gpu_prepared;
unique_ptr<QueryResult> res;
unique_ptr<Connection> conn;
unique_ptr<GPUContext> gpu_context;
string query;
bool enable_optimizer;
bool finished = false;
bool plan_error = false;
//! Original options from the connection
ClientConfig original_config;
set<OptimizerType> original_disabled_optimizers;
void PrepareConnection(ClientContext& context)
{
// First collect original options
original_config = context.config;
original_disabled_optimizers = DBConfig::GetConfig(context).options.disabled_optimizers;
// The user might want to disable the optimizer of the new connection
context.config.enable_optimizer = enable_optimizer;
// We want for sure to disable the internal compression optimizations.
// These are DuckDB specific, no other system implements these. Also,
// respect the user's settings if they chose to disable any specific optimizers.
//
// The InClauseRewriter optimization converts large `IN` clauses to a
// "mark join" against a `ColumnDataCollection`, which may not make
// sense in other systems and would complicate the conversion to Substrait.
set<OptimizerType> disabled_optimizers =
DBConfig::GetConfig(context).options.disabled_optimizers;
disabled_optimizers.insert(OptimizerType::IN_CLAUSE);
disabled_optimizers.insert(OptimizerType::COMPRESSED_MATERIALIZATION);
// STATISTICS_PROPAGATION folds ungrouped MIN/MAX aggregates into constant
// expressions using partition statistics, producing EXPRESSION_GET + DUMMY_SCAN.
// The GPU pipeline cannot schedule COLUMN_DATA_SCAN sources, so disable this
// to keep the query on the scan -> aggregate path where the GPU can execute it.
disabled_optimizers.insert(OptimizerType::STATISTICS_PROPAGATION);
#ifdef DEBUG
disabled_optimizers.insert(OptimizerType::COLUMN_LIFETIME);
#endif
// disabled_optimizers.insert(OptimizerType::MATERIALIZED_CTE);
// If error(varchar) gets implemented in substrait this can be removed
// context.config.scalar_subquery_error_on_multiple_rows = false;
DBConfig::GetConfig(context).options.disabled_optimizers = disabled_optimizers;
}
// Reset configuration
void CleanupConnection(ClientContext& context) const
{
DBConfig::GetConfig(context).options.disabled_optimizers = original_disabled_optimizers;
context.config = original_config;
}
unique_ptr<LogicalOperator> ExtractPlan(ClientContext& context)
{
PrepareConnection(context);
unique_ptr<LogicalOperator> plan;
try {
Parser parser(context.GetParserOptions());
parser.ParseQuery(query);
Planner planner(context);
planner.CreatePlan(std::move(parser.statements[0]));
D_ASSERT(planner.plan);
plan = std::move(planner.plan);
if (context.config.enable_optimizer) {
Optimizer optimizer(*planner.binder, context);
plan = optimizer.Optimize(std::move(plan));
}
// After optimization, refresh types before column binding resolution
// to ensure types are consistent (some optimizers may have set stale types)
plan->ResolveOperatorTypes();
ColumnBindingResolver resolver;
ColumnBindingResolver::Verify(*plan);
resolver.VisitOperator(*plan);
} catch (...) {
CleanupConnection(context);
throw;
}
CleanupConnection(context);
return plan;
}
};
void do_nothing_context(ClientContext*) {}
static unique_ptr<GPUPhysicalOperator> GPUGeneratePhysicalPlan(
ClientContext& context,
GPUContext& gpu_context,
unique_ptr<LogicalOperator>& logical_plan,
Connection& new_conn)
{
GPUPhysicalPlanGenerator physical_planner = GPUPhysicalPlanGenerator(context, gpu_context);
auto physical_plan = physical_planner.CreatePlan(std::move(logical_plan));
return physical_plan;
}
// The result of the GPUProcessingBind function is a unique pointer to a FunctionData object.
// This result of this function is used as an argument to the GPUProcessingFunction function (data_p
// argument), which is called to execute the table function.
unique_ptr<FunctionData> SiriusExtension::GPUProcessingBind(ClientContext& context,
TableFunctionBindInput& input,
vector<LogicalType>& return_types,
vector<string>& names)
{
auto result = make_uniq<GPUTableFunctionData>();
result->conn = make_uniq<Connection>(*context.db);
result->query = input.inputs[0].ToString();
result->enable_optimizer = true;
result->gpu_context = make_uniq<GPUContext>(context);
if (input.inputs[0].IsNull()) {
throw BinderException("gpu_processing cannot be called with a NULL parameter");
}
// Parse the query just to get the result type information and to create preparedstatmement data
auto statements = result->conn->context->ParseStatements(result->query);
Planner planner(context);
auto statement_type = statements[0]->type;
planner.CreatePlan(std::move(statements[0]));
D_ASSERT(planner.plan);
auto prepared = make_shared_ptr<PreparedStatementData>(statement_type);
prepared->names = planner.names;
prepared->types = planner.types;
prepared->value_map = std::move(planner.value_map);
// generate physical plan from the logical plan
unique_ptr<LogicalOperator> query_plan = result->ExtractPlan(context);
SIRIUS_LOG_DEBUG("Query plan:\n{}", query_plan->ToString());
if (buffer_is_initialized) {
try {
auto gpu_physical_plan =
GPUGeneratePhysicalPlan(context, *result->gpu_context, query_plan, *result->conn);
auto gpu_prepared = make_shared_ptr<GPUPreparedStatementData>(std::move(prepared),
std::move(gpu_physical_plan));
result->gpu_prepared = gpu_prepared;
} catch (std::exception& e) {
ErrorData error(e);
SIRIUS_LOG_ERROR("Error in GPUGeneratePhysicalPlan: {}", error.RawMessage());
result->plan_error = true;
}
} else {
result->gpu_prepared = nullptr;
}
for (auto& column : planner.names) {
names.emplace_back(column);
}
for (auto& type : planner.types) {
return_types.emplace_back(type);
}
return std::move(result);
}
void SiriusExtension::GPUProcessingFunction(ClientContext& context,
TableFunctionInput& data_p,
DataChunk& output)
{
auto& data = (GPUTableFunctionData&)*data_p.bind_data;
if (data.finished) { return; }
if (!data.res) {
auto start = std::chrono::high_resolution_clock::now();
if (!buffer_is_initialized) {
printf("\033[1;31m");
printf("GPUBufferManager not initialized, please call gpu_buffer_init first\n");
printf("\033[0m");
printf(
"=============================================\nError in GPUExecuteQuery, fallback to "
"DuckDB\n=============================================\n");
data.res = data.conn->Query(data.query);
} else if (data.plan_error) {
printf(
"=============================================\nError in GPUExecuteQuery, fallback to "
"DuckDB\n=============================================\n");
data.res = data.conn->Query(data.query);
} else {
data.res = data.gpu_context->GPUExecuteQuery(context, data.query, data.gpu_prepared, {});
if (data.res->HasError()) {
printf(
"=============================================\nError in GPUExecuteQuery, fallback to "
"DuckDB\n=============================================\n");
data.res = data.conn->Query(data.query);
}
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
SIRIUS_LOG_INFO("Execute query time: {:.2f} ms", duration.count() / 1000.0);
}
auto result_chunk = data.res->Fetch();
if (result_chunk == nullptr) {
output.SetCardinality(0);
return;
}
output.Reference(*result_chunk);
return;
}
static void RegisterLegacyGPUFunctions(CatalogTransaction& transaction, Catalog& catalog)
{
TableFunction gpu_processing("gpu_processing",
{LogicalType::VARCHAR},
SiriusExtension::GPUProcessingFunction,
SiriusExtension::GPUProcessingBind);
gpu_processing.named_parameters["enable_optimizer"] = LogicalType::BOOLEAN;
CreateTableFunctionInfo gpu_processing_info(gpu_processing);
catalog.CreateTableFunction(transaction, gpu_processing_info);
}
#endif // SIRIUS_ENABLE_LEGACY
static unique_ptr<sirius::op::sirius_physical_operator> SiriusGeneratePhysicalPlan(
ClientContext& context, unique_ptr<LogicalOperator>& logical_plan)
{
sirius::planner::sirius_physical_plan_generator physical_planner =
sirius::planner::sirius_physical_plan_generator(context);
auto physical_plan = physical_planner.create_plan(std::move(logical_plan));
return physical_plan;
}
// The result of the GPUExecutionBind function is a unique pointer to a FunctionData object.
// This result of this function is used as an argument to the GPUExecutionFunction function (data_p
// argument), which is called to execute the table function.
unique_ptr<FunctionData> SiriusExtension::GPUExecutionBind(ClientContext& context,
TableFunctionBindInput& input,
vector<LogicalType>& return_types,
vector<string>& names)
{
auto result = make_uniq<SiriusTableFunctionData>();
result->conn = make_uniq<Connection>(*context.db);
result->query = input.inputs[0].ToString();
result->enable_optimizer = true;
result->sirius_iface = make_uniq<::sirius::sirius_interface>(context);
if (input.inputs[0].IsNull()) {
throw BinderException("gpu_execution cannot be called with a NULL parameter");
}
// Parse the query just to get the result type information and to create preparedstatmement data
Parser parser(context.GetParserOptions());
parser.ParseQuery(result->query);
Planner planner(context);
auto statement_type = parser.statements[0]->type;
planner.CreatePlan(std::move(parser.statements[0]));
D_ASSERT(planner.plan);
auto prepared = make_shared_ptr<PreparedStatementData>(statement_type);
prepared->names = planner.names;
prepared->types = planner.types;
prepared->value_map = std::move(planner.value_map);
// generate physical plan from the logical plan
unique_ptr<LogicalOperator> query_plan = result->ExtractPlan(context);
SIRIUS_LOG_DEBUG("Query plan:\n{}", query_plan->ToString());
try {
auto sirius_physical_plan = SiriusGeneratePhysicalPlan(context, query_plan);
SIRIUS_LOG_DEBUG("Done generating sirius physical plan");
auto gpu_prepared = make_shared_ptr<::sirius::sirius_prepared_statement_data>(
std::move(prepared), std::move(sirius_physical_plan));
result->gpu_prepared = gpu_prepared;
} catch (std::exception& e) {
ErrorData error(e);
SIRIUS_LOG_ERROR("Error in SiriusGeneratePhysicalPlan: {}", error.RawMessage());
if (Config::ENABLE_DUCKDB_FALLBACK) {
result->plan_error = true;
} else {
throw std::runtime_error("Error in SiriusGeneratePhysicalPlan: " + error.RawMessage());
return nullptr;
}
}
for (auto& column : planner.names) {
names.emplace_back(column);
}
for (auto& type : planner.types) {
return_types.emplace_back(type);
}
return std::move(result);
}
void SiriusExtension::GPUExecutionFunction(ClientContext& context,
TableFunctionInput& data_p,
DataChunk& output)
{
auto& data = (SiriusTableFunctionData&)*data_p.bind_data;
if (data.finished) { return; }
if (!data.res) {
auto start = std::chrono::high_resolution_clock::now();
if (data.plan_error) {
printf(
"=============================================\nError in SiriusExecuteQuery, fallback to "
"DuckDB\n=============================================\n");
data.res = data.conn->Query(data.query);
} else {
data.res =
data.sirius_iface->sirius_execute_query(context, data.query, data.gpu_prepared, {});
if (data.res->HasError()) {
if (Config::ENABLE_DUCKDB_FALLBACK) {
SIRIUS_LOG_ERROR("SiriusExecuteQuery error: {}", data.res->GetError());
printf(
"=============================================\nError in SiriusExecuteQuery, fallback "
"to DuckDB\n=============================================\n");
data.res = data.conn->Query(data.query);
} else {
throw std::runtime_error("SiriusExecuteQuery error: " + data.res->GetError());
return;
}
}
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
SIRIUS_LOG_INFO("Execute query time: {:.2f} ms", duration.count() / 1000.0);
}
auto result_chunk = data.res->Fetch();
if (result_chunk == nullptr) {
output.SetCardinality(0);
return;
}
output.Reference(*result_chunk);
return;
}
static unique_ptr<LogicalOperator> OptimizePlan(ClientContext& context,
Planner& planner,
Connection& new_conn)
{
unique_ptr<LogicalOperator> plan;
plan = std::move(planner.plan);
Optimizer optimizer(*planner.binder, context);
plan = optimizer.Optimize(std::move(plan));
SIRIUS_LOG_DEBUG("Query plan:\n{}", plan->ToString());
ColumnBindingResolver resolver;
resolver.Verify(*plan);
resolver.VisitOperator(*plan);
plan->ResolveOperatorTypes();
return plan;
}
struct GPUBufferInitFunctionData : public TableFunctionData {
GPUBufferInitFunctionData() {}
bool finished = false;
size_t cache_size;
size_t processing_size;
size_t pinned_memory_size;
};
unique_ptr<FunctionData> SiriusExtension::GPUBufferInitBind(ClientContext& context,
TableFunctionBindInput& input,
vector<LogicalType>& return_types,
vector<string>& names)
{
auto result = make_uniq<GPUBufferInitFunctionData>();
string gpu_cache_size = input.inputs[0].ToString();
string gpu_processing_size = input.inputs[1].ToString();
string pinned_memory_size("0 GB"); // Default size of pinned memory
if (input.named_parameters.find(PINNED_MEMORY_PARAM_KEY) != input.named_parameters.end()) {
// If the pinned memory size is specified in the arguments then use that
pinned_memory_size = input.named_parameters[PINNED_MEMORY_PARAM_KEY].ToString();
}
// parsing 2GB or 2GiB to size_t
// Function to parse size strings like "2GB" or "2GiB" to size_t
auto parse_size = [](const string& size_str) -> size_t {
size_t result = 0;
size_t multiplier = 1;
string num_part;
string unit_part;
size_t i = 0;
// Skip any whitespace between number and unit
while (i < size_str.length() && isspace(size_str[i])) {
i++;
}
// Find where the number ends and unit begins
while (i < size_str.length() && (isdigit(size_str[i]) || size_str[i] == '.')) {
num_part += size_str[i];
i++;
}
// Skip any whitespace between number and unit
while (i < size_str.length() && isspace(size_str[i])) {
i++;
}
// Extract unit part
unit_part = size_str.substr(i);
// Convert number part to double
double num_value = stod(num_part);
// Determine multiplier based on unit
if (unit_part == "B") {
multiplier = 1;
} else if (unit_part == "KB" || unit_part == "KiB") {
multiplier = 1024;
} else if (unit_part == "MB" || unit_part == "MiB") {
multiplier = 1024 * 1024;
} else if (unit_part == "GB" || unit_part == "GiB") {
multiplier = 1024 * 1024 * 1024;
} else if (unit_part == "TB" || unit_part == "TiB") {
multiplier = 1024ULL * 1024ULL * 1024ULL * 1024ULL;
} else {
throw InvalidInputException("Invalid format");
}
result = (size_t)(num_value * multiplier);
return result;
};
// Parse the input sizes
result->cache_size = parse_size(gpu_cache_size);
result->processing_size = parse_size(gpu_processing_size);
result->pinned_memory_size = parse_size(pinned_memory_size);
auto type = LogicalType(LogicalTypeId::BOOLEAN);
return_types.emplace_back(type);
names.emplace_back("Success");
return std::move(result);
}
void SiriusExtension::GPUBufferInitFunction(ClientContext& context,
TableFunctionInput& data_p,
DataChunk& output)
{
auto& data = data_p.bind_data->CastNoConst<GPUBufferInitFunctionData>();
if (data.finished) { return; }
size_t cache_size = data.cache_size;
size_t processing_size = data.processing_size;
size_t pinned_memory_size = data.pinned_memory_size;
if (pinned_memory_size == 0) { pinned_memory_size = std::max(cache_size, processing_size); }
if (!buffer_is_initialized) {
SIRIUS_LOG_DEBUG(
"GPU Buffer Manager initialized with args: Cache Size - {}, Processing Size - {}, Pinned Mem "
"Size - {}\n",
cache_size,
processing_size,
pinned_memory_size);
GPUBufferManager* gpuBufferManager =
&(GPUBufferManager::GetInstance(cache_size, processing_size, pinned_memory_size));
buffer_is_initialized = true;
} else {
SIRIUS_LOG_WARN("GPUBufferManager already initialized");
}
data.finished = true;
}
static unique_ptr<FunctionData> ProfilerBind(ClientContext& context,
TableFunctionBindInput& input,
vector<LogicalType>& return_types,
vector<string>& names)
{
return_types.push_back(LogicalType::BOOLEAN);
names.push_back("ok");
return nullptr;
}
struct ProfilerFunctionData : public GlobalTableFunctionState {
bool finished = false;
};
static unique_ptr<GlobalTableFunctionState> ProfilerInit(ClientContext& context,
TableFunctionInitInput& input)
{
return make_uniq<ProfilerFunctionData>();
}
static void ProfilerStartFunction(ClientContext& context,
TableFunctionInput& data_p,
DataChunk& output)
{
auto& data = data_p.global_state->Cast<ProfilerFunctionData>();
if (data.finished) return;
cudaProfilerStart();
output.SetCardinality(1);
output.SetValue(0, 0, Value::BOOLEAN(true));
data.finished = true;
}
static void ProfilerStopFunction(ClientContext& context,
TableFunctionInput& data_p,
DataChunk& output)
{
auto& data = data_p.global_state->Cast<ProfilerFunctionData>();
if (data.finished) return;
cudaProfilerStop();
output.SetCardinality(1);
output.SetValue(0, 0, Value::BOOLEAN(true));
data.finished = true;
}
void SiriusExtension::RegisterGPUFunctions(DatabaseInstance& instance)
{
auto transaction = CatalogTransaction::GetSystemTransaction(instance);
auto& catalog = Catalog::GetSystemCatalog(instance);
TableFunction gpu_buffer_init("gpu_buffer_init",
{LogicalType::VARCHAR, LogicalType::VARCHAR},
GPUBufferInitFunction,
GPUBufferInitBind);
gpu_buffer_init.named_parameters[PINNED_MEMORY_PARAM_KEY] = LogicalType::VARCHAR;
CreateTableFunctionInfo gpu_buffer_init_info(gpu_buffer_init);
catalog.CreateTableFunction(transaction, gpu_buffer_init_info);
#ifdef SIRIUS_ENABLE_LEGACY
RegisterLegacyGPUFunctions(transaction, catalog);
#endif
TableFunction gpu_execution("gpu_execution",
{LogicalType::VARCHAR},
GPUExecutionFunction,
SiriusExtension::GPUExecutionBind);
gpu_execution.named_parameters["enable_optimizer"] = LogicalType::BOOLEAN;
CreateTableFunctionInfo gpu_execution_info(gpu_execution);
catalog.CreateTableFunction(transaction, gpu_execution_info);
// Profiler control functions for nsys --capture-range=cudaProfilerApi
TableFunction profiler_start(
"profiler_start", {}, ProfilerStartFunction, ProfilerBind, ProfilerInit);
CreateTableFunctionInfo profiler_start_info(profiler_start);
catalog.CreateTableFunction(transaction, profiler_start_info);
TableFunction profiler_stop(
"profiler_stop", {}, ProfilerStopFunction, ProfilerBind, ProfilerInit);
CreateTableFunctionInfo profiler_stop_info(profiler_stop);
catalog.CreateTableFunction(transaction, profiler_stop_info);
}
static void SetUsePinMemory(ClientContext& context, SetScope scope, Value& parameter)
{
Config::USE_PIN_MEM_FOR_CPU_PROCESSING = BooleanValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config USE_PIN_MEM_FOR_CPU_PROCESSING to {}",
Config::USE_PIN_MEM_FOR_CPU_PROCESSING);
}
static void SetUsePinMemoryForCaching(ClientContext& context, SetScope scope, Value& parameter)
{
Config::USE_PIN_MEM_FOR_CACHING = BooleanValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config USE_PIN_MEM_FOR_CACHING to {}", Config::USE_PIN_MEM_FOR_CACHING);
}
static void SetUseCudfExpr(ClientContext& context, SetScope scope, Value& parameter)
{
Config::USE_CUDF_EXPR = BooleanValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config USE_CUDF_EXPR to {}", Config::USE_CUDF_EXPR);
}
static void SetExpressionExecutorStrategy(ClientContext& context, SetScope scope, Value& parameter)
{
auto value = StringValue::Get(parameter);
if (value != "materialize" && value != "ast_interpret" && value != "ast_jit") {
throw InvalidInputException(
"Invalid expression_executor_strategy '{}'. Valid values: materialize, ast_interpret, "
"ast_jit",
value);
}
Config::EXPRESSION_EXECUTOR_STRATEGY = std::move(value);
SIRIUS_LOG_DEBUG("Updated config EXPRESSION_EXECUTOR_STRATEGY to {}",
Config::EXPRESSION_EXECUTOR_STRATEGY);
}
static void SetUseCustomTopN(ClientContext& context, SetScope scope, Value& parameter)
{
Config::USE_CUSTOM_TOP_N = BooleanValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config USE_CUSTOM_TOP_N to {}", Config::USE_CUSTOM_TOP_N);
}
static void SetUseOptTableScan(ClientContext& context, SetScope scope, Value& parameter)
{
Config::USE_OPT_TABLE_SCAN = BooleanValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config USE_OPT_TABLE_SCAN to {}", Config::USE_OPT_TABLE_SCAN);
}
static void SetOptTableScanNumStreams(ClientContext& context, SetScope scope, Value& parameter)
{
Config::OPT_TABLE_SCAN_NUM_CUDA_STREAMS = IntegerValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config OPT_TABLE_SCAN_NUM_CUDA_STREAMS to {}",
Config::OPT_TABLE_SCAN_NUM_CUDA_STREAMS);
}
static void SetOptTableScanMemcpySize(ClientContext& context, SetScope scope, Value& parameter)
{
Config::OPT_TABLE_SCAN_CUDA_MEMCPY_SIZE = UBigIntValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config OPT_TABLE_SCAN_CUDA_MEMCPY_SIZE to {}",
Config::OPT_TABLE_SCAN_CUDA_MEMCPY_SIZE);
}
static void SetPrintGPUTableMaxRows(ClientContext& context, SetScope scope, Value& parameter)
{
Config::PRINT_GPU_TABLE_MAX_ROWS = UBigIntValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config PRINT_GPU_TABLE_MAX_ROWS to {}",
Config::PRINT_GPU_TABLE_MAX_ROWS);
}
static void SetEnableFallbackCheck(ClientContext& context, SetScope scope, Value& parameter)
{
Config::ENABLE_FALLBACK_CHECK = BooleanValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config ENABLE_FALLBACK_CHECK to {}", Config::ENABLE_FALLBACK_CHECK);
}
static void SetEnableDuckdbFallback(ClientContext& context, SetScope scope, Value& parameter)
{
Config::ENABLE_DUCKDB_FALLBACK = BooleanValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config ENABLE_DUCKDB_FALLBACK to {}", Config::ENABLE_DUCKDB_FALLBACK);
}
static void SetEnableRegexJitImpl(ClientContext& context, SetScope scope, Value& parameter)
{
Config::ENABLE_REGEX_JIT_IMPL = BooleanValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config ENABLE_REGEX_JIT_IMPL to {}", Config::ENABLE_REGEX_JIT_IMPL);
}
static void SetModifiedPipeline(ClientContext& context, SetScope scope, Value& parameter)
{
Config::MODIFIED_PIPELINE = BooleanValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config MODIFIED_PIPELINE to {}", Config::MODIFIED_PIPELINE);
}
static void SetCacheScanLevel(ClientContext& context, SetScope scope, Value& parameter)
{
auto sirius_ctx = context.registered_state->Get<duckdb::SiriusContext>("sirius_state");
if (sirius_ctx == nullptr) {
SIRIUS_LOG_DEBUG("SiriusContext not available; cache_scan_level SET ignored");
return;
}
auto level_str = StringValue::Get(parameter);
sirius::op::scan::cache_level level;
if (!sirius::op::scan::string_to_enum(level_str, level)) {
throw InvalidInputException(
"Invalid cache_scan_level '{}'. Valid values: none, table_gpu, table_host, parquet",
level_str);
}
auto& cfg = sirius_ctx->get_config();
cfg.set_cache_level(level);
SIRIUS_LOG_DEBUG("Updated config cache_scan_level to {}", level_str);
}
static sirius::operator_params* get_operator_params(ClientContext& context)
{
auto sirius_ctx = context.registered_state->Get<duckdb::SiriusContext>("sirius_state");
if (sirius_ctx == nullptr) {
SIRIUS_LOG_DEBUG("SiriusContext not available; operator_params SET ignored");
return nullptr;
}
return &sirius_ctx->get_config().get_operator_params();
}
static void SetDefaultScanTaskBatchSize(ClientContext& context, SetScope scope, Value& parameter)
{
auto* params = get_operator_params(context);
if (!params) { return; }
params->scan_task_batch_size = UBigIntValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config SCAN_TASK_BATCH_SIZE to {}", params->scan_task_batch_size);
}
static void SetDefaultScanTaskVarcharSize(ClientContext& context, SetScope scope, Value& parameter)
{
auto* params = get_operator_params(context);
if (!params) { return; }
params->default_scan_task_varchar_size = UBigIntValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config DEFAULT_SCAN_TASK_VARCHAR_SIZE to {}",
params->default_scan_task_varchar_size);
}
static void SetMaxSortPartitionBytes(ClientContext& context, SetScope scope, Value& parameter)
{
auto* params = get_operator_params(context);
if (!params) { return; }
params->max_sort_partition_bytes = UBigIntValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config MAX_SORT_PARTITION_BYTES to {}",
params->max_sort_partition_bytes);
}
static void SetHashPartitionBytes(ClientContext& context, SetScope scope, Value& parameter)
{
auto* params = get_operator_params(context);
if (!params) { return; }
params->hash_partition_bytes = UBigIntValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config HASH_PARTITION_BYTES to {}", params->hash_partition_bytes);
}
static void SetConcatBatchBytes(ClientContext& context, SetScope scope, Value& parameter)
{
auto* params = get_operator_params(context);
if (!params) { return; }
params->concat_batch_bytes = UBigIntValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config CONCAT_BATCH_BYTES to {}", params->concat_batch_bytes);
}
static void SetLogLevel(ClientContext& context, SetScope scope, Value& parameter)
{
Config::LOG_LEVEL = StringValue::Get(parameter);
SetGlobalLogLevel(Config::LOG_LEVEL);
SIRIUS_LOG_DEBUG("Updated config LOG_LEVEL to {}", Config::LOG_LEVEL);
}
static void SetLogDir(ClientContext& context, SetScope scope, Value& parameter)
{
Config::LOG_DIR = StringValue::Get(parameter);
InitGlobalLogger(Config::LOG_LEVEL, Config::LOG_DIR, Config::LOG_FLUSH_SECONDS);
SIRIUS_LOG_DEBUG("Updated config LOG_DIR to {}", Config::LOG_DIR);
}
static void SetLogFlushSeconds(ClientContext& context, SetScope scope, Value& parameter)
{
Config::LOG_FLUSH_SECONDS = IntegerValue::Get(parameter);
SetGlobalLogFlush(Config::LOG_FLUSH_SECONDS);
SIRIUS_LOG_DEBUG("Updated config LOG_FLUSH_SECONDS to {}", Config::LOG_FLUSH_SECONDS);
}
static void SetMaxBuildHashTableBytes(ClientContext& context, SetScope scope, Value& parameter)
{
auto* params = get_operator_params(context);
if (!params) { return; }
params->max_build_hash_table_bytes = UBigIntValue::Get(parameter);
SIRIUS_LOG_DEBUG("Updated config MAX_BUILD_HASH_TABLE_BYTES to {}",
params->max_build_hash_table_bytes);
}
void SiriusExtension::InitialGPUConfigs(DBConfig& config)
{
// Add in config option for gpu buffer manager
config.AddExtensionOption("use_pin_memory",
"Whether or not the buffer manager is initialized with pinned memory",
LogicalType::BOOLEAN,
Value::BOOLEAN(Config::USE_PIN_MEM_FOR_CPU_PROCESSING),
SetUsePinMemory);
config.AddExtensionOption(
"use_pin_memory_for_caching",
"Whether or not the cache buffer is allocated with pinned host memory instead of GPU memory",
LogicalType::BOOLEAN,
Value::BOOLEAN(Config::USE_PIN_MEM_FOR_CACHING),
SetUsePinMemoryForCaching);
// Add in config option for expression executor
config.AddExtensionOption("use_cudf_expr",
"Whether or not cudf is used to evaluate expressions",
LogicalType::BOOLEAN,
Value::BOOLEAN(Config::USE_CUDF_EXPR),
SetUseCudfExpr);
config.AddExtensionOption(
"expression_executor_strategy",
"Strategy for the experimental gpu_expression_executor: 'materialize', 'ast_interpret', or "
"'ast_jit'",
LogicalType::VARCHAR,
Value(Config::EXPRESSION_EXECUTOR_STRATEGY),
SetExpressionExecutorStrategy);
// Add in config option for top-N
config.AddExtensionOption("use_custom_top_n",
"Whether or not custom kernel is used to evalaute top n",
LogicalType::BOOLEAN,
Value::BOOLEAN(Config::USE_CUSTOM_TOP_N),
SetUseCustomTopN);
// Add in config options for custom table scan
config.AddExtensionOption("use_opt_table_scan",
"Whether or not the optional table scan is used",
LogicalType::BOOLEAN,
Value::BOOLEAN(Config::USE_OPT_TABLE_SCAN),
SetUseOptTableScan);
config.AddExtensionOption("opt_table_scan_num_streams",
"The number of cuda streams to use in the optional table scan",
LogicalType::INTEGER,
Value::INTEGER(Config::OPT_TABLE_SCAN_NUM_CUDA_STREAMS),
SetOptTableScanNumStreams);
config.AddExtensionOption("opt_table_scan_memcpy_size",
"The memcpy size (in bytes) used by the optional table scan",
LogicalType::UBIGINT,
Value::UBIGINT(Config::OPT_TABLE_SCAN_CUDA_MEMCPY_SIZE),
SetOptTableScanMemcpySize);
// Add in config options for printing gpu table
config.AddExtensionOption("print_gpu_table_max_rows",
"Maximal amount of rows to render when printing gpu table",
LogicalType::UBIGINT,
Value::UBIGINT(Config::PRINT_GPU_TABLE_MAX_ROWS),
SetPrintGPUTableMaxRows);
// Add in config options for duckdb fallback checking
config.AddExtensionOption("enable_fallback_check",
"Whether to enable fallback checking",
LogicalType::BOOLEAN,
Value::BOOLEAN(Config::ENABLE_FALLBACK_CHECK),
SetEnableFallbackCheck);
config.AddExtensionOption(
"enable_duckdb_fallback",
"Whether to enable fallback to duckdb execution after an error is detected",
LogicalType::BOOLEAN,
Value::BOOLEAN(Config::ENABLE_DUCKDB_FALLBACK),
SetEnableDuckdbFallback);
// Add in config options for special JIT implementation for regex
config.AddExtensionOption(
"enable_regex_jit_impl",
"Whether to use special JIT implementation for particular regex evaluation",
LogicalType::BOOLEAN,
Value::BOOLEAN(Config::ENABLE_REGEX_JIT_IMPL),
SetEnableRegexJitImpl);
// Add in config options for modified pipeline
config.AddExtensionOption("modified_pipeline",
"Whether to use modified pipeline for GPU execution",
LogicalType::BOOLEAN,
Value::BOOLEAN(Config::MODIFIED_PIPELINE),
SetModifiedPipeline);
// Add in config options for duckdb scan task
// Default batch size
config.AddExtensionOption("scan_task_batch_size",
"The default batch size for a duckdb scan task",
LogicalType::UBIGINT,
Value::UBIGINT(sirius::operator_params{}.scan_task_batch_size),
SetDefaultScanTaskBatchSize);
// Default varchar size for estimating rows per batch
config.AddExtensionOption(
"default_scan_task_varchar_size",
"The default varchar size for estimating rows per batch in a duckdb scan task",
LogicalType::UBIGINT,
Value::UBIGINT(sirius::operator_params{}.default_scan_task_varchar_size),
SetDefaultScanTaskVarcharSize);
// Add in config option for sort partition size
config.AddExtensionOption("max_sort_partition_bytes",
"Maximum bytes per sort partition (0 = auto based on 33% GPU memory)",
LogicalType::UBIGINT,
Value::UBIGINT(sirius::operator_params{}.max_sort_partition_bytes),
SetMaxSortPartitionBytes);