Skip to content

Commit 196cdff

Browse files
committed
Merge remote-tracking branch 'origin/main' into codex/ui-audit-local
2 parents a93875f + 1533930 commit 196cdff

9 files changed

Lines changed: 756 additions & 57 deletions

File tree

‎docs/kubernetes-upgrades.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ For a declared database schema transition, preflight locally renders the checksu
2828

2929
Replace `plan` with `apply` and add `--acknowledge-interruption`. Only an existing release is upgraded; first installation remains the chart's existing Helm workflow. The tool verifies the current server workload against the supplied accepted digest before mutation and writes private operation/recovery records under `--output`.
3030

31-
Maintenance transitions pause the release's CronJobs (a release still on the 0.2 chart has them; from 0.3 the server does the scheduled work itself and there are none), wait for their recorded active Jobs, scale server admission to zero and wait for old server pods to leave before running the backup command. The backup executable must create and verify the backup identified by `--backup-reference`, exit nonzero on failure, and use the customer's existing database/cloud credentials. A preexisting backup alone is insufficient for a maintenance transition: the command is required so it runs after quiescence. The tool does not invent a cloud snapshot implementation or silently assume a successful empty command produced a restorable backup.
31+
A release whose recovery is restoring a backup (`rollbackCompatible: false`), or that declares downtime, runs the backup command before Helm, and the command is required: a preexisting backup alone is insufficient. Only a release that declares downtime (`upgrade.requiresDowntime`) stops the server first: it pauses the release's CronJobs (a release still on the 0.2 chart has them; from 0.3 the server does the scheduled work itself and there are none), waits for their recorded active Jobs, scales server admission to zero and waits for old server pods to leave before running the backup command. Every other release keeps serving while the backup runs, and the chart's rolling update replaces the servers one by one, because the previous release works on the database the new one's migrations leave ([api-and-migrations.md](api-and-migrations.md#the-database-a-migration-never-breaks-a-running-server)). `rollbackCompatible` decides the recovery, not downtime. The backup executable must create and verify the backup identified by `--backup-reference`, exit nonzero on failure, and use the customer's existing database/cloud credentials. The tool does not invent a cloud snapshot implementation or silently assume a successful empty command produced a restorable backup.
3232

3333
Helm receives the exact chart archive, the release's previous values, the customer values, and a generated file containing only the pinned image and release annotations. For a release that Helm 4 applies server-side (`helm get metadata` reports `applyMethod: ssa`), the upgrade passes `--force-conflicts`. The chart's declared values then take back the CronJob suspension and replica count this tool set with kubectl, as client-side apply does. Without it, the upgrade stops on a field-manager conflict after the migration hook has already run. `--wait`, `--wait-for-jobs` and a timeout bound the operation. In a chart with a migrations Job, as the `openbot` chart had up to 0.2, the pre-upgrade migration hook blocks workload promotion on migration failure and retains the database's advisory lock and history-reach checks. The special first installation with bundled PostgreSQL continues using an ordinary migration Job so the database can be created first. That distinction is unchanged. In a chart whose server applies its own migrations, as 0.3 does, there is no hook, and the server migrates as it starts.
3434

@@ -38,7 +38,7 @@ After the candidate is verified, every CronJob this operation suspended is put b
3838

3939
No `--atomic`/automatic rollback is used. A failed migration can commit durable changes, so restoring an old Helm revision does not restore SQL.
4040

41-
A refusal before anything changed (a plan refusal, or a current workload that does not match the accepted release) writes no journal. A failure after quiescing began but before Helm ran (a CronJob wait, the scale-down or the backup) puts the replica count and CronJobs back exactly and records `failed`, which does not block another attempt. A failure once Helm has started records `recovery-required`. A maintenance transition then keeps server writes and scheduled work paused; a rollback-compatible transition without downtime is left serving, because the previous code accepts the resulting schema. Shutdown failure is reported alongside the original error. Previous replica counts and CronJob suspension states are retained for operator recovery. A `recovery-required` journal blocks another promotion from the same output directory; retain one directory per installation rather than bypassing its lock with a new path.
41+
A refusal before anything changed (a plan refusal, or a current workload that does not match the accepted release) writes no journal. A failure after quiescing began but before Helm ran (a CronJob wait, the scale-down or the backup) puts the replica count and CronJobs back exactly and records `failed`, which does not block another attempt. A failure once Helm has started records `recovery-required`. A release that declared downtime then keeps server writes and scheduled work paused; one without downtime is left serving, because the previous release works on the resulting database. Shutdown failure is reported alongside the original error. Previous replica counts and CronJob suspension states are retained for operator recovery. A `recovery-required` journal blocks another promotion from the same output directory; retain one directory per installation rather than bypassing its lock with a new path.
4242

4343
Operators must review configuration/storage differences and ensure no other controller reopens write admission during maintenance. The tool serializes one operator invocation locally; it does not introduce a cluster-wide deployment operator or replace customer deployment concurrency policy. Backup restore, forward recovery and old-code compatibility remain explicit operator decisions.
4444

‎docs/managed-upgrades.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,11 @@ you set one in the agent's `window` value. Before an upgrade that changes the da
134134
that the backup settings name the database OpenBot actually uses, then takes a verified backup. If
135135
the check fails, it changes nothing and stops for a person. It never rolls back by itself.
136136

137+
**OpenBot keeps serving during an upgrade.** The backup runs while OpenBot serves, and the new
138+
release replaces the servers one by one, its database changes first: every release keeps working on
139+
the database the next one leaves. Only a release that says it needs downtime (rare, and named in its
140+
changelog) stops OpenBot for the backup and the upgrade.
141+
137142
**Every chart is signature-checked first.** OpenBot signs each release's charts with its own cosign
138143
key (the public key is [`docs/cosign.pub`](cosign.pub)), and the `openbot-agent` chart carries that
139144
key, so the check is on with nothing to set up. Before an upgrade touches anything, the agent has Flux

‎management-agent/src/agent.ts‎

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616
import {
1717
identityMatches,
1818
imageParts,
19-
needsMaintenance,
19+
needsFreshBackup,
20+
needsQuiescing,
2021
type PromotionJournal,
2122
promotionValues,
2223
type ReleaseIdentity,
@@ -516,8 +517,8 @@ export class ManagementAgent {
516517
*
517518
* No quiescing and no backup. The database is the one the accepted release was accepted with
518519
* (or the backup the person restored for it), so returning to that release changes nothing in
519-
* it, and the failed promotion already left the server stopped. Quiescing would also record
520-
* those zero replicas as the ones to put back.
520+
* it, and a failed promotion of a release that declared downtime already left the server stopped.
521+
* Quiescing would also record those zero replicas as the ones to put back.
521522
*
522523
* Pods of a StatefulSet that the failed release left stuck are deleted while it goes back on
523524
* (`forcedRollback`), as Kubernetes asks. Then every workload of the release is restarted, so
@@ -553,8 +554,9 @@ export class ManagementAgent {
553554
pinned ? `chart ${pinned}` : "none",
554555
accepted.version,
555556
);
556-
// The failed promotion scaled the server to zero. The chart puts its replicas back; when
557-
// an autoscaler owns them, one replica lets the autoscaler take over again.
557+
// A failed promotion that declared downtime scaled the server to zero. The chart puts its
558+
// replicas back; when an autoscaler owns them, one replica lets the autoscaler take over
559+
// again.
558560
journal.previousReplicas = 1;
559561
await runPromotion({
560562
target,
@@ -563,7 +565,8 @@ export class ManagementAgent {
563565
journal,
564566
save: (entry) => this.saveJournal(entry),
565567
before: await this.cluster.serverDeployment(target),
566-
maintenance: false,
568+
quiesce: false,
569+
freshBackup: false,
567570
backup: async () => {},
568571
apply: async () => {
569572
const done = new AbortController();
@@ -954,23 +957,29 @@ export class ManagementAgent {
954957
const before = await this.cluster.serverDeployment(target);
955958
verifyDeployment(before, current, false);
956959
const operation = operationId(this.clock());
957-
const maintenance =
958-
needsMaintenance(candidate) ||
960+
// The server stops only for a release that declares downtime. Every upgrade that changes the
961+
// database, or whose recovery is restoring a backup, takes a fresh one first; without downtime
962+
// it runs while the server serves, and the chart's rolling update carries the release, its
963+
// migration first (shared/kubernetes-promotion.ts says why).
964+
const quiesce = needsQuiescing(candidate);
965+
const freshBackup =
966+
needsFreshBackup(candidate) ||
959967
current.compatibility.database.to !== candidate.compatibility.database.to;
960968
const journal = this.newJournal(
961969
current.version,
962970
candidate.version,
963-
maintenance ? `openbot-${operation}` : "none",
971+
freshBackup ? `openbot-${operation}` : "none",
964972
);
965-
if (maintenance) await this.confirmBackupTarget(journal, operation);
973+
if (freshBackup) await this.confirmBackupTarget(journal, operation);
966974
await runPromotion({
967975
target,
968976
cluster: this.cluster,
969977
candidate,
970978
journal,
971979
save: (journal) => this.saveJournal(journal),
972980
before,
973-
maintenance,
981+
quiesce,
982+
freshBackup,
974983
backup: async () => {
975984
await runJob(
976985
this.kube,
@@ -1228,7 +1237,8 @@ export class ManagementAgent {
12281237
journal: this.newJournal(from.version, previous.version),
12291238
save: (entry) => this.saveJournal(entry),
12301239
before: await this.cluster.serverDeployment(target),
1231-
maintenance: false,
1240+
quiesce: false,
1241+
freshBackup: false,
12321242
backup: async () => {},
12331243
apply: () => this.applyRelease(previous, manifest),
12341244
declaredSuspension: async () => new Set(),

‎management-agent/tests/agent-cluster.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ describe("a promotion through the agent's own client", () => {
222222
phases.push(entry.phase);
223223
},
224224
before: await agentCluster.serverDeployment(target),
225-
maintenance: true,
225+
quiesce: true,
226226
backup: async () => {
227227
// Taken with writes stopped: no server pod left, the CronJob suspended.
228228
backedUpWith = [serverPods(api).length];

‎management-agent/tests/agent-kind.test.ts‎

Lines changed: 123 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@
1414
* inside it, a copy of that release that is unsigned, then one signed with another key, is
1515
* refused before anything is touched: no backup, no quiescing, Flux left on the accepted chart,
1616
* and the heartbeat says why;
17-
* 3. inside the window: quiesce, a backup Job (backup.kind=command, pg_dump of the bundle's real
17+
* 3. inside the window: a backup Job (backup.kind=command, pg_dump of the bundle's real
1818
* PostgreSQL, verified with pg_restore) that finishes before Flux is pinned to the new chart
19-
* digest, then verification through /release;
19+
* digest, then verification through /release. A release without downtime is never stopped:
20+
* the server's Service has a ready endpoint at every moment of the upgrade, backup and
21+
* migration included; one that declares downtime is quiesced first;
2022
* 4. a signed rollback is refused because the release's policy says restore-backup;
2123
* 5. a release whose image does not exist: backup, Flux fails the upgrade, recovery-required;
2224
* then, as a person recovers (journal.json removed, the desired version set back to the
@@ -329,6 +331,80 @@ const backupJobs = () =>
329331
kubectl("-n", SYSTEM, "get", "jobs", "-o", "name")
330332
.split("\n")
331333
.filter((name) => name.includes("openbot-backup-"));
334+
const SERVER_SELECTOR =
335+
"app.kubernetes.io/instance=openbot,app.kubernetes.io/component=server";
336+
/**
337+
* The ready addresses behind the server's Service, as its EndpointSlices list them: what a load
338+
* balancer sends requests to (the ALB's targets on OpenBot Cloud). None means every request fails.
339+
*/
340+
async function servingEndpoints() {
341+
const services = (
342+
JSON.parse(
343+
await shAsync("kubectl", [
344+
"-n",
345+
PRODUCT,
346+
"get",
347+
"service",
348+
"-l",
349+
SERVER_SELECTOR,
350+
"-o",
351+
"json",
352+
]),
353+
) as { items: { metadata: { name: string } }[] }
354+
).items
355+
.map((service) => service.metadata.name)
356+
.filter((name) => !name.endsWith("-internal"));
357+
const slices = (
358+
JSON.parse(
359+
await shAsync("kubectl", [
360+
"-n",
361+
PRODUCT,
362+
"get",
363+
"endpointslices.discovery.k8s.io",
364+
"-o",
365+
"json",
366+
]),
367+
) as {
368+
items: {
369+
metadata: { labels?: Record<string, string> };
370+
endpoints?: { conditions?: { ready?: boolean } }[] | null;
371+
}[];
372+
}
373+
).items.filter((slice) =>
374+
services.includes(
375+
slice.metadata.labels?.["kubernetes.io/service-name"] ?? "",
376+
),
377+
);
378+
if (!services.length) throw new Error("no server Service");
379+
return slices
380+
.flatMap((slice) => slice.endpoints ?? [])
381+
.filter((endpoint) => endpoint.conditions?.ready === true).length;
382+
}
383+
/** Samples `servingEndpoints` about every second until stopped. */
384+
function watchServing() {
385+
const samples: { at: string; ready: number }[] = [];
386+
let stopped = false;
387+
const done = (async () => {
388+
while (!stopped) {
389+
try {
390+
samples.push({
391+
at: new Date().toISOString(),
392+
ready: await servingEndpoints(),
393+
});
394+
} catch {
395+
// A read that failed (the API server busy, say) is no sample; the next one is.
396+
}
397+
await Bun.sleep(1_000);
398+
}
399+
})();
400+
return {
401+
samples,
402+
stop: async () => {
403+
stopped = true;
404+
await done;
405+
},
406+
};
407+
}
332408
/** How long Flux gives a product install or upgrade, through the agent chart's values. */
333409
const productTimeout = (value: string) =>
334410
shAsync("helm", [
@@ -750,7 +826,11 @@ run("management agent on a real cluster", () => {
750826
);
751827
expect(failed.error).toContain("failed");
752828
expect(failed.databaseMayHaveChanged).toBe(false);
753-
// Writes are back: the server at its replicas, the CronJobs it suspended running again.
829+
// Writes are back: the server at its replicas, the CronJobs it suspended running again. A
830+
// release without downtime never stopped the server, so it records no replicas to put back.
831+
expect(failed.previousReplicas === undefined).toBe(
832+
!JSON.parse(to.manifest).upgrade.requiresDowntime,
833+
);
754834
await until(
755835
"the server back at its replicas",
756836
() => {
@@ -767,9 +847,11 @@ run("management agent on a real cluster", () => {
767847
"-l",
768848
"app.kubernetes.io/instance=openbot,app.kubernetes.io/component=server",
769849
).items[0];
850+
const replicas = failed.previousReplicas ?? server?.spec.replicas ?? 1;
770851
return (
771-
server?.spec.replicas === failed.previousReplicas &&
772-
server.status.readyReplicas === failed.previousReplicas
852+
replicas > 0 &&
853+
server?.spec.replicas === replicas &&
854+
server.status.readyReplicas === replicas
773855
);
774856
},
775857
10,
@@ -810,17 +892,27 @@ run("management agent on a real cluster", () => {
810892
});
811893

812894
test("inside the window: backs up first, then upgrades and verifies", async () => {
895+
// From before Flux moves until the new release is verified, how many ready addresses the
896+
// server's Service has. The agent restarted at the end of the last test is still coming up.
897+
const serving = watchServing();
898+
await until("the first sample", () => serving.samples.length > 0, 2);
899+
const pinnedAtStart = pinned();
813900
service.window = { weekday: 0, startUtc: "00:00", hours: 168 };
814-
await until(
815-
`${to.version} installed and verified`,
816-
() => {
817-
const last = latest();
818-
return (
819-
last?.openbot.version === to.version && last.upgrade.state === "idle"
820-
);
821-
},
822-
40,
823-
);
901+
try {
902+
await until(
903+
`${to.version} installed and verified`,
904+
() => {
905+
const last = latest();
906+
return (
907+
last?.openbot.version === to.version &&
908+
last.upgrade.state === "idle"
909+
);
910+
},
911+
40,
912+
);
913+
} finally {
914+
await serving.stop();
915+
}
824916
expect(pinned()).toBe(to.digest);
825917

826918
const state = json<{ data: Record<string, string> }>(
@@ -836,6 +928,22 @@ run("management agent on a real cluster", () => {
836928
expect(journal.toVersion).toBe(to.version);
837929
expect(journal.backupReference).toMatch(/^openbot-/);
838930

931+
// Without declared downtime the server is never stopped: not for the backup, not while the
932+
// release migrates, not while the new pods replace the old. Sampling began before Flux moved.
933+
const toManifest = JSON.parse(to.manifest);
934+
const fromManifest = JSON.parse(from.manifest);
935+
console.log(
936+
`upgrade ${from.version} -> ${to.version}: database ${fromManifest.compatibility.database.to} -> ${toManifest.compatibility.database.to}, requiresDowntime ${toManifest.upgrade.requiresDowntime}, ${serving.samples.length} samples, fewest ready endpoints ${Math.min(...serving.samples.map((s) => s.ready))}`,
937+
);
938+
if (!toManifest.upgrade.requiresDowntime) {
939+
expect(pinnedAtStart).toBe(from.digest);
940+
expect(journal.previousReplicas).toBeUndefined();
941+
expect(serving.samples.length).toBeGreaterThan(10);
942+
expect(serving.samples.filter((sample) => sample.ready === 0)).toEqual(
943+
[],
944+
);
945+
} else expect(journal.previousReplicas).toBeGreaterThan(0);
946+
839947
const job = json<{
840948
status: { succeeded?: number; completionTime?: string };
841949
}>(

0 commit comments

Comments
 (0)