-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.rs
More file actions
2405 lines (2120 loc) · 86.2 KB
/
main.rs
File metadata and controls
2405 lines (2120 loc) · 86.2 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 2026 The Spice.ai OSS Authors
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
https://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.
*/
use anyhow::{Result, anyhow};
use arrow_schema::DataType;
use async_trait::async_trait;
use clap::{Parser, Subcommand, ValueEnum};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::sync::Arc;
use std::{collections::HashMap, time::Duration};
use system_adapter_protocol::{
AdbcDriver, DatasetConfig, EtlSinkType, Handler, IngestionMetrics, MetricsResponse,
ResourceMetrics, Server, SetupResponse, TeardownResponse,
};
use uuid::Uuid;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Run the system adapter over stdio JSON-RPC.
Stdio(StdioArgs),
}
#[derive(Parser, Debug, Clone)]
struct StdioArgs {
/// Databricks endpoint host, e.g. dbc-xxxx.cloud.databricks.com
#[arg(long, env = "DATABRICKS_ENDPOINT")]
databricks_endpoint: String,
/// Databricks personal access token
#[arg(long, env = "DATABRICKS_TOKEN")]
databricks_token: String,
/// SQL Warehouse HTTP path (used for ADBC URI), e.g. sql/protocolv1/o/123/0123-456789-abcdef
#[arg(long, env = "DATABRICKS_HTTP_PATH")]
databricks_http_path: String,
/// Databricks compute mode for setup/teardown SQL operations.
#[arg(
long,
env = "DATABRICKS_COMPUTE_MODE",
value_enum,
default_value = "sql-warehouse"
)]
databricks_compute_mode: ComputeMode,
/// SQL Warehouse ID for statement execution API
#[arg(long, env = "DATABRICKS_SQL_WAREHOUSE_ID")]
databricks_sql_warehouse_id: Option<String>,
/// Existing Databricks cluster ID to use in spark-cluster mode.
#[arg(long, env = "DATABRICKS_CLUSTER_ID")]
databricks_cluster_id: Option<String>,
/// Databricks cluster name to discover or create in spark-cluster mode.
#[arg(long, env = "DATABRICKS_CLUSTER_NAME", default_value = "spicebench")]
databricks_cluster_name: String,
/// Databricks runtime version for newly created clusters in spark-cluster mode.
#[arg(
long,
env = "DATABRICKS_CLUSTER_SPARK_VERSION",
default_value = "15.4.x-scala2.12"
)]
databricks_cluster_spark_version: String,
/// Databricks node type for newly created clusters in spark-cluster mode.
#[arg(
long,
env = "DATABRICKS_CLUSTER_NODE_TYPE_ID",
default_value = "i3.xlarge"
)]
databricks_cluster_node_type_id: String,
/// Number of workers for newly created clusters in spark-cluster mode.
#[arg(long, env = "DATABRICKS_CLUSTER_NUM_WORKERS", default_value_t = 1)]
databricks_cluster_num_workers: i32,
/// Auto termination minutes for newly created clusters in spark-cluster mode.
#[arg(
long,
env = "DATABRICKS_CLUSTER_AUTOTERMINATION_MINUTES",
default_value_t = 30
)]
databricks_cluster_autotermination_minutes: i32,
/// Databricks catalog for created external tables
#[arg(long, env = "DATABRICKS_CATALOG", default_value = "spiceai_sandbox")]
databricks_catalog: String,
/// Databricks schema for created external tables
#[arg(long, env = "DATABRICKS_SCHEMA", default_value = "tpch")]
databricks_schema: String,
/// Drop created tables during teardown
#[arg(
long,
env = "DATABRICKS_DROP_TABLES_ON_TEARDOWN",
default_value_t = true
)]
drop_tables_on_teardown: bool,
/// Table format to use when creating Lakebase tables.
#[arg(
long,
env = "DATABRICKS_TABLE_FORMAT",
value_enum,
default_value = "parquet"
)]
databricks_table_format: TableFormat,
/// Staging Volume Path.
#[arg(long, env = "DATABRICKS_STAGING_VOLUME_PATH")]
databricks_staging_volume_path: String,
/// Lakebase PostgreSQL endpoint host (required for lakebase compute mode).
#[arg(long, env = "LAKEBASE_PG_HOST")]
lakebase_pg_host: Option<String>,
/// Lakebase PostgreSQL username (required for lakebase compute mode).
#[arg(long, env = "LAKEBASE_PG_USER")]
lakebase_pg_user: Option<String>,
/// Lakebase PostgreSQL database name.
#[arg(long, env = "LAKEBASE_PG_DB_NAME", default_value = "spicebench")]
lakebase_pg_db_name: String,
/// Lakebase PostgreSQL schema for search_path (defaults to --databricks-schema).
#[arg(long, env = "LAKEBASE_PG_SCHEMA")]
lakebase_pg_schema: Option<String>,
/// Lakebase database instance name (for Provisioned synced table creation).
/// Mutually exclusive with --lakebase-project.
#[arg(
long,
env = "LAKEBASE_DATABASE_INSTANCE",
conflicts_with = "lakebase_project"
)]
lakebase_database_instance: Option<String>,
/// Lakebase project name (for Autoscaling synced table creation).
/// Mutually exclusive with --lakebase-database-instance.
#[arg(
long,
env = "LAKEBASE_PROJECT",
conflicts_with = "lakebase_database_instance",
conflicts_with = "lakebase_pg_db_name"
)]
lakebase_project: Option<String>,
/// Lakebase branch name (used with --lakebase-project, defaults to "production").
#[arg(long, env = "LAKEBASE_BRANCH", default_value = "production")]
lakebase_branch: String,
}
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
#[value(rename_all = "kebab-case")]
enum DatabricksVariant {
Databricks,
Lakebase,
}
impl DatabricksVariant {
fn from_metadata_value(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"databricks" | "sql" | "databricks-sql" => Some(Self::Databricks),
"lakebase" | "databricks-lakebase" => Some(Self::Lakebase),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, ValueEnum)]
#[value(rename_all = "kebab-case")]
enum ComputeMode {
SqlWarehouse,
SparkCluster,
Lakebase,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
#[value(rename_all = "kebab-case")]
enum TableFormat {
Parquet,
Delta,
Iceberg,
}
impl TableFormat {
fn as_sql_using(self) -> &'static str {
match self {
Self::Parquet => "PARQUET",
Self::Delta => "DELTA",
Self::Iceberg => "ICEBERG",
}
}
fn from_metadata_value(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"parquet" => Some(Self::Parquet),
"delta" => Some(Self::Delta),
"iceberg" => Some(Self::Iceberg),
_ => None,
}
}
}
#[derive(Debug, Clone, Default)]
struct PgIoBaseline {
reads: i64,
writes: i64,
op_bytes: i64,
}
#[derive(Debug, Clone)]
struct RunState {
_table_format: TableFormat,
variant: DatabricksVariant,
scenario_slug: String,
created_tables: Vec<String>,
cluster_id: Option<String>,
cluster_created_by_adapter: bool,
/// Epoch millis when the run was set up (for Query History time-range filtering).
started_at_ms: u64,
/// Baseline `pg_stat_io` counters snapshotted after setup. Because `pg_stat_reset()` is
/// denied on Lakebase (requires elevated privileges), server-wide I/O counters accumulate across
/// runs. We subtract these baseline values at each metrics scrape to get per-run disk read/write bytes.
pg_io_baseline: Option<PgIoBaseline>,
}
struct DatabricksAdapter {
config: AdapterConfig,
runs: HashMap<Uuid, RunState>,
client: reqwest::Client,
}
#[derive(Debug, Clone)]
struct AdapterConfig {
endpoint: String,
token: String,
http_path: String,
table_format: TableFormat,
warehouse_id: String,
compute_target: ComputeTarget,
catalog: String,
schema: String,
drop_tables_on_teardown: bool,
staging_volume_path: String,
}
#[derive(Debug, Clone)]
enum ComputeTarget {
SqlWarehouse,
SparkCluster(ClusterConfig),
Lakebase(LakebaseConfig),
}
#[derive(Debug, Clone)]
struct ClusterConfig {
cluster_id: Option<String>,
cluster_name: String,
spark_version: String,
node_type_id: String,
num_workers: i32,
autotermination_minutes: i32,
}
#[derive(Debug, Clone)]
struct LakebaseConfig {
user: String,
host: String,
db_name: String,
schema: String,
target: LakebaseSyncTarget,
}
#[derive(Debug, Clone)]
enum LakebaseSyncTarget {
/// Provisioned Lakebase instance
Instance { name: String },
/// Autoscaling Lakebase project + branch
Project { name: String, branch: String },
}
impl AdapterConfig {
fn from_args(args: StdioArgs) -> Result<Self> {
if args.databricks_endpoint.starts_with("http://")
|| args.databricks_endpoint.starts_with("https://")
{
return Err(anyhow!(
"Invalid Databricks endpoint '{}': use hostname only (no scheme)",
args.databricks_endpoint
));
}
if args.databricks_endpoint.contains('/') {
return Err(anyhow!(
"Invalid Databricks endpoint '{}': do not include path segments",
args.databricks_endpoint
));
}
if args.databricks_http_path.starts_with('/') {
return Err(anyhow!(
"Invalid Databricks HTTP path '{}': do not start with '/'",
args.databricks_http_path
));
}
if args.databricks_http_path.trim().is_empty() {
return Err(anyhow!("Databricks HTTP path must not be empty"));
}
let warehouse_id = args.databricks_sql_warehouse_id.unwrap_or_else(|| {
args.databricks_http_path
.rsplit('/')
.find(|s| !s.is_empty())
.unwrap_or_default()
.to_string()
});
let compute_target = match args.databricks_compute_mode {
ComputeMode::SqlWarehouse => {
if warehouse_id.is_empty() {
return Err(anyhow!(
"Missing Databricks warehouse ID. Set --databricks-sql-warehouse-id or provide it in --databricks-http-path"
));
}
ComputeTarget::SqlWarehouse
}
ComputeMode::Lakebase => {
if warehouse_id.is_empty() {
return Err(anyhow!(
"Missing Databricks warehouse ID. Set --databricks-sql-warehouse-id or provide it in --databricks-http-path"
));
}
let pg_host = args.lakebase_pg_host.ok_or_else(|| {
anyhow!("--lakebase-pg-host is required for lakebase compute mode")
})?;
let pg_user = args.lakebase_pg_user.ok_or_else(|| {
anyhow!("--lakebase-pg-user is required for lakebase compute mode")
})?;
let pg_schema = args
.lakebase_pg_schema
.unwrap_or_else(|| args.databricks_schema.clone());
let sync_target = if let Some(instance) = args.lakebase_database_instance {
LakebaseSyncTarget::Instance { name: instance }
} else if let Some(project) = args.lakebase_project {
LakebaseSyncTarget::Project {
name: project,
branch: args.lakebase_branch.clone(),
}
} else {
return Err(anyhow!(
"Either --lakebase-database-instance or --lakebase-project is required for lakebase compute mode"
));
};
ComputeTarget::Lakebase(LakebaseConfig {
user: pg_user,
host: pg_host,
db_name: args.lakebase_pg_db_name.clone(),
schema: pg_schema,
target: sync_target,
})
}
ComputeMode::SparkCluster => {
if args.databricks_cluster_name.trim().is_empty()
&& args
.databricks_cluster_id
.as_deref()
.unwrap_or_default()
.is_empty()
{
return Err(anyhow!(
"Missing Databricks cluster configuration. Set --databricks-cluster-id or --databricks-cluster-name"
));
}
if args.databricks_cluster_num_workers < 0 {
return Err(anyhow!(
"Invalid Databricks cluster num workers '{}': must be >= 0",
args.databricks_cluster_num_workers
));
}
if args.databricks_cluster_autotermination_minutes < 0 {
return Err(anyhow!(
"Invalid Databricks cluster autotermination minutes '{}': must be >= 0",
args.databricks_cluster_autotermination_minutes
));
}
ComputeTarget::SparkCluster(ClusterConfig {
cluster_id: args
.databricks_cluster_id
.as_ref()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty()),
cluster_name: args.databricks_cluster_name,
spark_version: args.databricks_cluster_spark_version,
node_type_id: args.databricks_cluster_node_type_id,
num_workers: args.databricks_cluster_num_workers,
autotermination_minutes: args.databricks_cluster_autotermination_minutes,
})
}
};
Ok(Self {
endpoint: args.databricks_endpoint,
token: args.databricks_token,
http_path: args.databricks_http_path,
table_format: args.databricks_table_format,
warehouse_id,
compute_target,
catalog: args.databricks_catalog,
schema: args.databricks_schema,
drop_tables_on_teardown: args.drop_tables_on_teardown,
staging_volume_path: args.databricks_staging_volume_path.clone(),
})
}
}
#[derive(Debug, Deserialize)]
struct DatabaseCredentialResponse {
token: String,
#[serde(alias = "expiration_time", alias = "expire_time")]
expiration_time: Option<String>,
}
impl DatabricksAdapter {
fn try_new(config: AdapterConfig) -> Result<Self> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(60))
.build()?;
Ok(Self {
config,
runs: HashMap::new(),
client,
})
}
fn databricks_uri(&self) -> String {
format!(
"databricks://token:{}@{}:443/{}?catalog={}&schema={}",
self.config.token,
self.config.endpoint,
self.config.http_path,
urlencoding::encode(&self.config.catalog),
urlencoding::encode(&self.config.schema),
)
}
fn uc_schema_full_name(&self) -> String {
format!("{}.{}", self.config.catalog, self.config.schema)
}
fn uc_table_full_name(&self, table_name: &str) -> String {
format!(
"{}.{}.{}",
self.config.catalog, self.config.schema, table_name
)
}
fn lakebase_synced_table_full_name(
&self,
table_name: &str,
lakebase_config: &LakebaseConfig,
) -> String {
format!(
"{}.{}.{}",
self.config.catalog, lakebase_config.schema, table_name
)
}
fn quoted_identifier(identifier: &str) -> String {
format!("`{}`", identifier.replace('`', "``"))
}
fn table_full_name(&self, table_name: &str) -> String {
format!(
"{}.{}.{}",
Self::quoted_identifier(&self.config.catalog),
Self::quoted_identifier(&self.config.schema),
Self::quoted_identifier(table_name)
)
}
fn scenario_slug(metadata: &HashMap<String, Value>) -> String {
let raw = metadata
.get("scenario")
.and_then(Value::as_str)
.or_else(|| metadata.get("scenario_name").and_then(Value::as_str))
.unwrap_or("default");
let mut slug = String::with_capacity(raw.len());
let mut last_was_separator = false;
for ch in raw.chars() {
let c = ch.to_ascii_lowercase();
if c.is_ascii_alphanumeric() {
slug.push(c);
last_was_separator = false;
} else if !last_was_separator {
slug.push('-');
last_was_separator = true;
}
}
let slug = slug.trim_matches('-').to_string();
if slug.is_empty() {
"default".to_string()
} else {
slug
}
}
fn notebook_path_for_scenario(scenario_slug: &str) -> String {
format!("/Shared/spicebench/sync_autoloader_{scenario_slug}")
}
fn job_name_for_scenario(scenario_slug: &str) -> String {
format!("spicebench_sync_tables_{scenario_slug}")
}
fn sql_type_for_arrow(data_type: &DataType) -> Result<String> {
match data_type {
DataType::Boolean => Ok("BOOLEAN".to_string()),
DataType::Int8
| DataType::Int16
| DataType::Int32
| DataType::UInt8
| DataType::UInt16 => Ok("INT".to_string()),
DataType::Int64 | DataType::UInt32 | DataType::UInt64 => Ok("BIGINT".to_string()),
DataType::Float16 | DataType::Float32 => Ok("FLOAT".to_string()),
DataType::Float64 => Ok("DOUBLE".to_string()),
DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => Ok("STRING".to_string()),
DataType::Date32 => Ok("DATE".to_string()),
DataType::Timestamp(_, tz) => Ok(match tz {
Some(_) => "TIMESTAMP".to_string(),
None => "TIMESTAMP_NTZ".to_string(),
}),
DataType::Decimal128(precision, scale) => {
let precision = (*precision).min(38);
Ok(format!("DECIMAL({precision}, {scale})"))
}
other => Err(anyhow!(
"Unsupported Arrow data type for Lakebase table creation: {other:?}"
)),
}
}
/// Parse a `bucket(N, col_name)` expression and return the column name.
fn parse_bucket_column(spec: &str) -> Option<String> {
let trimmed = spec.trim();
if !trimmed.starts_with("bucket(") || !trimmed.ends_with(')') {
return None;
}
let inner = &trimmed["bucket(".len()..trimmed.len() - 1];
let (_n, col) = inner.split_once(',')?;
Some(col.trim().to_string())
}
fn create_table_ddl(
&self,
table_name: &str,
dataset_cfg: &DatasetConfig,
table_format: TableFormat,
) -> Result<String> {
// Separate partition columns into plain (Hive) and bucket (clustering).
let mut plain_partition_cols: Vec<&str> = Vec::new();
let mut cluster_cols: Vec<String> = Vec::new();
for spec in &dataset_cfg.partition_columns {
if let Some(col_name) = Self::parse_bucket_column(spec) {
cluster_cols.push(col_name);
} else {
plain_partition_cols.push(spec.as_str());
}
}
let partition_set: std::collections::HashSet<&str> =
plain_partition_cols.iter().copied().collect();
let columns = dataset_cfg
.schema
.fields()
.iter()
.filter(|field| !partition_set.contains(field.name().as_str()))
.map(|field| {
let col_type = Self::sql_type_for_arrow(field.data_type())?;
Ok::<_, anyhow::Error>(format!(
"{} {}",
Self::quoted_identifier(field.name()),
col_type
))
})
.collect::<Result<Vec<_>>>()?
.join(", ");
let mut ddl = format!(
"CREATE TABLE {} ({columns}) USING {}",
self.table_full_name(table_name),
table_format.as_sql_using()
);
use std::fmt::Write;
if !plain_partition_cols.is_empty() {
let partition_defs = plain_partition_cols
.iter()
.map(|col_name| {
let field =
dataset_cfg.schema.field_with_name(col_name).map_err(|_| {
anyhow!("Partition column '{col_name}' not found in schema for table '{table_name}'")
})?;
let col_type = Self::sql_type_for_arrow(field.data_type())?;
Ok::<_, anyhow::Error>(format!(
"{} {col_type}",
Self::quoted_identifier(col_name)
))
})
.collect::<Result<Vec<_>>>()?
.join(", ");
write!(&mut ddl, " PARTITIONED BY ({partition_defs})").unwrap();
}
if !cluster_cols.is_empty() {
let cluster_idents: Vec<String> = cluster_cols
.iter()
.map(|c| Self::quoted_identifier(c))
.collect();
write!(&mut ddl, " CLUSTER BY ({})", cluster_idents.join(", ")).unwrap();
}
Ok(ddl)
}
fn table_format_from_setup_metadata(
&self,
variant: DatabricksVariant,
metadata: &HashMap<String, Value>,
) -> Result<TableFormat> {
// Databricks managed tables only support Delta format.
if variant == DatabricksVariant::Databricks {
return Ok(TableFormat::Delta);
}
if let Some(value) = metadata.get("table_format")
&& let Some(s) = value.as_str()
{
return TableFormat::from_metadata_value(s).ok_or_else(|| {
anyhow!("Unsupported table_format '{s}'. Allowed values: parquet, delta, iceberg")
});
}
Ok(self.config.table_format)
}
fn variant_from_setup_metadata(metadata: &HashMap<String, Value>) -> Result<DatabricksVariant> {
if let Some(value) = metadata.get("system_adapter_variant")
&& let Some(s) = value.as_str()
{
return DatabricksVariant::from_metadata_value(s).ok_or_else(|| {
anyhow!(
"Unsupported system_adapter_variant '{s}'. Allowed values: databricks, sql, lakebase"
)
});
}
if let Some(value) = metadata.get("system_under_test")
&& let Some(s) = value.as_str()
{
return DatabricksVariant::from_metadata_value(s).ok_or_else(|| {
anyhow!(
"Unsupported system_under_test '{s}' for Databricks adapter. Expected databricks-sql or databricks-lakebase"
)
});
}
Ok(DatabricksVariant::Databricks)
}
async fn ensure_uc_schema_exists(&self) -> Result<()> {
let schema_full_name = self.uc_schema_full_name();
let get_url = format!(
"https://{}/api/2.1/unity-catalog/schemas/{schema_full_name}",
self.config.endpoint
);
let get_response = self
.client
.get(get_url)
.bearer_auth(&self.config.token)
.send()
.await?;
if get_response.status() == StatusCode::OK {
return Ok(());
}
if get_response.status() != StatusCode::NOT_FOUND {
let status = get_response.status();
let body = get_response.text().await.unwrap_or_default();
return Err(anyhow!(
"Databricks Unity Catalog schemas/get failed ({status}): {body}"
));
}
let create_url = format!(
"https://{}/api/2.1/unity-catalog/schemas",
self.config.endpoint
);
let create_response = self
.client
.post(create_url)
.bearer_auth(&self.config.token)
.json(&UcSchemaCreateRequest {
catalog_name: self.config.catalog.clone(),
name: self.config.schema.clone(),
})
.send()
.await?;
if !create_response.status().is_success() {
let status = create_response.status();
let body = create_response.text().await.unwrap_or_default();
return Err(anyhow!(
"Databricks Unity Catalog schemas/create failed ({status}): {body}"
));
}
Ok(())
}
async fn execute_sql_statement(&self, statement: &str) -> Result<()> {
let execute_url = format!("https://{}/api/2.0/sql/statements/", self.config.endpoint);
let payload = json!({
"warehouse_id": self.config.warehouse_id,
"catalog": self.config.catalog,
"schema": self.config.schema,
"statement": statement,
"wait_timeout": "20s",
});
let response = self
.client
.post(execute_url)
.bearer_auth(&self.config.token)
.json(&payload)
.send()
.await?;
if response.status() != StatusCode::OK {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(anyhow!(
"Databricks SQL statement execute failed ({status}): {body}"
));
}
let body: StatementResponse = response.json().await?;
match body.status.state {
StatementState::Succeeded => Ok(()),
StatementState::Failed => Err(anyhow!(
"Databricks SQL statement failed: {}",
body.status.error_message()
)),
StatementState::Canceled => Err(anyhow!("Databricks SQL statement canceled")),
StatementState::Pending | StatementState::Running => {
self.wait_for_statement_completion(&body.statement_id).await
}
}
}
async fn delete_job(&self, job_id: i64) -> Result<()> {
let url = format!("https://{}/api/2.1/jobs/delete", self.config.endpoint);
let response = self
.client
.post(&url)
.bearer_auth(&self.config.token)
.json(&json!({ "job_id": job_id }))
.send()
.await?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(anyhow!("Databricks jobs/delete failed ({status}): {body}"));
}
eprintln!("[databricks-adapter] deleted job: job_id={job_id}");
Ok(())
}
async fn find_notebook(&self, notebook_path: &str) -> Result<bool> {
let url = format!(
"https://{}/api/2.0/workspace/get-status",
self.config.endpoint
);
let response = self
.client
.get(&url)
.bearer_auth(&self.config.token)
.query(&[("path", notebook_path)])
.send()
.await?;
if response.status() == StatusCode::NOT_FOUND {
return Ok(false);
}
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(anyhow!(
"Databricks workspace/get-status failed ({status}): {body}"
));
}
Ok(true)
}
async fn delete_notebook(&self, notebook_path: &str) -> Result<()> {
let url = format!("https://{}/api/2.0/workspace/delete", self.config.endpoint);
let response = self
.client
.post(&url)
.bearer_auth(&self.config.token)
.json(&json!({
"path": notebook_path,
"recursive": false
}))
.send()
.await?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(anyhow!(
"Databricks workspace/delete failed ({status}): {body}"
));
}
eprintln!("[databricks-adapter] deleted notebook: path={notebook_path}");
Ok(())
}
async fn wait_for_statement_completion(&self, statement_id: &str) -> Result<()> {
let status_url = format!(
"https://{}/api/2.0/sql/statements/{statement_id}",
self.config.endpoint
);
let deadline = std::time::Instant::now() + Duration::from_secs(180);
loop {
if std::time::Instant::now() > deadline {
return Err(anyhow!(
"Timed out waiting for Databricks SQL statement {statement_id}"
));
}
let response = self
.client
.get(&status_url)
.bearer_auth(&self.config.token)
.send()
.await?;
if response.status() != StatusCode::OK {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(anyhow!(
"Databricks SQL statement status check failed ({status}): {body}"
));
}
let body: StatementResponse = response.json().await?;
match body.status.state {
StatementState::Succeeded => return Ok(()),
StatementState::Failed => {
return Err(anyhow!(
"Databricks SQL statement failed: {}",
body.status.error_message()
));
}
StatementState::Canceled => {
return Err(anyhow!("Databricks SQL statement canceled"));
}
StatementState::Pending | StatementState::Running => {
tokio::time::sleep(Duration::from_millis(750)).await;
}
}
}
}
/// Fire a tagged marker query and wait for it to appear in the Query History
/// API. Once the marker is visible, all earlier queries from this warehouse
/// are also guaranteed to be visible.
///
/// Returns the `query_start_time_ms` of the marker query so the caller can
/// use it as the upper bound for the time window.
async fn fire_marker_and_wait(&self, marker_tag: &str) -> Result<()> {
// Fire a lightweight SELECT that embeds the marker tag in a comment.
let marker_sql = format!("SELECT 1 /* spicebench_marker:{marker_tag} */");
self.execute_sql_statement(&marker_sql).await?;
// Now poll the Query History API until we see a FINISHED query whose
// query_text contains the marker tag.
let deadline = std::time::Instant::now() + Duration::from_secs(600);
let history_url = format!(
"https://{}/api/2.0/sql/history/queries",
self.config.endpoint
);
loop {
if std::time::Instant::now() > deadline {
return Err(anyhow!(
"Timed out (10 min) waiting for marker query to appear in Query History"
));
}
let filter = json!({
"filter_by": {
"warehouse_ids": [self.config.warehouse_id],
"query_text": {
"pattern": format!("spicebench_marker:{marker_tag}")
},
"statuses": ["FINISHED"]
},
"max_results": 1
});
let response = self
.client
.get(&history_url)
.bearer_auth(&self.config.token)
.query(&[("include_metrics", "true")])
.json(&filter)
.send()
.await?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(anyhow!("Query History API failed ({status}): {body}"));
}
let body: QueryHistoryResponse = response.json().await?;
if !body.res.is_empty() {
eprintln!(
"[databricks-adapter] marker query appeared in Query History: tag={marker_tag}"
);
return Ok(());
}
eprintln!(
"[databricks-adapter] waiting for marker query in Query History: tag={marker_tag}"
);
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
/// Sum `read_bytes` and `write_remote_bytes + spill_to_disk_bytes` from query
/// history for all FINISHED queries on this warehouse since `start_time_ms`.
///
/// Uses the REST Query History API (`/api/2.0/sql/history/queries`).
///
/// An alternative is querying `system.query.history` via SQL (see
/// `sum_query_history_io_sql`) which avoids pagination, but requires the
/// service principal to have `USE SCHEMA` on `system.query` — a privilege
/// most workspace-scoped tokens lack.
async fn sum_query_history_io(&self, start_time_ms: u64) -> Result<(u64, u64)> {
self.sum_query_history_io_rest(start_time_ms).await
}