Skip to content
Open
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
33 changes: 28 additions & 5 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -907,13 +907,27 @@ jobs:
echo "::error::Rollback requires the captured machine identities and original source configuration."
exit 1
fi
mapfile -t machine_ids < <(jq -r 'sort_by(.config.metadata.fly_process_group)[] | .id' "${RUNNER_TEMP}/postil-source-machines.json")
select_recovery_machine() {
jq -r --arg image "${SOURCE_IMAGE}" '
def healthy: .state == "started" and .host_status == "ok" and
all(.checks[]?; .status == "passing");
map(select((healthy | not) or
(.image_ref.registry + "/" + .image_ref.repository + "@" + .image_ref.digest) != $image)) |
sort_by([(if healthy then 1 else 0 end), .config.metadata.fly_process_group, .id]) |
.[0].id // empty
'
}
umask 077
for id in "${machine_ids[@]}"; do
read_deploy_machines rollback | jq -ce --arg id "${id}" '
# Health can change during restoration. Select from each fresh read,
# restoring unhealthy members before restarting any healthy peer.
for ((attempt = 0; attempt < 15; attempt++)); do
current_machines=$(read_deploy_machines rollback)
id=$(select_recovery_machine <<<"${current_machines}")
[[ -n "${id}" ]] || break
jq -ce --arg id "${id}" '
[.[] | select(.id == $id)] |
if length == 1 then .[0] else error("captured machine identity is not unique") end
' > "${RUNNER_TEMP}/postil-before-update.json"
' <<<"${current_machines}" > "${RUNNER_TEMP}/postil-before-update.json"
if ! jq -e --slurpfile source "${RUNNER_TEMP}/postil-source-machines.json" --arg id "${id}" '
def runtime_config: .config | del(.image,
.metadata.fly_release_id, .metadata.fly_release_version, .metadata.fly_flyctl_version,
Expand Down Expand Up @@ -947,6 +961,9 @@ jobs:
exit 1
fi
current_machines=$(read_deploy_machines rollback)
# Reconsider delayed failures observed during the runtime probe.
next_id=$(select_recovery_machine <<<"${current_machines}")
[[ "${next_id}" == "${id}" ]] || continue
if ! jq -e --slurpfile source "${RUNNER_TEMP}/postil-source-machines.json" --arg id "${id}" '
def runtime_config: .config | del(.image,
.metadata.fly_release_id, .metadata.fly_release_version, .metadata.fly_flyctl_version,
Expand Down Expand Up @@ -974,8 +991,14 @@ jobs:
fi
verify_source_secrets
# Each update retains the machine configuration and attached volume.
# Supplying the verified config keeps immutable image identities out
# of flyctl's tag-resolution path.
umask 077
source_config="${RUNNER_TEMP}/postil-restore-config.json"
jq --arg image "${SOURCE_IMAGE}" '.config | .image = $image' \
"${RUNNER_TEMP}/postil-before-update.json" > "${source_config}"
if ! flyctl machine update "${id}" --app postil-web \
--image "${SOURCE_IMAGE}" --wait-timeout 120 --yes >/dev/null 2>&1; then
--machine-config "${source_config}" --wait-timeout 120 --yes >/dev/null 2>&1; then
Comment thread
morgaesis marked this conversation as resolved.
Resolved
echo "::error::A captured machine could not return to the source image."
exit 1
fi
Expand Down
10 changes: 9 additions & 1 deletion scripts/verify-managed-fleet.jq
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,17 @@ def release_group:
.config.metadata.fly_process_group == "monitor"
)];

def resolved_image:
.image_ref |
if (.registry | type == "string" and length > 0) and
(.repository | type == "string" and length > 0) and
(.digest | type == "string" and test("^sha256:[0-9a-f]{64}$"))
then .registry + "/" + .repository + "@" + .digest
else error("managed image identity is unresolved") end;

release_group as $release
| [$release[] | select(.config.metadata.fly_platform_version == "v2")] as $managed
| [$managed[].config.image] | unique as $images
| [$managed[] | resolved_image] | unique as $images
| [$managed[] | select(
.config.metadata.fly_process_group == "web" and .state == "started"
)] as $web
Expand Down
1 change: 1 addition & 0 deletions src/lib/server-observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,7 @@ function sanitizePostHogFrame(frame: Record<string, unknown>): Record<string, un
return {
platform: "node:javascript",
filename: match[1],
function: "?",
lineno: Number(match[2]),
colno: Number(match[3]),
in_app: true,
Expand Down
68 changes: 54 additions & 14 deletions tests/deploy-workflow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,13 +160,26 @@ function runStep(id: string, machines = fleet(), snapshot = fleet(), secrets = i
jq -er --arg id "$3" '.[] | select(.id == $id and .state != "stopped") | .release' "$RUNNER_TEMP/machines.json" ;;
"machine status") echo 'Error: unknown flag: --json' >&2; return 64 ;;
"machine update")
printf '%s\\n' "$*" >> "$RUNNER_TEMP/updates"
if [[ "\${TEST_REJECT_IMAGE_RESOLUTION:-0}" == "1" && "$*" == *"--image "* ]]; then return 1; fi
local restore_config="" previous="" argument
for argument in "$@"; do
if [[ "$previous" == "--machine-config" ]]; then restore_config="$argument"; fi
previous="$argument"
done
[[ -n "$restore_config" && -f "$restore_config" ]] || return 96
jq -e --arg image "$SOURCE_IMAGE" '.image == $image' "$restore_config" >/dev/null || return 96
printf 'machine update %s --app postil-web --machine-config [private] --wait-timeout 120 --yes\\n' "$3" >> "$RUNNER_TEMP/updates"
if [[ "\${TEST_FAIL_UPDATE_ID:-}" == "$3" ]]; then return 1; fi
jq --arg id "$3" --arg image "$SOURCE_IMAGE" --arg sha "$SOURCE_RELEASE_SHA" --arg unhealthy "\${TEST_LEAVE_UNHEALTHY_ID:-}" '
map(if .id == $id then .config.image = $image | .image_ref.digest = ($image | split("@")[1]) | .release = $sha | .state = "started" | .host_status = "ok" | (.checks[]?.status) = "passing" |
jq --slurpfile config "$restore_config" --arg id "$3" --arg image "$SOURCE_IMAGE" --arg sha "$SOURCE_RELEASE_SHA" --arg unhealthy "\${TEST_LEAVE_UNHEALTHY_ID:-}" '
map(if .id == $id then .config = $config[0] | .image_ref.digest = ($image | split("@")[1]) | .release = $sha | .state = "started" | .host_status = "ok" | (.checks[]?.status) = "passing" |
if .id == $unhealthy then .checks[0].status = "critical" else . end else . end)
' "$RUNNER_TEMP/machines.json" > "$RUNNER_TEMP/next.json"
mv "$RUNNER_TEMP/next.json" "$RUNNER_TEMP/machines.json"
if [[ "\${TEST_DELAYED_WEB_FAILURE:-0}" == "1" && "$3" == "a2" ]]; then
jq 'map(if .id == "a1" then .checks[0].status = "critical" else . end)' \
"$RUNNER_TEMP/machines.json" > "$RUNNER_TEMP/next.json"
mv "$RUNNER_TEMP/next.json" "$RUNNER_TEMP/machines.json"
fi
if [[ -f "$RUNNER_TEMP/after-update-machines.json" ]]; then
cp "$RUNNER_TEMP/after-update-machines.json" "$RUNNER_TEMP/status-machines.json"
else
Expand Down Expand Up @@ -280,7 +293,16 @@ describe("managed deployment contract", () => {
}
expect(assignments).toBe(30);
expect(recoveredPrefixes).toBe(150);
}, 120_000);
// Each restored prefix now reads fresh health before selecting its next member.
}, 240_000);

test("rollback restores immutable images without the image resolution path", () => {
const result = runStep("rollback", mixedFleet(), fleet(), undefined,
undefined, undefined, undefined, { TEST_REJECT_IMAGE_RESOLUTION: "1" });
expect(result.code, result.error).toBe(0);
expect(result.machines.every((machine: ReturnType<typeof fleet>[number]) =>
machine.image_ref.digest === digest)).toBe(true);
});

test("peer deployment accepts the unchanged partial feedback-secret deployment after phase one", () => {
const partialSecrets = [...secretMetadata, { ...stagedFeedback, status: "Partial" }];
Expand Down Expand Up @@ -359,7 +381,7 @@ describe("managed deployment contract", () => {
expect(failed.machines.find((machine: ReturnType<typeof fleet>[number]) =>
machine.id === updateOrder[boundary - 1])?.release).toBe(targetSha);
}
});
}, 15_000);

test("supplied immutable runtime can differ from the workflow SHA; a build cannot", () => {
const supplied = runStep("admission", fleet(), fleet(), secretMetadata, undefined,
Expand Down Expand Up @@ -1173,7 +1195,7 @@ describe("managed deployment contract", () => {
}
const result = runStep("rollback", machines, snapshot);
expect(result.code, result.error).toBe(0);
expect(result.updates.trim()).toBe(`machine update a1 --app postil-web --image ${sourceImage} --wait-timeout 120 --yes`);
expect(result.updates.trim()).toBe(`machine update a1 --app postil-web --machine-config [private] --wait-timeout 120 --yes`);
expect(result.machines[1].release).toBe(sourceSha);
expect(result.machines[1].image_ref.digest).toBe(digest);
expect(result.machines[1].config.metadata).toEqual(machines[1]!.config.metadata);
Expand Down Expand Up @@ -1212,7 +1234,7 @@ describe("managed deployment contract", () => {
machines[1]!.release = targetSha;
const result = runStep("rollback", machines);
expect(result.code, result.error).toBe(0);
expect(result.updates.trim()).toBe(`machine update a1 --app postil-web --image ${sourceImage} --wait-timeout 120 --yes`);
expect(result.updates.trim()).toBe(`machine update a1 --app postil-web --machine-config [private] --wait-timeout 120 --yes`);
expect(result.machines).toEqual(fleet());
const taggedSource = fleet();
for (const machine of taggedSource) machine.config.image = "registry.fly.io/postil-web:source";
Expand All @@ -1230,7 +1252,7 @@ describe("managed deployment contract", () => {
stoppedSource[1]!.state = "stopped";
const sourceResult = runStep("rollback", stoppedSource);
expect(sourceResult.code, sourceResult.error).toBe(0);
expect(sourceResult.updates.trim()).toBe(`machine update a1 --app postil-web --image ${sourceImage} --wait-timeout 120 --yes`);
expect(sourceResult.updates.trim()).toBe(`machine update a1 --app postil-web --machine-config [private] --wait-timeout 120 --yes`);
expect(sourceResult.machines).toEqual(fleet());

const stoppedTarget = fleet();
Expand All @@ -1240,7 +1262,7 @@ describe("managed deployment contract", () => {
stoppedTarget[1]!.release = targetSha;
const targetResult = runStep("rollback", stoppedTarget);
expect(targetResult.code, targetResult.error).toBe(0);
expect(targetResult.updates.trim()).toBe(`machine update a1 --app postil-web --image ${sourceImage} --wait-timeout 120 --yes`);
expect(targetResult.updates.trim()).toBe(`machine update a1 --app postil-web --machine-config [private] --wait-timeout 120 --yes`);
expect(targetResult.machines).toEqual(fleet());
});

Expand All @@ -1255,15 +1277,15 @@ describe("managed deployment contract", () => {
const result = runStep("rollback", machines);
expect(result.code, result.error).toBe(0);
expect(result.updates.trim().split("\n")).toEqual(["a0", "a1", "a2", "a4"].map(id =>
`machine update ${id} --app postil-web --image ${sourceImage} --wait-timeout 120 --yes`));
`machine update ${id} --app postil-web --machine-config [private] --wait-timeout 120 --yes`));
expect(result.machines).toEqual(fleet());

for (const environment of [{ TEST_FAIL_UPDATE_ID: "a0" }, { TEST_LEAVE_UNHEALTHY_ID: "a0" }] as Record<string, string>[]) {
const failed = runStep("rollback", structuredClone(machines), fleet(), stagedSecrets, undefined,
structuredClone(machines), undefined, environment);
expect(failed.code).not.toBe(0);
expect(failed.updates.trim().split("\n")).toEqual([
`machine update a0 --app postil-web --image ${sourceImage} --wait-timeout 120 --yes`,
`machine update a0 --app postil-web --machine-config [private] --wait-timeout 120 --yes`,
]);
}

Expand All @@ -1274,15 +1296,33 @@ describe("managed deployment contract", () => {
expect(rejected.updates).toBe("");
});

test("does not replace a healthy machine without a healthy same-group peer", () => {
test("restores the unhealthy same-group peer before replacing a healthy machine", () => {
const machines = fleet();
machines[0]!.image_ref.digest = `sha256:${"c".repeat(64)}`;
machines[0]!.config.image = `registry.fly.io/postil-web@${machines[0]!.image_ref.digest}`;
machines[0]!.release = targetSha;
machines[1]!.state = "stopped";
const result = runStep("rollback", machines);
expect(result.code).not.toBe(0);
expect(result.updates).toBe("");
expect(result.code, result.error).toBe(0);
expect(result.updates.trim().split("\n")).toEqual(["a1", "a0"].map(id =>
`machine update ${id} --app postil-web --machine-config [private] --wait-timeout 120 --yes`));
expect(result.machines).toEqual(fleet());
});

test("reselects an unhealthy replica when a peer fails during recovery", () => {
const machines = fleet();
for (const machine of machines.filter(machine => ["a0", "a1", "a2"].includes(machine.id))) {
machine.image_ref.digest = targetImage.split("@")[1]!;
machine.config.image = targetImage;
machine.release = targetSha;
}
machines[2]!.checks[0]!.status = "critical";
const result = runStep("rollback", machines, fleet(), stagedSecrets, undefined,
machines, undefined, { TEST_DELAYED_WEB_FAILURE: "1" });
expect(result.code, result.error).toBe(0);
expect(result.updates.trim().split("\n")).toEqual(["a2", "a1", "a0"].map(id =>
`machine update ${id} --app postil-web --machine-config [private] --wait-timeout 120 --yes`));
expect(result.machines).toEqual(fleet());
});

test("refuses an unavailable runtime identity on a healthy machine", () => {
Expand Down
15 changes: 15 additions & 0 deletions tests/env-validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,16 @@ describe("worker startup environment validation", () => {
managedMachine("monitor"),
];
expect(verifyManagedFleet(root, validFleet).exitCode).toBe(0);
const equivalentReferences = structuredClone(validFleet);
equivalentReferences[0]!.config.image =
`registry.fly.io/postil-web@${equivalentReferences[0]!.image_ref.digest}`;
expect(verifyManagedFleet(root, equivalentReferences).exitCode).toBe(0);
const differentResolvedImage = structuredClone(validFleet);
differentResolvedImage[0]!.image_ref.digest = `sha256:${"b".repeat(64)}`;
expect(verifyManagedFleet(root, differentResolvedImage).exitCode).not.toBe(0);
const unresolvedImage = structuredClone(validFleet);
unresolvedImage[0]!.image_ref.digest = "";
expect(verifyManagedFleet(root, unresolvedImage).exitCode).not.toBe(0);
expect(
verifyManagedFleet(root, [...validFleet, managedMachine("worker", "0", "1")])
.exitCode,
Expand Down Expand Up @@ -243,6 +253,11 @@ function managedMachine(
) {
return {
state,
image_ref: {
registry: "registry.fly.io",
repository: "postil-web",
digest: `sha256:${(image.endsWith(":other") ? "b" : "a").repeat(64)}`,
},
config: {
image,
metadata: {
Expand Down
15 changes: 13 additions & 2 deletions tests/server-observability.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ const TOKEN = "phc_test_project_token_abcdefghijklmnopqrstuvwxyz";
const NOW = Date.parse("2026-07-13T12:00:00.000Z");

describe("server operational observability", () => {
test("sends only a scrubbed exception envelope for hostile errors", async () => {
test.each(["web", "worker", "monitor"] as const)("sends only a scrubbed exception envelope for hostile errors (%s)", async (processGroup) => {
const requests: string[] = [];
const observability = new ServerObservability({
processGroup: "worker",
processGroup,
environment: {
POSTHOG_ERROR_CAPTURE: "1",
POSTHOG_PROJECT_TOKEN: TOKEN,
Expand Down Expand Up @@ -46,6 +46,17 @@ describe("server operational observability", () => {
const outbound = requests.join("\n");
expect(outbound).toContain("job_permanently_failed");
expect(outbound).toContain("src/worker/review.ts");
const events = requests.flatMap((body) => JSON.parse(body).batch);
expect(events).toHaveLength(1);
const stacktrace = events[0].properties.$exception_list[0].stacktrace;
expect(stacktrace.type).toBe("raw");
expect(stacktrace.frames).toHaveLength(1);
// PostHog's Node frame decoder requires filename and function strings.
expect(stacktrace.frames[0]).toMatchObject({
platform: "node:javascript",
filename: "src/worker/review.ts",
function: "?",
});
for (const sentinel of [
"private@example.test",
"session-secret",
Expand Down