Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ jobs:
python3 scripts/test-provider-release-resolution.py
./scripts/sync-install-embed.sh check
./scripts/test-prod-env-refresh.sh
python3 scripts/test_model_publishing.py
- name: Test startup observer against local stubs
run: python3 -m unittest discover -s scripts/startup_measurement -t scripts -p 'test_*.py'

Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- Model publishing stops before uploads on failed or empty R2 credential reads. Rollback preparation validates registry inputs before copying objects, cleans its local staging on exit, and reaches promotion on macOS Bash.

## Release candidate v0.9.2 — Gemma QAT caching, adaptive MTP and Nemotron Lightning (not shipped; 2026-09-10)

Source changes since `v0.9.1`. Provider changes require a new signed bundle.
Expand Down
6 changes: 5 additions & 1 deletion docs/developer/build.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Build

> Last updated: 2026-09-10 · commit `4f29957d2`
> Last updated: 2026-09-11 · commit `e10709696`

How to build every component of Darkbloom from a fresh clone: the Go
coordinator, the Rust prompt-contract sidecar, the Swift provider CLI (with its
Expand All @@ -10,6 +10,10 @@ of it; the per-component steps below explain what each target runs.
Model publishing can pass `HUGGING_FACE_ARTIFACT_JSON` through
`scripts/publish-model.sh` to registration. See the
[model publishing procedure](../operations/model-migration.md).
Publishing scripts stop on failed or empty R2 credential lookups. The rollback
helper validates identifiers and numeric registration fields before copying
objects; its offline checks use command stubs, including Swift, and require no
provider build. See [the script checks](test.md#model-publishing-script-checks).

Profiler wire changes require both coordinator and provider builds; the shared
Go/Swift fixture and focused checks are described in [test.md](test.md) and
Expand Down
17 changes: 16 additions & 1 deletion docs/developer/test.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Test

> Last updated: 2026-09-11 · commit `d22ad0cf3`
> Last updated: 2026-09-11 · commit `e10709696`

How to run the unit tests for each component, the end-to-end suite that boots a
real coordinator + Swift provider against ephemeral Postgres, and the docs
Expand Down Expand Up @@ -998,6 +998,21 @@ This prevents task scheduling from silently changing admission order. Sources: `
(`summarize_controls`), `provider-swift/Sources/ProviderBenchmark/ThroughputSweep.swift`
(`measureDecode`). See [GPT-OSS optimization results](../reports/2026-09-05-gptoss20b-optimization-results.md).

#### Model publishing script checks

Run `python3 scripts/test_model_publishing.py` from the repository root. These
offline fixtures replace `gcloud`, `aws`, `curl` and `swift` with local stubs.
They verify failed/empty credential lookup refusal before uploads, rollback
identifier and positive-int64 validation before remote operations, upload/API
ordering, and owned staging cleanup after failure. The successful rollback
case also reaches promotion with the system Bash used by the caller.

The Release Integrity job runs these fixtures in `.github/workflows/ci.yml`.
Run `bash scripts/test-publish-model.sh` for the existing required-capability
and pinned Hugging Face workflow payload checks. Neither command publishes a
model or proves that a real artifact loads; use the
[model migration runbook](../operations/model-migration.md) for those checks.

### 7. Docs lint

```bash
Expand Down
12 changes: 11 additions & 1 deletion docs/operations/model-migration.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Migrate a public model to a new build

> Last updated: 2026-09-06 · commit `32b28b0a7`
> Last updated: 2026-09-11 · commit `e10709696`

Runbook for moving a public model name (an **alias**, e.g. `gemma-4-26b`) from
one concrete build to another with no downtime and without consumers ever
Expand Down Expand Up @@ -102,6 +102,8 @@ from id + version), uploads every file plus the manifest to
`s3://darkbloom-models/<r2_prefix>/` with concurrency 8, and prints the exact
`gh workflow run register-model.yml …` command for step 2. Manifest fields:
[`../reference/model-registry-format.md`](../reference/model-registry-format.md).
Failed or empty Secret Manager credential reads stop the publisher before any
R2 upload; inspect the reported lookup error before retrying.

### 2. Register the build in the coordinator catalog

Expand Down Expand Up @@ -241,6 +243,14 @@ R2_ACCOUNT_ID=… GCP_PROJECT=… scripts/preposition-rollback-build.sh \
# <src-model-id> <src-version> <new-model-id> <coordinator> <key> <quant> <min-ram-gb> <max-ctx> <max-out> <in-µ$/Mtok> <out-µ$/Mtok> [caps-csv]
```

The helper requires a distinct destination ID and prepares registration and
promotion JSON before copying objects. Invalid registry identifiers, empty
quantization, non-positive or out-of-range integer fields, and failed/empty R2
credential lookups stop before remote writes. It removes its local staging
directory on exit. A later copy or API failure can still leave destination R2
objects or a registered model; inspect that state before retrying. The script
does not undo completed remote operations.

## Verification

| Check | Expected |
Expand Down
73 changes: 51 additions & 22 deletions scripts/preposition-rollback-build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,48 @@ R2_SECRET_KEY_SECRET="${R2_SECRET_KEY_SECRET:-darkbloom-r2-secret-access-key}"
: "${R2_ACCOUNT_ID:?R2_ACCOUNT_ID is required}"
: "${GCP_PROJECT:?GCP_PROJECT is required}"

for tool in python3 gcloud aws curl; do
command -v "$tool" >/dev/null 2>&1 || { printf 'Missing required command: %s\n' "$tool" >&2; exit 1; }
done

TMP="$(mktemp -d "${TMPDIR:-/tmp}/darkbloom-model-rollback.XXXXXX")"
trap 'rm -rf "$TMP"' EXIT

# Validate and encode both API requests before any credential lookup or copy.
python3 - "$TMP" "$SRC_MODEL_ID" "$NEW_MODEL_ID" "$SRC_VERSION" "$QUANT" "$MIN_RAM_GB" "$MAX_CONTEXT" "$MAX_OUTPUT" "$INPUT_PRICE" "$OUTPUT_PRICE" "$CAPABILITIES" <<'PY'
import json, re, sys
from pathlib import Path

directory, source_id, new_id, version, quant, *values, caps = sys.argv[1:]
# Match validRegistryIdentifier and positive int64 fields in
# coordinator/api/model_registry_handlers.go (validateRegisterModelRequest).
for name, value, pattern in (("source model id", source_id, r"[A-Za-z0-9._/-]+"),
("new model id", new_id, r"[A-Za-z0-9._/-]+"),
("version", version, r"[A-Za-z0-9._-]+")):
if not re.fullmatch(pattern, value) or value.startswith("/") or ".." in value:
raise SystemExit(f"Invalid {name}")
if source_id == new_id:
raise SystemExit("Rollback requires a distinct new model id")
if not quant.strip():
raise SystemExit("quantization is required")
fields = ("min_ram_gb", "max_context_length", "max_output_length", "input_price", "output_price")
numbers = {}
for name, value in zip(fields, values):
try:
number = int(value)
except ValueError:
raise SystemExit(f"{name} must be a positive int64")
if not 0 < number <= 2**63 - 1:
raise SystemExit(f"{name} must be a positive int64")
numbers[name] = number
payload = {"model_id": new_id, "version": version,
"display_name": new_id + " (rollback)", "quantization": quant,
**numbers, "capabilities": [c for c in caps.split(",") if c]}
root = Path(directory)
(root / "register.json").write_text(json.dumps(payload), encoding="utf-8")
(root / "promote.json").write_text(json.dumps({"version": version}), encoding="utf-8")
PY

# Mirror coordinator/api/model_registry_handlers.go readableModelSlug+modelR2Prefix:
# slug = sanitized id, trimmed of '-', + "--" + first 12 hex of sha256(model_id);
# prefix = v2/<slug>/<version>
Expand All @@ -64,15 +106,19 @@ SRC_PREFIX="v2/$(slug "$SRC_MODEL_ID")/$SRC_VERSION"
NEW_PREFIX="v2/$(slug "$NEW_MODEL_ID")/$SRC_VERSION"
ENDPOINT="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com"

export AWS_ACCESS_KEY_ID="$(gcloud secrets versions access latest --project "$GCP_PROJECT" --secret "$R2_ACCESS_KEY_SECRET")"
export AWS_SECRET_ACCESS_KEY="$(gcloud secrets versions access latest --project "$GCP_PROJECT" --secret "$R2_SECRET_KEY_SECRET")"
AWS_ACCESS_KEY_ID="$(gcloud secrets versions access latest --project "$GCP_PROJECT" --secret "$R2_ACCESS_KEY_SECRET")"
AWS_SECRET_ACCESS_KEY="$(gcloud secrets versions access latest --project "$GCP_PROJECT" --secret "$R2_SECRET_KEY_SECRET")"
if [[ -z "$AWS_ACCESS_KEY_ID" || -z "$AWS_SECRET_ACCESS_KEY" ]]; then
printf 'R2 credentials must not be empty.\n' >&2
exit 1
fi
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY

echo "Copying s3://$R2_BUCKET/$SRC_PREFIX → s3://$R2_BUCKET/$NEW_PREFIX (server-side)…"
aws s3 cp "s3://$R2_BUCKET/$SRC_PREFIX/" "s3://$R2_BUCKET/$NEW_PREFIX/" \
--recursive --endpoint-url "$ENDPOINT" --copy-props none

echo "Rewriting manifest model_id/r2_prefix…"
TMP=$(mktemp -d)
aws s3 cp "s3://$R2_BUCKET/$NEW_PREFIX/manifest.json" "$TMP/manifest.json" --endpoint-url "$ENDPOINT"
python3 - "$TMP/manifest.json" "$NEW_MODEL_ID" "$NEW_PREFIX" <<'PY'
import json, sys
Expand All @@ -85,30 +131,13 @@ PY
aws s3 cp "$TMP/manifest.json" "s3://$R2_BUCKET/$NEW_PREFIX/manifest.json" --endpoint-url "$ENDPOINT"

echo "Registering $NEW_MODEL_ID with the coordinator…"
python3 - "$NEW_MODEL_ID" "$SRC_VERSION" "$QUANT" "$MIN_RAM_GB" "$MAX_CONTEXT" "$MAX_OUTPUT" "$INPUT_PRICE" "$OUTPUT_PRICE" "$CAPABILITIES" <<'PY' > "$TMP/register.json"
import json, sys
new_id, version, quant, min_ram, max_ctx, max_out, in_p, out_p, caps = sys.argv[1:10]
print(json.dumps({
"model_id": new_id,
"version": version,
"display_name": new_id + " (rollback)",
"quantization": quant,
"min_ram_gb": int(min_ram),
"max_context_length": int(max_ctx),
"max_output_length": int(max_out),
"input_price": int(in_p),
"output_price": int(out_p),
"capabilities": [c for c in caps.split(",") if c],
}))
PY
curl -fsS -X POST "$COORD/v1/admin/models/register" \
-H "Authorization: Bearer $PUBLISH_KEY" -H "Content-Type: application/json" \
--data @"$TMP/register.json"
echo
echo "Promoting $NEW_MODEL_ID $SRC_VERSION…"
printf 'Promoting %s %s...\n' "$NEW_MODEL_ID" "$SRC_VERSION"
curl -fsS -X POST "$COORD/v1/admin/models/$NEW_MODEL_ID/promote" \
-H "Authorization: Bearer $PUBLISH_KEY" -H "Content-Type: application/json" \
--data "{\"version\": \"$SRC_VERSION\"}"
--data @"$TMP/promote.json"
echo
echo "Done. Rollback is now a normal alias flip: desired_build=$NEW_MODEL_ID."
rm -rf "$TMP"
9 changes: 7 additions & 2 deletions scripts/publish-model.sh
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,13 @@ PY
)"

printf 'Fetching R2 credentials from GCP Secret Manager...\n'
export AWS_ACCESS_KEY_ID="$(gcloud secrets versions access latest --project "$GCP_PROJECT" --secret "$R2_ACCESS_KEY_SECRET")"
export AWS_SECRET_ACCESS_KEY="$(gcloud secrets versions access latest --project "$GCP_PROJECT" --secret "$R2_SECRET_KEY_SECRET")"
AWS_ACCESS_KEY_ID="$(gcloud secrets versions access latest --project "$GCP_PROJECT" --secret "$R2_ACCESS_KEY_SECRET")"
AWS_SECRET_ACCESS_KEY="$(gcloud secrets versions access latest --project "$GCP_PROJECT" --secret "$R2_SECRET_KEY_SECRET")"
if [[ -z "$AWS_ACCESS_KEY_ID" || -z "$AWS_SECRET_ACCESS_KEY" ]]; then
printf 'R2 credentials must not be empty.\n' >&2
exit 1
fi
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY
export AWS_DEFAULT_REGION="auto"
export R2_ENDPOINT="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com"

Expand Down
176 changes: 176 additions & 0 deletions scripts/test_model_publishing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"""Exercise publishing preflight and failure cleanup with offline command stubs."""

import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest


ROOT = Path(__file__).resolve().parents[1]
STUB = r'''#!/usr/bin/env python3
import json
import os
from pathlib import Path
import sys

tool, args = Path(sys.argv[0]).name, sys.argv[1:]
root = Path(os.environ["PUBLISH_FIXTURE_ROOT"])
event = {"tool": tool, "args": args}
if tool == "aws":
event["credentials"] = [os.environ.get(key) for key in
("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY")]
if tool == "curl":
data = args[args.index("--data") + 1]
event["payload"] = json.loads(Path(data[1:]).read_text() if data.startswith("@") else data)
with (root / "events.jsonl").open("a") as stream:
stream.write(json.dumps(event) + "\n")
if tool == "gcloud":
secret = args[args.index("--secret") + 1]
if secret == os.environ.get("PUBLISH_FIXTURE_FAILED_SECRET"):
print("fixture secret lookup failed", file=sys.stderr)
raise SystemExit(7)
if secret != os.environ.get("PUBLISH_FIXTURE_EMPTY_SECRET"):
print("verified-" + secret)
elif tool == "swift":
Path(args[args.index("-o") + 1]).write_text(json.dumps({
"r2_prefix": "v2/published/v1", "files": [{"path": "weights.safetensors"}]
}))
elif tool == "aws":
if os.environ.get("PUBLISH_FIXTURE_FAIL_TOOL") == tool:
raise SystemExit(8)
if args[:2] == ["s3", "cp"] and not args[3].startswith("s3://"):
Path(args[3]).write_text(json.dumps({
"model_id": "source/model", "version": "v1", "r2_prefix": "old-prefix",
"files": [{"path": "weights.safetensors", "sha256": "unchanged"}]
}))
elif tool == "curl":
if os.environ.get("PUBLISH_FIXTURE_FAIL_TOOL") == tool:
raise SystemExit(9)
print("{}")
'''


class ModelPublishingTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.bin = self.root / "bin"
self.bin.mkdir()
self.staging = self.root / "staging"
self.staging.mkdir()
self.model = self.root / "model"
self.model.mkdir()
(self.model / "weights.safetensors").write_bytes(b"fixture")
for tool in ("swift", "gcloud", "aws", "curl"):
path = self.bin / tool
path.write_text(STUB)
path.chmod(0o755)
self.env = {**os.environ, "PATH": str(self.bin) + os.pathsep + os.environ["PATH"],
"PUBLISH_FIXTURE_ROOT": str(self.root), "TMPDIR": str(self.staging),
"GCP_PROJECT": "fixture", "R2_ACCOUNT_ID": "fixture",
"R2_ACCESS_KEY_SECRET": "access-id", "R2_SECRET_KEY_SECRET": "secret-key",
"R2_BUCKET": "fixture-models", "HUGGING_FACE_ARTIFACT_JSON": "null",
"AWS_ACCESS_KEY_ID": "stale-access", "AWS_SECRET_ACCESS_KEY": "stale-secret"}

def events(self):
path = self.root / "events.jsonl"
return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []

def invoke(self, lane, *, env=None, fields=None):
if lane == "publish":
args = ["bash", str(ROOT / "scripts/publish-model.sh")]
data = f"{self.model}\npublished-model\nv1\n\n"
else:
values = ["source/model", "v1", "rollback/model", "https://coordinator.invalid",
"fixture-key", "4bit", "16", "8192", "1024", "10", "20", "chat,tools"]
for index, value in (fields or {}).items():
values[index] = value
args = ["bash", str(ROOT / "scripts/preposition-rollback-build.sh"), *values]
data = None
return subprocess.run(args, input=data, text=True, errors="replace", capture_output=True,
env={**self.env, **(env or {})}, timeout=20)

def reset(self):
(self.root / "events.jsonl").unlink(missing_ok=True)

def test_secret_failure_stops_both_publishers_before_any_remote_write(self):
for lane in ("publish", "rollback"):
for secret in ("access-id", "secret-key"):
with self.subTest(lane=lane, secret=secret):
self.reset()
result = self.invoke(lane, env={"PUBLISH_FIXTURE_FAILED_SECRET": secret})
self.assertNotEqual(result.returncode, 0, result.stdout)
self.assertFalse(any(e["tool"] in ("aws", "curl") for e in self.events()))
self.assertEqual(list(self.staging.iterdir()), [])

def test_empty_secrets_stop_both_publishers_before_any_remote_write(self):
for lane in ("publish", "rollback"):
for secret in ("access-id", "secret-key"):
with self.subTest(lane=lane, secret=secret):
self.reset()
result = self.invoke(lane, env={"PUBLISH_FIXTURE_EMPTY_SECRET": secret})
self.assertNotEqual(result.returncode, 0, result.stdout)
self.assertFalse(any(e["tool"] in ("aws", "curl") for e in self.events()))
self.assertEqual(list(self.staging.iterdir()), [])

def test_invalid_registry_numbers_fail_before_credential_lookup_or_copy(self):
for index in range(6, 11):
for value in ("not-an-integer", "0", "-1", str(2**63)):
with self.subTest(index=index, value=value):
self.reset()
result = self.invoke("rollback", fields={index: value})
self.assertNotEqual(result.returncode, 0, result.stdout)
self.assertEqual(self.events(), [])
self.assertEqual(list(self.staging.iterdir()), [])

def test_rollback_identifiers_and_distinct_destination_are_preflighted(self):
for fields in ({0: "../bad"}, {1: "bad/version"}, {1: 'bad"version'},
{2: "/bad"}, {2: "bad%2fmodel"}, {2: "source/model"}, {5: " "}):
with self.subTest(fields=fields):
self.reset()
result = self.invoke("rollback", fields=fields)
self.assertNotEqual(result.returncode, 0, result.stdout)
self.assertEqual(self.events(), [])
self.assertEqual(list(self.staging.iterdir()), [])

def test_success_keeps_verified_credentials_upload_order_and_registration(self):
for lane in ("publish", "rollback"):
with self.subTest(lane=lane):
self.reset()
result = self.invoke(lane)
self.assertEqual(result.returncode, 0, result.stderr)
events = self.events()
uploads = [e for e in events if e["tool"] == "aws"]
self.assertTrue(uploads)
for event in uploads:
self.assertEqual(event["credentials"], ["verified-access-id", "verified-secret-key"])
if lane == "publish":
self.assertTrue(uploads[-1]["args"][3].endswith("/manifest.json"))
self.assertFalse(any(e["tool"] == "curl" for e in events))
else:
calls = [e for e in events if e["tool"] == "curl"]
self.assertEqual(len(calls), 2)
registration = calls[0]["payload"]
self.assertEqual(registration["model_id"], "rollback/model")
self.assertEqual(registration["capabilities"], ["chat", "tools"])
self.assertEqual(registration["input_price"], 10)
self.assertEqual(calls[1]["payload"], {"version": "v1"})
self.assertLess(events.index(uploads[-1]), events.index(calls[0]))
self.assertEqual(list(self.staging.iterdir()), [])

def test_failed_copy_or_registration_cleans_owned_staging_and_stops(self):
for tool in ("aws", "curl"):
with self.subTest(tool=tool):
self.reset()
result = self.invoke("rollback", env={"PUBLISH_FIXTURE_FAIL_TOOL": tool})
self.assertNotEqual(result.returncode, 0)
calls = [e for e in self.events() if e["tool"] == "curl"]
self.assertEqual(len(calls), 0 if tool == "aws" else 1)
self.assertEqual(list(self.staging.iterdir()), [])


if __name__ == "__main__":
unittest.main()
Loading