-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeploy.sh
More file actions
executable file
·2827 lines (2627 loc) · 115 KB
/
Copy pathdeploy.sh
File metadata and controls
executable file
·2827 lines (2627 loc) · 115 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
#!/usr/bin/env bash
# =========================================================================
# Databricks Forge — One-command deployment
#
# Usage:
# ./deploy.sh Interactive (pick a warehouse)
# ./deploy.sh --warehouse "Name" Non-interactive
# ./deploy.sh --zero-egress Build locally, package as split archive (no npm install on target)
# ./deploy.sh --full Full sync (default: diff sync — only changed files)
# ./deploy.sh --profile "my-profile" Use a specific CLI profile
# ./deploy.sh --app-name "forge-demo" Deploy as a separate named instance
# ./deploy.sh --destroy Remove the app
#
# Override model endpoints (advanced):
# ./deploy.sh --endpoint "model" --fast-endpoint "fast-model" --review-endpoint "review-model"
# ./deploy.sh --reasoning-endpoint-2 "model" --generation-endpoint "model" --sql-endpoint "model"
# ./deploy.sh --allowed-models "model1,model2"
#
# Lakebase resource binding (auto-provisioned by default):
# ./deploy.sh # auto-provision project = sanitized app-name
# ./deploy.sh --lakebase-project-id "my-project" # auto-provision into a named project
#
# Power-user override (skip auto-provision; use an existing project/branch/database):
# ./deploy.sh --lakebase-branch "projects/<PROJECT_ID>/branches/<BRANCH_ID>"
# --lakebase-database "projects/<PROJECT_ID>/branches/<BRANCH_ID>/databases/<DB_ID>"
#
# Discover existing via:
# databricks postgres list-projects
# databricks postgres list-branches projects/<PROJECT_ID>
# databricks postgres list-databases projects/<PROJECT_ID>/branches/<BRANCH_ID>
#
# Scale-to-zero (Lakebase Autoscaling) — applied to the branch at deploy time:
# ./deploy.sh --lakebase-scale-to-zero-seconds 300 # default
# ./deploy.sh --lakebase-scale-to-zero-seconds 0 # disabled (always-on)
#
# Optional Lakebase bootstrap grants (defaults to deploying user when auto-provisioning):
# ./deploy.sh --lakebase-bootstrap-user "user@company.com"
# ./deploy.sh --lakebase-bootstrap-user "" # explicit opt-out
#
# Destroy flow (interactive prompt + non-interactive flags):
# ./deploy.sh --destroy # prompts about the Lakebase project
# ./deploy.sh --destroy --destroy-database # also delete the project (soft)
# ./deploy.sh --destroy --purge-database # also delete the project (hard / immediate)
# ./deploy.sh --destroy --keep-database # skip the prompt, preserve the project
# Optional benchmark seeding behavior:
# ./deploy.sh --seed-benchmarks --seed-benchmarks-all-industries
# --seed-benchmark-industries "banking,hls,rcg"
# Optional benchmark admin restriction:
# ./deploy.sh --benchmark-admins "alice@company.com,bob@company.com"
# Optional metric views (disabled by default):
# ./deploy.sh --enable-metric-views
# Optional Fabric / Power BI features (disabled by default):
# ./deploy.sh --enable-fabric
# Optional Demo Mode for Field Engineering / Sales (disabled by default):
# ./deploy.sh --enable-demo-mode
# Optional cost governance (both fields are optional; applied only when set):
# ./deploy.sh --budget-policy-id "<policy-id>"
# --tag team=data-eng --tag cost-center=1234
# =========================================================================
set -euo pipefail
# Absolute directory of this script, so sibling helpers resolve correctly no
# matter which working directory the operator invoked deploy.sh from.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# -------------------------------------------------------------------------
# Defaults
# -------------------------------------------------------------------------
APP_NAME="databricks-forge"
APP_DESC="Discover AI-powered use cases from Unity Catalog metadata"
DEFAULT_ENDPOINT="databricks-claude-opus-4-7"
DEFAULT_FAST_ENDPOINT="databricks-claude-sonnet-4-6"
DEFAULT_EMBEDDING_ENDPOINT="databricks-qwen3-embedding-0-6b"
DEFAULT_REVIEW_ENDPOINT="databricks-gpt-5-4"
DEFAULT_REASONING_ENDPOINT_2="databricks-gemini-3-flash"
DEFAULT_GENERATION_ENDPOINT="databricks-llama-4-maverick"
DEFAULT_SQL_ENDPOINT=""
DEFAULT_LIGHTWEIGHT_ENDPOINT="databricks-gemini-3-1-flash-lite"
# -------------------------------------------------------------------------
# State (populated during execution)
# -------------------------------------------------------------------------
USER_EMAIL=""
DATABRICKS_HOST=""
WAREHOUSE_ID=""
WAREHOUSE_NAME=""
WORKSPACE_PATH=""
# -------------------------------------------------------------------------
# Parse arguments
# -------------------------------------------------------------------------
ARG_APP_NAME=""
ARG_WAREHOUSE=""
ARG_PROFILE=""
ARG_ENDPOINT=""
ARG_FAST_ENDPOINT=""
ARG_EMBEDDING_ENDPOINT=""
ARG_REVIEW_ENDPOINT=""
ARG_REASONING_ENDPOINT_2=""
ARG_GENERATION_ENDPOINT=""
ARG_SQL_ENDPOINT=""
ARG_LIGHTWEIGHT_ENDPOINT=""
ARG_ALLOWED_MODELS=""
ARG_LAKEBASE_BOOTSTRAP_USER=""
ARG_LAKEBASE_BOOTSTRAP_USER_SET=false
ARG_LAKEBASE_BRANCH=""
ARG_LAKEBASE_DATABASE=""
ARG_LAKEBASE_PROJECT_ID=""
ARG_LAKEBASE_SCALE_TO_ZERO_SECONDS=""
ARG_LAKEBASE_SCALE_TO_ZERO_SET=false
ARG_DESTROY_DATABASE=false
ARG_PURGE_DATABASE=false
ARG_KEEP_DATABASE=false
ARG_SEED_BENCHMARKS=false
ARG_SEED_BENCHMARKS_ALL_INDUSTRIES=false
ARG_SEED_BENCHMARK_INDUSTRIES=""
ARG_BENCHMARK_ADMINS=""
ARG_ENABLE_METRIC_VIEWS=false
ARG_ENABLE_FABRIC=false
ARG_ENABLE_DEMO_MODE=false
ARG_DISABLE_USER_ISOLATION=false
ARG_MAX_PIPELINE_PER_USER=""
ARG_MAX_SCANS_PER_USER=""
ARG_MAX_GENIE_DEPLOYS_PER_USER=""
ARG_MAX_DEMO_ENGINES_PER_USER=""
ARG_SKIP_PROBE=false
ARG_ZERO_EGRESS=false
ARG_FULL_SYNC=false
ARG_DESTROY=false
ARG_BUDGET_POLICY_ID=""
ARG_TAGS=()
print_usage() {
cat <<'USAGE'
Databricks Forge — One-command deployment
Usage:
./deploy.sh Interactive deployment
./deploy.sh --warehouse "My Warehouse" Skip warehouse prompt
./deploy.sh --profile "my-profile" Use a specific CLI profile
./deploy.sh --destroy Remove the app
Options:
--app-name NAME Custom app name for multi-instance deployments.
Isolates the Databricks App and Lakebase database.
(default: databricks-forge)
--warehouse NAME SQL Warehouse name (skips interactive prompt)
--profile NAME Databricks CLI profile name
--endpoint NAME Premium model endpoint (default: databricks-claude-opus-4-7)
--fast-endpoint NAME Fast model endpoint (default: databricks-claude-sonnet-4-6)
--embedding-endpoint NAME Embedding model endpoint (default: databricks-qwen3-embedding-0-6b)
--review-endpoint NAME Review model endpoint (default: databricks-gpt-5-4)
--reasoning-endpoint-2 NAME Optional second reasoning model for parallel routing
--generation-endpoint NAME Optional generation model endpoint
--sql-endpoint NAME Optional SQL/codex model endpoint
--lightweight-endpoint NAME Optional lightweight/fast-classification model endpoint
--allowed-models CSV Comma-separated list of models the app may use
--lakebase-bootstrap-user EMAIL
Databricks user email to bootstrap with the same
Postgres grants as the app's service principal.
Defaults to the deploying user's email when the
script auto-provisions the Lakebase project on
this run. Pass an empty string to opt out:
--lakebase-bootstrap-user ""
--lakebase-project-id ID Optional override for the auto-provisioned
Lakebase project ID. Defaults to a sanitized
form of --app-name. Ignored when --lakebase-branch
and --lakebase-database are both passed.
--lakebase-branch NAME (Advanced) Lakebase branch resource name. Only
needed to bind an existing, externally-managed
project/branch. Default: auto-resolved from the
app's existing binding, else auto-provisioned.
Format: projects/<PROJECT_ID>/branches/<BRANCH_ID>
--lakebase-database NAME (Advanced) Lakebase database resource name. Only
needed alongside --lakebase-branch to bind an
existing, externally-managed database.
Format: projects/<PROJECT_ID>/branches/<BRANCH_ID>/databases/<DB_ID>
--lakebase-scale-to-zero-seconds N
Inactivity timeout (seconds) before the Lakebase
branch scales to zero. Default: 300 on auto-
provisioned projects, leave existing branches
untouched on re-deploys. Set to 0 to disable
scale-to-zero (always-on; latency-critical prod).
Minimum: 60 (Lakebase floor).
--seed-benchmarks Seed benchmark catalog during app startup
--seed-benchmarks-all-industries
Include generated baseline records for every
industry in lib/domain/industry-outcomes/
--seed-benchmark-industries CSV
Seed only these industry ids (e.g. banking,hls).
Applies to curated packs and generated baselines.
--benchmark-admins CSV Comma-separated emails allowed to manage benchmarks.
If unset, all authenticated users can manage them.
--enable-metric-views Enable metric view generation (off by default)
--enable-fabric Enable Fabric / Power BI features (off by default)
--enable-demo-mode Enable Demo Mode for FE/Sales (off by default)
--disable-user-isolation Run as a single-tenant deployment: per-user
quotas are not enforced and the Sharing UI
is hidden. (Data-layer ownerEmail filters
always apply -- this flag does not roll
back isolation.) Defaults to enabled.
--max-pipeline-runs-per-user N
Per-user cap on concurrent pipeline runs
(default 1). Excess runs are queued and
promoted by the scheduler.
--max-scans-per-user N Per-user cap on concurrent estate scans (default 1).
--max-genie-deploys-per-user N
Per-user cap on concurrent Genie deploys (default 2).
--max-demo-engines-per-user N
Per-user cap on concurrent demo engines (default 1).
--budget-policy-id ID Optional serverless budget policy ID to attach
to the Databricks App and the Lakebase project
for cost attribution. Applied at create time
and reconciled on every subsequent deploy.
--tag KEY=VALUE Optional custom tag (repeatable) applied to the
Databricks App and the Lakebase project for
cost attribution. Example:
--tag team=data-eng --tag cost-center=1234
Passing --tag at least once opts in to tag
management. In that case, two default tags
are injected unless overridden with --tag
<same-key>=<value>:
project=databricks_forge
owner=<user running the deploy>
To opt out of a specific default (e.g. when a
workspace tag policy rejects its value), pass
an empty value: --tag project=
When --tag is not passed at all, no tags are
applied and existing tags on either the App or
the Lakebase project are left untouched.
App tags are written via the workspace
tag-assignments endpoint; Lakebase project tags
via FORGE_CUSTOM_TAGS at runtime.
--skip-probe Skip model availability probing (use defaults without checking).
Useful for air-gapped workspaces or when probing is slow.
--zero-egress Build locally and package as a split archive.
Zero npm install required on the platform -- ideal for
workspaces that block serverless egress.
--full Full sync: upload all files (slower, but guarantees clean state).
Default is diff sync: only upload changed files since last deploy.
--destroy Remove the app and clean up workspace files.
Interactively prompts about deleting the
associated Lakebase project (default: keep).
Non-interactive operation:
--destroy-database delete the project (soft)
--purge-database delete the project (hard)
--keep-database preserve the project, no prompt
--destroy-database Used with --destroy: delete the Lakebase project
(soft delete; recoverable) without prompting.
--purge-database Used with --destroy: hard-delete the Lakebase
project (immediate, unrecoverable). Implies
--destroy-database.
--keep-database Used with --destroy: preserve the Lakebase
project and skip the prompt (useful in CI).
-h, --help Show this help message
Prerequisites:
- Databricks CLI installed (https://docs.databricks.com/dev-tools/cli/install.html)
- Authenticated CLI profile (run: databricks auth login)
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--app-name) ARG_APP_NAME="$2"; shift 2 ;;
--warehouse) ARG_WAREHOUSE="$2"; shift 2 ;;
--profile) ARG_PROFILE="$2"; shift 2 ;;
--endpoint) ARG_ENDPOINT="$2"; shift 2 ;;
--fast-endpoint) ARG_FAST_ENDPOINT="$2"; shift 2 ;;
--embedding-endpoint) ARG_EMBEDDING_ENDPOINT="$2"; shift 2 ;;
--review-endpoint) ARG_REVIEW_ENDPOINT="$2"; shift 2 ;;
--reasoning-endpoint-2) ARG_REASONING_ENDPOINT_2="$2"; shift 2 ;;
--generation-endpoint) ARG_GENERATION_ENDPOINT="$2"; shift 2 ;;
--sql-endpoint) ARG_SQL_ENDPOINT="$2"; shift 2 ;;
--lightweight-endpoint) ARG_LIGHTWEIGHT_ENDPOINT="$2"; shift 2 ;;
--allowed-models) ARG_ALLOWED_MODELS="$2"; shift 2 ;;
--lakebase-bootstrap-user) ARG_LAKEBASE_BOOTSTRAP_USER="$2"; ARG_LAKEBASE_BOOTSTRAP_USER_SET=true; shift 2 ;;
--lakebase-branch) ARG_LAKEBASE_BRANCH="$2"; shift 2 ;;
--lakebase-database) ARG_LAKEBASE_DATABASE="$2"; shift 2 ;;
--lakebase-project-id) ARG_LAKEBASE_PROJECT_ID="$2"; shift 2 ;;
--lakebase-scale-to-zero-seconds) ARG_LAKEBASE_SCALE_TO_ZERO_SECONDS="$2"; ARG_LAKEBASE_SCALE_TO_ZERO_SET=true; shift 2 ;;
--seed-benchmarks) ARG_SEED_BENCHMARKS=true; shift ;;
--seed-benchmarks-all-industries) ARG_SEED_BENCHMARKS_ALL_INDUSTRIES=true; shift ;;
--seed-benchmark-industries) ARG_SEED_BENCHMARK_INDUSTRIES="$2"; shift 2 ;;
--benchmark-admins) ARG_BENCHMARK_ADMINS="$2"; shift 2 ;;
--enable-metric-views) ARG_ENABLE_METRIC_VIEWS=true; shift ;;
--enable-fabric) ARG_ENABLE_FABRIC=true; shift ;;
--enable-demo-mode) ARG_ENABLE_DEMO_MODE=true; shift ;;
--disable-user-isolation) ARG_DISABLE_USER_ISOLATION=true; shift ;;
--max-pipeline-runs-per-user) ARG_MAX_PIPELINE_PER_USER="$2"; shift 2 ;;
--max-scans-per-user) ARG_MAX_SCANS_PER_USER="$2"; shift 2 ;;
--max-genie-deploys-per-user) ARG_MAX_GENIE_DEPLOYS_PER_USER="$2"; shift 2 ;;
--max-demo-engines-per-user) ARG_MAX_DEMO_ENGINES_PER_USER="$2"; shift 2 ;;
--budget-policy-id) ARG_BUDGET_POLICY_ID="$2"; shift 2 ;;
--tag) ARG_TAGS+=("$2"); shift 2 ;;
--skip-probe) ARG_SKIP_PROBE=true; shift ;;
--zero-egress) ARG_ZERO_EGRESS=true; shift ;;
--full) ARG_FULL_SYNC=true; shift ;;
--destroy) ARG_DESTROY=true; shift ;;
--destroy-database) ARG_DESTROY_DATABASE=true; shift ;;
--purge-database) ARG_PURGE_DATABASE=true; ARG_DESTROY_DATABASE=true; shift ;;
--keep-database) ARG_KEEP_DATABASE=true; shift ;;
-h|--help) print_usage; exit 0 ;;
*) printf "\n ERROR: Unknown flag: %s\n Run ./deploy.sh --help\n\n" "$1" >&2; exit 1 ;;
esac
done
if [[ -n "$ARG_APP_NAME" ]]; then
APP_NAME="$ARG_APP_NAME"
fi
if [[ -n "$ARG_PROFILE" ]]; then
export DATABRICKS_CONFIG_PROFILE="$ARG_PROFILE"
fi
# -------------------------------------------------------------------------
# Output helpers (defined early so flag-validation guards below can call die).
# -------------------------------------------------------------------------
die() { printf "\n ERROR: %s\n\n" "$1" >&2; exit 1; }
warn() { printf "\n WARN: %s\n" "$1" >&2; }
info() { printf " %-48s" "$1"; }
ok() { if [ -n "${1:-}" ]; then printf "OK (%s)\n" "$1"; else printf "OK\n"; fi; }
# Extract a value from JSON via Python 3.
# Usage: echo '{"k":"v"}' | json_val "['k']"
json_val() { python3 -c "import sys,json; print(json.load(sys.stdin)$1)"; }
ENDPOINT="${ARG_ENDPOINT:-$DEFAULT_ENDPOINT}"
FAST_ENDPOINT="${ARG_FAST_ENDPOINT:-$DEFAULT_FAST_ENDPOINT}"
EMBEDDING_ENDPOINT="${ARG_EMBEDDING_ENDPOINT:-$DEFAULT_EMBEDDING_ENDPOINT}"
REVIEW_ENDPOINT="${ARG_REVIEW_ENDPOINT:-$DEFAULT_REVIEW_ENDPOINT}"
REASONING_ENDPOINT_2="${ARG_REASONING_ENDPOINT_2:-$DEFAULT_REASONING_ENDPOINT_2}"
GENERATION_ENDPOINT="${ARG_GENERATION_ENDPOINT:-$DEFAULT_GENERATION_ENDPOINT}"
SQL_ENDPOINT="${ARG_SQL_ENDPOINT:-$DEFAULT_SQL_ENDPOINT}"
LIGHTWEIGHT_ENDPOINT="${ARG_LIGHTWEIGHT_ENDPOINT:-$DEFAULT_LIGHTWEIGHT_ENDPOINT}"
ALLOWED_MODELS="${ARG_ALLOWED_MODELS:-}"
LAKEBASE_BOOTSTRAP_USER="${ARG_LAKEBASE_BOOTSTRAP_USER:-}"
LAKEBASE_BOOTSTRAP_USER_SET="${ARG_LAKEBASE_BOOTSTRAP_USER_SET}"
LAKEBASE_BRANCH="${ARG_LAKEBASE_BRANCH:-}"
LAKEBASE_DATABASE="${ARG_LAKEBASE_DATABASE:-}"
LAKEBASE_PROJECT_ID="${ARG_LAKEBASE_PROJECT_ID:-}"
LAKEBASE_SCALE_TO_ZERO_SECONDS="${ARG_LAKEBASE_SCALE_TO_ZERO_SECONDS:-}"
LAKEBASE_SCALE_TO_ZERO_SET="${ARG_LAKEBASE_SCALE_TO_ZERO_SET}"
LAKEBASE_AUTOPROVISIONED=false
LAKEBASE_ENDPOINT_PATH=""
DESTROY_DATABASE="${ARG_DESTROY_DATABASE}"
PURGE_DATABASE="${ARG_PURGE_DATABASE}"
KEEP_DATABASE="${ARG_KEEP_DATABASE}"
SEED_BENCHMARKS="${ARG_SEED_BENCHMARKS}"
SEED_BENCHMARKS_ALL_INDUSTRIES="${ARG_SEED_BENCHMARKS_ALL_INDUSTRIES}"
SEED_BENCHMARK_INDUSTRIES="${ARG_SEED_BENCHMARK_INDUSTRIES:-}"
BENCHMARK_ADMINS="${ARG_BENCHMARK_ADMINS:-}"
ENABLE_METRIC_VIEWS="${ARG_ENABLE_METRIC_VIEWS}"
ENABLE_FABRIC="${ARG_ENABLE_FABRIC}"
ENABLE_DEMO_MODE="${ARG_ENABLE_DEMO_MODE}"
DISABLE_USER_ISOLATION="${ARG_DISABLE_USER_ISOLATION}"
MAX_PIPELINE_PER_USER="${ARG_MAX_PIPELINE_PER_USER}"
MAX_SCANS_PER_USER="${ARG_MAX_SCANS_PER_USER}"
MAX_GENIE_DEPLOYS_PER_USER="${ARG_MAX_GENIE_DEPLOYS_PER_USER}"
MAX_DEMO_ENGINES_PER_USER="${ARG_MAX_DEMO_ENGINES_PER_USER}"
# -------------------------------------------------------------------------
# Cost governance (all optional). BUDGET_POLICY_ID is applied to the
# Databricks App and propagated to the Lakebase project. CUSTOM_TAGS_JSON
# is a JSON array of {key, value} objects applied only to the Lakebase
# project (the Databricks Apps API does not accept tags on the App).
#
# Two default tags are injected unless overridden by --tag with the same
# key: project=databricks_forge and owner=<user running the deploy>.
# The owner tag is skipped when USER_EMAIL could not be resolved. The
# JSON is built inside build_custom_tags_json() after USER_EMAIL is
# populated by check_prerequisites; here we only validate the raw input.
# -------------------------------------------------------------------------
BUDGET_POLICY_ID="${ARG_BUDGET_POLICY_ID:-}"
CUSTOM_TAGS_JSON=""
if [[ ${#ARG_TAGS[@]} -gt 0 ]]; then
ARG_TAGS_RAW="$(printf '%s\n' "${ARG_TAGS[@]}")" python3 - <<'PY'
import os, sys
raw = os.environ.get("ARG_TAGS_RAW", "").splitlines()
seen = set()
for entry in raw:
entry = entry.strip()
if not entry:
continue
if "=" not in entry:
sys.stderr.write(f"ERROR: --tag expects KEY=VALUE, got: {entry!r}\n")
sys.exit(1)
key, _ = entry.split("=", 1)
key = key.strip()
if not key:
sys.stderr.write(f"ERROR: --tag has empty key in: {entry!r}\n")
sys.exit(1)
if key in seen:
sys.stderr.write(f"ERROR: duplicate --tag key: {key}\n")
sys.exit(1)
seen.add(key)
PY
if [[ $? -ne 0 ]]; then
printf "\n ERROR: Failed to parse --tag arguments. Expected KEY=VALUE per flag.\n\n" >&2
exit 1
fi
fi
if [[ "$SEED_BENCHMARKS_ALL_INDUSTRIES" = "true" && "$SEED_BENCHMARKS" != "true" ]]; then
SEED_BENCHMARKS=true
fi
if [[ -n "$SEED_BENCHMARK_INDUSTRIES" && "$SEED_BENCHMARKS" != "true" ]]; then
SEED_BENCHMARKS=true
fi
if [[ -n "$LAKEBASE_BRANCH" && -z "$LAKEBASE_DATABASE" ]] || \
[[ -z "$LAKEBASE_BRANCH" && -n "$LAKEBASE_DATABASE" ]]; then
die "--lakebase-branch and --lakebase-database must be provided together."
fi
if [[ -n "$LAKEBASE_BRANCH" ]]; then
case "$LAKEBASE_BRANCH" in
projects/*/branches/*) ;;
*)
die "Invalid --lakebase-branch '$LAKEBASE_BRANCH'. Expected: projects/<id>/branches/<id>"
;;
esac
fi
if [[ -n "$LAKEBASE_DATABASE" ]]; then
case "$LAKEBASE_DATABASE" in
projects/*/branches/*/databases/*) ;;
*)
die "Invalid --lakebase-database '$LAKEBASE_DATABASE'. Expected: projects/<id>/branches/<id>/databases/<id>"
;;
esac
fi
# Validate scale-to-zero flag (when passed): integer >= 0; non-zero values
# must respect the Lakebase floor of 60 seconds.
if [[ "$LAKEBASE_SCALE_TO_ZERO_SET" = "true" ]]; then
if ! [[ "$LAKEBASE_SCALE_TO_ZERO_SECONDS" =~ ^[0-9]+$ ]]; then
die "--lakebase-scale-to-zero-seconds must be a non-negative integer (got '$LAKEBASE_SCALE_TO_ZERO_SECONDS')."
fi
if [[ "$LAKEBASE_SCALE_TO_ZERO_SECONDS" -gt 0 && "$LAKEBASE_SCALE_TO_ZERO_SECONDS" -lt 60 ]]; then
die "--lakebase-scale-to-zero-seconds must be 0 (disabled) or >= 60 (Lakebase floor). Got: $LAKEBASE_SCALE_TO_ZERO_SECONDS"
fi
fi
# Destroy-database flag conflict guard.
if [[ "$DESTROY_DATABASE" = "true" && "$KEEP_DATABASE" = "true" ]]; then
die "--destroy-database / --purge-database conflict with --keep-database. Pick one."
fi
# These flags are only meaningful with --destroy.
if [[ "$ARG_DESTROY" != "true" ]]; then
if [[ "$DESTROY_DATABASE" = "true" || "$PURGE_DATABASE" = "true" || "$KEEP_DATABASE" = "true" ]]; then
die "--destroy-database / --purge-database / --keep-database only apply with --destroy."
fi
fi
# --lakebase-project-id is only meaningful when we auto-provision. If the
# operator also passed --lakebase-branch (i.e. opted into manual binding),
# the project-id override is ignored — surface that immediately rather than
# silently dropping it.
if [[ -n "$LAKEBASE_PROJECT_ID" && -n "$LAKEBASE_BRANCH" ]]; then
die "--lakebase-project-id is only valid for auto-provisioned deploys. It cannot be combined with --lakebase-branch/--lakebase-database; the project is implied by the branch path."
fi
# -------------------------------------------------------------------------
# Model endpoint probing and fallback
#
# Before binding endpoints, verify each model exists in the workspace.
# If a preferred model is unavailable, walk a fallback chain of alternatives
# until one is found. This handles cross-region/cloud model availability
# differences silently.
# -------------------------------------------------------------------------
source "$SCRIPT_DIR/scripts/deploy-endpoint-selection.sh"
# Check if a serving endpoint exists. Returns 0 if available, 1 otherwise.
probe_endpoint() {
local name="$1"
if [ -z "$name" ]; then return 1; fi
databricks serving-endpoints get "$name" --output json &>/dev/null
}
# Probe all endpoint roles and resolve to best available.
# Skips probing for roles where the user provided an explicit --flag override.
# Sets the global ENDPOINT, FAST_ENDPOINT, etc. variables.
probe_and_resolve_endpoints() {
if [ "$ARG_SKIP_PROBE" = "true" ]; then
printf "\n Model probing skipped (--skip-probe).\n"
return
fi
printf "\n Probing model availability...\n"
local resolved="" preferred="" label="" selection_status=0 did_fallback=false
# Helper: probe a role and print status
# Usage: probe_role "Label" "required|optional" "user_override" "fallback chain" VARNAME
probe_role() {
local role_label="$1"
local requirement="$2"
local user_override="$3"
local chain="$4"
local varname="$5"
if [ -n "$user_override" ]; then
printf " %-20s %s (user override)\n" "$role_label:" "$user_override"
assign_endpoint_var "$varname" "$user_override"
return
fi
preferred="${chain%% *}"
if resolved=$(select_endpoint_for_role "$requirement" "$chain"); then
selection_status=0
else
selection_status=$?
fi
if [ "$selection_status" -eq 0 ]; then
if [ "$resolved" != "$preferred" ]; then
printf " %-20s %s → %s\n" "$role_label:" "$preferred" "$resolved"
did_fallback=true
else
printf " %-20s %s\n" "$role_label:" "$preferred"
fi
assign_endpoint_var "$varname" "$resolved"
elif [ "$selection_status" -eq 2 ]; then
printf " %-20s %s (all probes failed; retaining required-role default)\n" "$role_label:" "$preferred"
assign_endpoint_var "$varname" "$resolved"
else
printf " %-20s %s (all probes failed; optional role not bound)\n" "$role_label:" "$preferred"
assign_endpoint_var "$varname" ""
fi
}
probe_role "Primary" "required" "$ARG_ENDPOINT" \
"databricks-claude-opus-4-7 databricks-claude-opus-4-6 databricks-claude-opus-4-5 databricks-gpt-5-4 databricks-claude-sonnet-4-6" \
ENDPOINT
probe_role "Fast" "required" "$ARG_FAST_ENDPOINT" \
"databricks-claude-sonnet-4-6 databricks-claude-sonnet-4-5 databricks-gemini-3-flash databricks-gemini-3-1-flash-lite" \
FAST_ENDPOINT
probe_role "Review" "required" "$ARG_REVIEW_ENDPOINT" \
"databricks-gpt-5-4 databricks-claude-opus-4-7 databricks-claude-opus-4-6 databricks-claude-sonnet-4-6" \
REVIEW_ENDPOINT
probe_role "Embedding" "required" "$ARG_EMBEDDING_ENDPOINT" \
"databricks-qwen3-embedding-0-6b" \
EMBEDDING_ENDPOINT
probe_role "Reasoning2" "optional" "$ARG_REASONING_ENDPOINT_2" \
"databricks-gemini-3-flash databricks-gemini-3-1-flash-lite databricks-llama-4-maverick" \
REASONING_ENDPOINT_2
probe_role "Generation" "optional" "$ARG_GENERATION_ENDPOINT" \
"databricks-llama-4-maverick databricks-gemini-3-flash databricks-gemini-3-1-flash-lite databricks-claude-sonnet-4-6" \
GENERATION_ENDPOINT
probe_role "Lightweight" "optional" "$ARG_LIGHTWEIGHT_ENDPOINT" \
"databricks-gemini-3-1-flash-lite databricks-gemini-3-flash databricks-claude-sonnet-4-5" \
LIGHTWEIGHT_ENDPOINT
if [ -n "$ARG_SQL_ENDPOINT" ]; then
printf " %-20s %s (user override)\n" "SQL:" "$ARG_SQL_ENDPOINT"
SQL_ENDPOINT="$ARG_SQL_ENDPOINT"
fi
if [ "$did_fallback" = true ]; then
printf "\n Some models were substituted. The app adapts automatically.\n"
printf " Use explicit --endpoint flags to override selections.\n"
fi
}
get_app_compute_state() {
local app_json
if ! app_json=$(databricks apps get "$APP_NAME" --output json 2>/dev/null); then
echo "MISSING"
return
fi
echo "$app_json" | python3 -c "import sys,json; print(json.load(sys.stdin).get('compute_status',{}).get('state','UNKNOWN'))" 2>/dev/null || echo "UNKNOWN"
}
wait_for_app_absent() {
local attempts=0
local max_attempts=90
local sleep_secs=10
local state
local last_logged_state=""
info "Waiting for app deletion (up to 15 min)..."
while [ $attempts -lt $max_attempts ]; do
state="$(get_app_compute_state)"
if [ "$state" = "MISSING" ]; then
ok "deleted"
return 0
fi
if [ "$state" != "$last_logged_state" ]; then
printf "\n app compute: %s (waiting)\n" "$state" >&2
last_logged_state="$state"
fi
sleep "$sleep_secs"
attempts=$((attempts + 1))
done
printf "TIMEOUT\n"
return 1
}
APP_YAML_BACKUP=""
DEPLOY_SHELL_PID=""
install_app_yaml_restore_traps() {
# $$ is intentionally not sufficient here: Bash keeps $$ stable in command
# substitutions. BASHPID identifies the actual shell process on Bash 4+,
# while BASH_SUBSHELL below covers normal subshell execution on older Bash
# versions. Bash 3.2 resets EXIT traps in command substitutions by default.
DEPLOY_SHELL_PID="${BASHPID:-$$}"
trap restore_app_yaml EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
}
# -------------------------------------------------------------------------
# Merge default tags (project, owner) with user-provided --tag values and
# serialize to CUSTOM_TAGS_JSON. User-provided tags override defaults on
# key collision. The owner tag is skipped when USER_EMAIL is empty.
#
# Opt-in contract: this function is a no-op unless the user passed at
# least one --tag flag. A plain `./deploy.sh` run (or one with only
# --budget-policy-id) leaves CUSTOM_TAGS_JSON empty, which keeps
# FORGE_CUSTOM_TAGS unset in app.yaml and tells the Lakebase runtime
# to skip both create-time and reconcile-time tag operations.
# Call order: after check_prerequisites (which sets USER_EMAIL) and
# before prepare_app_yaml (which consumes CUSTOM_TAGS_JSON).
# -------------------------------------------------------------------------
build_custom_tags_json() {
CUSTOM_TAGS_JSON=""
if [[ ${#ARG_TAGS[@]} -eq 0 ]]; then
return
fi
CUSTOM_TAGS_JSON=$(USER_EMAIL="$USER_EMAIL" \
ARG_TAGS_RAW="$(printf '%s\n' "${ARG_TAGS[@]}")" python3 - <<'PY'
import json, os
user_email = os.environ.get("USER_EMAIL", "").strip()
raw = os.environ.get("ARG_TAGS_RAW", "").splitlines()
# Defaults are inserted first so user --tag with the same key overrides them.
defaults = [{"key": "project", "value": "databricks_forge"}]
if user_email:
defaults.append({"key": "owner", "value": user_email})
merged = {t["key"]: t["value"] for t in defaults}
for entry in raw:
entry = entry.strip()
if not entry or "=" not in entry:
continue
key, value = entry.split("=", 1)
key = key.strip()
value = value.strip()
# Empty value opts out of a default (or no-ops a user-provided key).
if value == "":
merged.pop(key, None)
continue
merged[key] = value
tags = [{"key": k, "value": v} for k, v in merged.items()]
print(json.dumps(tags, separators=(",", ":")))
PY
)
}
prepare_app_yaml() {
# Back up and patch app.yaml with instance-specific env vars for syncing.
# The Python matcher below strips known managed entries before re-appending
# them, so we patch directly on top of the working tree (including any
# uncommitted local edits). This lets operators run deploy.sh against an
# in-progress branch without losing their refactor work to a `git checkout`.
APP_YAML_BACKUP="$(mktemp)"
cp "app.yaml" "$APP_YAML_BACKUP"
# Discover the Lakebase endpoint resource path so we can inject
# LAKEBASE_ENDPOINT as a static env var. The Apps platform auto-injects
# PGHOST/PGUSER/PGDATABASE/PGPORT/PGSSLMODE from the `postgres` resource
# binding, but NOT the endpoint resource path — that has to come from
# `databricks postgres list-endpoints` against the bound branch.
# Reuse the endpoint path resolved by resolve_lakebase_binding(). If for
# some reason it wasn't populated (e.g. someone called prepare_app_yaml
# in isolation), fall back to discovery here.
LAKEBASE_ENDPOINT_NAME="$LAKEBASE_ENDPOINT_PATH"
if [ -z "$LAKEBASE_ENDPOINT_NAME" ] && [ -n "$LAKEBASE_BRANCH" ]; then
info "Discovering Lakebase endpoint on $LAKEBASE_BRANCH..."
resolve_lakebase_endpoint_path "$LAKEBASE_BRANCH"
LAKEBASE_ENDPOINT_NAME="$LAKEBASE_ENDPOINT_PATH"
ok "$LAKEBASE_ENDPOINT_NAME"
fi
# The deploying user is auto-seeded as the first Portfolio (CDO) org-admin so
# the cross-estate portfolio works with zero config; they can then grant
# access to others from the UI without a redeploy. Prefer the deployer's
# email, fall back to the Lakebase bootstrap user.
PORTFOLIO_BOOTSTRAP_ADMIN="${USER_EMAIL:-${LAKEBASE_BOOTSTRAP_USER:-}}"
export APP_NAME
export LAKEBASE_BOOTSTRAP_USER
export PORTFOLIO_BOOTSTRAP_ADMIN
export LAKEBASE_ENDPOINT_NAME
export SEED_BENCHMARKS
export SEED_BENCHMARKS_ALL_INDUSTRIES
export SEED_BENCHMARK_INDUSTRIES
export BENCHMARK_ADMINS
export ENABLE_METRIC_VIEWS
export ENABLE_FABRIC
export ENABLE_DEMO_MODE
export DISABLE_USER_ISOLATION
export MAX_PIPELINE_PER_USER
export MAX_SCANS_PER_USER
export MAX_GENIE_DEPLOYS_PER_USER
export MAX_DEMO_ENGINES_PER_USER
export REASONING_ENDPOINT_2
export GENERATION_ENDPOINT
export SQL_ENDPOINT
export LIGHTWEIGHT_ENDPOINT
export ALLOWED_MODELS
export BUDGET_POLICY_ID
export CUSTOM_TAGS_JSON
python3 - <<'PY'
import os
from pathlib import Path
app_name = os.environ.get("APP_NAME", "databricks-forge").strip()
bootstrap_user = os.environ.get("LAKEBASE_BOOTSTRAP_USER", "").strip()
portfolio_bootstrap_admin = os.environ.get("PORTFOLIO_BOOTSTRAP_ADMIN", "").strip()
lakebase_endpoint_name = os.environ.get("LAKEBASE_ENDPOINT_NAME", "").strip()
seed_benchmarks = os.environ.get("SEED_BENCHMARKS", "").strip().lower() == "true"
seed_benchmarks_all = os.environ.get("SEED_BENCHMARKS_ALL_INDUSTRIES", "").strip().lower() == "true"
seed_benchmark_industries = os.environ.get("SEED_BENCHMARK_INDUSTRIES", "").strip()
benchmark_admins = os.environ.get("BENCHMARK_ADMINS", "").strip()
enable_metric_views = os.environ.get("ENABLE_METRIC_VIEWS", "").strip().lower() == "true"
enable_fabric = os.environ.get("ENABLE_FABRIC", "").strip().lower() == "true"
enable_demo_mode = os.environ.get("ENABLE_DEMO_MODE", "").strip().lower() == "true"
disable_user_isolation = os.environ.get("DISABLE_USER_ISOLATION", "").strip().lower() == "true"
max_pipeline_per_user = os.environ.get("MAX_PIPELINE_PER_USER", "").strip()
max_scans_per_user = os.environ.get("MAX_SCANS_PER_USER", "").strip()
max_genie_deploys_per_user = os.environ.get("MAX_GENIE_DEPLOYS_PER_USER", "").strip()
max_demo_engines_per_user = os.environ.get("MAX_DEMO_ENGINES_PER_USER", "").strip()
reasoning_endpoint_2 = os.environ.get("REASONING_ENDPOINT_2", "").strip()
generation_endpoint = os.environ.get("GENERATION_ENDPOINT", "").strip()
sql_endpoint = os.environ.get("SQL_ENDPOINT", "").strip()
lightweight_endpoint = os.environ.get("LIGHTWEIGHT_ENDPOINT", "").strip()
allowed_models = os.environ.get("ALLOWED_MODELS", "").strip()
budget_policy_id = os.environ.get("BUDGET_POLICY_ID", "").strip()
custom_tags_json = os.environ.get("CUSTOM_TAGS_JSON", "").strip()
path = Path("app.yaml")
lines = path.read_text().splitlines()
out: list[str] = []
i = 0
def is_managed_name_line(s: str) -> bool:
t = s.strip()
if not t.startswith("- name:"):
return False
return (
"FORGE_APP_NAME" in t
or "LAKEBASE_BOOTSTRAP_USER" in t
or "FORGE_PORTFOLIO_BOOTSTRAP_ADMIN" in t
or "LAKEBASE_ENDPOINT" in t
# Legacy env vars retired by the OAuth-only refactor.
# Listed here so any stale entry in a pre-refactor app.yaml gets
# stripped on the transition deploy and does not leak into the
# app's environment.
or "LAKEBASE_AUTH_MODE" in t
or "LAKEBASE_NATIVE_USER" in t
or "LAKEBASE_NATIVE_PASSWORD" in t
or "LAKEBASE_RUNTIME_MODE" in t
or "LAKEBASE_ENABLE_POOLER_EXPERIMENT" in t
or "LAKEBASE_SCALE_TO_ZERO_TIMEOUT" in t
or "FORGE_SEED_BENCHMARKS" in t
or "FORGE_SEED_BENCHMARKS_ALL_INDUSTRIES" in t
or "FORGE_SEED_BENCHMARK_INDUSTRIES" in t
or "FORGE_BENCHMARK_ADMINS" in t
or "FORGE_METRIC_VIEWS_ENABLED" in t
or "FORGE_FABRIC_ENABLED" in t
or "FORGE_DEMO_MODE_ENABLED" in t
or "FORGE_USER_ISOLATION" in t
or "FORGE_MAX_ACTIVE_PIPELINE_RUNS_PER_USER" in t
or "FORGE_MAX_ACTIVE_SCANS_PER_USER" in t
or "FORGE_MAX_ACTIVE_GENIE_DEPLOYS_PER_USER" in t
or "FORGE_MAX_ACTIVE_DEMO_ENGINES_PER_USER" in t
or "DATABRICKS_SERVING_ENDPOINT_REASONING_2" in t
or "DATABRICKS_SERVING_ENDPOINT_GENERATION" in t
or "DATABRICKS_SERVING_ENDPOINT_SQL" in t
or "DATABRICKS_SERVING_ENDPOINT_LIGHTWEIGHT" in t
or "DATABRICKS_ALLOWED_MODELS" in t
or "FORGE_BUDGET_POLICY_ID" in t
or "FORGE_CUSTOM_TAGS" in t
)
while i < len(lines):
line = lines[i]
if is_managed_name_line(line):
i += 1
while i < len(lines):
nxt = lines[i]
if nxt.startswith(" - name:"):
break
i += 1
continue
out.append(line)
i += 1
if app_name != "databricks-forge":
out.append(" - name: FORGE_APP_NAME")
out.append(f' value: "{app_name}"')
if bootstrap_user:
out.append(" - name: LAKEBASE_BOOTSTRAP_USER")
out.append(f' value: "{bootstrap_user}"')
if portfolio_bootstrap_admin:
out.append(" - name: FORGE_PORTFOLIO_BOOTSTRAP_ADMIN")
out.append(f' value: "{portfolio_bootstrap_admin}"')
if lakebase_endpoint_name:
out.append(" - name: LAKEBASE_ENDPOINT")
out.append(f' value: "{lakebase_endpoint_name}"')
out.append(" - name: FORGE_SEED_BENCHMARKS")
out.append(f' value: "{"true" if seed_benchmarks else "false"}"')
out.append(" - name: FORGE_SEED_BENCHMARKS_ALL_INDUSTRIES")
out.append(f' value: "{"true" if seed_benchmarks_all else "false"}"')
if seed_benchmark_industries:
out.append(" - name: FORGE_SEED_BENCHMARK_INDUSTRIES")
out.append(f' value: "{seed_benchmark_industries}"')
if benchmark_admins:
out.append(" - name: FORGE_BENCHMARK_ADMINS")
out.append(f' value: "{benchmark_admins}"')
if enable_metric_views:
out.append(" - name: FORGE_METRIC_VIEWS_ENABLED")
out.append(' value: "true"')
if enable_fabric:
out.append(" - name: FORGE_FABRIC_ENABLED")
out.append(' value: "true"')
if enable_demo_mode:
out.append(" - name: FORGE_DEMO_MODE_ENABLED")
out.append(' value: "true"')
if disable_user_isolation:
out.append(" - name: FORGE_USER_ISOLATION")
out.append(' value: "false"')
if max_pipeline_per_user:
out.append(" - name: FORGE_MAX_ACTIVE_PIPELINE_RUNS_PER_USER")
out.append(f' value: "{max_pipeline_per_user}"')
if max_scans_per_user:
out.append(" - name: FORGE_MAX_ACTIVE_SCANS_PER_USER")
out.append(f' value: "{max_scans_per_user}"')
if max_genie_deploys_per_user:
out.append(" - name: FORGE_MAX_ACTIVE_GENIE_DEPLOYS_PER_USER")
out.append(f' value: "{max_genie_deploys_per_user}"')
if max_demo_engines_per_user:
out.append(" - name: FORGE_MAX_ACTIVE_DEMO_ENGINES_PER_USER")
out.append(f' value: "{max_demo_engines_per_user}"')
if reasoning_endpoint_2:
out.append(" - name: DATABRICKS_SERVING_ENDPOINT_REASONING_2")
out.append(" valueFrom: serving-endpoint-reasoning-2")
if generation_endpoint:
out.append(" - name: DATABRICKS_SERVING_ENDPOINT_GENERATION")
out.append(" valueFrom: serving-endpoint-generation")
if sql_endpoint:
out.append(" - name: DATABRICKS_SERVING_ENDPOINT_SQL")
out.append(" valueFrom: serving-endpoint-sql")
if lightweight_endpoint:
out.append(" - name: DATABRICKS_SERVING_ENDPOINT_LIGHTWEIGHT")
out.append(" valueFrom: serving-endpoint-lightweight")
if allowed_models:
out.append(" - name: DATABRICKS_ALLOWED_MODELS")
out.append(f' value: "{allowed_models}"')
if budget_policy_id:
out.append(" - name: FORGE_BUDGET_POLICY_ID")
out.append(f' value: "{budget_policy_id}"')
if custom_tags_json:
# Serialize as a single-line JSON value; escape any embedded double quotes
# so the YAML remains valid. Consumed at runtime by provision.ts.
escaped = custom_tags_json.replace('"', '\\"')
out.append(" - name: FORGE_CUSTOM_TAGS")
out.append(f' value: "{escaped}"')
path.write_text("\n".join(out) + "\n")
PY
}
restore_app_yaml() {
local current_shell_pid="${BASHPID:-$$}"
if [ -z "$DEPLOY_SHELL_PID" ] \
|| [ "$current_shell_pid" != "$DEPLOY_SHELL_PID" ] \
|| [ "${BASH_SUBSHELL:-0}" -ne 0 ]; then
return 0
fi
if [ -n "$APP_YAML_BACKUP" ] && [ -f "$APP_YAML_BACKUP" ]; then
mv "$APP_YAML_BACKUP" "app.yaml"
APP_YAML_BACKUP=""
fi
}
# -------------------------------------------------------------------------
# Zero-egress package assembly
#
# Builds the Next.js standalone bundle locally, then packages it as a
# split tar.gz archive that requires ZERO npm install on the platform.
# Designed for workspaces that block serverless egress.
#
# The deploy wrapper contains only:
# - app.yaml (command: sh bootstrap.sh)
# - bootstrap.sh (reassembles archive, extracts, delegates to start.sh)
# - bundle.tar.gz.part-* (split archive chunks, each <10MB)
# - .prebuilt marker file
#
# Inside the archive:
# - server.js + .next/ (Next.js standalone app)
# - node_modules/ (pruned runtime deps + prisma CLI with linux engine)
# - public/ + .next/static/ (static assets)
# - scripts/ (start.sh, provision-lakebase.mjs, etc.)
# - prisma/ + prisma.config.ts
# - data/benchmark/*.json (optional)
# -------------------------------------------------------------------------
DEPLOY_PKG=".deploy-pkg"
DEPLOY_WRAPPER=".deploy-pkg-ze"
CHUNK_SIZE_MB=9
create_zero_egress_archive() {
local bundle_path="$1"
if [ "$(uname -s)" != "Darwin" ]; then
if ! COPYFILE_DISABLE=1 tar -czf "$bundle_path" -C "$DEPLOY_PKG" .; then
die "Failed to create zero-egress archive."
fi
return 0
fi
# macOS 15 protects com.apple.provenance from removal even when xattr -d/-c
# reports success. BSD tar's --no-xattrs prevents those attributes from
# becoming LIBARCHIVE.xattr.* pax headers in the archive.
if ! COPYFILE_DISABLE=1 tar --no-xattrs -czf "$bundle_path" -C "$DEPLOY_PKG" .; then
die "Failed to create zero-egress archive."
fi
}
assemble_zero_egress() {
printf "\n Assembling zero-egress deploy package...\n"
# -- Install Linux sharp binaries for cross-platform build ---------------
info "Installing Linux sharp binaries..."
if npm install --no-save --no-audit --no-fund --force \
@img/sharp-linux-x64 @img/sharp-libvips-linux-x64 2>/dev/null; then
ok
else
ok "skipped (non-critical)"
fi
# -- Local build ---------------------------------------------------------
info "Building locally (prisma generate + next build)..."
if ! npm run build 2>&1 | tail -3; then
die "Local build failed. Fix errors and retry."
fi
ok
# -- Locate standalone root (Next.js nests it under the project path) ----
local standalone_root=".next/standalone"
local nested
nested=$(find "$standalone_root" -name "server.js" -maxdepth 6 -not -path "*/node_modules/*" | head -1)
if [ -z "$nested" ]; then
die "server.js not found in $standalone_root. Build may have failed."
fi
local standalone_app_dir
standalone_app_dir=$(dirname "$nested")
# -- Clean and create deploy package directory ---------------------------
info "Assembling $DEPLOY_PKG/..."
rm -rf "$DEPLOY_PKG" "$DEPLOY_WRAPPER"
mkdir -p "$DEPLOY_PKG"
cp -a "$standalone_app_dir/." "$DEPLOY_PKG/"
rm -rf "$DEPLOY_PKG/public"
if [ -d "$standalone_root/public" ]; then
cp -a "$standalone_root/public" "$DEPLOY_PKG/public"
fi
if [ -d "$standalone_root/.next/static" ]; then
mkdir -p "$DEPLOY_PKG/.next"
cp -a "$standalone_root/.next/static" "$DEPLOY_PKG/.next/static"
fi
# -- Resolve Turbopack hashed external modules ----------------------------
# Turbopack creates .next/node_modules/ with symlinks like:
# pg-61d4919a4f0d7081 -> ../../node_modules/pg
# These are hashed package names used in server chunks. We must:
# 1. Copy the hashed entries as real directories (dereference symlinks)
# 2. Copy their transitive deps into the root node_modules/
if [ -d ".next/node_modules" ]; then
info "Resolving Turbopack externals..."
# Remove the standalone's copy (contains broken symlinks to dev machine)
rm -rf "$DEPLOY_PKG/.next/node_modules"
# Re-copy with -L to dereference symlinks into real directories
cp -aL ".next/node_modules" "$DEPLOY_PKG/.next/node_modules"