Skip to content

DAR-327 Phase 2: true blue-green coordinator deploy - #394

Closed
Gajesh2007 wants to merge 7 commits into
masterfrom
dar-327-phase2-blue-green
Closed

Gajesh2007 wants to merge 7 commits into
masterfrom
dar-327-phase2-blue-green

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 17, 2026 •

Copy link
Copy Markdown
Member

DAR-327 Phase 2 of 3 — true blue-green coordinator deploy (independent, on top of Phase 0 / DAR-326). Phase 1 = #393.

Makes coordinator upgrades zero-gap on the consumer HTTP path by splitting the single container into a long-lived platform service (step-ca + MicroMDM + the /mnt/disks/userdata volume) and a swappable coordinator-only service (@blue/@green, ports 8080/8081, sharing /data). A host-Caddy upstream flip + graceful reload performs the cutover; rollback = flip back.

What's here (11 files, secret-free)

  • New container roles: coordinator/deploy/start-platform.sh, coordinator/deploy/start-coordinator.sh. Original coordinator/deploy/start.sh left byte-for-byte unchanged (EigenCloud combined path keeps working).
  • Orchestrator: root deploy.sh — detect active color → start idle color → gate on /health+/readyz → flip_upstream Caddy 8080↔8081 + caddy reload → drain old via POST /v1/admin/drain + poll /readyz until inflight==0 → stop old color. --dry-run supported; main guarded by [ "${BASH_SOURCE[0]}" = "$0" ] so sourcing/tests never deploy. Rollback flag flips back.
  • systemd (newly tracked under deploy/gcp/prod/): darkbloom-platform.service, darkbloom-coordinator@.service (templated %i), darkbloom-run.sh, plus Caddyfile (was untracked on the box) and deploy_test.sh.
  • Guardrail: .gitignore += *.key, *.crt. Dockerfile: additive COPY+chmod for the two new scripts (CMD ["start.sh"] unchanged).
  • Docs: docs/operations/coordinator-blue-green.md (split, swap sequence, rollback, manual validation).

Decisions / risks

  • MDM webhook routing: start.sh's hardcoded localhost:8080 would miss green. Fix: EIGENINFERENCE_MDM_WEBHOOK_URL (default preserves legacy) pointed at a loopback-only Caddy listener 127.0.0.1:8090 that imports the same (coordinator_routes) snippet, so the single upstream flip reroutes the webhook to the active color too — no extra swap point.
  • flip_upstream only matches the bare-loopback coordinator reverse_proxy line (skips :9000/:9002), preserves indentation/inode, returns rc 3 on no-op.
  • Newly tracked deploy/gcp/prod/* — flagged for maintainer confirmation (previously untracked, verified secret-free).

Cross-phase contracts (separate PRs)

Phase 1 (#393): GET /readyz, POST /v1/admin/drain. Phase 3: stopping a coordinator broadcasts going_away → providers reconnect instantly to the new color.

Verification (infra-free; NO real deploy run)

  • shellcheck 0.11.0 clean on all 5 scripts (one justified inline SC2329).
  • bash -n / sh -n pass on all scripts.
  • deploy_test.sh: 26/26 pass (flip changes only the coordinator line; reversible; idempotent; :9000/:9002/:8090 untouched).
  • deploy.sh --dry-run prints the full plan and mutates nothing.

Confirmed: no secrets committed (runtime secrets stay Secret Manager → tmpfs /etc/d-inference/env → --env-file; coordinator/.env remains gitignored). Real blue-green validation is human-only on the GCP box.


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

@vercel

vercel Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 20, 2026 9:40pm
d-inference-console-ui-dev Ready Ready Preview Jun 20, 2026 9:40pm
d-inference-landing Ready Ready Preview Jun 20, 2026 9:40pm

Request Review

@github-actions

github-actions Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

No threat-model-covered files were changed; however, several deployment files introduce or modify infrastructure surface that warrants a brief security note.


Trust boundaries touched

None of the changed files match an affected_files pattern in the current threat model. The closest boundary is TB-001 (consumer → coordinator HTTP) and TB-006 (admin → coordinator), both of which depend on the correct operation of the reverse proxy and service startup configuration modified here.


New / modified attack surface not covered by an existing threat

The changes are purely operational (Dockerfile, systemd units, Caddy config, deploy scripts, blue-green runbook), but a few items are worth flagging for the next threat model revision:

  1. deploy/gcp/prod/Caddyfile — This file is now the authoritative source of TLS termination, X-Forwarded-Proto injection, and any security-header configuration for the production coordinator. The threat model notes (TB-004, T-019) that no CSP/HSTS/X-Frame-Options headers are configured at the application layer, but it does not track whether these headers are set at the Caddy layer. If Caddy is also not setting them, SEC-014 remains fully open. Recommend adding Caddyfile to the affected_files list for T-019 and T-040 — T-040 specifically calls out that X-Forwarded-Proto / Host header trustworthiness depends on the proxy; Caddy's trusted_proxies and header directives are the enforcement point.

  2. deploy/gcp/prod/darkbloom-run.sh and start-coordinator.sh — These scripts inject environment variables into the coordinator process, including (per the threat model) EIGENINFERENCE_BASE_URL, PROFILE_SIGNING_P12_B64, the Solana mnemonic, and MDM credentials. If these scripts log, echo, or otherwise expose env vars (e.g. set -x in a script that sources secrets), that is a T-032 / T-041 class issue. Recommend adding startup scripts to the affected_files for T-032 and T-041 so future diffs to secret injection paths get reviewed.

  3. deploy/gcp/prod/darkbloom-coordinator@.service — The systemd unit controls CapabilityBoundingSet, PrivateTmp, NoNewPrivileges, and similar hardening knobs that bound the coordinator's OS privilege. These settings are not currently modelled in any threat entry. Weakening them (e.g. removing NoNewPrivileges=yes or adding CAP_SYS_PTRACE) would meaningfully affect TB-006 and the SEV-SNP memory protection assumption in T-032. Recommend adding the service unit file to a new or existing threat entry covering coordinator OS-level privilege.

  4. docs/operations/coordinator-blue-green.md — Runbook-only, no runtime security impact. No action needed.


Open findings resolved by this PR

None.


Recommendation

No immediate security regression is visible from file names alone (no diff content was provided), but the three files above (Caddyfile, darkbloom-run.sh / start-coordinator.sh, and the systemd unit) represent a gap in the threat model's affected_files coverage. They should be added to the relevant threat entries so future PRs touching them are automatically reviewed.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@blacksmith-sh

blacksmith-sh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/TestIntegration_ConcurrentRequests View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b67a40b49f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread deploy.sh Outdated

# 2. Start the idle color.
confirm "Start idle color '$idle_color'?" || die "aborted before starting idle color"
run_cmd "$SYSTEMCTL_BIN" start "darkbloom-coordinator@${idle_color}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restart an already-running idle color

When the idle color is still running from a previous deploy/rollback or because the operator chose to leave the old color up, this systemctl start does not re-exec darkbloom-run.sh after pin_image updates DINF_IMAGE; systemctl --help distinguishes start (“Start (activate)”) from restart (“Start or restart”). In that case the health checks pass against the already-running stale container and the cutover silently routes production back to the old image instead of the requested one.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
log "Deploy finished (old color intentionally not stopped)."
return 0
fi
run_cmd "$SYSTEMCTL_BIN" stop "darkbloom-coordinator@${active_color}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fail the deploy if stopping the old color fails

Because main does not enable set -e, a nonzero systemctl stop darkbloom-coordinator@<old> return is ignored here and the script still prints that the old color is stopped and the new color is the sole live coordinator. If Docker/systemd fails to stop the old unit, existing WebSocket/provider connections can remain attached to the retired coordinator indefinitely while operators believe the rollback window is closed and cleanup completed.

Useful? React with 👍 / 👎.

Comment thread deploy.sh
Comment on lines +286 to +289
if ! "$CURL_BIN" -fsS -X POST \
-H "Authorization: Bearer ${EIGENINFERENCE_ADMIN_KEY:-}" \
--max-time 10 \
"http://${HEALTH_HOST}:${port}${DRAIN_PATH}" >/dev/null; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Source the admin key before draining

In the documented GCP setup the admin key is written to /etc/d-inference/env by deploy/gcp/refresh-env.sh, not exported into the shell that runs deploy.sh. With the default environment this sends Authorization: Bearer , the admin-authenticated drain endpoint rejects the request, and the script merely warns and proceeds to stop the old color without ever putting it into drain mode.

Useful? React with 👍 / 👎.

Comment on lines +31 to +33
After=docker.service network-online.target darkbloom-platform.service cloud-sql-proxy.service
Requires=docker.service
Wants=network-online.target darkbloom-platform.service

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require Cloud SQL before starting coordinators

This unit only orders itself after cloud-sql-proxy.service; it does not require the proxy to be started. The existing GCP coordinator unit in deploy/gcp/vm-startup.sh uses Requires=docker.service cloud-sql-proxy.service, and with EIGENINFERENCE_DATABASE_URL set the coordinator selects Postgres and refuses the memory fallback, so booting or manually starting a color without an active proxy leaves that color crash-looping instead of bringing up a healthy idle target.

Useful? React with 👍 / 👎.

Comment thread deploy/gcp/prod/Caddyfile
Comment on lines +50 to +52
# Everything else -> coordinator (HTTP + WebSocket). Blue-green swap target.
# THE single upstream line flipped by deploy.sh / flip_upstream (8080<->8081).
reverse_proxy 127.0.0.1:8080 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve /dl static bundle routing

The new host Caddyfile sends every non-ACME/MDM path to the coordinator, but the coordinator has no /dl/* handler; the combined coordinator/Caddyfile serves /dl/* from /var/www/html and handleLatestRelease still falls back to a /dl/eigeninference-bundle-macos-arm64.tar.gz URL when no active release row exists. On a fresh or partially restored prod database that fallback makes install.sh receive a download URL that now 404s through this proxy.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
Comment on lines +401 to +402
if [ -n "$IMAGE_REF" ]; then
pin_image "$IMAGE_REF"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Defer image pinning until deploy is accepted

Pinning the image happens before any confirmation. If an operator runs sudo ./deploy.sh --image <ref> and then declines the first prompt, or if the idle health check later aborts, /etc/d-inference/deploy.env is still left pointing at that image; the next systemd restart of the active color or platform will pull it even though no deploy was accepted. Move the pin behind a confirmation or roll it back on abort/failure.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 856df86c03

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread deploy.sh Outdated
log "Rollback window OPEN: run '$0 --rollback' to revert to $active_color (valid until it is stopped)."

# 5. Drain the old color.
drain_color "$active_color" "$active_port"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reconnect providers before the cutover drain

In a normal deploy, this line keeps the old color running and drains it after Caddy has already routed all new HTTP/WebSocket traffic to the idle color. Provider capacity is attached to the old coordinator's in-process registry until providers reconnect/register on a new WebSocket (coordinator/api/provider.go:143-207), and this script only triggers the Phase 3 going_away reconnect when the old color is stopped later. That leaves the new color serving consumer requests with no provider WebSockets during the drain window (and indefinitely if the operator declines the stop prompt), causing requests to 429/fail instead of achieving a zero-gap cutover.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
Comment on lines +295 to +298
set -a
# shellcheck source=/dev/null
. "$DINF_ENV_FILE"
set +a

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Parse the admin key without sourcing secrets

When draining, this sources the entire Docker env file as shell code, but the file generated by deploy/gcp/refresh-env.sh is raw --env-file syntax and includes values like the 12-word MNEMONIC and URLs that are not shell-quoted. On a real env file, words after the first mnemonic word or characters like & are parsed as commands/operators while running as root, which can leak secret words to deploy logs or execute unintended commands before the drain request; read only the EIGENINFERENCE_ADMIN_KEY= line instead of sourcing the whole file.

Useful? React with 👍 / 👎.

Comment on lines +171 to +172
sudo systemctl enable --now darkbloom-platform.service
sudo systemctl enable --now darkbloom-coordinator@blue # initial active color

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stop the legacy unit before enabling the split

On an existing GCE box created by deploy/gcp/vm-startup.sh, d-inference-coordinator.service is enabled and already owns ports 8080, 9000, and 9002. Following this install sequence starts darkbloom-platform/darkbloom-coordinator@blue without first disabling the legacy combined unit, so the new containers either fail with port conflicts or Caddy continues to proxy to the old coordinator; add an explicit systemctl disable --now d-inference-coordinator.service migration step before these enable --now commands.

Useful? React with 👍 / 👎.

Comment on lines +176 to +177
Secrets are unchanged: GCP Secret Manager → tmpfs `/etc/d-inference/env`
(written by `deploy/gcp/refresh-env.sh`) → `--env-file` inside

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use a prod env writer for prod

This runbook points the prod split at /etc/d-inference/env written by deploy/gcp/refresh-env.sh, but that script hardcodes dev values such as EIGENINFERENCE_BASE_URL=https://api.dev.darkbloom.xyz and DOMAIN=api.dev.darkbloom.xyz. In this split start-platform.sh passes DOMAIN to MicroMDM's -server-url, so following the prod runbook as written would generate/check in MDM enrollment against the dev host while Caddy is serving api.darkbloom.dev; use a prod-specific env generator or require those values to be overridden before starting the services.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
Comment on lines +376 to +377
flip_upstream "$CADDYFILE" "$cur_port" "$target_port" || die "flip_upstream failed (rc $?)"
reload_caddy || die "caddy reload failed after rollback flip"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore the Caddyfile if rollback reload fails

During rollback, this flips the on-disk Caddyfile and then dies if caddy reload fails, unlike the normal cutover path which flips the file back on reload failure. If the reload fails because the Caddy admin endpoint is unavailable or another runtime error occurs after validation, live Caddy keeps serving the current color while current_upstream_port now reads the target color from disk; the next deploy/rollback will make decisions from stale file state and can stop or flip the wrong color.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
Comment on lines +339 to +340
warn "$color did not reach inflight==0 within ${DRAIN_TIMEOUT}s; the graceful container stop (docker stop -t) will finish remaining requests."
return 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Don't stop the old color after a failed drain

When /readyz never reports inflight==0, this timeout path still returns success, so main proceeds to the stop prompt and then sends systemctl stop to the old color. The coordinator's actual SIGTERM handling only gives HTTP requests 15 seconds to finish (coordinator/cmd/coordinator/main.go:604-610), so any long-running in-flight request that survived the drain timeout can still be cut off; return non-zero or leave the old color running unless the operator explicitly forces an incomplete drain.

Useful? React with 👍 / 👎.

@Gajesh2007

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1ce51452bb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread deploy.sh Outdated
Comment on lines +465 to +466
warn "$color did not report providers>0 within ${PROVIDERS_TIMEOUT}s; providers may still be reconnecting (heartbeat timeout). Proceeding to drain the old color — monitor capacity."
return 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Abort when the new color has no providers

If the going-away POST is rejected or provider reconnects do not land within PROVIDERS_TIMEOUT, this timeout path still returns success, so the caller proceeds to drain and stop the old color while Caddy is already routing users to the new color. In a deploy where the old color had the only providers attached, that creates the exact zero-provider window this script is trying to avoid and consumer requests will 429; make this a hard failure unless an explicit force path is used.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
Comment on lines +597 to +598
if [ -n "$IMAGE_REF" ]; then
pin_image "$IMAGE_REF"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fail if the image pin cannot be written

When --image is used, this call's result is ignored and main is not running with set -e, so failures writing /etc/d-inference/deploy.env can still let the deploy continue. In the common failure modes of an unwritable/full env directory, the idle color is restarted with the previous/default DINF_IMAGE and can be cut over as if the requested image was deployed; check pin_image and abort before restarting the idle color.

Useful? React with 👍 / 👎.

Comment thread coordinator/deploy/start-coordinator.sh Outdated
Comment on lines +38 to +40
if [ "$i" -ge "$WAIT_SECS" ]; then
echo "start-coordinator: WARNING: $CA_ROOT still absent after ${WAIT_SECS}s; starting anyway." >&2
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep waiting for the step-ca root before starting

On a cold boot where the platform takes more than COORDINATOR_PLATFORM_WAIT_SECS to initialize step-ca, this fallback starts the coordinator without the CA root; cmd/coordinator/main.go only reads EIGENINFERENCE_STEP_CA_ROOT at startup, so ACME client-cert verification remains disabled for that coordinator until it is restarted even after the platform finishes. The combined entrypoint did not have this race because it initialized step-ca before exec coordinator; fail/retry instead of starting without the root.

Useful? React with 👍 / 👎.

Comment thread deploy/gcp/prod/Caddyfile
Comment on lines +64 to +66
# Everything else -> coordinator (HTTP + WebSocket). Blue-green swap target.
# THE single upstream line flipped by deploy.sh / flip_upstream (8080<->8081).
reverse_proxy 127.0.0.1:8080 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the static enrollment profile route

With this prod Caddyfile, GET /enroll.mobileconfig now falls through to the coordinator catch-all even though the combined coordinator/Caddyfile served that path from /var/www/html and scripts/deploy-acme.sh still directs operators to open it. A repo-wide search shows the coordinator only registers POST /v1/enroll, so static ACME enrollment-profile reinstalls will 404 unless the same static handler is added before this reverse proxy.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
Comment on lines +501 to +502
confirm "Flip Caddy upstream $cur_port -> $target_port and reload?" || { log "Rollback aborted."; return 1; }
flip_upstream "$CADDYFILE" "$cur_port" "$target_port" || die "flip_upstream failed (rc $?)"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Move providers back during rollback

When --rollback is run after the normal going-away step has moved providers to the new color, this path only flips Caddy back to the old port; existing provider WebSockets stay attached to the current color and are not affected by a Caddy reload. In that rollback window, consumers can be routed to a live but provider-empty old coordinator and 429 until providers reconnect manually, so rollback needs to signal/migrate providers back and wait for them before declaring success.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
if [ -f "$DINF_DEPLOY_ENV" ]; then
grep -v '^DINF_IMAGE=' "$DINF_DEPLOY_ENV" > "$tmp" || true
fi
printf 'DINF_IMAGE=%s\n' "$ref" >> "$tmp"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pin the candidate image per idle color

This writes the requested --image into the single shared deploy env file consumed by both color units, so if the live color restarts after the pin is written but before cutover is accepted, systemd will pull and run the candidate image in place on the live port. That defeats the blue-green safety boundary for exactly the failure mode the idle-color health gate is meant to catch; use a per-color/idle-only pin or pass the candidate image only to the idle restart.

Useful? React with 👍 / 👎.

Split the container entrypoint into a long-lived platform (step-ca + MicroMDM + shared /data volume) and a swappable coordinator-only role, add systemd units, a blue-green-ready host Caddyfile with a single upstream swap point, and a root deploy.sh orchestrator with a unit-tested flip_upstream, --dry-run, and rollback. Fix the MDM webhook coupling so MicroMDM reaches the ACTIVE color via a stable loopback Caddy listener that imports the same routing snippet.

New (container roles): coordinator/deploy/start-platform.sh, coordinator/deploy/start-coordinator.sh. start.sh is intentionally LEFT UNCHANGED as the EigenCloud combined path; Dockerfile gains COPY+chmod for the two new scripts (default CMD unchanged).

Newly tracked under deploy/gcp/prod/: Caddyfile (was untracked on the box), darkbloom-platform.service, darkbloom-coordinator@.service (templated %i=blue|green), darkbloom-run.sh (color->port + metadata-token registry auth, mirrors vm-startup.sh), deploy_test.sh (26 infra-free assertions).

Also: root deploy.sh orchestrator (detect active color, start idle, wait /health+/readyz, flip Caddy + graceful reload, drain via /v1/admin/drain, stop old) with sourcing guard so tests never auto-deploy; docs/operations/coordinator-blue-green.md; .gitignore now ignores *.key and *.crt.

Cross-phase contracts referenced only (separate PRs): Phase 1 = GET /readyz + POST /v1/admin/drain; Phase 3 = graceful stop broadcasts going_away. No secrets committed: runtime secrets stay Secret Manager -> tmpfs /etc/d-inference/env -> --env-file.
…t on start (Phase 2 review)

Quality Gate review of the DAR-327 Phase 2 blue-green orchestrator found three
minor issues in deploy.sh:

1. Admin key never reached the drain call. deploy.sh sent
   `Authorization: Bearer ${EIGENINFERENCE_ADMIN_KEY:-}` but never loaded
   /etc/d-inference/env, so the bearer was empty and the coordinator drain
   would not trigger. Add load_admin_env(): source the secrets env file with
   `set -a` only at real drain time (never in --dry-run), warn-and-continue if
   the key is still empty. Path overridable via DINF_ENV_FILE.

2. Rollback didn't verify the target color is alive, risking a flip onto a dead
   port (502s). do_rollback now does a single-shot /health liveness probe before
   the flip and refuses by default; an explicit --force flag overrides with a
   loud warning. --dry-run still mutates nothing.

3. `systemctl start` return code was unchecked, so a failed idle-color start was
   only detected after wait_healthy timed out (up to 120s). Check the rc and
   fail fast with a clear message before polling.

shellcheck clean (0 warnings); deploy_test.sh unchanged (no signatures changed)
and still 26/26. Documented --force and the admin-key sourcing in
docs/operations/coordinator-blue-green.md. No secret values printed or committed.
True blue-green coordinator deploy — Phase 2 Codex review fixes.

A SECURITY: load_admin_env no longer sources /etc/d-inference/env (docker
  --env-file syntax, NOT shell — sourcing executed secret values like the
  12-word MNEMONIC / URL chars as ROOT). Parse only the EIGENINFERENCE_ADMIN_KEY
  line via grep/cut, strip optional quotes, never echo. No source/. of the env
  file remains anywhere.
B Reorder cutover so providers move to the NEW color BEFORE the old is drained:
  restart idle → wait health+readyz → flip Caddy → POST /v1/admin/going-away to
  OLD (Phase 3, PR #396; {"sent":N}) → wait NEW /health providers>0 → drain OLD →
  stop OLD. Removes the zero-provider 429 window.
C Restart (not start) the idle color so a stale container re-execs with the
  newly pinned image.
D Fail (nonzero) if stopping the old color fails.
E Fail (nonzero) and do NOT stop on an incomplete drain (unless --force).
F Rollback restores the on-disk Caddyfile if `caddy reload` fails after the flip.
G Defer/auto-rollback the image pin: snapshot deploy.env, restore on any
  pre-cutover abort (EXIT trap), keep only once cutover is accepted.
H darkbloom-coordinator@.service: Requires=docker.service cloud-sql-proxy.service.
I Prod Caddyfile: add /dl/* static handler (/var/www/html) so the bundle
  fallback URL doesn't 404 and break scripts/install.sh.
J Docs: disable legacy d-inference-coordinator.service before the split.
K Docs: require prod DOMAIN/EIGENINFERENCE_BASE_URL override before starting prod.

Tests: deploy_test.sh adds load_admin_env coverage (incl. a security canary
proving env-file values are never executed) and image-pin rollback — 43/43 pass.
shellcheck clean; bash -n clean; --dry-run and --rollback --dry-run mutate
nothing and print the new ordering; sourcing deploy.sh still never runs main.
No secrets committed.
…rain+clear going_away+push providers back), align coordinator stop timeout to drain budget

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7c76933810

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread deploy.sh Outdated
Comment on lines +838 to +841
err "NOT draining or stopping $active_color: $idle_color did not report providers>0 within ${PROVIDERS_TIMEOUT}s."
err "Caddy is already -> $idle_color; the old color stays RUNNING so providers/in-flight work are not disrupted."
err "Investigate provider reconnects, run '$0 --rollback' before stopping $active_color if needed, or re-run with --force to continue despite capacity risk."
die "deploy aborted: providers did not land on new color (cutover done, $active_color left running)"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restore the old color when provider handoff fails

When the going-away POST is rejected or reconnects do not land before PROVIDERS_TIMEOUT, this branch exits after the Caddy flip and explicitly leaves Caddy pointing at $idle_color. Since the old providers are still attached to $active_color and the new color reported no providers, production traffic stays on a provider-empty coordinator until a human notices and runs rollback; the safe failure mode is to flip/reload back before exiting. Fresh evidence vs the earlier timeout finding: the current code now aborts instead of draining, but it still leaves Caddy is already -> $idle_color on this failure path.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
Comment on lines +582 to +583
count="$(printf '%s' "$body" | sed -n 's/.*"providers"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' | head -n1)"
if [ -n "$count" ] && [ "$count" -gt 0 ]; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Wait for routable capacity, not raw registrations

In a normal handoff, /health's providers field is just registry.ProviderCount() (handleHealth), and a freshly registered provider is counted while it still has TrustNone/ChallengeVerifiedSIP=false; routing rejects it until attestation/trust reuse and privacy gates pass. This count > 0 can therefore let the script drain/stop the old color as soon as one WebSocket registers on the new color even though the new coordinator still has no routable providers, causing consumer requests to 429 during the attestation window; poll a routable/capacity signal instead.

Useful? React with 👍 / 👎.

Comment thread deploy.sh Outdated
Comment on lines +673 to +674
if ! wait_for_providers "$target_color" "$target_port"; then
warn "Rollback routing is already restored to $target_color; continuing despite provider wait timeout. Monitor capacity and provider reconnects."

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fail rollback when providers do not return

During rollback after the forward deploy latched the old color as going-away, if the undrain/clear-going-away POSTs are rejected or the push-back reconnects never land, this branch only warns and still reports rollback complete with Caddy already flipped to the target. In that scenario the restored color can remain drained, still refusing provider registrations, or simply provider-empty, so rollback routes consumers to 429s instead of preserving the known-good current color; make this a hard failure or revert the Caddy flip unless capacity actually returns.

Useful? React with 👍 / 👎.

# on 127.0.0.1:5432, so requiring cloud-sql-proxy.service avoids a crash-loop on a
# cold/failed proxy (mirrors deploy/gcp/vm-startup.sh's d-inference-coordinator).
Requires=docker.service cloud-sql-proxy.service
Wants=network-online.target darkbloom-platform.service

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require the platform service for color starts

On any box where the CA root already exists from a previous boot, start-coordinator.sh only checks that file before exec coordinator, so this unit can start and pass /health even if darkbloom-platform.service failed and step-ca/MicroMDM are not listening on 9000/9002. Because the new Caddyfile routes /acme/*, /scep, and /mdm/* to those platform processes and MDM verification depends on them, a deploy can cut over to a coordinator whose trust/enrollment plane is dead; make the platform a Requires= dependency, not just a best-effort Wants=.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c2717aa1b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread deploy.sh
Comment on lines +573 to +574
body=json.load(sys.stdin)
print(len(body.get("models") or []))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Require ready capacity before retiring old color

Fresh evidence vs the earlier /health-based finding: the current code now polls /v1/models/capacity, but capacity_model_count still returns len(models) and ignores each entry's ready/can_accept state. ModelCapacitySnapshot can emit model entries with ready:false when providers pass trust gates but have no concurrency/token headroom (coordinator/registry/registry.go:4720-4735), so during a handoff with saturated or non-accepting providers this returns success and the script proceeds to drain/stop the old color while the new color still 429s consumer requests.

Useful? React with 👍 / 👎.

Comment thread deploy.sh
Comment on lines +793 to +797
if [ -n "$IMAGE_REF" ]; then
if ! pin_image "$idle_color" "$IMAGE_REF"; then
die "deploy aborted: failed to pin image for idle color '$idle_color'; not restarting it"
fi
fi

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear stale color pins when --image is omitted

When --image is omitted after a previous pinned deploy, this branch leaves /etc/d-inference/deploy-<idle>.env untouched; darkbloom-run.sh gives DINF_IMAGE priority over the metadata DINF_IMAGE_TAG, so restarting the idle color can silently reuse that stale per-color image and cut over to an old build even though the operator expected the current metadata/default image. Either reject image-less deploys while a pin exists or clear/refresh the idle color's pin before restarting it.

Useful? React with 👍 / 👎.

Comment thread deploy.sh
Comment on lines +804 to +805
if ! run_cmd "$SYSTEMCTL_BIN" restart "darkbloom-coordinator@${idle_color}"; then
die "failed to (re)start idle color '$idle_color' ($SYSTEMCTL_BIN restart darkbloom-coordinator@${idle_color} exited non-zero); Caddy untouched ($active_color still live). Inspect: $SYSTEMCTL_BIN status darkbloom-coordinator@${idle_color}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Enable the live color after cutover

The install flow enables only darkbloom-coordinator@blue, and this restart starts the idle color for the current boot but never enables the color that becomes live or disables the retired one. Checked systemctl --help: restart is “Start or restart” while enable is “Enable one or more unit files”, so after a blue→green deploy a VM reboot starts the stopped-but-enabled blue unit while Caddy still proxies to green’s disabled/dead 8081, causing production 502s until manual recovery.

Useful? React with 👍 / 👎.

# loopback Caddy webhook listener (http://127.0.0.1:8090/v1/mdm/webhook).
MDM_WEBHOOK_URL="${EIGENINFERENCE_MDM_WEBHOOK_URL:-http://localhost:8080/v1/mdm/webhook}"
if [ -n "${EIGENINFERENCE_MDM_WEBHOOK_SECRET:-}" ]; then
MDM_WEBHOOK_URL="${MDM_WEBHOOK_URL}?token=${EIGENINFERENCE_MDM_WEBHOOK_SECRET}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not log the MDM webhook secret

When EIGENINFERENCE_MDM_WEBHOOK_SECRET is set, this puts the shared secret in the webhook query string, and the new deploy/gcp/prod/Caddyfile imports a shared log { output stdout ... } block for the internal 127.0.0.1:8090 listener as well as the public sites. That means every MicroMDM callback to /v1/mdm/webhook?token=... can write the secret-bearing URI into Caddy logs; either keep the secret out of the URL for the Caddy hop or disable/sanitize access logging on the loopback webhook listener.

Useful? React with 👍 / 👎.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — 2 finding(s)

  • 🔵 [INFO] deploy.sh:582-592 — Potential command injection in load_admin_env function
    • Suggestion: The grep pattern and cut command could be vulnerable if DINF_ENV_FILE contains shell metacharacters. Consider using safer file parsing or additional input validation.
  • 🔵 [INFO] deploy.sh:582-592 — Unvalidated file path in load_admin_env
    • Suggestion: DINF_ENV_FILE path is not validated before use in grep/cut commands. Consider validating the path is within expected directories.

Performance — 5 finding(s) (3 blocking)

  • 🟡 [MEDIUM] deploy.sh:1-907 — Large shell script with potential memory growth from unbounded string operations
    • Suggestion: Consider breaking this 900+ line script into smaller functions or separate scripts to reduce memory footprint and improve maintainability
  • 🔵 [INFO] coordinator/deploy/start-coordinator.sh:34-44 — Blocking sleep loop without exponential backoff could delay startup
    • Suggestion: Implement exponential backoff in the wait loop: sleep $((i < 10 ? 1 : i < 30 ? 2 : 5)) to reduce CPU usage during long waits
  • 🟡 [MEDIUM] coordinator/deploy/start-platform.sh:175-193 — Tight polling loop with fixed 5-second sleep may be inefficient
    • Suggestion: Use exponential backoff or longer initial sleep intervals to reduce unnecessary CPU usage during supervision
  • 🟡 [MEDIUM] deploy.sh:580-600 — Synchronous HTTP requests in polling loops without connection pooling
    • Suggestion: Add connection reuse flags to curl commands: --keepalive-time 2 --max-time 5 to reduce connection overhead in tight polling loops
  • 🔵 [INFO] deploy.sh:850-870 — Repeated curl calls and JSON parsing in capacity polling
    • Suggestion: Cache capacity responses for a few seconds or batch multiple checks to reduce redundant HTTP requests and JSON parsing overhead

Type_diligence — 8 finding(s) (4 blocking)

  • 🔵 [INFO] coordinator/deploy/start-coordinator.sh:35 — Untyped string comparison with numeric value
    • Suggestion: Use explicit numeric comparison: [ "$i" -ge "$WAIT_SECS" ] or convert to integer arithmetic
  • 🔵 [INFO] coordinator/deploy/start-platform.sh:61-75 — jq manipulation uses untyped JSON processing
    • Suggestion: Consider validating JSON structure before modification or using typed configuration structs
  • 🔵 [INFO] deploy.sh:378-388 — String-based port matching in awk without type validation
    • Suggestion: Add explicit port number validation or use typed port constants
  • 🔵 [INFO] deploy.sh:406-416 — String-based port extraction without validation
    • Suggestion: Validate extracted port is numeric before returning
  • 🟡 [MEDIUM] deploy.sh:758-760 — sed regex extraction of numeric field without validation
    • Suggestion: Validate extracted inflight value is numeric: inflight=$(echo "$body" | jq -r '.inflight // ""') && [ "$inflight" -eq "$inflight" ] 2>/dev/null
  • 🟡 [MEDIUM] deploy.sh:810-812 — sed regex extraction of numeric field without validation
    • Suggestion: Validate extracted sent value is numeric before using
  • 🟡 [MEDIUM] deploy.sh:862-864 — sed regex extraction without validation
    • Suggestion: Validate extracted cleared value is boolean before comparison
  • 🟡 [MEDIUM] deploy.sh:890-892 — Python JSON parsing with untyped dictionary access
    • Suggestion: Add type validation: models = body.get('models'); print(len(models) if isinstance(models, list) else 0)

Additive_complexity — 8 finding(s) (5 blocking)

  • 🔴 [CRITICAL] deploy.sh:1-907 — 907-line bash script with complex state management and error handling
    • Suggestion: Split into smaller focused scripts: one for health checks, one for Caddy operations, one for systemd operations. Consider using a proper deployment tool instead of bash for this complexity.
  • 🟡 [MEDIUM] deploy.sh:85-120 — Multiple similar HTTP polling functions with repeated curl/timeout patterns
    • Suggestion: Extract a common poll_endpoint function that takes endpoint, expected response pattern, and timeout as parameters.
  • 🟡 [MEDIUM] deploy.sh:400-500 — Deployment orchestrator parsing secrets and managing container state
    • Suggestion: Move secret parsing to a dedicated secrets management module. Container lifecycle should be handled by the systemd units, not the deployment script.
  • 🔵 [INFO] coordinator/deploy/start-platform.sh:1-193 — Duplicates initialization logic from start.sh with minor variations
    • Suggestion: Extract common initialization steps into shared functions or use the existing start.sh with conditional logic based on environment variables.
  • 🔵 [INFO] deploy/gcp/prod/darkbloom-run.sh:1-90 — Multiple environment variables for image resolution and container naming
    • Suggestion: Consolidate image resolution logic and reduce the number of configurable parameters to essential ones only.
  • 🟡 [MEDIUM] deploy.sh:200-300 — Complex image pinning system with backup/restore state management
    • Suggestion: Use atomic file operations or a simpler approach like temporary directories instead of manual backup state tracking.
  • 🟡 [MEDIUM] deploy.sh:600-700 — Rollback logic tightly coupled with forward deployment state
    • Suggestion: Separate rollback into an independent operation that can determine current state without depending on forward deployment variables.
  • 🔵 [INFO] deploy/gcp/prod/deploy_test.sh:1-301 — Test setup code repeated across multiple test cases
    • Suggestion: Extract common test setup into helper functions to reduce duplication and improve maintainability.

23 finding(s) total, 12 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — 2 finding(s)

  • 🔵 [INFO] deploy.sh:584-594 — Potential command injection in load_admin_env function
    • Suggestion: Use safer parsing method or validate input format before processing
  • 🔵 [INFO] deploy.sh:584-594 — Missing validation on EIGENINFERENCE_ADMIN_KEY format
    • Suggestion: Add validation to ensure the key contains only expected characters

Performance — 6 finding(s) (3 blocking)

  • 🟡 [MEDIUM] deploy.sh:1-907 — Large shell script with potential memory growth from unbounded string operations
    • Suggestion: Consider breaking this 900+ line script into smaller functions or separate scripts to reduce memory footprint and improve maintainability
  • 🔵 [INFO] coordinator/deploy/start-coordinator.sh:34-44 — Blocking sleep loop without exponential backoff could cause startup delays
    • Suggestion: Implement exponential backoff in the wait loop: sleep $((i < 10 ? 1 : i < 30 ? 2 : 5)) to reduce CPU usage during long waits
  • 🟡 [MEDIUM] coordinator/deploy/start-platform.sh:175-193 — Tight polling loop with fixed 5-second sleep may consume unnecessary CPU
    • Suggestion: Use exponential backoff or longer sleep intervals for the supervision loop: sleep $((failures < 3 ? 5 : 15)) to reduce CPU overhead
  • 🔵 [INFO] deploy.sh:500-520 — HTTP health checks in tight loops without caching or circuit breaker
    • Suggestion: Add circuit breaker pattern or cache successful health checks for a few seconds to reduce redundant HTTP calls during wait loops
  • 🔵 [INFO] deploy.sh:700-720 — Repeated JSON parsing in capacity polling loop
    • Suggestion: Cache the capacity count for a few seconds or use jq with streaming to avoid re-parsing the same JSON response multiple times
  • 🟡 [MEDIUM] deploy/gcp/prod/darkbloom-run.sh:50-55 — Synchronous HTTP call to metadata server without timeout in startup path
    • Suggestion: Add explicit timeout to the curl command: curl -fsSL --max-time 10 to prevent indefinite blocking during container startup

Type_diligence — 4 finding(s)

  • 🔵 [INFO] coordinator/deploy/start-coordinator.sh:35 — Untyped string comparison with numeric value
    • Suggestion: Use explicit numeric comparison: [ "$i" -ge "$WAIT_SECS" ] or convert to integer arithmetic
  • 🔵 [INFO] coordinator/deploy/start-platform.sh:61-75 — jq manipulation uses untyped JSON processing
    • Suggestion: Consider validating JSON structure before modification or using typed configuration approach
  • 🔵 [INFO] deploy.sh:598 — String-based port comparison without type validation
    • Suggestion: Add numeric validation: case "$1" in [!0-9]) return 2 ;; esac before comparison
  • 🔵 [INFO] deploy.sh:604 — String-based port comparison without type validation
    • Suggestion: Add numeric validation: case "$1" in [!0-9]) return 2 ;; esac before comparison

Additive_complexity — 8 finding(s) (4 blocking)

  • 🟡 [MEDIUM] deploy.sh:1-907 — 907-line monolithic script with multiple responsibilities
    • Suggestion: Split into focused modules: deployment orchestrator, Caddy management, health checking, and admin operations. Each should have a single responsibility and be independently testable.
  • 🟡 [MEDIUM] deploy.sh:31-50 — 20+ environment variables for configuration
    • Suggestion: Group related config into structured objects or reduce to essential knobs. Many of these could have sensible defaults or be derived from fewer base settings.
  • 🟡 [MEDIUM] deploy.sh:580-650 — Repeated curl + JSON parsing pattern across multiple functions
    • Suggestion: Extract a common http_json_request helper that handles authentication, timeouts, and JSON response parsing. Functions like drain_color, signal_going_away, wait_for_providers all follow the same pattern.
  • 🔵 [INFO] deploy.sh:700-800 — Similar error handling and confirmation patterns repeated
    • Suggestion: Create common helpers for confirmation prompts with dry-run awareness and error handling with context. The pattern of 'if DRY_RUN log else execute' appears many times.
  • 🟡 [MEDIUM] coordinator/deploy/start-platform.sh:1-193 — Substantial code duplication with existing start.sh
    • Suggestion: Since the comment says to keep this 'diff-able against start.sh', consider extracting shared functions into a common library that both scripts can source, rather than maintaining parallel implementations.
  • 🔵 [INFO] deploy/gcp/prod/darkbloom-run.sh:1-90 — Similar container launch patterns for platform vs coordinator
    • Suggestion: The docker run commands share most arguments. Extract a common launch_container function that takes role-specific parameters to reduce duplication and ensure consistency.
  • 🔵 [INFO] deploy.sh:400-500 — Image pinning logic mixed with deployment orchestration
    • Suggestion: Move pin_image, restore_image_pin, accept_image_pin functions to a separate image management module. The deployment orchestrator should call image management functions, not implement them.
  • 🔵 [INFO] deploy/gcp/prod/deploy_test.sh:1-301 — Test framework reinventing basic assertion patterns
    • Suggestion: The custom pass/fail/assert_* functions could be replaced with standard bash testing patterns or a lightweight existing framework. The current approach adds cognitive overhead without significant benefit.

20 finding(s) total, 7 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread deploy.sh
Comment on lines +584 to +594
local color="$1" port="$2"
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would poll http://${HEALTH_HOST}:${port}${CAPACITY_PATH} for routable capacity>0 (timeout ${PROVIDERS_TIMEOUT}s)"
return 0
fi
log "Waiting for $color (port $port) to report routable capacity>0 via $CAPACITY_PATH (timeout ${PROVIDERS_TIMEOUT}s)..."
local now deadline body count
now="$(date +%s)"
deadline=$(( now + PROVIDERS_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
body="$($CURL_BIN -fsS --max-time 5 "http://${HEALTH_HOST}:${port}${CAPACITY_PATH}" 2>/dev/null || true)"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🔒 Potential command injection in load_admin_env function

💡 Suggestion: Use safer parsing method or validate input format before processing

📊 Score: 3×2 = 6 · Category: command-injection

Comment thread deploy.sh
Comment on lines +584 to +594
local color="$1" port="$2"
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would poll http://${HEALTH_HOST}:${port}${CAPACITY_PATH} for routable capacity>0 (timeout ${PROVIDERS_TIMEOUT}s)"
return 0
fi
log "Waiting for $color (port $port) to report routable capacity>0 via $CAPACITY_PATH (timeout ${PROVIDERS_TIMEOUT}s)..."
local now deadline body count
now="$(date +%s)"
deadline=$(( now + PROVIDERS_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
body="$($CURL_BIN -fsS --max-time 5 "http://${HEALTH_HOST}:${port}${CAPACITY_PATH}" 2>/dev/null || true)"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🔒 Missing validation on EIGENINFERENCE_ADMIN_KEY format

💡 Suggestion: Add validation to ensure the key contains only expected characters

📊 Score: 2×3 = 6 · Category: missing-input-validation

Comment thread deploy.sh
Comment on lines +1 to +907
#!/usr/bin/env bash
# deploy.sh — DAR-327 Phase 2: true blue-green coordinator deploy orchestrator.
#
# Runs ON the GCE coordinator box. Performs a zero-downtime color swap. Providers
# are moved to the new color BEFORE the old color is drained/stopped, so the new
# color never serves consumers with zero providers (which would 429):
#
# 1. detect the active color from the on-box Caddyfile upstream port
# 2. (optional) pin the new image in the idle color's per-color env file
# (rolled back if the deploy is aborted before cutover; kept once accepted)
# 3. restart the IDLE color (systemctl restart darkbloom-coordinator@<idle>)
# — restart, NOT start, so a stale idle container re-execs with the new image
# 4. wait for idle /health AND /readyz (DAR-327 Phase 1 endpoints)
# 5. flip the Caddy upstream old->new + graceful `caddy reload` (cutover)
# 6. POST /v1/admin/going-away to the OLD color (DAR-327 Phase 3, PR #396) so its
# providers reconnect and — Caddy already flipped — land on the NEW color
# 7. wait until the NEW color reports routable capacity>0 (providers landed + trusted)
# 8. drain the OLD color (POST /v1/admin/drain, Phase 1) until inflight==0
# 9. stop the OLD color (systemctl stop darkbloom-coordinator@<old>)
#
# Steps 6-7 explicitly hand providers to the new color via the Phase 3
# going-away endpoint; the drain (8) and stop (9) then retire the old color with
# no capacity gap. If providers do not land on the new color, or if the drain
# does not complete, the old color is NOT drained/stopped unless --force is given.
#
# ROLLBACK (valid any time AFTER the flip and BEFORE the old color is stopped):
# ./deploy.sh --rollback
# restores BOTH routing AND capacity to the previous color. A bare Caddy flip is
# NOT sufficient once the forward deploy has signalled going-away to the old color:
# that latches the old color to REFUSE new provider registrations (503) and pushes
# its providers one-way onto the new color, so flipping back alone would route
# consumers to a color with no providers (429). Rollback therefore (1) re-enables
# the target color (undrain + clear its going-away latch so it accepts providers
# again), (2) flips the Caddy upstream back to it and reloads (restoring the
# on-disk Caddyfile if the reload itself fails), (3) broadcasts going-away to the
# now-abandoned color so its providers reconnect and land back on the restored
# color, and (4) waits for the restored color to report routable capacity>0.
#
# SAFETY:
# * --dry-run prints the full plan (new ordering) and mutates NOTHING.
# * destructive steps require interactive confirmation (skip with -y/--yes).
# * the Caddy port flip is the self-contained, unit-tested function
# flip_upstream(); see deploy/gcp/prod/deploy_test.sh.
# * sourcing this file (e.g. from the test) defines the functions but NEVER
# runs main — see the BASH_SOURCE guard at the bottom.
# * the ONLY secret touched here is EIGENINFERENCE_ADMIN_KEY: it is PARSED (a
# single grep'd line — never `source`d/`.`d) from /etc/d-inference/env
# (Secret Manager -> tmpfs -> --env-file) at cutover time to authenticate the
# admin going-away/drain POSTs. That file is docker --env-file syntax, NOT
# shell: sourcing it would execute secret values (e.g. the 12-word MNEMONIC,
# '&'/URL chars) as shell commands AS ROOT, so we never source it. The key is
# never printed or written, and is NOT read in --dry-run. All other
# coordinator secrets stay in that file and are never touched here.
#
# Cross-phase contracts (separate PRs; referenced, not implemented here):
# Phase 1 : GET /readyz + POST /v1/admin/drain (bodyless POST = start draining;
# POST {"draining":false} = clear the drain latch / undrain)
# Phase 3 : POST /v1/admin/going-away (admin-gated). Empty body = broadcast+latch,
# returns 200 {"sent":N}. {"cancel":true} = clear the latch,
# returns 200 {"going_away":false,"cleared":true}.

# NOTE: shell options are set inside main() so that sourcing this file for tests
# does not mutate the caller's shell. The functions below are written to not
# depend on `set -e`.

# ---------------------------------------------------------------------------
# Configuration (all overridable via environment)
# ---------------------------------------------------------------------------
CADDYFILE_DEFAULT="/etc/caddy/Caddyfile"
CADDYFILE="${CADDYFILE:-}"
BLUE_PORT="${BLUE_PORT:-8080}"
GREEN_PORT="${GREEN_PORT:-8081}"
HEALTH_HOST="${HEALTH_HOST:-127.0.0.1}"
HEALTH_PATH="${HEALTH_PATH:-/health}"
READYZ_PATH="${READYZ_PATH:-/readyz}"
DRAIN_PATH="${DRAIN_PATH:-/v1/admin/drain}"
CAPACITY_PATH="${CAPACITY_PATH:-/v1/models/capacity}"
# Phase 3 (PR #396) endpoint: tells the OLD color's providers to reconnect so
# they re-land on the already-flipped NEW color. Admin-gated; returns {"sent":N}.
GOING_AWAY_PATH="${GOING_AWAY_PATH:-/v1/admin/going-away}"
HEALTH_TIMEOUT="${HEALTH_TIMEOUT:-120}"
DRAIN_TIMEOUT="${DRAIN_TIMEOUT:-120}"
# How long to wait for the NEW color to report routable capacity>0 after going-away.
PROVIDERS_TIMEOUT="${PROVIDERS_TIMEOUT:-60}"
CADDY_BIN="${CADDY_BIN:-caddy}"
SYSTEMCTL_BIN="${SYSTEMCTL_BIN:-systemctl}"
CURL_BIN="${CURL_BIN:-curl}"
DINF_DEPLOY_ENV_TMPL="${DINF_DEPLOY_ENV_TMPL:-/etc/d-inference/deploy-%s.env}"
# Secrets env file (Secret Manager -> tmpfs). Holds EIGENINFERENCE_ADMIN_KEY,
# whose single line is PARSED (never sourced; see load_admin_env) at cutover time
# to authenticate the admin going-away/drain POSTs. Distinct from the non-secret
# per-color DINF_DEPLOY_ENV_TMPL image-pin files above. Overridable for tests.
DINF_ENV_FILE="${DINF_ENV_FILE:-/etc/d-inference/env}"

# Runtime flags (main overrides from CLI args).
DRY_RUN="${DRY_RUN:-0}"
ROLLBACK=0
ASSUME_YES=0
FORCE=0
IMAGE_REF=""

# Image-pin rollback state (set by pin_image, consumed by restore/accept).
# DINF_DEPLOY_ENV_BAK="" means "no pin to roll back"; DINF_DEPLOY_ENV_PINNED
# keeps restore/accept pointed at the exact per-color file pin_image touched.
DINF_DEPLOY_ENV_BAK=""
DINF_DEPLOY_ENV_EXISTED=0
DINF_DEPLOY_ENV_PINNED=""

# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
log() { printf '[deploy] %s\n' "$*"; }
warn() { printf '[deploy] WARNING: %s\n' "$*" >&2; }
err() { printf '[deploy] ERROR: %s\n' "$*" >&2; }
die() { err "$*"; exit 1; }

# ===========================================================================
# Pure, unit-tested helpers (no side effects beyond the named file).
# ===========================================================================

# flip_upstream <caddyfile> <from_port> <to_port>
#
# Rewrites ONLY the coordinator upstream line inside the (coordinator_routes)
# snippet:
# reverse_proxy 127.0.0.1:<from_port> -> reverse_proxy 127.0.0.1:<to_port>
# The step-ca (https://127.0.0.1:9000) and MicroMDM (https://127.0.0.1:9002)
# upstreams are NOT touched: they use the https:// scheme and different ports.
# All other bytes — indentation, comments, the proxy block body — are preserved,
# and the original file's inode/permissions are kept (in-place truncate+write).
#
# Returns: 0 = at least one upstream line flipped; 2 = bad args/missing file;
# 3 = no matching upstream line found (file left untouched).
flip_upstream() {
if [ "$#" -ne 3 ]; then
echo "flip_upstream: usage: flip_upstream <caddyfile> <from_port> <to_port>" >&2
return 2
fi
local caddyfile="$1" from_port="$2" to_port="$3"
if [ ! -f "$caddyfile" ]; then
echo "flip_upstream: file not found: $caddyfile" >&2
return 2
fi
local tmp
tmp="$(mktemp)" || return 2

awk -v fromp="$from_port" -v top="$to_port" '
# Only the coordinator upstream: a reverse_proxy to bare loopback (no
# https:// scheme) on the from-port, delimited so :808 never matches :8080.
/^[[:space:]]*reverse_proxy[[:space:]]+127\.0\.0\.1:/ && $0 !~ /https:\/\// {
if ($0 ~ ("127\\.0\\.0\\.1:" fromp "([^0-9]|$)")) {
sub("127\\.0\\.0\\.1:" fromp, "127.0.0.1:" top)
changed++
}
}
{ print }
END { exit (changed + 0 == 0) ? 3 : 0 }
' "$caddyfile" > "$tmp"
local rc=$?

if [ "$rc" -ne 0 ]; then
rm -f "$tmp"
return "$rc"
fi
if ! cat "$tmp" > "$caddyfile"; then
rm -f "$tmp"
echo "flip_upstream: failed to write $caddyfile" >&2
return 2
fi
rm -f "$tmp"
return 0
}

# current_upstream_port <caddyfile>
# Prints the coordinator upstream port (the blue-green swap target). Returns 3
# if no coordinator upstream line is present.
current_upstream_port() {
if [ "$#" -ne 1 ]; then
echo "current_upstream_port: usage: current_upstream_port <caddyfile>" >&2
return 2
fi
local caddyfile="$1"
if [ ! -f "$caddyfile" ]; then
echo "current_upstream_port: file not found: $caddyfile" >&2
return 2
fi
awk '
/^[[:space:]]*reverse_proxy[[:space:]]+127\.0\.0\.1:/ && $0 !~ /https:\/\// {
if (match($0, /127\.0\.0\.1:[0-9]+/)) {
tok = substr($0, RSTART, RLENGTH)
sub(/.*:/, "", tok)
print tok
found = 1
exit
}
}
END { if (found != 1) exit 3 }
' "$caddyfile"
}

port_for_color() {
case "$1" in
blue) echo "$BLUE_PORT" ;;
green) echo "$GREEN_PORT" ;;
*) echo "port_for_color: unknown color: $1" >&2; return 2 ;;
esac
}

color_for_port() {
if [ "$1" = "$BLUE_PORT" ]; then
echo blue
elif [ "$1" = "$GREEN_PORT" ]; then
echo green
else
echo "color_for_port: port '$1' is neither blue($BLUE_PORT) nor green($GREEN_PORT)" >&2
return 2
fi
}

other_color() {
case "$1" in
blue) echo green ;;
green) echo blue ;;
*) echo "other_color: unknown color: $1" >&2; return 2 ;;
esac
}

deploy_env_for_color() {
if [ "$#" -ne 1 ]; then
echo "deploy_env_for_color: usage: deploy_env_for_color <blue|green>" >&2
return 2
fi
local color="$1"
case "$color" in
blue|green) ;;
*) echo "deploy_env_for_color: unknown color: $color" >&2; return 2 ;;
esac
case "$DINF_DEPLOY_ENV_TMPL" in
*%s*) printf '%s\n' "${DINF_DEPLOY_ENV_TMPL/\%s/$color}" ;;
*) echo "deploy_env_for_color: DINF_DEPLOY_ENV_TMPL must contain %s: $DINF_DEPLOY_ENV_TMPL" >&2; return 2 ;;
esac
}

# ===========================================================================
# Effectful helpers (dry-run aware).
# ===========================================================================

run_cmd() {
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN exec: $*"
return 0
fi
"$@"
}

confirm() {
[ "$ASSUME_YES" -eq 1 ] && return 0
[ "$DRY_RUN" -eq 1 ] && return 0
local prompt="$1" ans
printf '%s [y/N] ' "$prompt" >&2
if ! IFS= read -r ans; then
return 1
fi
case "$ans" in
y|Y|yes|YES|Yes) return 0 ;;
*) return 1 ;;
esac
}

http_code() {
# No -f: we WANT the real status code for 4xx/5xx (not a curl error). On a
# connection failure curl prints "000"; default to 000 if it prints nothing.
local code
code="$("$CURL_BIN" -sS -o /dev/null -w '%{http_code}' --max-time 5 "$1" 2>/dev/null)"
printf '%s' "${code:-000}"
}

reload_caddy() {
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would run: $CADDY_BIN validate --config $CADDYFILE --adapter caddyfile"
log "DRY-RUN: would run: $CADDY_BIN reload --config $CADDYFILE --adapter caddyfile"
return 0
fi
log "Validating Caddyfile ($CADDYFILE)..."
if ! "$CADDY_BIN" validate --config "$CADDYFILE" --adapter caddyfile; then
err "caddy validate failed; not reloading"
return 1
fi
log "Reloading Caddy (graceful, zero-downtime)..."
"$CADDY_BIN" reload --config "$CADDYFILE" --adapter caddyfile
}

# pin_image <color> <ref> — write DINF_IMAGE=<ref> to the idle color's per-color
# deploy env file so only that color re-execs with the new image. The previous
# pin state is snapshotted first so restore_image_pin can undo it if the deploy
# is aborted BEFORE the cutover is accepted. The pin is made permanent by
# accept_image_pin once the cutover succeeds.
pin_image() {
if [ "$#" -ne 2 ]; then
echo "pin_image: usage: pin_image <blue|green> <image-ref>" >&2
return 2
fi
local color="$1" ref="$2" pin_file
pin_file="$(deploy_env_for_color "$color")" || return $?
log "Pinning $color image: DINF_IMAGE=$ref -> $pin_file"
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would snapshot $pin_file, then write DINF_IMAGE=$ref (read by darkbloom-run.sh via EnvironmentFile); the pin is rolled back if the deploy aborts before cutover, kept once cutover is accepted"
return 0
fi
local dir bak tmp rc
dir="$(dirname "$pin_file")"
if ! mkdir -p "$dir"; then
err "failed to create deploy env directory $dir"
return 1
fi
# Snapshot the current pin so an aborted/declined/unhealthy deploy can restore
# it. An empty backup with DINF_DEPLOY_ENV_EXISTED=0 marks "file did not exist".
bak="$(mktemp)" || { err "mktemp failed"; return 1; }
if [ -f "$pin_file" ]; then
if ! cat "$pin_file" > "$bak"; then
rm -f "$bak"
err "failed to snapshot existing image pin $pin_file"
return 1
fi
DINF_DEPLOY_ENV_EXISTED=1
else
DINF_DEPLOY_ENV_EXISTED=0
fi
DINF_DEPLOY_ENV_BAK="$bak"
DINF_DEPLOY_ENV_PINNED="$pin_file"

tmp="$(mktemp)" || { err "mktemp failed"; return 1; }
if [ -f "$pin_file" ]; then
grep -v '^DINF_IMAGE=' "$pin_file" > "$tmp"
rc=$?
if [ "$rc" -gt 1 ]; then
rm -f "$tmp"
err "failed to read existing image pin $pin_file"
return 1
fi
fi
if ! printf 'DINF_IMAGE=%s\n' "$ref" >> "$tmp"; then
rm -f "$tmp"
err "failed to write temporary image pin for $pin_file"
return 1
fi
if ! cat "$tmp" > "$pin_file"; then
rm -f "$tmp"
err "failed to write image pin $pin_file"
return 1
fi
rm -f "$tmp"
if ! chmod 644 "$pin_file"; then
err "failed to chmod image pin $pin_file"
return 1
fi
}

# restore_image_pin — undo a pin_image() write. Called on any exit BEFORE the
# cutover is accepted (via the EXIT trap in main). No-op if nothing was pinned or
# the pin was already accepted (accept_image_pin clears the backup).
restore_image_pin() {
[ -n "${DINF_DEPLOY_ENV_BAK:-}" ] || return 0
[ "$DRY_RUN" -eq 1 ] && return 0
local pin_file="${DINF_DEPLOY_ENV_PINNED:-}"
if [ -z "$pin_file" ]; then
warn "Deploy aborted before cutover, but no pinned deploy env path was recorded; cannot restore image pin."
rm -f "$DINF_DEPLOY_ENV_BAK"
DINF_DEPLOY_ENV_BAK=""
return 0
fi
if [ "${DINF_DEPLOY_ENV_EXISTED:-0}" -eq 1 ]; then
warn "Deploy aborted before cutover: restoring previous image pin in $pin_file."
cat "$DINF_DEPLOY_ENV_BAK" > "$pin_file" 2>/dev/null || warn "failed to restore $pin_file"
chmod 644 "$pin_file" 2>/dev/null || true
else
warn "Deploy aborted before cutover: removing image pin $pin_file (created this run)."
rm -f "$pin_file" 2>/dev/null || warn "failed to remove $pin_file"
fi
rm -f "$DINF_DEPLOY_ENV_BAK"
DINF_DEPLOY_ENV_BAK=""
DINF_DEPLOY_ENV_PINNED=""
}

# accept_image_pin — keep the pin permanently (cutover succeeded) and disarm the
# restore_image_pin rollback by dropping the backup.
accept_image_pin() {
[ -n "${DINF_DEPLOY_ENV_BAK:-}" ] || return 0
rm -f "$DINF_DEPLOY_ENV_BAK"
DINF_DEPLOY_ENV_BAK=""
DINF_DEPLOY_ENV_PINNED=""
}

# wait_healthy <color> <port> — poll /health AND /readyz until both 200 or timeout.
wait_healthy() {
local color="$1" port="$2"
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would poll http://${HEALTH_HOST}:${port}${HEALTH_PATH} AND ${READYZ_PATH} until 200 (timeout ${HEALTH_TIMEOUT}s)"
return 0
fi
log "Waiting for $color (port $port) /health + /readyz (timeout ${HEALTH_TIMEOUT}s)..."
local now deadline h r
now="$(date +%s)"
deadline=$(( now + HEALTH_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
h="$(http_code "http://${HEALTH_HOST}:${port}${HEALTH_PATH}")"
r="$(http_code "http://${HEALTH_HOST}:${port}${READYZ_PATH}")"
if [ "$h" = "200" ] && [ "$r" = "200" ]; then
log "$color is healthy (/health=200, /readyz=200)."
return 0
fi
log " $color /health=$h /readyz=$r; waiting..."
sleep 2
done
err "$color did not become healthy within ${HEALTH_TIMEOUT}s."
return 1
}

# load_admin_env — read ONLY the EIGENINFERENCE_ADMIN_KEY line from the secrets
# env file into the global of the same name, for the authenticated going-away +
# drain requests.
#
# SECURITY: that file is docker --env-file syntax (KEY=VALUE), NOT shell. Sourcing
# it (`.`/`source`) would execute values — the 12-word MNEMONIC, '&', URL/`$()`
# chars — as shell commands AS ROOT (secret leak / RCE). So we never source it; we
# grep the single line and strip optional surrounding quotes. No eval, no source.
# The value is never printed. Called only at real cutover time (after the
# --dry-run early returns) so the plan stays secret-free. No-op + warning if the
# file is absent/unreadable (caller still warns on empty key and continues).
load_admin_env() {
if [ -r "$DINF_ENV_FILE" ]; then
# First match wins; cut -f2- keeps '=' chars in the value; 2>/dev/null + the
# lack of `set -e` make a no-match safely yield an empty key.
EIGENINFERENCE_ADMIN_KEY="$(grep -E '^EIGENINFERENCE_ADMIN_KEY=' "$DINF_ENV_FILE" 2>/dev/null | head -n1 | cut -d= -f2-)"
# Strip one pair of surrounding quotes if the value is quoted in the env file.
case "$EIGENINFERENCE_ADMIN_KEY" in
'"'*'"') EIGENINFERENCE_ADMIN_KEY="${EIGENINFERENCE_ADMIN_KEY#\"}"; EIGENINFERENCE_ADMIN_KEY="${EIGENINFERENCE_ADMIN_KEY%\"}" ;;
"'"*"'") EIGENINFERENCE_ADMIN_KEY="${EIGENINFERENCE_ADMIN_KEY#\'}"; EIGENINFERENCE_ADMIN_KEY="${EIGENINFERENCE_ADMIN_KEY%\'}" ;;
esac
else
warn "secrets env file not readable at $DINF_ENV_FILE; admin key unavailable for going-away/drain auth"
fi
}

# drain_color <color> <port> — POST /v1/admin/drain then poll /readyz inflight==0.
# Returns 0 once inflight==0, NON-ZERO on timeout so the caller does NOT stop a
# color that still has in-flight requests (stopping would cut them at the SIGTERM
# deadline). EIGENINFERENCE_ADMIN_KEY is loaded once by the caller (load_admin_env).
drain_color() {
local color="$1" port="$2"
log "Draining $color (port $port): POST $DRAIN_PATH, then poll $READYZ_PATH inflight==0..."
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would POST $DRAIN_PATH to $color:$port and poll inflight==0 (timeout ${DRAIN_TIMEOUT}s)"
return 0
fi
# Phase 1 contract: admin-authenticated drain endpoint. The bearer key was
# parsed (not sourced) from the env file by the caller's load_admin_env.
if ! "$CURL_BIN" -fsS -X POST \
-H "Authorization: Bearer ${EIGENINFERENCE_ADMIN_KEY:-}" \
--max-time 10 \
"http://${HEALTH_HOST}:${port}${DRAIN_PATH}" >/dev/null; then
warn "drain request to $color returned an error (continuing to poll readiness)"
fi
local now deadline body inflight
now="$(date +%s)"
deadline=$(( now + DRAIN_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
body="$("$CURL_BIN" -fsS --max-time 5 "http://${HEALTH_HOST}:${port}${READYZ_PATH}" 2>/dev/null || true)"
# Phase 1 contract: /readyz exposes an inflight counter, e.g. {"inflight":0}.
inflight="$(printf '%s' "$body" | sed -n 's/.*"inflight"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' | head -n1)"
if [ -n "$inflight" ] && [ "$inflight" -eq 0 ]; then
log "$color drained (inflight=0)."
return 0
fi
log " $color inflight=${inflight:-unknown}; waiting..."
sleep 3
done
err "$color did not reach inflight==0 within ${DRAIN_TIMEOUT}s."
return 1
}

# undrain_color <color> <port> — POST /v1/admin/drain {"draining":false} to CLEAR a
# color's drain latch so it re-accepts work (the inverse of drain_color's bodyless
# POST, which STARTS draining). Used by --rollback to re-enable the rollback target,
# which the forward deploy may have drained. Best-effort: warns and continues on any
# failure so a not-yet-deployed endpoint degrades gracefully. DRY_RUN-aware.
# EIGENINFERENCE_ADMIN_KEY is loaded once by the caller (load_admin_env).
undrain_color() {
local color="$1" port="$2"
log "Undraining $color (port $port): POST $DRAIN_PATH {\"draining\":false} (re-accept work)..."
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would POST $DRAIN_PATH {\"draining\":false} to $color:$port"
return 0
fi
# Phase 1 contract: the drain endpoint accepts {"draining":false} to UN-drain.
if ! "$CURL_BIN" -fsS -X POST \
-H "Authorization: Bearer ${EIGENINFERENCE_ADMIN_KEY:-}" \
-H "Content-Type: application/json" \
--max-time 10 \
--data '{"draining":false}' \
"http://${HEALTH_HOST}:${port}${DRAIN_PATH}" >/dev/null; then
warn "undrain request to $color returned an error (continuing; it may already accept work, or the endpoint is not deployed yet)."
else
log "$color undrained (now re-accepting work)."
fi
}

# signal_going_away <color> <port> — POST /v1/admin/going-away to the OLD color so
# its providers reconnect and (Caddy already flipped) re-land on the NEW color.
# Phase 3 (PR #396) contract: admin-gated, returns 200 {"sent":N}. Best-effort:
# warns and continues if it fails (providers still reconnect within the heartbeat
# timeout, and the drain + graceful stop still finish in-flight work).
# EIGENINFERENCE_ADMIN_KEY is loaded once by the caller (load_admin_env).
signal_going_away() {
local color="$1" port="$2"
log "Going-away to OLD color $color (port $port): POST $GOING_AWAY_PATH (providers reconnect -> new color)..."
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would POST $GOING_AWAY_PATH to $color:$port (admin-gated; expect 200 {\"sent\":N})"
return 0
fi
local body sent
body="$("$CURL_BIN" -fsS -X POST \
-H "Authorization: Bearer ${EIGENINFERENCE_ADMIN_KEY:-}" \
--max-time 10 \
"http://${HEALTH_HOST}:${port}${GOING_AWAY_PATH}" 2>/dev/null || true)"
# Contract response: {"sent":N}.
sent="$(printf '%s' "$body" | sed -n 's/.*"sent"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' | head -n1)"
if [ -n "$sent" ]; then
log "going-away accepted by $color (sent=$sent; those providers will reconnect to the new color)."
else
warn "going-away to $color did not return a parseable {\"sent\":N} (continuing; providers will still reconnect within the heartbeat timeout)."
fi
}

# clear_going_away <color> <port> — POST /v1/admin/going-away {"cancel":true} to
# CLEAR a color's going-away latch (set by a prior signal_going_away). Until cleared
# that latch makes the color REFUSE new provider registrations (503), so --rollback
# MUST clear it on the rollback target before flipping traffic back, or the restored
# color would route consumers to zero providers. Phase 3 (PR #396) contract:
# admin-gated; empty body = broadcast+latch (signal_going_away), {"cancel":true} =
# clear, returns 200 {"going_away":false,"cleared":true}. Best-effort: warns and
# continues on failure (a not-yet-deployed endpoint degrades gracefully).
# DRY_RUN-aware. EIGENINFERENCE_ADMIN_KEY is loaded once by the caller (load_admin_env).
clear_going_away() {
local color="$1" port="$2"
log "Clearing going-away latch on $color (port $port): POST $GOING_AWAY_PATH {\"cancel\":true} (re-accept providers)..."
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would POST $GOING_AWAY_PATH {\"cancel\":true} to $color:$port (admin-gated; expect 200 {\"going_away\":false,\"cleared\":true})"
return 0
fi
local body cleared
body="$("$CURL_BIN" -fsS -X POST \
-H "Authorization: Bearer ${EIGENINFERENCE_ADMIN_KEY:-}" \
-H "Content-Type: application/json" \
--max-time 10 \
--data '{"cancel":true}' \
"http://${HEALTH_HOST}:${port}${GOING_AWAY_PATH}" 2>/dev/null || true)"
# Contract response: {"going_away":false,"cleared":true}.
cleared="$(printf '%s' "$body" | sed -n 's/.*"cleared"[[:space:]]*:[[:space:]]*true.*/true/p' | head -n1)"
if [ "$cleared" = "true" ]; then
log "going-away latch cleared on $color (now re-accepts provider registrations)."
else
warn "clear going-away on $color did not confirm {\"cleared\":true} (continuing; endpoint may not be deployed yet — providers will still re-register once it accepts them)."
fi
}

# capacity_model_count reads GET /v1/models/capacity JSON from stdin and prints the
# number of routable capacity entries. Empty/malformed bodies produce 0. Uses
# python3 instead of jq because the GCE deploy box already relies on python3 in
# darkbloom-run.sh for registry auth, while jq may not be installed.
capacity_model_count() {
python3 -c 'import json,sys
try:
body=json.load(sys.stdin)
print(len(body.get("models") or []))
except Exception:
print(0)'
}

# wait_for_providers <color> <port> — after going-away, poll the NEW color's
# routable capacity feed until at least one model has capacity. Raw /health
# providers only proves a WebSocket registered; /v1/models/capacity proves the
# provider is trusted/routable enough for consumers. Returns nonzero on timeout.
wait_for_providers() {
local color="$1" port="$2"
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would poll http://${HEALTH_HOST}:${port}${CAPACITY_PATH} for routable capacity>0 (timeout ${PROVIDERS_TIMEOUT}s)"
return 0
fi
log "Waiting for $color (port $port) to report routable capacity>0 via $CAPACITY_PATH (timeout ${PROVIDERS_TIMEOUT}s)..."
local now deadline body count
now="$(date +%s)"
deadline=$(( now + PROVIDERS_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
body="$($CURL_BIN -fsS --max-time 5 "http://${HEALTH_HOST}:${port}${CAPACITY_PATH}" 2>/dev/null || true)"
count="$(printf '%s' "$body" | capacity_model_count)"
if [ -n "$count" ] && [ "$count" -gt 0 ]; then
log "$color now has $count routable capacity entr(ies)."
return 0
fi
log " $color routable_capacity=${count:-0}; waiting for trusted/routable providers..."
sleep 2
done
warn "$color did not report routable capacity>0 within ${PROVIDERS_TIMEOUT}s; providers may still be reconnecting/attesting."
return 1
}

# ===========================================================================
# Rollback
# ===========================================================================
do_rollback() {
local cur_port cur_color target_color target_port
cur_port="$(current_upstream_port "$CADDYFILE")" || die "could not read current upstream port from $CADDYFILE"
cur_color="$(color_for_port "$cur_port")" || die "current upstream port $cur_port is not a known color"
target_color="$(other_color "$cur_color")"
target_port="$(port_for_color "$target_color")"
log "ROLLBACK: Caddy currently -> $cur_color ($cur_port); reverting to $target_color ($target_port)."
log "Rollback restores routing AND capacity: re-enable $target_color (undrain + clear its going-away latch), flip Caddy back, then push providers off $cur_color back onto $target_color."
warn "The $target_color container must still be RUNNING (rollback is valid only before it was stopped)."
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would health-check $target_color at http://${HEALTH_HOST}:${target_port}${HEALTH_PATH} before flipping."
log "DRY-RUN: would load_admin_env (parse EIGENINFERENCE_ADMIN_KEY for the admin POSTs below)."
log "DRY-RUN: STEP A — would re-enable $target_color: POST $DRAIN_PATH {\"draining\":false} (undrain) + POST $GOING_AWAY_PATH {\"cancel\":true} (clear going-away latch) to ${HEALTH_HOST}:${target_port}."
log "DRY-RUN: STEP B — would flip_upstream $CADDYFILE $cur_port $target_port, then reload Caddy (auto-revert to $cur_color if reload fails)."
log "DRY-RUN: STEP C — would POST $GOING_AWAY_PATH to the now-abandoned $cur_color ($cur_port) so its providers reconnect and land on $target_color."
log "DRY-RUN: STEP D — would poll $target_color ($target_port) $CAPACITY_PATH for routable capacity>0 (timeout ${PROVIDERS_TIMEOUT}s)."
log "DRY-RUN: would leave $cur_color running (idle, providers drained off) for inspection; stop it manually with '$SYSTEMCTL_BIN stop darkbloom-coordinator@${cur_color}'."
return 0
fi
# Never flip onto a dead port (connection refused -> 502s): probe the target's
# liveness BEFORE flipping. Single-shot http_code (not the up-to-${HEALTH_TIMEOUT}s
# wait_healthy poll) so a dead target is refused fast. /health is liveness only:
# a drained-but-running old color stays rollback-able even if /readyz is not 200.
local target_health
target_health="$(http_code "http://${HEALTH_HOST}:${target_port}${HEALTH_PATH}")"
if [ "$target_health" = "200" ]; then
log "Rollback target $target_color (port $target_port) is alive (/health=200)."
elif [ "$FORCE" -eq 1 ]; then
warn "!!! Rollback target $target_color (port $target_port) is NOT healthy (/health=$target_health); proceeding anyway because --force was given — traffic may hit a dead port (502s) !!!"
else
err "Rollback target $target_color (port $target_port) is NOT healthy (/health=$target_health)."
err "Refusing to flip Caddy onto a dead/unhealthy port (would cause 502s)."
err "Start it first (e.g. '$SYSTEMCTL_BIN start darkbloom-coordinator@${target_color}'), or re-run with --force to flip anyway."
return 1
fi
confirm "Roll back to $target_color: re-enable it, flip Caddy $cur_port -> $target_port, and push providers back?" || { log "Rollback aborted."; return 1; }

# Parse the admin key for the authenticated undrain + going-away POSTs below. Real
# run only — the --dry-run path returned above, so the plan stays secret-free.
load_admin_env
if [ -z "${EIGENINFERENCE_ADMIN_KEY:-}" ]; then
warn "EIGENINFERENCE_ADMIN_KEY is empty ($DINF_ENV_FILE missing or unset); the undrain/going-away POSTs will be unauthenticated and likely rejected — continuing (best-effort)."
fi

# STEP A — re-enable the rollback target BEFORE flipping traffic onto it. The
# forward deploy latched it going-away (it now refuses new provider registrations,
# 503) and may have drained it; undo BOTH so it can re-accept providers once Caddy
# points back at it. Best-effort (warn + continue) so a not-yet-deployed Phase 1/3
# endpoint degrades gracefully.
undrain_color "$target_color" "$target_port"
clear_going_away "$target_color" "$target_port"

# STEP B — flip Caddy cur->target + reload. Mirror the cutover path: if the reload
# fails after flipping the on-disk Caddyfile, flip it BACK so on-disk state matches
# live Caddy (still -> $cur_color); otherwise a later run would read the stale
# on-disk port and flip/stop the wrong color.
flip_upstream "$CADDYFILE" "$cur_port" "$target_port" || die "flip_upstream failed (rc $?)"
if ! reload_caddy; then
err "caddy reload failed after rollback flip; restoring Caddyfile to $cur_color ($cur_port) so on-disk state matches live Caddy."
flip_upstream "$CADDYFILE" "$target_port" "$cur_port" || err "restore flip ALSO failed — manual intervention required on $CADDYFILE"
reload_caddy || true
die "rollback aborted: caddy reload failed (Caddyfile restored to $cur_color)"
fi
log "Caddy now -> $target_color ($target_port)."

# STEP C — push providers off the now-abandoned $cur_color back onto $target_color.
# Broadcast going-away to $cur_color: its providers reconnect and — Caddy already
# flipped — land on $target_color. (signal_going_away logs this as the "OLD" color;
# in a rollback that is the abandoned new color we are retiring.) Best-effort like
# the forward path; providers also reconnect within the heartbeat timeout.
log "Pushing providers off the abandoned $cur_color back onto $target_color..."
signal_going_away "$cur_color" "$cur_port"

# STEP D — confirm routable capacity actually returned to $target_color. If it
# does not, restore routing to the previously-live $cur_color rather than
# declaring rollback success on a provider-empty target.
if ! wait_for_providers "$target_color" "$target_port"; then
warn "Rollback target $target_color did not regain routable capacity; restoring Caddy back to $cur_color."
undrain_color "$cur_color" "$cur_port"
clear_going_away "$cur_color" "$cur_port"
flip_upstream "$CADDYFILE" "$target_port" "$cur_port" || die "rollback recovery failed: could not flip Caddy back to $cur_color ($cur_port); manual intervention required"
if ! reload_caddy; then
die "rollback recovery failed: Caddy reload back to $cur_color ($cur_port) failed; manual intervention required"
fi
signal_going_away "$target_color" "$target_port"
wait_for_providers "$cur_color" "$cur_port" || warn "Previously-live $cur_color did not confirm routable capacity after rollback recovery; monitor capacity immediately."
die "rollback aborted: providers did not return to $target_color; Caddy restored to $cur_color"
fi

log "ROLLBACK complete: Caddy -> $target_color ($target_port); providers pushed back to it."
log "The abandoned $cur_color ($cur_port) is left RUNNING (idle, providers drained off) for inspection; stop it manually with '$SYSTEMCTL_BIN stop darkbloom-coordinator@${cur_color}'."
}

# ===========================================================================
# CLI
# ===========================================================================
usage_main() {
cat <<'USAGE'
Usage: deploy.sh [options]

Blue-green coordinator deploy on the GCE box. Detects the active color from the
Caddy upstream, brings up the idle color, cuts over, drains, and stops the old.

Options:
--image <ref> Pin this container image for the idle color before starting.
--caddyfile <path> Caddyfile to read/flip (default: /etc/caddy/Caddyfile).
--rollback Roll back to the other (still-running) color: re-enable it
(undrain + clear its going-away latch), flip Caddy back +
reload, then push providers back onto it and wait for
routable capacity>0.
--force Forward: continue drain/stop even if providers do not land or
drain times out. Rollback: flip even if target health fails
(DANGEROUS — may route traffic to a dead port).
--dry-run Print the plan; change nothing.
-y, --yes Assume "yes" to all confirmation prompts (non-interactive).
-h, --help Show this help.

Environment overrides: CADDYFILE, BLUE_PORT(8080), GREEN_PORT(8081), HEALTH_HOST,
HEALTH_TIMEOUT, DRAIN_TIMEOUT, PROVIDERS_TIMEOUT(60), GOING_AWAY_PATH,
CAPACITY_PATH(/v1/models/capacity), CADDY_BIN, SYSTEMCTL_BIN, CURL_BIN,
DINF_DEPLOY_ENV_TMPL(/etc/d-inference/deploy-%s.env), DINF_ENV_FILE(/etc/d-inference/env).
USAGE
}

main() {
set -uo pipefail

DRY_RUN=0
ROLLBACK=0
ASSUME_YES=0
FORCE=0
IMAGE_REF=""

while [ "$#" -gt 0 ]; do
case "$1" in
--dry-run) DRY_RUN=1 ;;
--rollback) ROLLBACK=1 ;;
--force) FORCE=1 ;;
-y|--yes) ASSUME_YES=1 ;;
--image) [ "$#" -ge 2 ] || { err "--image requires a value"; return 2; }; IMAGE_REF="$2"; shift ;;
--image=*) IMAGE_REF="${1#*=}" ;;
--caddyfile) [ "$#" -ge 2 ] || { err "--caddyfile requires a value"; return 2; }; CADDYFILE="$2"; shift ;;
--caddyfile=*) CADDYFILE="${1#*=}" ;;
-h|--help) usage_main; return 0 ;;
*) err "unknown argument: $1"; usage_main; return 2 ;;
esac
shift
done

CADDYFILE="${CADDYFILE:-$CADDYFILE_DEFAULT}"
[ -f "$CADDYFILE" ] || die "Caddyfile not found: $CADDYFILE (use --caddyfile or set CADDYFILE)"

if [ "$ROLLBACK" -eq 1 ]; then
do_rollback
return $?
fi

local active_port active_color idle_color idle_port image_pin_file
active_port="$(current_upstream_port "$CADDYFILE")" || die "could not detect active upstream port in $CADDYFILE"
active_color="$(color_for_port "$active_port")" || die "active upstream port $active_port is neither blue($BLUE_PORT) nor green($GREEN_PORT)"
idle_color="$(other_color "$active_color")"
idle_port="$(port_for_color "$idle_color")"
if [ -n "$IMAGE_REF" ]; then
image_pin_file="$(deploy_env_for_color "$idle_color")" || die "could not compute deploy env path for idle color $idle_color"
fi

log "=============================================================="
log " Blue-green deploy plan"
log " Caddyfile : $CADDYFILE"
log " Active (live) : $active_color (port $active_port)"
log " Idle (target) : $idle_color (port $idle_port)"
[ -n "$IMAGE_REF" ] && log " New image : $IMAGE_REF"
[ -n "$IMAGE_REF" ] && log " Image pin file : $image_pin_file"
[ "$DRY_RUN" -eq 1 ] && log " MODE : DRY-RUN (no changes will be made)"
log "=============================================================="

# Roll the image pin back automatically on ANY exit before the cutover is
# accepted (declined confirm, failed start, unhealthy idle, failed flip/reload).
# accept_image_pin() disarms this once the cutover succeeds. No-op without --image.
trap 'restore_image_pin' EXIT

# 1. Pin image for the idle color (optional). Snapshotted so it is rolled back
# if the deploy aborts before cutover.
if [ -n "$IMAGE_REF" ]; then
if ! pin_image "$idle_color" "$IMAGE_REF"; then
die "deploy aborted: failed to pin image for idle color '$idle_color'; not restarting it"
fi
fi

# 2. Restart the idle color. RESTART (not start) so a stale already-running idle
# container re-execs darkbloom-run.sh and picks up the newly pinned image.
# Check the rc and fail fast: a failed unit (re)start would otherwise only
# surface after wait_healthy times out (up to ${HEALTH_TIMEOUT}s).
confirm "Restart idle color '$idle_color' (re-exec with the pinned image)?" || die "aborted before starting idle color"
if ! run_cmd "$SYSTEMCTL_BIN" restart "darkbloom-coordinator@${idle_color}"; then
die "failed to (re)start idle color '$idle_color' ($SYSTEMCTL_BIN restart darkbloom-coordinator@${idle_color} exited non-zero); Caddy untouched ($active_color still live). Inspect: $SYSTEMCTL_BIN status darkbloom-coordinator@${idle_color}"
fi

# 3. Wait for idle health + readiness.
if ! wait_healthy "$idle_color" "$idle_port"; then
err "Idle color $idle_color failed health check; stopping it. Caddy untouched ($active_color still live)."
run_cmd "$SYSTEMCTL_BIN" stop "darkbloom-coordinator@${idle_color}"
die "deploy aborted: idle color unhealthy"
fi

# 4. Cutover: flip Caddy upstream active->idle + graceful reload (DESTRUCTIVE).
if ! confirm "CUTOVER: flip Caddy $active_port -> $idle_port (live traffic to $idle_color) and reload?"; then
err "Cutover declined; stopping idle color. Caddy still -> $active_color."
run_cmd "$SYSTEMCTL_BIN" stop "darkbloom-coordinator@${idle_color}"
die "deploy aborted before cutover"
fi
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would flip_upstream $CADDYFILE $active_port $idle_port, then reload Caddy."
else
flip_upstream "$CADDYFILE" "$active_port" "$idle_port" || die "flip_upstream failed (rc $?); Caddy unchanged, $active_color still live"
if ! reload_caddy; then
err "caddy reload failed after flip; attempting automatic rollback flip."
flip_upstream "$CADDYFILE" "$idle_port" "$active_port" || err "rollback flip ALSO failed — manual intervention required on $CADDYFILE"
reload_caddy || true
die "deploy aborted: caddy reload failed (attempted rollback to $active_color)"
fi
fi
# Cutover accepted: the NEW color is live. Keep the image pin permanently and
# disarm the EXIT-trap rollback.
accept_image_pin
log "Cutover complete: Caddy -> $idle_color ($idle_port). $active_color still running for drain."
log "Rollback window OPEN: run '$0 --rollback' to revert to $active_color (valid until it is stopped)."

# Parse the admin key ONCE (real run only; never in --dry-run so the plan stays
# secret-free) for the authenticated going-away + drain POSTs below.
if [ "$DRY_RUN" -ne 1 ]; then
load_admin_env
if [ -z "${EIGENINFERENCE_ADMIN_KEY:-}" ]; then
warn "EIGENINFERENCE_ADMIN_KEY is empty ($DINF_ENV_FILE missing or unset); going-away and drain POSTs will be unauthenticated and likely rejected — continuing."
fi
fi

# 5. Move providers to the NEW color BEFORE draining the old one: POST
# going-away to the OLD color so its providers reconnect and land on the
# (already-flipped) new color. Without this the new color would serve
# consumers with zero providers during the drain window (429s).
signal_going_away "$active_color" "$active_port"

# 6. Wait until the NEW color actually has routable capacity (reconnects landed
# and providers are trusted/routable). If this times out, do NOT drain/stop
# the old color unless --force is set: old providers have not proven they
# landed on the new color yet.
if ! wait_for_providers "$idle_color" "$idle_port"; then
if [ "$FORCE" -eq 1 ]; then
warn "Routable capacity did not land on $idle_color within ${PROVIDERS_TIMEOUT}s, but --force was given; proceeding to drain/stop $active_color despite capacity risk."
else
err "NOT draining or stopping $active_color: $idle_color did not report routable capacity>0 within ${PROVIDERS_TIMEOUT}s."
err "Restoring Caddy back to $active_color so production traffic returns to the known-capacity color."
undrain_color "$active_color" "$active_port"
clear_going_away "$active_color" "$active_port"
flip_upstream "$CADDYFILE" "$idle_port" "$active_port" || die "provider handoff failed and Caddy restore flip back to $active_color failed; manual intervention required"
if ! reload_caddy; then
die "provider handoff failed and Caddy reload back to $active_color failed; manual intervention required"
fi
signal_going_away "$idle_color" "$idle_port"
wait_for_providers "$active_color" "$active_port" || warn "$active_color did not confirm routable capacity after restore; monitor capacity immediately."
die "deploy aborted: providers did not land on new color; Caddy restored to $active_color and $active_color left running"
fi
fi

# 7. Drain the old color. If it does NOT drain in time, do NOT stop it (stopping
# would cut in-flight requests at the container SIGTERM deadline): abort with
# a nonzero exit (Caddy already -> new color, old color left running) unless
# --force is given.
if ! drain_color "$active_color" "$active_port"; then
if [ "$FORCE" -eq 1 ]; then
warn "Drain of $active_color did not complete, but --force was given; proceeding to stop it (in-flight requests may be cut at the container SIGTERM deadline)."
else
err "NOT stopping $active_color: its drain did not reach inflight==0 within ${DRAIN_TIMEOUT}s."
err "Caddy is already -> $idle_color; the old color stays RUNNING (rollback still possible)."
err "Investigate, then stop manually ('$SYSTEMCTL_BIN stop darkbloom-coordinator@${active_color}'), or re-run with --force to stop despite in-flight requests."
die "deploy aborted: old color drain incomplete (cutover done, $active_color left running)"
fi
fi

# 8. Stop the old color (closes the rollback window). Fail if the stop fails:
# a still-running old color stays attached to providers and must not linger
# silently as if the deploy succeeded.
if ! confirm "Stop old color '$active_color'? (closes rollback window)"; then
warn "Old color $active_color left RUNNING. Stop later with: $SYSTEMCTL_BIN stop darkbloom-coordinator@${active_color}"
log "Deploy finished (old color intentionally not stopped)."
return 0
fi
if ! run_cmd "$SYSTEMCTL_BIN" stop "darkbloom-coordinator@${active_color}"; then
die "failed to stop old color '$active_color' ($SYSTEMCTL_BIN stop darkbloom-coordinator@${active_color} exited non-zero); it may still be attached to providers — investigate: $SYSTEMCTL_BIN status darkbloom-coordinator@${active_color}"
fi
log "Old color $active_color stopped. Deploy complete: $idle_color is now the sole live coordinator."
}

# Only auto-run when executed directly — NEVER when sourced (e.g. by the test).
if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
main "$@"
fi

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ Large shell script with potential memory growth from unbounded string operations

💡 Suggestion: Consider breaking this 900+ line script into smaller functions or separate scripts to reduce memory footprint and improve maintainability

📊 Score: 3×4 = 12 · Category: unbounded_allocations

Comment on lines +34 to +44
i=0
while [ ! -f "$CA_ROOT" ]; do
if [ "$i" -eq 0 ]; then
echo "start-coordinator: waiting (up to ${WAIT_SECS}s) for platform step-ca root cert at $CA_ROOT ..."
fi
if [ "$i" -ge "$WAIT_SECS" ]; then
echo "start-coordinator: ERROR: $CA_ROOT still absent after ${WAIT_SECS}s; refusing to start coordinator. Supervisor will retry." >&2
exit 1
fi
i=$((i + 1))
sleep 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] ⚡ Blocking sleep loop without exponential backoff could cause startup delays

💡 Suggestion: Implement exponential backoff in the wait loop: sleep $((i < 10 ? 1 : i < 30 ? 2 : 5)) to reduce CPU usage during long waits

📊 Score: 2×3 = 6 · Category: blocking_io

Comment on lines +175 to +193
fi
exit 0
}
trap term TERM INT

echo "Platform ready (step-ca :9000$( [ -n "${MICROMDM_PID:-}" ] && printf ', MicroMDM :9002' )). Supervising..."
while kill -0 "$STEP_CA_PID" 2>/dev/null; do
if [ -n "${MICROMDM_PID:-}" ]; then
if ! kill -0 "$MICROMDM_PID" 2>/dev/null; then
echo "platform: MicroMDM (pid $MICROMDM_PID) exited — restarting platform." >&2
kill "$STEP_CA_PID" 2>/dev/null || true
exit 1
fi
fi
sleep 5
done

echo "platform: step-ca (pid $STEP_CA_PID) exited — restarting platform." >&2
exit 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ Tight polling loop with fixed 5-second sleep may consume unnecessary CPU

💡 Suggestion: Use exponential backoff or longer sleep intervals for the supervision loop: sleep $((failures < 3 ? 5 : 15)) to reduce CPU overhead

📊 Score: 2×4 = 8 · Category: blocking_io

Comment thread deploy.sh
Comment on lines +700 to +800
log "The abandoned $cur_color ($cur_port) is left RUNNING (idle, providers drained off) for inspection; stop it manually with '$SYSTEMCTL_BIN stop darkbloom-coordinator@${cur_color}'."
}

# ===========================================================================
# CLI
# ===========================================================================
usage_main() {
cat <<'USAGE'
Usage: deploy.sh [options]

Blue-green coordinator deploy on the GCE box. Detects the active color from the
Caddy upstream, brings up the idle color, cuts over, drains, and stops the old.

Options:
--image <ref> Pin this container image for the idle color before starting.
--caddyfile <path> Caddyfile to read/flip (default: /etc/caddy/Caddyfile).
--rollback Roll back to the other (still-running) color: re-enable it
(undrain + clear its going-away latch), flip Caddy back +
reload, then push providers back onto it and wait for
routable capacity>0.
--force Forward: continue drain/stop even if providers do not land or
drain times out. Rollback: flip even if target health fails
(DANGEROUS — may route traffic to a dead port).
--dry-run Print the plan; change nothing.
-y, --yes Assume "yes" to all confirmation prompts (non-interactive).
-h, --help Show this help.

Environment overrides: CADDYFILE, BLUE_PORT(8080), GREEN_PORT(8081), HEALTH_HOST,
HEALTH_TIMEOUT, DRAIN_TIMEOUT, PROVIDERS_TIMEOUT(60), GOING_AWAY_PATH,
CAPACITY_PATH(/v1/models/capacity), CADDY_BIN, SYSTEMCTL_BIN, CURL_BIN,
DINF_DEPLOY_ENV_TMPL(/etc/d-inference/deploy-%s.env), DINF_ENV_FILE(/etc/d-inference/env).
USAGE
}

main() {
set -uo pipefail

DRY_RUN=0
ROLLBACK=0
ASSUME_YES=0
FORCE=0
IMAGE_REF=""

while [ "$#" -gt 0 ]; do
case "$1" in
--dry-run) DRY_RUN=1 ;;
--rollback) ROLLBACK=1 ;;
--force) FORCE=1 ;;
-y|--yes) ASSUME_YES=1 ;;
--image) [ "$#" -ge 2 ] || { err "--image requires a value"; return 2; }; IMAGE_REF="$2"; shift ;;
--image=*) IMAGE_REF="${1#*=}" ;;
--caddyfile) [ "$#" -ge 2 ] || { err "--caddyfile requires a value"; return 2; }; CADDYFILE="$2"; shift ;;
--caddyfile=*) CADDYFILE="${1#*=}" ;;
-h|--help) usage_main; return 0 ;;
*) err "unknown argument: $1"; usage_main; return 2 ;;
esac
shift
done

CADDYFILE="${CADDYFILE:-$CADDYFILE_DEFAULT}"
[ -f "$CADDYFILE" ] || die "Caddyfile not found: $CADDYFILE (use --caddyfile or set CADDYFILE)"

if [ "$ROLLBACK" -eq 1 ]; then
do_rollback
return $?
fi

local active_port active_color idle_color idle_port image_pin_file
active_port="$(current_upstream_port "$CADDYFILE")" || die "could not detect active upstream port in $CADDYFILE"
active_color="$(color_for_port "$active_port")" || die "active upstream port $active_port is neither blue($BLUE_PORT) nor green($GREEN_PORT)"
idle_color="$(other_color "$active_color")"
idle_port="$(port_for_color "$idle_color")"
if [ -n "$IMAGE_REF" ]; then
image_pin_file="$(deploy_env_for_color "$idle_color")" || die "could not compute deploy env path for idle color $idle_color"
fi

log "=============================================================="
log " Blue-green deploy plan"
log " Caddyfile : $CADDYFILE"
log " Active (live) : $active_color (port $active_port)"
log " Idle (target) : $idle_color (port $idle_port)"
[ -n "$IMAGE_REF" ] && log " New image : $IMAGE_REF"
[ -n "$IMAGE_REF" ] && log " Image pin file : $image_pin_file"
[ "$DRY_RUN" -eq 1 ] && log " MODE : DRY-RUN (no changes will be made)"
log "=============================================================="

# Roll the image pin back automatically on ANY exit before the cutover is
# accepted (declined confirm, failed start, unhealthy idle, failed flip/reload).
# accept_image_pin() disarms this once the cutover succeeds. No-op without --image.
trap 'restore_image_pin' EXIT

# 1. Pin image for the idle color (optional). Snapshotted so it is rolled back
# if the deploy aborts before cutover.
if [ -n "$IMAGE_REF" ]; then
if ! pin_image "$idle_color" "$IMAGE_REF"; then
die "deploy aborted: failed to pin image for idle color '$idle_color'; not restarting it"
fi
fi

# 2. Restart the idle color. RESTART (not start) so a stale already-running idle
# container re-execs darkbloom-run.sh and picks up the newly pinned image.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Similar error handling and confirmation patterns repeated

💡 Suggestion: Create common helpers for confirmation prompts with dry-run awareness and error handling with context. The pattern of 'if DRY_RUN log else execute' appears many times.

📊 Score: 2×3 = 6 · Category: duplicate logic

Comment on lines +1 to +193
#!/bin/sh
set -e

# ============================================================================
# start-platform.sh — long-lived "platform" half of the blue-green split.
# (DAR-327 Phase 2)
#
# Owns the stateful, NON-swappable services so they survive a coordinator
# color flip untouched:
# - the persistent /mnt/disks/userdata volume + the /data symlink
# - step-ca (ACME device-attest-01 CA) on :9000, incl. first-boot init
# - MicroMDM (SCEP + MDM checkin/connect) on :9002
#
# It does NOT start the coordinator. The coordinator runs in its own
# per-color container via start-coordinator.sh and is swapped behind Caddy.
#
# This is a faithful factoring of coordinator/deploy/start.sh (lines 1-125):
# the combined start.sh is intentionally LEFT UNCHANGED as the EigenCloud
# entrypoint. Keep this file diff-able against start.sh so the two stay in sync.
#
# MDM webhook coupling fix: start.sh hardcodes the command-webhook URL to
# http://localhost:8080/v1/mdm/webhook, which only works when the coordinator
# shares the container on :8080. In the split the active coordinator may be on
# :8080 (blue) or :8081 (green), so the webhook target is now configurable via
# EIGENINFERENCE_MDM_WEBHOOK_URL. In the GCE blue-green deployment the platform
# unit points it at a stable loopback Caddy listener
# (http://127.0.0.1:8090/v1/mdm/webhook) that imports the same (coordinator_routes)
# snippet as the public sites, so the SINGLE upstream swap in that snippet
# reroutes the webhook to the active color automatically. Default below keeps
# legacy localhost:8080 behavior for any combined-style use.
# ============================================================================

# EigenCloud / GCE persistent storage (survives upgrades + color swaps).
PERSIST=${USER_PERSISTENT_DATA_PATH:-/mnt/disks/userdata}
mkdir -p "$PERSIST/step-ca" "$PERSIST/micromdm"

# Symlink /data -> persistent storage so all components use the same paths.
ln -sfn "$PERSIST" /data

# ---- step-ca ----
if [ ! -d "/data/step-ca/config" ]; then
echo "Initializing step-ca (first boot)..."
mkdir -p /data/step-ca/secrets
echo "eigeninference-step-ca" > /data/step-ca/secrets/password

# Copy Apple attestation root CA and ACME template to persistent storage
mkdir -p /data/step-ca/apple /data/step-ca/templates
cp /opt/step-ca-seed/acme-device.tpl /data/step-ca/templates/

STEPPATH=/data/step-ca step ca init \
--name "Darkbloom CA" \
--dns "${DOMAIN:-localhost}" \
--address ":9000" \
--provisioner "eigeninference-admin" \
--password-file /data/step-ca/secrets/password \
--deployment-type standalone \
--acme 2>&1
echo "step-ca initialized."

# Patch ca.json: replace the default ACME provisioner with one configured
# for device-attest-01 (Apple Secure Enclave attestation).
echo "Configuring ACME device-attest-01 provisioner..."
CA_JSON=/data/step-ca/config/ca.json
jq '(.authority.provisioners[] | select(.type == "ACME")) |=
{
"type": "ACME",
"name": "eigeninference-acme",
"challenges": ["device-attest-01"],
"attestationFormats": ["apple"],
"forceCN": false,
"options": {
"x509": {
"templateFile": "/data/step-ca/templates/acme-device.tpl"
}
}
}' "$CA_JSON" > /tmp/ca.json && mv /tmp/ca.json "$CA_JSON"
echo "ACME provisioner configured."
fi
echo "Starting step-ca..."
STEPPATH=/data/step-ca step-ca /data/step-ca/config/ca.json \
--password-file /data/step-ca/secrets/password \
>> /data/step-ca.log 2>&1 &
STEP_CA_PID=$!
echo "step-ca started (port 9000, pid $STEP_CA_PID)."

# ---- MicroMDM ----
MICROMDM_PID=""
if [ -n "$MICROMDM_API_KEY" ]; then
# Decode push cert from PKCS#12 bundle on first boot
# P12 is base64url-encoded (no +/) to survive KMS/shell pipeline intact.
if [ -n "$MDM_PUSH_P12_B64" ] && [ ! -f /data/micromdm/push.crt ]; then
echo "Decoding MDM push certificate from PKCS#12..."
printf '%s' "$MDM_PUSH_P12_B64" | tr '_-' '/+' | base64 -d > /tmp/push.p12
openssl pkcs12 -in /tmp/push.p12 -clcerts -nokeys -passin pass:eigeninference \
-out /data/micromdm/push.crt 2>/dev/null
openssl pkcs12 -in /tmp/push.p12 -nocerts -nodes -passin pass:eigeninference \
-out /tmp/push_pkcs8.key 2>/dev/null
openssl rsa -in /tmp/push_pkcs8.key -traditional -out /data/micromdm/push.key 2>/dev/null
rm -f /tmp/push.p12 /tmp/push_pkcs8.key
chmod 600 /data/micromdm/push.key
echo "Key format: $(head -1 /data/micromdm/push.key)"
fi

# Generate self-signed TLS cert for MicroMDM on first boot (internal only)
if [ ! -f /data/micromdm/server.crt ]; then
echo "Generating MicroMDM self-signed TLS cert..."
openssl req -x509 -newkey rsa:2048 -nodes \
-keyout /data/micromdm/server.key \
-out /data/micromdm/server.crt \
-days 3650 -subj "/CN=localhost" 2>/dev/null
fi

# If the coordinator is configured with EIGENINFERENCE_MDM_WEBHOOK_SECRET it
# rejects any MDM callback that doesn't present that secret. MicroMDM has no
# option to set a header on the command webhook, so the shared secret rides
# as a ?token= query param (the coordinator also accepts the X-Webhook-Token
# header — see HandleMDMWebhook). These MUST stay in sync: setting the secret
# on the coordinator without this token would 403 every legitimate
# SecurityInfo/MDA callback and stall provider hardware-trust verification.
#
# Blue-green: the base URL is configurable so MicroMDM reaches the ACTIVE
# coordinator color. Default stays localhost:8080 (legacy/combined). In the
# split, the platform unit sets EIGENINFERENCE_MDM_WEBHOOK_URL to the stable
# loopback Caddy webhook listener (http://127.0.0.1:8090/v1/mdm/webhook).
MDM_WEBHOOK_URL="${EIGENINFERENCE_MDM_WEBHOOK_URL:-http://localhost:8080/v1/mdm/webhook}"
if [ -n "${EIGENINFERENCE_MDM_WEBHOOK_SECRET:-}" ]; then
MDM_WEBHOOK_URL="${MDM_WEBHOOK_URL}?token=${EIGENINFERENCE_MDM_WEBHOOK_SECRET}"
fi

echo "Starting MicroMDM (webhook -> ${EIGENINFERENCE_MDM_WEBHOOK_URL:-http://localhost:8080/v1/mdm/webhook})..."
micromdm serve \
-server-url "https://${DOMAIN:-localhost}" \
-api-key "${MICROMDM_API_KEY:-eigeninference-micromdm-api}" \
-filerepo /data/micromdm \
-config-path /data/micromdm \
-tls-cert /data/micromdm/server.crt \
-tls-key /data/micromdm/server.key \
-http-addr :9002 \
-http-proxy-headers \
-command-webhook-url "${MDM_WEBHOOK_URL}" \
>> /data/micromdm.log 2>&1 &
MICROMDM_PID=$!

# Wait for MicroMDM to be ready, then import push cert if needed
sleep 2
if [ -f /data/micromdm/push.crt ] && [ ! -f /data/micromdm/.push_imported ]; then
echo "Importing MDM push certificate..."
mdmctl config set \
-name eigeninference \
-server-url "https://localhost:9002" \
-api-token "${MICROMDM_API_KEY:-eigeninference-micromdm-api}" \
-skip-verify
mdmctl mdmcert upload \
-cert /data/micromdm/push.crt \
-private-key /data/micromdm/push.key \
2>&1 || echo "Push cert import failed (may already exist)"
touch /data/micromdm/.push_imported
fi
echo "MicroMDM ready (port 9002, pid $MICROMDM_PID)."
else
echo "MICROMDM_API_KEY not set — skipping MicroMDM."
fi

# ---- Supervise (PID 1) ----
# The platform has no foreground process of its own (step-ca + MicroMDM run in
# the background above), so block here to keep the container alive and to
# forward termination signals. Exit non-zero if a critical child dies so the
# supervisor (systemd Restart=always, or EigenCloud) restarts the platform.
# shellcheck disable=SC2329 # invoked indirectly via `trap term TERM INT` below
term() {
echo "platform: signal received — shutting down children..."
kill "$STEP_CA_PID" 2>/dev/null || true
if [ -n "${MICROMDM_PID:-}" ]; then
kill "$MICROMDM_PID" 2>/dev/null || true
fi
exit 0
}
trap term TERM INT

echo "Platform ready (step-ca :9000$( [ -n "${MICROMDM_PID:-}" ] && printf ', MicroMDM :9002' )). Supervising..."
while kill -0 "$STEP_CA_PID" 2>/dev/null; do
if [ -n "${MICROMDM_PID:-}" ]; then
if ! kill -0 "$MICROMDM_PID" 2>/dev/null; then
echo "platform: MicroMDM (pid $MICROMDM_PID) exited — restarting platform." >&2
kill "$STEP_CA_PID" 2>/dev/null || true
exit 1
fi
fi
sleep 5
done

echo "platform: step-ca (pid $STEP_CA_PID) exited — restarting platform." >&2
exit 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] 🧩 Substantial code duplication with existing start.sh

💡 Suggestion: Since the comment says to keep this 'diff-able against start.sh', consider extracting shared functions into a common library that both scripts can source, rather than maintaining parallel implementations.

📊 Score: 3×4 = 12 · Category: duplicate logic

Comment on lines +1 to +90
#!/bin/bash
# darkbloom-run.sh (DAR-327 Phase 2) — blue-green container launcher for the
# GCE coordinator box. Invoked by the systemd units:
# darkbloom-platform.service -> darkbloom-run.sh platform
# darkbloom-coordinator@<color> -> darkbloom-run.sh coordinator <blue|green>
#
# Mirrors deploy/gcp/vm-startup.sh's d-inference-run.sh: resolves the pinned
# image (explicit DINF_IMAGE, else the DINF_IMAGE_TAG instance-metadata tag,
# else :latest), authenticates to Artifact Registry using the VM service-account
# token from the metadata server, pulls, then launches the requested container.
#
# Secret-safety: nothing secret is baked in here. Registry auth uses the
# metadata server (no stored key); app config + secrets are read by the
# container from --env-file /etc/d-inference/env (written by refresh-env.sh from
# GCP Secret Manager). The per-color EIGENINFERENCE_PORT is passed as an
# explicit `-e` AFTER --env-file so it overrides the file's default.
set -euo pipefail

usage() {
echo "usage: darkbloom-run.sh platform" >&2
echo " darkbloom-run.sh coordinator <blue|green>" >&2
exit 2
}

ROLE="${1:-}"
[ -n "$ROLE" ] || usage

META="http://metadata.google.internal/computeMetadata/v1/instance"

# ---- Resolve image ref ----
# DINF_IMAGE (full ref) wins; otherwise build from repo + metadata tag.
IMAGE_REPO="${DINF_IMAGE_REPO:-us-central1-docker.pkg.dev/sepolia-ai/coordinator/coordinator}"
if [ -n "${DINF_IMAGE:-}" ]; then
IMAGE="$DINF_IMAGE"
else
TAG="$(curl -fsSL -H 'Metadata-Flavor: Google' "$META/attributes/DINF_IMAGE_TAG" 2>/dev/null || echo latest)"
IMAGE="${IMAGE_REPO}:${TAG}"
fi
REGISTRY_HOST="${IMAGE%%/*}"

DATA_MOUNT="${DINF_DATA_MOUNT:-/mnt/disks/userdata}"
ENV_FILE="${DINF_ENV_FILE:-/etc/d-inference/env}"
DOCKER="${DOCKER:-/usr/bin/docker}"

echo "darkbloom-run: role=$ROLE image=$IMAGE"

# ---- Registry auth via metadata service-account token ----
# Skip when DINF_SKIP_REGISTRY_LOGIN=1 (image already present, or public).
if [ "${DINF_SKIP_REGISTRY_LOGIN:-0}" != "1" ]; then
TOKEN="$(curl -fsSL -H 'Metadata-Flavor: Google' \
"$META/service-accounts/default/token" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["access_token"])')"
printf '%s' "$TOKEN" | "$DOCKER" login -u oauth2accesstoken --password-stdin "$REGISTRY_HOST"
unset TOKEN
fi

"$DOCKER" pull "$IMAGE"

case "$ROLE" in
platform)
NAME="${DINF_PLATFORM_NAME:-darkbloom-platform}"
# MicroMDM webhook -> stable loopback Caddy listener (active color follows
# the single upstream swap). Override via EIGENINFERENCE_MDM_WEBHOOK_URL.
WEBHOOK_URL="${EIGENINFERENCE_MDM_WEBHOOK_URL:-http://127.0.0.1:8090/v1/mdm/webhook}"
exec "$DOCKER" run --rm --name "$NAME" \
--network host \
--env-file "$ENV_FILE" \
-e "EIGENINFERENCE_MDM_WEBHOOK_URL=${WEBHOOK_URL}" \
--mount "type=bind,source=${DATA_MOUNT},target=${DATA_MOUNT}" \
"$IMAGE" start-platform.sh
;;
coordinator)
COLOR="${2:-}"
case "$COLOR" in
blue) PORT="${BLUE_PORT:-8080}" ;;
green) PORT="${GREEN_PORT:-8081}" ;;
*) echo "darkbloom-run: unknown color '${COLOR}' (want blue|green)" >&2; usage ;;
esac
exec "$DOCKER" run --rm --name "darkbloom-coordinator-${COLOR}" \
--network host \
--env-file "$ENV_FILE" \
-e "EIGENINFERENCE_PORT=${PORT}" \
--mount "type=bind,source=${DATA_MOUNT},target=${DATA_MOUNT}" \
"$IMAGE" start-coordinator.sh
;;
*)
echo "darkbloom-run: unknown role '${ROLE}'" >&2
usage
;;
esac

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Similar container launch patterns for platform vs coordinator

💡 Suggestion: The docker run commands share most arguments. Extract a common launch_container function that takes role-specific parameters to reduce duplication and ensure consistency.

📊 Score: 2×3 = 6 · Category: duplicate logic

Comment thread deploy.sh
Comment on lines +400 to +500
log "Waiting for $color (port $port) /health + /readyz (timeout ${HEALTH_TIMEOUT}s)..."
local now deadline h r
now="$(date +%s)"
deadline=$(( now + HEALTH_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
h="$(http_code "http://${HEALTH_HOST}:${port}${HEALTH_PATH}")"
r="$(http_code "http://${HEALTH_HOST}:${port}${READYZ_PATH}")"
if [ "$h" = "200" ] && [ "$r" = "200" ]; then
log "$color is healthy (/health=200, /readyz=200)."
return 0
fi
log " $color /health=$h /readyz=$r; waiting..."
sleep 2
done
err "$color did not become healthy within ${HEALTH_TIMEOUT}s."
return 1
}

# load_admin_env — read ONLY the EIGENINFERENCE_ADMIN_KEY line from the secrets
# env file into the global of the same name, for the authenticated going-away +
# drain requests.
#
# SECURITY: that file is docker --env-file syntax (KEY=VALUE), NOT shell. Sourcing
# it (`.`/`source`) would execute values — the 12-word MNEMONIC, '&', URL/`$()`
# chars — as shell commands AS ROOT (secret leak / RCE). So we never source it; we
# grep the single line and strip optional surrounding quotes. No eval, no source.
# The value is never printed. Called only at real cutover time (after the
# --dry-run early returns) so the plan stays secret-free. No-op + warning if the
# file is absent/unreadable (caller still warns on empty key and continues).
load_admin_env() {
if [ -r "$DINF_ENV_FILE" ]; then
# First match wins; cut -f2- keeps '=' chars in the value; 2>/dev/null + the
# lack of `set -e` make a no-match safely yield an empty key.
EIGENINFERENCE_ADMIN_KEY="$(grep -E '^EIGENINFERENCE_ADMIN_KEY=' "$DINF_ENV_FILE" 2>/dev/null | head -n1 | cut -d= -f2-)"
# Strip one pair of surrounding quotes if the value is quoted in the env file.
case "$EIGENINFERENCE_ADMIN_KEY" in
'"'*'"') EIGENINFERENCE_ADMIN_KEY="${EIGENINFERENCE_ADMIN_KEY#\"}"; EIGENINFERENCE_ADMIN_KEY="${EIGENINFERENCE_ADMIN_KEY%\"}" ;;
"'"*"'") EIGENINFERENCE_ADMIN_KEY="${EIGENINFERENCE_ADMIN_KEY#\'}"; EIGENINFERENCE_ADMIN_KEY="${EIGENINFERENCE_ADMIN_KEY%\'}" ;;
esac
else
warn "secrets env file not readable at $DINF_ENV_FILE; admin key unavailable for going-away/drain auth"
fi
}

# drain_color <color> <port> — POST /v1/admin/drain then poll /readyz inflight==0.
# Returns 0 once inflight==0, NON-ZERO on timeout so the caller does NOT stop a
# color that still has in-flight requests (stopping would cut them at the SIGTERM
# deadline). EIGENINFERENCE_ADMIN_KEY is loaded once by the caller (load_admin_env).
drain_color() {
local color="$1" port="$2"
log "Draining $color (port $port): POST $DRAIN_PATH, then poll $READYZ_PATH inflight==0..."
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would POST $DRAIN_PATH to $color:$port and poll inflight==0 (timeout ${DRAIN_TIMEOUT}s)"
return 0
fi
# Phase 1 contract: admin-authenticated drain endpoint. The bearer key was
# parsed (not sourced) from the env file by the caller's load_admin_env.
if ! "$CURL_BIN" -fsS -X POST \
-H "Authorization: Bearer ${EIGENINFERENCE_ADMIN_KEY:-}" \
--max-time 10 \
"http://${HEALTH_HOST}:${port}${DRAIN_PATH}" >/dev/null; then
warn "drain request to $color returned an error (continuing to poll readiness)"
fi
local now deadline body inflight
now="$(date +%s)"
deadline=$(( now + DRAIN_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
body="$("$CURL_BIN" -fsS --max-time 5 "http://${HEALTH_HOST}:${port}${READYZ_PATH}" 2>/dev/null || true)"
# Phase 1 contract: /readyz exposes an inflight counter, e.g. {"inflight":0}.
inflight="$(printf '%s' "$body" | sed -n 's/.*"inflight"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' | head -n1)"
if [ -n "$inflight" ] && [ "$inflight" -eq 0 ]; then
log "$color drained (inflight=0)."
return 0
fi
log " $color inflight=${inflight:-unknown}; waiting..."
sleep 3
done
err "$color did not reach inflight==0 within ${DRAIN_TIMEOUT}s."
return 1
}

# undrain_color <color> <port> — POST /v1/admin/drain {"draining":false} to CLEAR a
# color's drain latch so it re-accepts work (the inverse of drain_color's bodyless
# POST, which STARTS draining). Used by --rollback to re-enable the rollback target,
# which the forward deploy may have drained. Best-effort: warns and continues on any
# failure so a not-yet-deployed endpoint degrades gracefully. DRY_RUN-aware.
# EIGENINFERENCE_ADMIN_KEY is loaded once by the caller (load_admin_env).
undrain_color() {
local color="$1" port="$2"
log "Undraining $color (port $port): POST $DRAIN_PATH {\"draining\":false} (re-accept work)..."
if [ "$DRY_RUN" -eq 1 ]; then
log "DRY-RUN: would POST $DRAIN_PATH {\"draining\":false} to $color:$port"
return 0
fi
# Phase 1 contract: the drain endpoint accepts {"draining":false} to UN-drain.
if ! "$CURL_BIN" -fsS -X POST \
-H "Authorization: Bearer ${EIGENINFERENCE_ADMIN_KEY:-}" \
-H "Content-Type: application/json" \
--max-time 10 \
--data '{"draining":false}' \
"http://${HEALTH_HOST}:${port}${DRAIN_PATH}" >/dev/null; then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Image pinning logic mixed with deployment orchestration

💡 Suggestion: Move pin_image, restore_image_pin, accept_image_pin functions to a separate image management module. The deployment orchestrator should call image management functions, not implement them.

📊 Score: 2×2 = 4 · Category: misplaced responsibility

Comment on lines +1 to +301
#!/usr/bin/env bash
# deploy_test.sh — infra-free unit tests for deploy.sh's pure functions
# (DAR-327 Phase 2). No Docker, systemd, Caddy, gcloud or network required.
#
# Sources deploy.sh (which, thanks to its BASH_SOURCE guard, defines functions
# without running main), writes a sample Caddyfile, and exercises flip_upstream
# and current_upstream_port: the upstream flips, is reversible and idempotent,
# and NO other line (step-ca :9000, MicroMDM :9002, internal :8090 listener) is
# mutated.
#
# Also covers two security/safety-critical helpers added in the Phase 2 review:
# - load_admin_env: PARSES (never sources) the EIGENINFERENCE_ADMIN_KEY line,
# incl. a regression canary proving env-file values are NOT executed.
# - pin_image / restore_image_pin / accept_image_pin: the per-color image-pin
# rollback so an aborted deploy never leaves the idle color on an unaccepted
# image.
#
# Run: ./deploy/gcp/prod/deploy_test.sh (or: bash deploy/gcp/prod/deploy_test.sh)
# Exit: 0 if all assertions pass, 1 otherwise.

# Intentionally NOT `set -e`: flip_upstream returns 3 (no-op) by design and the
# idempotency test asserts on that non-zero return.
set -u

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOY_SH="${DEPLOY_SH:-${SCRIPT_DIR}/../../../deploy.sh}"

if [ ! -f "$DEPLOY_SH" ]; then
echo "deploy_test: cannot find deploy.sh at $DEPLOY_SH" >&2
exit 1
fi

# shellcheck source=/dev/null
source "$DEPLOY_SH"

PASS=0
FAIL=0
pass() { printf 'ok - %s\n' "$1"; PASS=$((PASS + 1)); }
fail() { printf 'NOT OK - %s\n' "$1"; [ -n "${2:-}" ] && printf ' %s\n' "$2"; FAIL=$((FAIL + 1)); }

assert_eq() { # <desc> <expected> <actual>
if [ "$2" = "$3" ]; then pass "$1"; else fail "$1" "expected [$2] got [$3]"; fi
}
assert_rc() { # <desc> <expected_rc> <actual_rc>
if [ "$2" -eq "$3" ]; then pass "$1"; else fail "$1" "expected rc $2 got $3"; fi
}
assert_contains() { # <desc> <file> <needle>
if grep -qF "$3" "$2"; then pass "$1"; else fail "$1" "missing [$3] in $2"; fi
}
assert_absent() { # <desc> <file> <needle>
if grep -qF "$3" "$2"; then fail "$1" "unexpected [$3] in $2"; else pass "$1"; fi
}

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

ORIG="$WORK/Caddyfile.orig"
CF="$WORK/Caddyfile"

# Sample mirrors deploy/gcp/prod/Caddyfile: the snippet contains the step-ca
# (:9000) and MicroMDM (:9002) https upstreams, the /dl/* and
# /enroll.mobileconfig static handlers, and the single coordinator upstream
# (:8080), imported by two public sites and the internal :8090 listener.
cat > "$ORIG" <<'CADDY'
(coordinator_routes) {
handle /acme/* {
reverse_proxy https://127.0.0.1:9000 {
transport http {
tls_insecure_skip_verify
}
header_up Host {host}
}
}
handle /mdm/* {
reverse_proxy https://127.0.0.1:9002 {
transport http {
tls_insecure_skip_verify
}
}
}
handle /dl/* {
root * /var/www/html
file_server
}
handle /enroll.mobileconfig {
root * /var/www/html
file_server
}
reverse_proxy 127.0.0.1:8080 {
health_uri /health
health_interval 30s
}
}

coord-staging.darkbloom.dev {
import coordinator_routes
}

api.darkbloom.dev {
tls /etc/caddy/certs/api.darkbloom.dev.crt /etc/caddy/certs/api.darkbloom.dev.key
import coordinator_routes
}

http://127.0.0.1:8090 {
import coordinator_routes
}
CADDY

cp "$ORIG" "$CF"

echo "# deploy_test: flip_upstream / current_upstream_port"

# ---- detect initial active port ----
port="$(current_upstream_port "$CF")"; rc=$?
assert_rc "current_upstream_port returns 0 on a valid file" 0 "$rc"
assert_eq "current_upstream_port reads 8080 initially" "8080" "$port"

# ---- flip 8080 -> 8081 ----
flip_upstream "$CF" 8080 8081; rc=$?
assert_rc "flip_upstream 8080->8081 returns 0" 0 "$rc"
assert_contains "coordinator upstream now 8081" "$CF" "reverse_proxy 127.0.0.1:8081"
assert_absent "old coordinator upstream 8080 gone" "$CF" "reverse_proxy 127.0.0.1:8080"
assert_eq "current_upstream_port reads 8081 after flip" "8081" "$(current_upstream_port "$CF")"

# ---- only the coordinator line changed (exactly 1 removed + 1 added) ----
diffout="$(diff "$ORIG" "$CF")"
removed="$(printf '%s\n' "$diffout" | grep -c '^<')"
added="$(printf '%s\n' "$diffout" | grep -c '^>')"
assert_eq "exactly one line removed by flip" "1" "$removed"
assert_eq "exactly one line added by flip" "1" "$added"

# ---- step-ca / MicroMDM / /dl static / internal-listener lines untouched ----
assert_contains "step-ca upstream :9000 untouched" "$CF" "reverse_proxy https://127.0.0.1:9000"
assert_contains "MicroMDM upstream :9002 untouched" "$CF" "reverse_proxy https://127.0.0.1:9002"
assert_contains "/dl/* static handler untouched by flip" "$CF" "handle /dl/* {"
assert_contains "/enroll.mobileconfig static handler untouched by flip" "$CF" "handle /enroll.mobileconfig {"
assert_contains "internal webhook listener :8090 untouched" "$CF" "http://127.0.0.1:8090 {"

# ---- reversible: flip back restores the file byte-for-byte ----
flip_upstream "$CF" 8081 8080; rc=$?
assert_rc "flip_upstream 8081->8080 returns 0" 0 "$rc"
if diff -q "$ORIG" "$CF" >/dev/null; then
pass "flip is reversible (file identical to original)"
else
fail "flip is reversible" "$(diff "$ORIG" "$CF")"
fi

# ---- idempotent: flipping when from-port is absent is a no-op (rc 3) ----
cp "$ORIG" "$CF"
flip_upstream "$CF" 8080 8081 >/dev/null; rc=$? # first: changes
assert_rc "first flip changes (rc 0)" 0 "$rc"
before_second="$(cat "$CF")"
flip_upstream "$CF" 8080 8081 >/dev/null 2>&1; rc=$? # second: 8080 already gone
assert_rc "second identical flip is a no-op (rc 3)" 3 "$rc"
assert_eq "file unchanged after no-op flip" "$before_second" "$(cat "$CF")"

# ---- error handling ----
flip_upstream "$WORK/does-not-exist" 8080 8081 >/dev/null 2>&1; rc=$?
assert_rc "flip_upstream on missing file returns 2" 2 "$rc"
flip_upstream "$CF" >/dev/null 2>&1; rc=$?
assert_rc "flip_upstream with too few args returns 2" 2 "$rc"
current_upstream_port "$WORK/does-not-exist" >/dev/null 2>&1; rc=$?
assert_rc "current_upstream_port on missing file returns 2" 2 "$rc"

# ---- a Caddyfile with no coordinator upstream -> rc 3 ----
printf 'example.com {\n\trespond "hi"\n}\n' > "$WORK/no-upstream"
current_upstream_port "$WORK/no-upstream" >/dev/null 2>&1; rc=$?
assert_rc "current_upstream_port with no upstream returns 3" 3 "$rc"

# ---- color/port helpers ----
assert_eq "port_for_color blue" "8080" "$(port_for_color blue)"
assert_eq "port_for_color green" "8081" "$(port_for_color green)"
assert_eq "color_for_port 8080" "blue" "$(color_for_port 8080)"
assert_eq "color_for_port 8081" "green" "$(color_for_port 8081)"
assert_eq "other_color blue" "green" "$(other_color blue)"
assert_eq "other_color green" "blue" "$(other_color green)"

echo
echo "# deploy_test: load_admin_env (PARSE the admin key — never source the env file)"

# load_admin_env reads ONLY EIGENINFERENCE_ADMIN_KEY from a docker --env-file
# (KEY=VALUE) file. It must NEVER source/eval it (the file holds secrets like the
# 12-word MNEMONIC and URLs with shell metacharacters that would run AS ROOT).
SECENV="$WORK/secrets.env"
# shellcheck disable=SC2034 # read by load_admin_env() in the sourced deploy.sh
DINF_ENV_FILE="$SECENV"

printf 'EIGENINFERENCE_ADMIN_KEY=plainkey123\nOTHER=x\n' > "$SECENV"
EIGENINFERENCE_ADMIN_KEY=""; load_admin_env
assert_eq "load_admin_env reads a plain key" "plainkey123" "${EIGENINFERENCE_ADMIN_KEY:-}"

printf 'EIGENINFERENCE_ADMIN_KEY=a=b=c\n' > "$SECENV"
EIGENINFERENCE_ADMIN_KEY=""; load_admin_env
assert_eq "load_admin_env keeps '=' chars in the value (cut -f2-)" "a=b=c" "${EIGENINFERENCE_ADMIN_KEY:-}"

printf 'EIGENINFERENCE_ADMIN_KEY="quotedkey"\n' > "$SECENV"
EIGENINFERENCE_ADMIN_KEY=""; load_admin_env
assert_eq "load_admin_env strips surrounding double quotes" "quotedkey" "${EIGENINFERENCE_ADMIN_KEY:-}"

printf "EIGENINFERENCE_ADMIN_KEY='quotedkey2'\n" > "$SECENV"
EIGENINFERENCE_ADMIN_KEY=""; load_admin_env
assert_eq "load_admin_env strips surrounding single quotes" "quotedkey2" "${EIGENINFERENCE_ADMIN_KEY:-}"

# SECURITY REGRESSION: hostile values (command substitution) must NOT execute.
# Sourcing the file (the bug this fixes) would run touch $CANARY; parsing must not.
CANARY="$WORK/CANARY_EXECUTED"
rm -f "$CANARY"
cat > "$SECENV" <<EOF2
MNEMONIC=word1 word2 \$(touch $CANARY) more
EVIL=\`touch $CANARY\`
EIGENINFERENCE_ADMIN_KEY=safekey
EOF2
EIGENINFERENCE_ADMIN_KEY=""; load_admin_env
assert_eq "load_admin_env reads the key past hostile lines" "safekey" "${EIGENINFERENCE_ADMIN_KEY:-}"
if [ ! -e "$CANARY" ]; then
pass "load_admin_env does NOT execute env-file values (no source/eval)"
else
fail "SECURITY: env-file value was executed" "canary $CANARY exists"
fi

printf 'OTHER=x\n' > "$SECENV"
EIGENINFERENCE_ADMIN_KEY=""; load_admin_env
assert_eq "load_admin_env yields empty key when absent" "" "${EIGENINFERENCE_ADMIN_KEY:-}"

echo
echo "# deploy_test: provider wait timeout"

# wait_for_providers must return nonzero on timeout so forward deploy can abort
# before draining/stopping the old color. Use a zero-second timeout so no network
# or curl mock is required.
# shellcheck disable=SC2034 # read by wait_for_providers in sourced deploy.sh
PROVIDERS_TIMEOUT=0
wait_for_providers blue 8080 >/dev/null 2>&1; rc=$?
assert_rc "wait_for_providers returns nonzero on timeout" 1 "$rc"
# shellcheck disable=SC2034 # read by wait_for_providers in sourced deploy.sh
DRY_RUN=1
wait_for_providers blue 8080 >/dev/null 2>&1; rc=$?
assert_rc "wait_for_providers dry-run returns 0" 0 "$rc"

echo
echo "# deploy_test: per-color image-pin rollback (pin_image / restore_image_pin / accept_image_pin)"

# shellcheck disable=SC2034 # DRY_RUN read by the dry-run guards in sourced deploy.sh
DRY_RUN=0
PIN_TMPL="$WORK/deploy-%s.env"
PINBLUE="$WORK/deploy-blue.env"
PINGREEN="$WORK/deploy-green.env"
# shellcheck disable=SC2034 # read by deploy_env_for_color/pin_image in sourced deploy.sh
DINF_DEPLOY_ENV_TMPL="$PIN_TMPL"
# DINF_DEPLOY_ENV_BAK / DINF_DEPLOY_ENV_EXISTED / DINF_DEPLOY_ENV_PINNED are set by
# pin_image itself, so the tests below intentionally do NOT pre-seed them.

assert_eq "deploy_env_for_color blue" "$PINBLUE" "$(deploy_env_for_color blue)"
assert_eq "deploy_env_for_color green" "$PINGREEN" "$(deploy_env_for_color green)"
deploy_env_for_color red >/dev/null 2>&1; rc=$?
assert_rc "deploy_env_for_color rejects unknown colors" 2 "$rc"

# (a) pin when the color file did NOT exist -> restore removes only that file.
rm -f "$PINBLUE" "$PINGREEN"
pin_image blue "repo/coord:abc" >/dev/null 2>&1; rc=$?
assert_rc "pin_image blue returns 0" 0 "$rc"
assert_contains "pin_image writes DINF_IMAGE to blue" "$PINBLUE" "DINF_IMAGE=repo/coord:abc"
if [ ! -f "$PINGREEN" ]; then pass "pin_image blue does not create green pin file"; else fail "pin_image blue should not create green pin file"; fi
restore_image_pin >/dev/null 2>&1
if [ ! -f "$PINBLUE" ]; then pass "restore_image_pin removes a blue pin file created this run"; else fail "restore_image_pin should remove a newly-created blue pin file"; fi

# (b) pin OVER an existing file -> accept keeps it (restore becomes a no-op).
printf 'OTHER=1\n' > "$PINGREEN"
pin_image green "repo/coord:def" >/dev/null 2>&1; rc=$?
assert_rc "pin_image green returns 0" 0 "$rc"
assert_contains "pin_image preserves other keys in green" "$PINGREEN" "OTHER=1"
assert_contains "pin_image sets the new image in green" "$PINGREEN" "DINF_IMAGE=repo/coord:def"
accept_image_pin
restore_image_pin >/dev/null 2>&1
assert_contains "accept_image_pin keeps the green pin (restore is a no-op)" "$PINGREEN" "DINF_IMAGE=repo/coord:def"

# (c) pin OVER an existing pinned file -> restore brings back the original image
# in the exact file pin_image touched, even if the template changes before restore.
printf 'DINF_IMAGE=old/img:1\nOTHER=2\n' > "$PINBLUE"
pin_image blue "new/img:2" >/dev/null 2>&1; rc=$?
assert_rc "pin_image blue over existing pin returns 0" 0 "$rc"
assert_contains "pin_image replaces the old blue image line" "$PINBLUE" "DINF_IMAGE=new/img:2"
assert_absent "pin_image drops the prior blue image line" "$PINBLUE" "DINF_IMAGE=old/img:1"
# shellcheck disable=SC2034 # restore_image_pin must use DINF_DEPLOY_ENV_PINNED, not this new template
DINF_DEPLOY_ENV_TMPL="$WORK/other-%s.env"
restore_image_pin >/dev/null 2>&1
assert_contains "restore_image_pin restores the prior blue image pin" "$PINBLUE" "DINF_IMAGE=old/img:1"
assert_absent "restore_image_pin drops the unaccepted blue image pin" "$PINBLUE" "DINF_IMAGE=new/img:2"
if [ ! -e "$WORK/other-blue.env" ]; then pass "restore_image_pin uses the pinned file, not the current template"; else fail "restore_image_pin wrote to the current template instead of pinned file"; fi

# (d) pin_image fails before restart if the per-color env path cannot be written.
BAD_PARENT="$WORK/not-a-dir"
printf 'x\n' > "$BAD_PARENT"
# shellcheck disable=SC2034 # read by deploy_env_for_color/pin_image in sourced deploy.sh
DINF_DEPLOY_ENV_TMPL="$BAD_PARENT/deploy-%s.env"
pin_image blue "bad/img:1" >/dev/null 2>&1; rc=$?
assert_rc "pin_image fails when deploy env directory cannot be created" 1 "$rc"

echo
echo "# deploy_test: ${PASS} passed, ${FAIL} failed"
[ "$FAIL" -eq 0 ]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Test framework reinventing basic assertion patterns

💡 Suggestion: The custom pass/fail/assert_* functions could be replaced with standard bash testing patterns or a lightweight existing framework. The current approach adds cognitive overhead without significant benefit.

📊 Score: 2×2 = 4 · Category: over-abstraction

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — 4c2717aa Deployed Jun 20, 2026 by vercel[bot]
Preview – d-inference — 4c2717aa Deployed Jun 20, 2026 by vercel[bot]
Preview – d-inference-landing — 4c2717aa Deployed Jun 20, 2026 by vercel[bot]
benchmarks — 4c2717aa Deployed Jun 20, 2026 by Gajesh2007 via E2E Benchmarks #1298
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants