Repository navigation
Expand file tree
/
Copy pathcloudbuild.yaml
More file actions
1056 lines (1029 loc) · 50.2 KB
/
Copy pathcloudbuild.yaml
File metadata and controls
1056 lines (1029 loc) · 50.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
# Continuous deployment for Daintree runbook search.
#
# Fired by the `deploy-main` Cloud Build trigger on every push to `main`; the
# trigger, service accounts and registry are created by infra/gcp/bootstrap.sh.
# Nothing here is built on a developer machine — this is what "release" means in
# this repo, and .claude/skills/release drives it.
#
# To run it with different substitutions, fire the TRIGGER
# (`gcloud builds triggers run deploy-main --substitutions=...`) rather than
# `gcloud builds submit`: COMMIT_SHA/SHORT_SHA are trigger-supplied, so a plain
# submit produces an empty build SHA and an image tagged with nothing.
#
# The commit SHA is the only version this system has: it tags the image, is baked
# into the container as BUILD_SHA, and is what `/version` reports back. That
# round trip is how a release is confirmed — the smoke step refuses to promote a
# revision whose /version disagrees with the commit that triggered the build.
#
# Before any of that, the candidate is QUALIFIED: the `qualify` steps run the
# serving checks and the shipped-selector routing gate against the exact catalog
# and model in the image, on its own runtime, and bind the record to this
# commit and selector.lock. Nothing deploys without it, and the promotion
# refuses a revision that does not serve the qualified catalog.
#
# Rollout is two-phase on purpose. A new revision is deployed with NO traffic
# behind a per-build `rc-<id>` tag and smoke-tested on its own URL; only a
# revision that satisfies infra/gcp/smoke.sh gets promoted to 100%. Readiness
# covers failures that are invisible at build time — an unparseable runbook file,
# a missing or corrupt selector artifact — so those turn into a red build
# instead of a broken production service.
#
# That candidate tag gives the revision a URL of its own, and a Cloud Run invoker
# binding is per-SERVICE — so on a public service the candidate is public too.
# `deploy-rc`, `smoke` and `promote` therefore declare `allowFailure` and record
# their success in marker files, and the final `release-gate` step, which cannot
# be skipped, retires this build's tag and only then decides whether the build is
# red. Cloud Build has no `always()`; this is how one is built out of what it has.
#
# Those markers are the VERDICT rather than a log line, so where they live is
# part of the mechanism: /workspace IS the repository checkout, and a marker
# there is a file the repo could have carried. Release state lives on
# `/release`, a build-scoped volume nothing in the tree can write, and every
# file under it opens with the id of the build that wrote it. Existence is not
# proof.
#
# That smoke is the SAME script an operator runs by hand against a deployed host,
# invoked with the release's own expectations rather than left to adapt to
# whatever is there. It is not a second, thinner definition of "working": this
# step used to carry one, and a copy that only the build runs is a copy that
# stops matching the one anybody edits.
substitutions:
# The Cloud Run service this build deploys onto.
_SERVICE: daintree-assistant
_REGION: us-central1
_AR_REPO: daintree
_RUNTIME_SA: daintree-assistant-run
# The application's ENVIRONMENT. `staging` and `production` withhold startup
# error detail from the unauthenticated /readyz.
_ENVIRONMENT: production
# Network ingress. `all` is what a public MCP endpoint needs; who may INVOKE
# the service is the IAM invoker binding (see infra/gcp/README.md). Validated
# against the closed set `gcloud run deploy` accepts.
_INGRESS: all
options:
logging: CLOUD_LOGGING_ONLY
machineType: E2_HIGHCPU_8
# The image build is a full `pip install` of the pinned runtime deps, and the
# qualification runs the serving tests and `bench local` over every case on top
# of it, so the 10-minute default is far too tight.
timeout: 3600s
steps:
# ---- Refuse a substitution that is not a name ----------------------------
#
# SIX substitutions are interpolated into SHELL SOURCE rather than passed as
# environment variables. Four of them are resource names: `_SERVICE`, `_REGION`, `_AR_REPO` and `_RUNTIME_SA`.
# Cloud Build expands them before bash parses, so each one is a fragment of the
# program rather than a value inside it — a `_RUNTIME_SA` of
# `x"); SERVICE_STATE=absent; REST=("` closes the flag array, overwrites the
# answer the service probe computed, and takes the full-traffic first-deploy
# branch onto a service that already exists.
#
# That is not a hypothetical shape of bug. It is how every gate in `deploy-rc`
# is bypassed at once — the environment checks and the deploy-shape refusal
# are all ordinary shell below the point
# where the injected text has already run — so it is the precondition those
# rules are built on rather than a rule beside them.
#
# They cannot simply become environment variables like everything else: they
# appear inside an image tag, a service-account address and a dozen gcloud
# flags across four steps, and one of the steps that needs them (`release-gate`)
# must keep working when the deploy never ran.
#
# THE ONE THING THAT MAKES THEM SAFE is that all four are NAMES. Cloud Run
# services, Artifact Registry repositories, regions and service-account ids live
# in the same narrow alphabet: a lowercase letter, then lowercase letters,
# digits and hyphens. No legal value contains a quote, a space, a dollar, a
# semicolon or a newline, so refusing everything outside that alphabet costs a
# correct release nothing and removes the entire class.
#
# THE OTHER TWO ARE BUILT-INS, and they are the ones nobody thinks to check.
# `$COMMIT_SHA` and `$SHORT_SHA` look platform-supplied, and on a trigger they
# are — but Cloud Build lets a MANUAL build override them, and `--labels=
# commit-sha=$SHORT_SHA` sits inside the same flag array as `_RUNTIME_SA`. They
# are git object names, so they are hex and nothing else. `$PROJECT_ID` and
# `$BUILD_ID` are not overridable and are not checked here; `$BUILD_ID` reaches
# bash as environment data anyway.
#
# It runs FIRST, and it has no `allowFailure`, so a bad value stops the build
# before any step has parsed it. A check inside `deploy-rc` could not do that:
# the interpolation happens before bash reads that step's first line.
- id: substitution-guard
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: bash
env:
- 'SERVICE=${_SERVICE}'
- 'REGION=${_REGION}'
- 'AR_REPO=${_AR_REPO}'
- 'RUNTIME_SA=${_RUNTIME_SA}'
- 'COMMIT_SHA=$COMMIT_SHA'
- 'SHORT_SHA=$SHORT_SHA'
args:
- -euo
- pipefail
- -c
- |
# Written as a `case` over a character class rather than a `grep -E`,
# because grep matches per LINE: a value of "daintree-assistant" followed
# by a newline and a payload satisfies `^[a-z0-9-]*$` on its first line
# and smuggles the rest past. `case` tests the whole string, and a newline
# is outside `[a-z0-9-]` like everything else.
#
# No `eval`, and no loop over variable NAMES that would need one: this
# step's entire purpose is that an operator value is never something bash
# parses, and an `eval` in the middle of it is the one construct that
# could make that untrue. Four lines written out is the honest cost.
check_name() {
# 63 is Artifact Registry's own maximum and the longest of the four
# limits; Cloud Run stops at 49 and a service-account id at 30, and
# those refusals belong to GCP rather than here. This bound exists to
# stop an unbounded value, not to restate the API's rules.
if [ "$${#2}" -le 63 ]; then
case "$$2" in
# Any character no name may hold — quote, space, dollar, semicolon,
# newline, uppercase, anything. Tested FIRST so it wins.
*[!a-z0-9-]*) ;;
# Starts with a lowercase letter and, by the arm above, holds
# nothing but the alphabet. That is a name.
[a-z]*) return 0 ;;
esac
fi
# The VALUE is never echoed. It is the thing we have just decided may be
# a program, and a build log outlives the build.
echo "ERROR: $$1 must be a resource NAME — a lowercase letter followed by" >&2
echo " lowercase letters, digits or hyphens, at most 62 characters." >&2
echo " These four substitutions are interpolated into shell source," >&2
echo " so a value outside that alphabet is a program rather than a" >&2
echo " name. The value is deliberately not echoed." >&2
return 1
}
# A git object name, and the same reasoning: COMMIT_SHA and SHORT_SHA are
# interpolated into an image tag, a build arg and a Cloud Run label, and a
# manual build can override both. Lowercase hex is the whole alphabet a
# git sha has, so the same `case` settles it — and an empty one is refused
# too, because `gcloud builds submit` produces exactly that and it would
# tag the image with nothing.
check_sha() {
if [ "$${#2}" -ge 7 ] && [ "$${#2}" -le 40 ]; then
case "$$2" in
*[!0-9a-f]*) ;;
*) return 0 ;;
esac
fi
echo "ERROR: $$1 must be a git object name — 7 to 40 lowercase hex" >&2
echo " characters. It is interpolated into shell source, an image" >&2
echo " tag and a Cloud Run label, and a manual build can set it." >&2
echo " Fire the trigger rather than 'gcloud builds submit', which" >&2
echo " supplies neither. The value is deliberately not echoed." >&2
return 1
}
# Every one is checked before any is reported, so an operator who got two
# wrong learns both in one build.
NAMES_OK=1
check_name _SERVICE "$$SERVICE" || NAMES_OK=0
check_name _REGION "$$REGION" || NAMES_OK=0
check_name _AR_REPO "$$AR_REPO" || NAMES_OK=0
check_name _RUNTIME_SA "$$RUNTIME_SA" || NAMES_OK=0
check_sha COMMIT_SHA "$$COMMIT_SHA" || NAMES_OK=0
check_sha SHORT_SHA "$$SHORT_SHA" || NAMES_OK=0
[ "$$NAMES_OK" -eq 1 ] || exit 1
echo "Interpolated substitutions are names; the steps below may quote them."
# ---- Initialise the release state ---------------------------------------
#
# /workspace IS the repository checkout, and every step below runs with it
# mounted. So a file the repo happened to contain arrives looking exactly like
# a file an earlier step wrote — and since `allowFailure` made the stage
# markers the only record of what happened, a checkout carrying
# `stage_deploy_ok` and `skip_smoke` could walk a FAILED deploy through the
# smoke, through the promotion, and out the other side as a green release. A
# pre-seeded `rc_tag` could aim the cleanup at another build's candidate.
#
# `/release` is a build-scoped volume rather than a directory in the tree, so
# nothing in the repository can put a file there. This step empties it and
# records which build it belongs to; every file written under it opens with
# that id and every reader checks it.
#
# It runs FIRST, ahead of the image build, because an unusable BUILD_ID makes
# the whole binding vacuous — a marker stamped with nothing matches a check for
# nothing — and that is worth learning in five seconds rather than after a
# ten-minute build and push.
- id: release-state-init
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: bash
env:
- 'BUILD_ID=$BUILD_ID'
volumes:
- name: release-state
path: /release
args:
- -euo
- pipefail
- -c
- |
if [ -z "$$BUILD_ID" ]; then
echo "ERROR: BUILD_ID is empty, so release state could not be bound to this" >&2
echo " build — and a marker bound to nothing is one anybody can write." >&2
echo " Fire the trigger rather than 'gcloud builds submit'." >&2
exit 1
fi
# Emptied rather than assumed empty. A Cloud Build volume is per-build
# today; this line is what makes that a property of this file instead of
# a property of the platform's current behaviour.
find /release -mindepth 1 -delete
printf '%s\n' "$$BUILD_ID" > /release/build_id
echo "Release state initialised for build $$BUILD_ID."
# ---- Fetch the selector model --------------------------------------------
# The model files (runbooks/local/artifacts/selector/**/*.onnx, tokenizer.json,
# vectors.npz) are not in Git. `selector.lock` names each one by SHA-256 and the
# bucket it lives in, and this step downloads exactly those files into the
# checkout the image is built from. It checks every byte against the lock, so a
# missing, truncated or substituted file is a red build here instead of a
# selector that fails at first load; production is untouched either way, because
# the candidate never takes traffic. The build service account reads the bucket
# through roles/storage.objectViewer (infra/gcp/bootstrap.sh); no secret is
# involved. `--no-cache` because the build starts from nothing and keeps nothing.
- id: fetch-selector
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: bash
args:
- -euo
- pipefail
- -c
- |
python3 training/selector_store.py fetch --no-cache
# ---- Build ---------------------------------------------------------------
# BUILD_SHA is a Dockerfile ARG that becomes a runtime ENV, so /version reports
# a real commit rather than an empty string.
- id: build
name: gcr.io/cloud-builders/docker
args:
- build
# Named, because the Dockerfile's last stage is not the only one: the
# `qualify` stage below the runtime is built by its own step.
- --target=runtime
- --build-arg=BUILD_SHA=$COMMIT_SHA
- --tag=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_AR_REPO}/${_SERVICE}:$COMMIT_SHA
- --tag=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_AR_REPO}/${_SERVICE}:latest
- .
# ---- Qualify the candidate's catalog and selector ------------------------
#
# The smoke below proves the candidate answers ONE search. A routing document
# over its token cap, a carve-out naming nothing or a recall drop all still
# answer it with a 200, so the smoke cannot be what decides that the catalog
# and the model may serve. This is.
#
# The Dockerfile's `qualify` stage is the builder's venv, the very layer the
# runtime image copies, on the same Linux base, plus the test tools: it reads
# what that venv would serve (benchmarks/qualify_release.py identity),
# checks the installed selector against selector.lock, runs the serving checks
# and `bench coverage` and `bench local`, and writes the record. A failing
# check fails the stage's build, and with it this step. A skipped test is a
# failure there: a model-dependent check that skipped has proved nothing.
#
# The record is then compared against the RUNTIME image itself, read by its
# own interpreter, so the qualified catalog, model files and installed
# distributions are the candidate's rather than a neighbour's. That runs from
# the build's own checkout and model fetch: no credential is added for it.
#
# No `allowFailure`, on this step or the next: an unqualified candidate stops
# the build before it is pushed or deployed, so there is no tag to retire.
- id: qualify
name: gcr.io/cloud-builders/docker
entrypoint: bash
env:
- 'BUILDKIT_PROGRESS=plain'
args:
- -euo
- pipefail
- -c
- |
rm -f /workspace/qualify_record.json /workspace/candidate_identity.json
docker build --target=qualify --build-arg=BUILD_SHA=$COMMIT_SHA \
--tag=qualify-$COMMIT_SHA .
docker run --rm --entrypoint cat qualify-$COMMIT_SHA /qualify/qualification.json \
> /workspace/qualify_record.json
docker run -i --rm --entrypoint python \
${_REGION}-docker.pkg.dev/$PROJECT_ID/${_AR_REPO}/${_SERVICE}:$COMMIT_SHA \
- identity < benchmarks/qualify_release.py > /workspace/candidate_identity.json
# Binds the record to this release and stamps it into release state, where
# `deploy-rc`, `promote` and `release-gate` each refuse to go on without it.
# Refused: a failed verdict, a missing or failed check, another commit, a
# selector.lock other than the one `fetch-selector` verified, or a catalog,
# model or runtime that differs from the candidate image's.
- id: qualify-record
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: bash
volumes:
# Release state is not kept in the checkout. See `release-state-init`.
- name: release-state
path: /release
env:
- 'BUILD_ID=$BUILD_ID'
- 'RELEASE_SHA=$COMMIT_SHA'
args:
- -euo
- pipefail
- -c
- |
stamp() {
STAMP_NAME="$$1"; shift
{
printf '%s\n' "$$BUILD_ID"
[ "$$#" -eq 0 ] || printf '%s\n' "$$@"
} > "/release/$$STAMP_NAME"
}
stamped() {
STAMP=""
[ -s "/release/$$1" ] || return 1
IFS= read -r STAMP < "/release/$$1" || :
[ "$$STAMP" = "$$BUILD_ID" ] || return 1
tail -n +2 "/release/$$1"
}
if [ -z "$${BUILD_ID:-}" ]; then
echo "ERROR: BUILD_ID is empty; release state cannot be bound to this build." >&2
exit 1
fi
python3 benchmarks/qualify_release.py verify \
--record /workspace/qualify_record.json \
--candidate /workspace/candidate_identity.json \
--lock selector.lock --build-sha "$$RELEASE_SHA" > /workspace/qualified_lines
# Catalog revision, selector.lock sha256, record sha256: one per line.
QUALIFIED_REVISION=""; QUALIFIED_LOCK=""; QUALIFIED_RECORD=""
{
IFS= read -r QUALIFIED_REVISION || :
IFS= read -r QUALIFIED_LOCK || :
IFS= read -r QUALIFIED_RECORD || :
} < /workspace/qualified_lines
if [ -z "$$QUALIFIED_REVISION" ] || [ -z "$$QUALIFIED_LOCK" ] \
|| [ -z "$$QUALIFIED_RECORD" ]; then
echo "ERROR: the qualification verdict was incomplete; refusing it." >&2
exit 1
fi
stamp qualification "$$QUALIFIED_REVISION" "$$QUALIFIED_LOCK" "$$QUALIFIED_RECORD"
echo "Qualified $$RELEASE_SHA: catalog $$QUALIFIED_REVISION, selector.lock $$QUALIFIED_LOCK."
# Pushed explicitly rather than via the top-level `images:` key, which only
# runs after every step and would leave the deploy below with no image.
#
# The deploy names the image by the DIGEST this push produced, never by the
# `:$COMMIT_SHA` tag. A tag is mutable: a second build of the same commit can
# push over it between this step and the deploy, on a different base image,
# and Cloud Run resolves a tag at deploy time. The digest is the image that
# was qualified above, because it is this daemon's own local image.
- id: push
name: gcr.io/cloud-builders/docker
entrypoint: bash
volumes:
# Release state is not kept in the checkout. See `release-state-init`.
- name: release-state
path: /release
env:
- 'BUILD_ID=$BUILD_ID'
args:
- -euo
- pipefail
- -c
- |
stamp() {
STAMP_NAME="$$1"; shift
{
printf '%s\n' "$$BUILD_ID"
[ "$$#" -eq 0 ] || printf '%s\n' "$$@"
} > "/release/$$STAMP_NAME"
}
stamped() {
STAMP=""
[ -s "/release/$$1" ] || return 1
IFS= read -r STAMP < "/release/$$1" || :
[ "$$STAMP" = "$$BUILD_ID" ] || return 1
tail -n +2 "/release/$$1"
}
if [ -z "$${BUILD_ID:-}" ]; then
echo "ERROR: BUILD_ID is empty; release state cannot be bound to this build." >&2
exit 1
fi
REPO="${_REGION}-docker.pkg.dev/$PROJECT_ID/${_AR_REPO}/${_SERVICE}"
docker push --all-tags "$$REPO"
DIGEST="$$(docker inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' \
"$$REPO:$COMMIT_SHA" | grep -m1 "^$$REPO@sha256:" || true)"
if [ -z "$$DIGEST" ]; then
echo "ERROR: the pushed image has no digest in $$REPO; refusing to deploy a tag." >&2
exit 1
fi
stamp image_digest "$$DIGEST"
echo "Pushed $$DIGEST."
# ---- Deploy the release candidate ---------------------------------------
#
# A no-traffic revision behind a per-build `rc-<id>` tag, so the smoke step can
# exercise it on its own URL before it takes any traffic. The first deploy of a
# service has no previous revision to hold traffic, so it goes out at 100%
# behind a `/readyz` check alone.
#
# The server holds no credential, so NOTHING is mounted from Secret Manager:
# `--clear-secrets` drops the provider keys earlier revisions carried, and the
# readback below fails the release if any secret reference survives.
- id: deploy-rc
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: bash
# Recorded rather than fatal so `release-gate` runs and retires the tag.
allowFailure: true
volumes:
# Release state is not kept in the checkout. See `release-state-init`.
- name: release-state
path: /release
env:
- 'BUILD_ID=$BUILD_ID'
- 'SERVICE=${_SERVICE}'
- 'ENVIRONMENT=${_ENVIRONMENT}'
- 'INGRESS=${_INGRESS}'
- 'LOG_LEVEL=INFO'
args:
- -euo
- pipefail
- -c
- |
stamp() {
STAMP_NAME="$$1"; shift
{
printf '%s\n' "$$BUILD_ID"
[ "$$#" -eq 0 ] || printf '%s\n' "$$@"
} > "/release/$$STAMP_NAME"
}
stamped() {
STAMP=""
[ -s "/release/$$1" ] || return 1
IFS= read -r STAMP < "/release/$$1" || :
[ "$$STAMP" = "$$BUILD_ID" ] || return 1
tail -n +2 "/release/$$1"
}
if [ -z "$${BUILD_ID:-}" ]; then
echo "ERROR: BUILD_ID is empty; release state cannot be bound to this build." >&2
exit 1
fi
# Nothing is deployed, not even with no traffic, without this build's
# qualification: the first deploy of a service takes all traffic at once.
QUALIFIED_REVISION=""
if ! QUALIFIED_REVISION="$$(stamped qualification | head -1)" \
|| [ -z "$$QUALIFIED_REVISION" ]; then
echo "ERROR: this build recorded no passing qualification; refusing to deploy." >&2
exit 1
fi
# The qualified image, by the digest `push` recorded. See `push`.
IMAGE=""
if ! IMAGE="$$(stamped image_digest)" \
|| [ "$${IMAGE%@sha256:*}" != "${_REGION}-docker.pkg.dev/$PROJECT_ID/${_AR_REPO}/${_SERVICE}" ]; then
echo "ERROR: this build recorded no pushed image digest; refusing to deploy a tag." >&2
exit 1
fi
case "$$ENVIRONMENT" in
development|test|staging|production) ;;
*) echo "ERROR: _ENVIRONMENT must be development|test|staging|production, got '$$ENVIRONMENT'." >&2
exit 1 ;;
esac
case "$$INGRESS" in
all|internal|internal-and-cloud-load-balancing) ;;
*) echo "ERROR: _INGRESS must be all|internal|internal-and-cloud-load-balancing," >&2
echo " got '$$INGRESS'." >&2
exit 1 ;;
esac
# The WHOLE environment, replaced on every release: a variable removed
# here is removed from the service.
python3 - <<'PYEOF' > /workspace/env_vars.json
import json, os
NAMES = ("ENVIRONMENT", "LOG_LEVEL")
env = {n: os.environ[n] for n in NAMES if os.environ.get(n, "").strip()}
json.dump(env, os.sys.stdout, indent=1, sort_keys=True)
PYEOF
echo "Deploying with env: $$(python3 -c 'import json;print(", ".join(sorted(json.load(open("/workspace/env_vars.json")))))')"
# Absent and unreadable are different answers, and only one is safe:
# reading "unreadable" as "absent" would deploy at full traffic,
# unsmoked, onto whatever is already serving. `gcloud run services
# describe` reports a missing service as "Cannot find service [name]"
# rather than as NOT_FOUND, so that wording is matched explicitly.
: > /workspace/service_err
SERVICE_STATUS=0
gcloud run services describe "${_SERVICE}" --region="${_REGION}" \
--format='value(status.url)' > /dev/null 2>/workspace/service_err || SERVICE_STATUS=$$?
if [ "$$SERVICE_STATUS" -eq 0 ]; then
DEPLOY_SHAPE=rc
elif grep -qi 'cannot find service\|not found\|NOT_FOUND\|does not exist' /workspace/service_err; then
DEPLOY_SHAPE=create
else
echo "ERROR: could not read ${_SERVICE}; refusing to guess whether it exists." >&2
cat /workspace/service_err >&2 || true
exit 1
fi
echo "Deploy shape: $$DEPLOY_SHAPE."
# One vCPU, one inference thread, one process. A search costs ~12ms of
# CPU and throughput per instance is flat past two requests in flight,
# so concurrency only decides how much queueing an instance absorbs
# before Cloud Run adds another: 16 keeps the worst queue near 200ms.
# It must not exceed the pool's QUEUE_DEPTH (runbooks/local/runtime.py,
# pinned by tests/unit/test_runtime_sizing.py). 1Gi holds a ~390MB
# resident process with room to spare. One warm instance keeps the ONNX
# load off a caller's first request; CPU is billed only during
# requests, so the idle instance is cheap.
FLAGS=(
--image="$$IMAGE"
--region="${_REGION}"
--service-account="${_RUNTIME_SA}@$PROJECT_ID.iam.gserviceaccount.com"
--port=8080
--cpu=1
--memory=1Gi
--cpu-boost
--cpu-throttling
--concurrency=16
--min-instances=1
--max-instances=20
--timeout=60
--ingress="$$INGRESS"
--startup-probe=httpGet.path=/healthz,httpGet.port=8080,initialDelaySeconds=0,periodSeconds=3,timeoutSeconds=3,failureThreshold=30
--liveness-probe=httpGet.path=/healthz,httpGet.port=8080,periodSeconds=30,timeoutSeconds=5,failureThreshold=3
--env-vars-file=/workspace/env_vars.json
--clear-secrets
--labels=commit-sha=$SHORT_SHA
--quiet
)
if [ "$$DEPLOY_SHAPE" = "rc" ]; then
RC_TAG="rc-$$(printf '%s' "$$BUILD_ID" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9' | cut -c1-12)"
if [ "$$RC_TAG" = "rc-" ]; then
echo "ERROR: BUILD_ID yielded no DNS-safe characters; refusing to share a tag." >&2
exit 1
fi
# Recorded BEFORE the deploy, so a deploy that half-applies still leaves
# `release-gate` a tag to retire.
stamp rc_tag "$$RC_TAG"
echo "Deploying $COMMIT_SHA as a no-traffic '$$RC_TAG' revision."
gcloud run deploy "${_SERVICE}" "$${FLAGS[@]}" --no-traffic --tag="$$RC_TAG"
gcloud run services describe "${_SERVICE}" --region="${_REGION}" --format=json \
| RC_TAG="$$RC_TAG" python3 -c 'import json,os,sys
tag = os.environ["RC_TAG"]
rows = json.load(sys.stdin)["status"]["traffic"]
row = next((r for r in rows if r.get("tag") == tag), None)
if row is None:
sys.exit("no traffic row carries tag %s; the candidate deploy did not take" % tag)
print(row["url"])
print(row["revisionName"])' \
> /workspace/rc_meta
stamp rc_url "$$(head -1 /workspace/rc_meta)"
stamp rc_revision "$$(tail -1 /workspace/rc_meta)"
echo "Release candidate: $$(stamped rc_revision) at $$(stamped rc_url)"
# Read the revision back: its environment must be exactly what this
# build generated (plus what the platform injects), and it must mount
# no secret at all.
gcloud run revisions describe "$$(stamped rc_revision)" \
--region="${_REGION}" --format=json > /workspace/revision_readback_json
python3 - <<'PYEOF' || exit 1
import json, sys
with open("/workspace/env_vars.json") as handle:
wanted = json.load(handle)
with open("/workspace/revision_readback_json") as handle:
revision = json.load(handle)
containers = revision["spec"]["containers"]
got = {
entry["name"]: entry["value"]
for container in containers
for entry in container.get("env", [])
if "value" in entry
}
secret_refs = sorted(
entry["name"]
for container in containers
for entry in container.get("env", [])
if (entry.get("valueFrom") or {}).get("secretKeyRef")
)
PLATFORM_EXACT = {"PORT"}
PLATFORM_PREFIXES = ("K_", "CLOUD_RUN_", "GOOGLE_", "GAE_", "CNB_")
missing = sorted(k for k in wanted if k not in got)
differing = sorted(k for k in wanted if k in got and got[k] != wanted[k])
unexpected = sorted(
k for k in got
if k not in wanted and k not in PLATFORM_EXACT and not k.startswith(PLATFORM_PREFIXES)
)
problems = []
if secret_refs:
problems.append("mounts secrets it has no use for: %s" % ", ".join(secret_refs))
if unexpected:
problems.append("carries variables this build did not generate: %s" % ", ".join(unexpected))
if missing:
problems.append("is missing: %s" % ", ".join(missing))
if differing:
problems.append("has a different value for: %s" % ", ".join(differing))
if problems:
for problem in problems:
print("ERROR: the deployed revision %s" % problem, file=sys.stderr)
sys.exit(1)
print("Revision environment matches the generated release configuration "
"(%d values, no secrets)." % len(wanted))
PYEOF
else
echo "No existing service — creating ${_SERVICE} and routing traffic to it."
gcloud run deploy "${_SERVICE}" "$${FLAGS[@]}"
NEW_URL="$$(gcloud run services describe "${_SERVICE}" --region="${_REGION}" \
--format='value(status.url)')"
# A new service is IAM-private until the public cutover
# (infra/gcp/README.md), so readiness is checked with an identity token.
echo "Created at $$NEW_URL — checking readiness with an identity token."
READY_CODE="$$(curl -sS -o /workspace/first_ready -w '%{http_code}' \
-H "Authorization: Bearer $$(gcloud auth print-identity-token)" \
--max-time 60 "$$NEW_URL/readyz" || echo 000)"
if [ "$$READY_CODE" != "200" ]; then
echo "ERROR: the new service answered /readyz with $$READY_CODE." >&2
cat /workspace/first_ready >&2 || true
exit 1
fi
FIRST_REVISION="$$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("catalog_revision",""))' \
/workspace/first_ready 2>/dev/null || true)"
if [ "$$FIRST_REVISION" != "$$QUALIFIED_REVISION" ]; then
echo "ERROR: the new service serves catalog '$${FIRST_REVISION:-<none>}'," >&2
echo " not the qualified $$QUALIFIED_REVISION." >&2
exit 1
fi
echo "First revision is ready and serves the qualified catalog."
stamp skip_smoke
fi
stamp stage_deploy_ok
# ---- Smoke-test the candidate before it can take traffic -----------------
#
# The SAME script an operator runs by hand against a deployed host, invoked
# with this release's own expectations: the candidate must be ready, report
# this commit, and answer a real runbook search over MCP.
- id: smoke
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: bash
allowFailure: true
volumes:
- name: release-state
path: /release
env:
- 'BUILD_ID=$BUILD_ID'
- 'RELEASE_SHA=$COMMIT_SHA'
args:
- -euo
- pipefail
- -c
- |
stamp() {
STAMP_NAME="$$1"; shift
{
printf '%s\n' "$$BUILD_ID"
[ "$$#" -eq 0 ] || printf '%s\n' "$$@"
} > "/release/$$STAMP_NAME"
}
stamped() {
STAMP=""
[ -s "/release/$$1" ] || return 1
IFS= read -r STAMP < "/release/$$1" || :
[ "$$STAMP" = "$$BUILD_ID" ] || return 1
tail -n +2 "/release/$$1"
}
if [ -z "$${BUILD_ID:-}" ]; then
echo "ERROR: BUILD_ID is empty; release state cannot be bound to this build." >&2
exit 1
fi
if ! stamped stage_deploy_ok >/dev/null; then
echo "ERROR: the candidate deploy did not complete; there is nothing to smoke." >&2
exit 1
fi
if stamped skip_smoke >/dev/null; then
echo "First deploy: readiness was checked with an identity token in deploy-rc."
echo "The service is IAM-private until an operator performs the public"
echo "cutover (infra/gcp/README.md), so there is no anonymous URL to smoke."
stamp stage_smoke_ok
exit 0
fi
URL=""
if ! URL="$$(stamped rc_url)" || [ -z "$$URL" ]; then
echo "ERROR: this build recorded no candidate URL to smoke." >&2
exit 1
fi
for attempt in 1 2 3 4 5; do
if curl -fsS --max-time 20 "$$URL/readyz" >/dev/null 2>&1; then
break
fi
echo "readyz not answering yet (attempt $$attempt/5)"
sleep 5
done
bash infra/gcp/smoke.sh --url "$$URL" --expect-build-sha "$$RELEASE_SHA"
echo "Candidate is ready and serving $$RELEASE_SHA."
stamp stage_smoke_ok
# ---- Promote to 100% -----------------------------------------------------
- id: promote
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: bash
# Recorded rather than fatal, like the two steps above, so `release-gate`
# runs. A promotion that fails between the traffic move and the tag removal
# is the least obvious of the stranding paths and the one no operator would
# think to check.
allowFailure: true
volumes:
# Release state is not kept in the checkout. See `release-state-init`.
- name: release-state
path: /release
env:
# Release state is bound to the build that wrote it.
- 'BUILD_ID=$BUILD_ID'
args:
- -euo
- pipefail
- -c
- |
# --- release state: read and written only through these ---------------
#
# `allowFailure` turned these markers into the VERDICT rather than a log
# line: a failed step no longer aborts the build, so what a later step
# believes about an earlier one is whatever it finds on disk. /workspace IS
# the repository checkout, so a marker there is a file the repo could have
# carried — and a checkout holding `stage_deploy_ok` and `skip_smoke` would
# have walked a failed deploy through the smoke, through the promotion, and
# out as a green release.
#
# /release is a build-scoped volume nothing in the tree can write, emptied
# by `release-state-init`, and every file under it opens with the id of the
# build that wrote it. So EXISTENCE IS NOT PROOF: a file the repo carried
# and a file a concurrent build wrote are both simply not ours, and a
# reader that only asked whether the path exists could not tell.
#
# This block is byte-identical in every step that touches release state,
# and tests/unit/test_deployment_wiring.py compares the copies character
# for character. Two trust checks that have drifted apart are worse than
# one, and the drift is invisible until the day it decides something.
stamp() {
STAMP_NAME="$$1"; shift
{
printf '%s\n' "$$BUILD_ID"
[ "$$#" -eq 0 ] || printf '%s\n' "$$@"
} > "/release/$$STAMP_NAME"
}
stamped() {
STAMP=""
[ -s "/release/$$1" ] || return 1
IFS= read -r STAMP < "/release/$$1" || :
[ "$$STAMP" = "$$BUILD_ID" ] || return 1
tail -n +2 "/release/$$1"
}
if [ -z "$${BUILD_ID:-}" ]; then
echo "ERROR: BUILD_ID is empty; release state cannot be bound to this build." >&2
exit 1
fi
# --- end release state helpers ----------------------------------------
if ! stamped stage_smoke_ok >/dev/null; then
echo "ERROR: the candidate was not smoked; refusing to move traffic to it." >&2
exit 1
fi
QUALIFIED_REVISION=""
if ! QUALIFIED_REVISION="$$(stamped qualification | head -1)" \
|| [ -z "$$QUALIFIED_REVISION" ]; then
echo "ERROR: this build recorded no passing qualification; refusing to promote." >&2
exit 1
fi
if stamped skip_smoke >/dev/null; then
echo "First deploy already carries all traffic."
stamp stage_promote_ok
exit 0
fi
# BY NAME, never --to-latest. The smoke proved one specific revision, and
# --to-latest re-resolves at this moment instead of naming what was proved
# — so an overlapping build that landed its own revision in between would
# have this step promote something no smoke ever saw. Reading the name back
# from the file the deploy wrote is what makes the two halves refer to the
# same thing.
#
# Drops the rc tag in the same call so tags do not accumulate one per
# release; the previous revision stays available for rollback.
REVISION=""
if ! REVISION="$$(stamped rc_revision)" || [ -z "$$REVISION" ]; then
echo "ERROR: this build recorded no candidate revision; refusing to guess." >&2
exit 1
fi
# THIS build's tag, read back from the file the deploy wrote. It used to
# be the literal `candidate`, which every concurrent build also carried:
# promoting A therefore removed the tag build B was about to describe,
# and B failed on a revision that was perfectly healthy. A tag no other
# build can name is a tag no other build can delete.
RC_TAG=""
if ! RC_TAG="$$(stamped rc_tag)" || [ -z "$$RC_TAG" ]; then
echo "ERROR: this build recorded no candidate tag; refusing to guess." >&2
exit 1
fi
# The revision about to take traffic must serve the catalog that was
# qualified, asked of the revision itself rather than assumed from the
# image name.
URL=""
if ! URL="$$(stamped rc_url)" || [ -z "$$URL" ]; then
echo "ERROR: this build recorded no candidate URL; refusing to guess." >&2
exit 1
fi
LIVE_REVISION="$$(curl -fsS --max-time 20 "$$URL/readyz" \
| python3 -c 'import json,sys;print(json.load(sys.stdin).get("catalog_revision",""))' \
2>/dev/null || true)"
if [ "$$LIVE_REVISION" != "$$QUALIFIED_REVISION" ]; then
echo "ERROR: the candidate serves catalog '$${LIVE_REVISION:-<unreadable>}'," >&2
echo " not the qualified $$QUALIFIED_REVISION; refusing to promote it." >&2
exit 1
fi
gcloud run services update-traffic "${_SERVICE}" \
--region="${_REGION}" --to-revisions="$$REVISION=100" \
--remove-tags="$$RC_TAG" --quiet
echo "Promoted $$REVISION ($COMMIT_SHA) to 100% of traffic."
stamp stage_promote_ok
# ---- Retire the candidate URL, then render the verdict -------------------
#
# THE STEP THAT ALWAYS RUNS, and the reason the three steps above declare
# `allowFailure`.
#
# A release candidate is deployed `--no-traffic --tag=rc-<build>`, which gives
# it its own URL — and Cloud Run's invoker binding is per-SERVICE, so on a
# public service that URL is public. The tag used to be removed on exactly one
# path: the promotion succeeding. A failed deploy, a failed environment
# readback, a failed smoke, or a promotion that fell over between the traffic
# move and the tag removal each left `rc-<build>` resolving indefinitely, on a
# revision that had just been judged unfit to take traffic.
#
# Cloud Build has no `always()` and a failed step aborts the build, so there was
# nowhere to put a cleanup that would actually run. `allowFailure` is what
# creates that place: each fallible step records success by writing a marker,
# every step declines to run without its predecessor's marker, and this step —
# which has NO allowFailure — runs regardless, removes the tag, and then fails
# the build if any marker is missing. The build's red/green is unchanged; what
# changed is that the tag is gone before it goes red.
#
# The residual is worth writing down rather than discovering: a build that is
# CANCELLED, or that hits the 3600s top-level timeout, kills this step too, and
# the tag survives. Nothing inside a build can cover that. It is bounded by the
# timeout and visible in the console, where a stranded tag was previously
# invisible in every case.
#
# And the markers are only a verdict because they cannot be forged. They are
# stamped with this build's id on a volume the checkout cannot reach, and every
# read goes through `stamped` — because once `allowFailure` stopped a failed
# step from aborting the build, "the file is there" became the whole of the
# evidence, and /workspace is the repository.
- id: release-gate
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: bash
volumes:
# Release state is not kept in the checkout. See `release-state-init`.
- name: release-state
path: /release
env:
# Release state is bound to the build that wrote it, and this step is the
# one that turns it into a verdict.
- 'BUILD_ID=$BUILD_ID'
args:
- -uo
- pipefail
- -c
- |
# --- release state: read and written only through these ---------------
#
# `allowFailure` turned these markers into the VERDICT rather than a log
# line: a failed step no longer aborts the build, so what a later step
# believes about an earlier one is whatever it finds on disk. /workspace IS
# the repository checkout, so a marker there is a file the repo could have
# carried — and a checkout holding `stage_deploy_ok` and `skip_smoke` would
# have walked a failed deploy through the smoke, through the promotion, and
# out as a green release.
#
# /release is a build-scoped volume nothing in the tree can write, emptied
# by `release-state-init`, and every file under it opens with the id of the
# build that wrote it. So EXISTENCE IS NOT PROOF: a file the repo carried
# and a file a concurrent build wrote are both simply not ours, and a
# reader that only asked whether the path exists could not tell.
#
# This block is byte-identical in every step that touches release state,
# and tests/unit/test_deployment_wiring.py compares the copies character
# for character. Two trust checks that have drifted apart are worse than
# one, and the drift is invisible until the day it decides something.
stamp() {
STAMP_NAME="$$1"; shift
{
printf '%s\n' "$$BUILD_ID"
[ "$$#" -eq 0 ] || printf '%s\n' "$$@"
} > "/release/$$STAMP_NAME"
}
stamped() {
STAMP=""
[ -s "/release/$$1" ] || return 1
IFS= read -r STAMP < "/release/$$1" || :
[ "$$STAMP" = "$$BUILD_ID" ] || return 1
tail -n +2 "/release/$$1"
}
if [ -z "$${BUILD_ID:-}" ]; then
echo "ERROR: BUILD_ID is empty; release state cannot be bound to this build." >&2
exit 1
fi
# --- end release state helpers ----------------------------------------
# No `-e`. This step's whole job is to reach its own last line, so every
# fallible command below is guarded explicitly instead. (The helper block
# above is the one exception, and deliberately so: without a build id
# nothing here can be trusted to be ours, and there is no tag we could
# safely name.)
CLEANUP_OK=1
# ONLY the tag this build recorded, read from the file the deploy wrote
# and never derived a second time. A tag is a name one build can create
# and no other build can guess, so a cleanup that can only name this one
# cannot touch a concurrent build's candidate — the property the shared
# `candidate` name destroyed, and the reason the promotion above stopped
# removing a literal.
#
# An absent or empty file means the deploy never got as far as tagging,
# so there is nothing to remove and nothing to guess at.
RC_TAG=""
if [ -e /release/rc_tag ]; then
# There is no `-e` here, so a failed read would leave RC_TAG empty and
# the cleanup would silently decide there was nothing to retire — the
# one outcome this step exists to prevent, arrived at quietly.
#
# `stamped` also refuses a tag some OTHER build wrote. That used to be
# reachable: the file lived in /workspace, which is the repository
# checkout, so a committed `rc_tag` would have aimed this cleanup at
# whatever name it contained — on a service where a concurrent build's
# candidate is exactly the kind of name that would be worth aiming it at.
if ! RC_TAG="$$(stamped rc_tag)"; then
echo "ERROR: a candidate tag is recorded but this build did not write it." >&2
echo " Refusing to act on it. Check the service's tags by hand." >&2
RC_TAG=""
CLEANUP_OK=0
fi
fi
if [ -n "$$RC_TAG" ]; then
# Asked before it is removed, because the successful path has already
# removed it inside the promotion's own traffic call and a second
# removal would be an error on the one run that went perfectly.
HOLDS=no
if gcloud run services describe "${_SERVICE}" --region="${_REGION}" \
--format=json > /workspace/cleanup_service.json 2>/dev/null; then
HOLDS="$$(RC_TAG="$$RC_TAG" python3 -c 'import json,os,sys
tag = os.environ["RC_TAG"]
rows = json.load(open("/workspace/cleanup_service.json"))["status"]["traffic"]
print("yes" if any(r.get("tag") == tag for r in rows) else "no")' 2>/dev/null || echo unknown)"
else
HOLDS=unknown
fi
if [ "$$HOLDS" = "yes" ]; then
echo "Retiring candidate tag $$RC_TAG so its URL stops resolving."
# No --to-revisions and no --to-latest: this call removes a tag and
# says nothing about the traffic split, so it cannot move traffic
# onto or away from anything. Retried, because a stranded public URL
# is worth three attempts, and then failed loudly rather than left.
REMOVED=0
for attempt in 1 2 3; do
if gcloud run services update-traffic "${_SERVICE}" \
--region="${_REGION}" --remove-tags="$$RC_TAG" --quiet; then
REMOVED=1
break
fi
echo "tag removal failed (attempt $$attempt/3)"