@jeffusion/bungee-core 6.14.1 → 6.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config-storage-worker.js +413 -216
- package/dist/main.js +16093 -13501
- package/dist/plugins/anthropic-request-sanitizer/index.js.map +1 -1
- package/dist/plugins/anthropic-tool-name-transformer/index.js.map +1 -1
- package/dist/plugins/chatgpt-oauth/control.js +13 -5
- package/dist/plugins/chatgpt-oauth/control.js.map +4 -4
- package/dist/plugins/chatgpt-oauth/index.js.map +1 -1
- package/dist/plugins/codex-router/control.js +2 -2
- package/dist/plugins/codex-router/control.js.map +4 -4
- package/dist/plugins/codex-router/index.js +99 -3
- package/dist/plugins/codex-router/index.js.map +8 -7
- package/dist/plugins/codex-router/manifest.json +6 -0
- package/dist/plugins/deepseek-reasoning-fix/index.js.map +1 -1
- package/dist/plugins/key-access/control.js +2 -2
- package/dist/plugins/key-access/control.js.map +4 -4
- package/dist/plugins/key-access/index.js.map +1 -1
- package/dist/plugins/key-access/ingress.js.map +1 -1
- package/dist/plugins/key-rate-limit/control.js +2 -2
- package/dist/plugins/key-rate-limit/control.js.map +4 -4
- package/dist/plugins/key-rate-limit/index.js +19 -7
- package/dist/plugins/key-rate-limit/index.js.map +4 -4
- package/dist/plugins/key-rate-limit/ingress.js +19 -7
- package/dist/plugins/key-rate-limit/ingress.js.map +3 -3
- package/dist/plugins/llm-protocol-adapter/control.js +113 -20
- package/dist/plugins/llm-protocol-adapter/control.js.map +9 -9
- package/dist/plugins/llm-protocol-adapter/index.js +100 -16
- package/dist/plugins/llm-protocol-adapter/index.js.map +8 -8
- package/dist/plugins/llm-tps/control.js +2 -2
- package/dist/plugins/llm-tps/control.js.map +3 -3
- package/dist/plugins/llm-tps/index.js.map +1 -1
- package/dist/plugins/model-mapping/control.js +2 -2
- package/dist/plugins/model-mapping/control.js.map +3 -3
- package/dist/plugins/model-mapping/index.js.map +1 -1
- package/dist/plugins/models-dev/control.js +13 -7
- package/dist/plugins/models-dev/control.js.map +3 -3
- package/dist/plugins/models-dev/index.js.map +1 -1
- package/dist/plugins/request-logs/index.js.map +1 -1
- package/dist/plugins/signature-repair/index.js.map +1 -1
- package/dist/plugins/token-budget/control.js +58 -47
- package/dist/plugins/token-budget/control.js.map +5 -5
- package/dist/plugins/token-budget/index.js.map +1 -1
- package/dist/plugins/token-metering/index.js.map +1 -1
- package/dist/plugins/token-stats/control.js +2 -2
- package/dist/plugins/token-stats/control.js.map +4 -4
- package/dist/plugins/token-stats/index.js.map +1 -1
- package/dist/plugins/user-auth/control.js +16 -15
- package/dist/plugins/user-auth/control.js.map +4 -4
- package/dist/plugins/user-auth/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -7865,6 +7865,141 @@ function parseProcessLifetimeGuardFacts(value) {
|
|
|
7865
7865
|
}
|
|
7866
7866
|
var inheritedDescriptors = new Map;
|
|
7867
7867
|
|
|
7868
|
+
// src/config-storage/runtime-recovery-budget.ts
|
|
7869
|
+
var BACKOFF_NS = [5000000000n, 30000000000n];
|
|
7870
|
+
var HEALTHY_RESET_NS = 30n * 60n * 1000000000n;
|
|
7871
|
+
var MAX_HEALTH_SAMPLE_GAP_NS = 60n * 1000000000n;
|
|
7872
|
+
function sample(input) {
|
|
7873
|
+
if (!isLowercaseUuid(input.owner) || typeof input.boot_id !== "string" || input.boot_id.length < 1 || input.boot_id.length > 256 || typeof input.monotonic_ns !== "string" || !/^(0|[1-9]\d{0,24})$/.test(input.monotonic_ns)) {
|
|
7874
|
+
throw new ConfigRepositoryError("invalid_operation", "runtime recovery sample is invalid");
|
|
7875
|
+
}
|
|
7876
|
+
return BigInt(input.monotonic_ns);
|
|
7877
|
+
}
|
|
7878
|
+
function readRuntimeRecoveryBudget(db) {
|
|
7879
|
+
const row = sqliteGet(db, "SELECT tickets,ticket_id,ticket_boot_id,retry_at_ns,healthy_owner,healthy_boot_id,healthy_since_ns,healthy_last_ns FROM runtime_recovery_budget WHERE id=1");
|
|
7880
|
+
if (row === null || !Number.isSafeInteger(row.tickets) || row.tickets < 0 || row.tickets > 2 || row.tickets > 0 && (row.ticket_id === null || !isLowercaseUuid(row.ticket_id) || typeof row.ticket_boot_id !== "string" || !row.ticket_boot_id.length || row.retry_at_ns === null) || row.healthy_owner !== null && (!isLowercaseUuid(row.healthy_owner) || typeof row.healthy_boot_id !== "string" || !row.healthy_boot_id.length || row.healthy_since_ns === null || row.healthy_last_ns === null) || [row.retry_at_ns, row.healthy_since_ns, row.healthy_last_ns].some((value) => value !== null && !/^(0|[1-9]\d{0,24})$/.test(value))) {
|
|
7881
|
+
throw new ConfigRepositoryError("schema_corrupt", "runtime recovery budget is corrupt");
|
|
7882
|
+
}
|
|
7883
|
+
return Object.freeze({
|
|
7884
|
+
tickets: row.tickets,
|
|
7885
|
+
last_ticket_id: row.ticket_id,
|
|
7886
|
+
retry_boot_id: row.ticket_boot_id,
|
|
7887
|
+
retry_at_ns: row.retry_at_ns,
|
|
7888
|
+
healthy_owner: row.healthy_owner,
|
|
7889
|
+
healthy_boot_id: row.healthy_boot_id,
|
|
7890
|
+
healthy_since_ns: row.healthy_since_ns,
|
|
7891
|
+
healthy_last_ns: row.healthy_last_ns
|
|
7892
|
+
});
|
|
7893
|
+
}
|
|
7894
|
+
function consumeRuntimeRecoveryRestartTicket(db, ticketId, input) {
|
|
7895
|
+
const now = sample(input);
|
|
7896
|
+
if (!isLowercaseUuid(ticketId))
|
|
7897
|
+
throw new ConfigRepositoryError("invalid_operation", "runtime recovery ticket identity is invalid");
|
|
7898
|
+
const before = readRuntimeRecoveryBudget(db);
|
|
7899
|
+
const prior = sqliteGet(db, "SELECT owner,boot_id FROM runtime_recovery_tickets WHERE ticket_id=?", ticketId);
|
|
7900
|
+
if (prior !== null) {
|
|
7901
|
+
if (prior.owner !== input.owner || prior.boot_id !== input.boot_id) {
|
|
7902
|
+
throw new ConfigRepositoryError("invalid_operation", "runtime recovery ticket belongs to another owner or kernel boot");
|
|
7903
|
+
}
|
|
7904
|
+
return before;
|
|
7905
|
+
}
|
|
7906
|
+
if (before.tickets >= 2)
|
|
7907
|
+
throw new ConfigRepositoryError("attempts_exhausted", "runtime recovery restart budget is exhausted");
|
|
7908
|
+
if (before.retry_at_ns !== null && before.retry_boot_id === input.boot_id && now < BigInt(before.retry_at_ns)) {
|
|
7909
|
+
throw new ConfigRepositoryError("retry_not_due", "runtime recovery restart backoff has not elapsed");
|
|
7910
|
+
}
|
|
7911
|
+
const retry = now + BACKOFF_NS[before.tickets];
|
|
7912
|
+
db.run("INSERT INTO runtime_recovery_tickets(ticket_id,owner,boot_id,consumed_at_ns,retry_at_ns) VALUES(?,?,?,?,?)", [ticketId, input.owner, input.boot_id, now.toString(), retry.toString()]);
|
|
7913
|
+
db.run(`UPDATE runtime_recovery_budget SET tickets=tickets+1,ticket_id=?,ticket_boot_id=?,retry_at_ns=?,
|
|
7914
|
+
healthy_owner=NULL,healthy_boot_id=NULL,healthy_since_ns=NULL,healthy_last_ns=NULL WHERE id=1`, [ticketId, input.boot_id, retry.toString()]);
|
|
7915
|
+
return readRuntimeRecoveryBudget(db);
|
|
7916
|
+
}
|
|
7917
|
+
function readRuntimeRecoveryStartupGate(db, input) {
|
|
7918
|
+
const now = sample(input);
|
|
7919
|
+
const budget = readRuntimeRecoveryBudget(db);
|
|
7920
|
+
if (budget.retry_at_ns === null)
|
|
7921
|
+
return { kind: "ready", budget };
|
|
7922
|
+
if (budget.retry_boot_id !== input.boot_id)
|
|
7923
|
+
return { kind: "stopped", reason: "clock_domain_unknown", budget };
|
|
7924
|
+
const remaining = BigInt(budget.retry_at_ns) - now;
|
|
7925
|
+
if (remaining > 0n)
|
|
7926
|
+
return { kind: "waiting", remaining_ms: Number((remaining + 999999n) / 1000000n), budget };
|
|
7927
|
+
return { kind: "ready", budget };
|
|
7928
|
+
}
|
|
7929
|
+
function observeRuntimeRecoveryHealth(db, input, healthy) {
|
|
7930
|
+
const now = sample(input);
|
|
7931
|
+
const before = readRuntimeRecoveryBudget(db);
|
|
7932
|
+
if (typeof healthy !== "boolean")
|
|
7933
|
+
throw new ConfigRepositoryError("invalid_operation", "runtime health sample is invalid");
|
|
7934
|
+
if (!healthy) {
|
|
7935
|
+
db.run("UPDATE runtime_recovery_budget SET healthy_owner=NULL,healthy_boot_id=NULL,healthy_since_ns=NULL,healthy_last_ns=NULL WHERE id=1");
|
|
7936
|
+
return readRuntimeRecoveryBudget(db);
|
|
7937
|
+
}
|
|
7938
|
+
const continuous = before.healthy_owner === input.owner && before.healthy_boot_id === input.boot_id && before.healthy_since_ns !== null && before.healthy_last_ns !== null && now >= BigInt(before.healthy_last_ns) && now - BigInt(before.healthy_last_ns) <= MAX_HEALTH_SAMPLE_GAP_NS;
|
|
7939
|
+
const since = continuous ? BigInt(before.healthy_since_ns) : now;
|
|
7940
|
+
if (now - since >= HEALTHY_RESET_NS) {
|
|
7941
|
+
db.run(`UPDATE runtime_recovery_budget SET tickets=0,ticket_id=NULL,ticket_boot_id=NULL,retry_at_ns=NULL,
|
|
7942
|
+
healthy_owner=?,healthy_boot_id=?,healthy_since_ns=?,healthy_last_ns=? WHERE id=1`, [input.owner, input.boot_id, since.toString(), now.toString()]);
|
|
7943
|
+
} else {
|
|
7944
|
+
db.run("UPDATE runtime_recovery_budget SET healthy_owner=?,healthy_boot_id=?,healthy_since_ns=?,healthy_last_ns=? WHERE id=1", [input.owner, input.boot_id, since.toString(), now.toString()]);
|
|
7945
|
+
}
|
|
7946
|
+
return readRuntimeRecoveryBudget(db);
|
|
7947
|
+
}
|
|
7948
|
+
|
|
7949
|
+
// src/config-storage/runtime-cutover.ts
|
|
7950
|
+
var CURRENT_RUNTIME_EPOCH = "(SELECT max(runtime_epoch) FROM runtime_cutovers)";
|
|
7951
|
+
function readRuntimeEpoch(db) {
|
|
7952
|
+
const row = sqliteGet(db, `SELECT ${CURRENT_RUNTIME_EPOCH} AS runtime_epoch`);
|
|
7953
|
+
if (row === null || !Number.isSafeInteger(row.runtime_epoch) || row.runtime_epoch < 0) {
|
|
7954
|
+
throw new ConfigRepositoryError("schema_corrupt", "current runtime epoch is invalid");
|
|
7955
|
+
}
|
|
7956
|
+
return row.runtime_epoch;
|
|
7957
|
+
}
|
|
7958
|
+
function isCurrentRuntimeOperation(db, mutationId) {
|
|
7959
|
+
return sqliteGet(db, `SELECT mutation_id FROM configuration_operations
|
|
7960
|
+
WHERE mutation_id=? AND runtime_epoch=${CURRENT_RUNTIME_EPOCH}`, mutationId) !== null;
|
|
7961
|
+
}
|
|
7962
|
+
function verifyRuntimeCutoverCatalog(db, available) {
|
|
7963
|
+
if (available === undefined || readRuntimeEpoch(db) === 0)
|
|
7964
|
+
return;
|
|
7965
|
+
const { selectedProvider } = readManagementProtection(db);
|
|
7966
|
+
if (selectedProvider !== null && !available.has(selectedProvider)) {
|
|
7967
|
+
throw new ConfigRepositoryError("invalid_configuration", "runtime cutover requires the protected management provider");
|
|
7968
|
+
}
|
|
7969
|
+
}
|
|
7970
|
+
function recordRuntimeCutover(db, stoppedContainerId, now) {
|
|
7971
|
+
if (typeof stoppedContainerId !== "string" || !/^[0-9a-f]{64}$/.test(stoppedContainerId) || !Number.isSafeInteger(now) || now < 0) {
|
|
7972
|
+
throw new ConfigRepositoryError("invalid_command", "runtime cutover requires a full stopped Docker container ID and confirmation time");
|
|
7973
|
+
}
|
|
7974
|
+
const prior = sqliteGet(db, `SELECT runtime_epoch,stopped_container_id,saved_revision,confirmed_at
|
|
7975
|
+
FROM runtime_cutovers WHERE stopped_container_id=?`, stoppedContainerId);
|
|
7976
|
+
if (prior !== null)
|
|
7977
|
+
return prior;
|
|
7978
|
+
const cutover = {
|
|
7979
|
+
runtime_epoch: readRuntimeEpoch(db) + 1,
|
|
7980
|
+
stopped_container_id: stoppedContainerId,
|
|
7981
|
+
saved_revision: readActiveRevision(db),
|
|
7982
|
+
confirmed_at: now
|
|
7983
|
+
};
|
|
7984
|
+
db.run(`INSERT INTO runtime_cutovers(runtime_epoch,stopped_container_id,saved_revision,confirmed_at,recovery_budget_json)
|
|
7985
|
+
VALUES (?,?,?,?,?)`, [
|
|
7986
|
+
cutover.runtime_epoch,
|
|
7987
|
+
cutover.stopped_container_id,
|
|
7988
|
+
cutover.saved_revision,
|
|
7989
|
+
cutover.confirmed_at,
|
|
7990
|
+
JSON.stringify(readRuntimeRecoveryBudget(db))
|
|
7991
|
+
]);
|
|
7992
|
+
db.run(`UPDATE runtime_recovery_budget SET tickets=0,ticket_id=NULL,ticket_boot_id=NULL,retry_at_ns=NULL,
|
|
7993
|
+
healthy_owner=NULL,healthy_boot_id=NULL,healthy_since_ns=NULL,healthy_last_ns=NULL WHERE id=1`);
|
|
7994
|
+
return cutover;
|
|
7995
|
+
}
|
|
7996
|
+
function auditRuntimeCutovers(db, activeRevision) {
|
|
7997
|
+
const cutovers = sqliteAll(db, "SELECT runtime_epoch,saved_revision FROM runtime_cutovers ORDER BY runtime_epoch");
|
|
7998
|
+
if (cutovers.length === 0 || cutovers.some((row, index) => row.runtime_epoch !== index || row.saved_revision < (cutovers[index - 1]?.saved_revision ?? 1) || row.saved_revision > activeRevision)) {
|
|
7999
|
+
throw new ConfigRepositoryError("schema_corrupt", "runtime cutover sequence is invalid");
|
|
8000
|
+
}
|
|
8001
|
+
}
|
|
8002
|
+
|
|
7868
8003
|
// src/config-storage/retirement-store.ts
|
|
7869
8004
|
function readPublicationRetirementRetry(db, requestId) {
|
|
7870
8005
|
if (!isLowercaseUuid(requestId))
|
|
@@ -7881,6 +8016,9 @@ function requestPublicationRetirementRetry(db, requestId, mutationId, revision,
|
|
|
7881
8016
|
throw new ConfigRepositoryError("cas_conflict", "retirement retry identity was reused");
|
|
7882
8017
|
return existing;
|
|
7883
8018
|
}
|
|
8019
|
+
if (readActiveRevision(db) !== revision)
|
|
8020
|
+
throw new ConfigRepositoryError("cas_conflict", "retirement retry revision changed");
|
|
8021
|
+
requireCurrentRuntime(db, mutationId);
|
|
7884
8022
|
const operation = sqliteGet(db, "SELECT state,committed_revision FROM configuration_operations WHERE mutation_id=?", mutationId);
|
|
7885
8023
|
const retirement = readPublicationRetirement(db, mutationId);
|
|
7886
8024
|
if (operation?.state !== "draining" || operation.committed_revision !== revision || retirement?.state !== "stopped")
|
|
@@ -7892,6 +8030,10 @@ function requestPublicationRetirementRetry(db, requestId, mutationId, revision,
|
|
|
7892
8030
|
function invalid2(message) {
|
|
7893
8031
|
throw new ConfigRepositoryError("invalid_operation", message);
|
|
7894
8032
|
}
|
|
8033
|
+
function requireCurrentRuntime(db, mutationId) {
|
|
8034
|
+
if (!isCurrentRuntimeOperation(db, mutationId))
|
|
8035
|
+
invalid2("retirement or serving authority does not belong to the current runtime");
|
|
8036
|
+
}
|
|
7895
8037
|
function natural(value, minimum = 0) {
|
|
7896
8038
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
|
|
7897
8039
|
}
|
|
@@ -7959,6 +8101,7 @@ function freezePublicationRetirement(db, mutationId, generation, value, now) {
|
|
|
7959
8101
|
return readPublicationRetirement(db, mutationId);
|
|
7960
8102
|
}
|
|
7961
8103
|
function freezePublicationRetirementDrainStart(db, mutationId, memberId, bootId, deadlineNs, now) {
|
|
8104
|
+
requireCurrentRuntime(db, mutationId);
|
|
7962
8105
|
const before = readPublicationRetirement(db, mutationId);
|
|
7963
8106
|
const member = before?.members.find((item) => item.identity.worker_instance_id === memberId);
|
|
7964
8107
|
if (!before || !member || member.deadline_boot_id !== bootId || !natural(now) || !/^[1-9]\d{0,24}$/.test(deadlineNs))
|
|
@@ -7971,6 +8114,7 @@ function freezePublicationRetirementDrainStart(db, mutationId, memberId, bootId,
|
|
|
7971
8114
|
return readPublicationRetirement(db, mutationId);
|
|
7972
8115
|
}
|
|
7973
8116
|
function recordPublicationRetirementEvidence(db, mutationId, memberId, exit, cleanup, now, deadline) {
|
|
8117
|
+
requireCurrentRuntime(db, mutationId);
|
|
7974
8118
|
if (!["live", "confirmed", "unknown"].includes(exit) || !["success", "failed", "unknown"].includes(cleanup) || !natural(now))
|
|
7975
8119
|
invalid2("retirement evidence is invalid");
|
|
7976
8120
|
const before = readPublicationRetirement(db, mutationId);
|
|
@@ -7997,6 +8141,7 @@ function recordPublicationRetirementEvidence(db, mutationId, memberId, exit, cle
|
|
|
7997
8141
|
return readPublicationRetirement(db, mutationId);
|
|
7998
8142
|
}
|
|
7999
8143
|
function stopPublicationRetirement(db, mutationId, reason, now) {
|
|
8144
|
+
requireCurrentRuntime(db, mutationId);
|
|
8000
8145
|
if (!["exit_unknown", "cleanup_unknown", "release_unknown"].includes(reason) || !natural(now))
|
|
8001
8146
|
invalid2("retirement stop reason is invalid");
|
|
8002
8147
|
const before = readPublicationRetirement(db, mutationId);
|
|
@@ -8008,6 +8153,7 @@ function stopPublicationRetirement(db, mutationId, reason, now) {
|
|
|
8008
8153
|
return readPublicationRetirement(db, mutationId);
|
|
8009
8154
|
}
|
|
8010
8155
|
function retryPublicationRetirement(db, mutationId, now) {
|
|
8156
|
+
requireCurrentRuntime(db, mutationId);
|
|
8011
8157
|
const before = readPublicationRetirement(db, mutationId);
|
|
8012
8158
|
if (!before || !natural(now))
|
|
8013
8159
|
invalid2("retirement retry is invalid");
|
|
@@ -8017,6 +8163,7 @@ function retryPublicationRetirement(db, mutationId, now) {
|
|
|
8017
8163
|
return readPublicationRetirement(db, mutationId);
|
|
8018
8164
|
}
|
|
8019
8165
|
function markPublicationRetirementReleased(db, mutationId, now) {
|
|
8166
|
+
requireCurrentRuntime(db, mutationId);
|
|
8020
8167
|
const before = readPublicationRetirement(db, mutationId);
|
|
8021
8168
|
if (!before || !natural(now))
|
|
8022
8169
|
invalid2("retirement release is invalid");
|
|
@@ -8103,6 +8250,7 @@ function freezePublicationServingSet(db, mutationId, generation, input) {
|
|
|
8103
8250
|
throw new ConfigRepositoryError("cas_conflict", "publication serving members are already frozen");
|
|
8104
8251
|
return before;
|
|
8105
8252
|
}
|
|
8253
|
+
requireCurrentRuntime(db, mutationId);
|
|
8106
8254
|
const operation = sqliteGet(db, "SELECT state,committed_revision,target_worker_count,drain_recovery_generation FROM configuration_operations WHERE mutation_id=?", mutationId);
|
|
8107
8255
|
if (!operation || operation.state === "converged" || operation.state === "degraded" || operation.state === "superseded" || operation.drain_recovery_generation !== generation || workers.length !== operation.target_worker_count || workers.some((worker) => worker.revision !== operation.committed_revision || worker.publication?.mutation_id !== mutationId || worker.publication.drain_recovery_generation !== generation))
|
|
8108
8256
|
invalid2("publication serving authority does not match the current attempt");
|
|
@@ -8120,6 +8268,7 @@ function freezePublicationServingSet(db, mutationId, generation, input) {
|
|
|
8120
8268
|
return readPublicationServingSet(db, mutationId, generation);
|
|
8121
8269
|
}
|
|
8122
8270
|
function confirmPublicationServingMemberExit(db, mutationId, generation, workerInstanceId) {
|
|
8271
|
+
requireCurrentRuntime(db, mutationId);
|
|
8123
8272
|
const before = readPublicationServingSet(db, mutationId, generation);
|
|
8124
8273
|
if (!before || !before.workers.some((worker) => worker.identity.worker_instance_id === workerInstanceId))
|
|
8125
8274
|
invalid2("publication serving member is outside durable authority");
|
|
@@ -8129,87 +8278,6 @@ function confirmPublicationServingMemberExit(db, mutationId, generation, workerI
|
|
|
8129
8278
|
return readPublicationServingSet(db, mutationId, generation);
|
|
8130
8279
|
}
|
|
8131
8280
|
|
|
8132
|
-
// src/config-storage/runtime-recovery-budget.ts
|
|
8133
|
-
var BACKOFF_NS = [5000000000n, 30000000000n];
|
|
8134
|
-
var HEALTHY_RESET_NS = 30n * 60n * 1000000000n;
|
|
8135
|
-
var MAX_HEALTH_SAMPLE_GAP_NS = 60n * 1000000000n;
|
|
8136
|
-
function sample(input) {
|
|
8137
|
-
if (!isLowercaseUuid(input.owner) || typeof input.boot_id !== "string" || input.boot_id.length < 1 || input.boot_id.length > 256 || typeof input.monotonic_ns !== "string" || !/^(0|[1-9]\d{0,24})$/.test(input.monotonic_ns)) {
|
|
8138
|
-
throw new ConfigRepositoryError("invalid_operation", "runtime recovery sample is invalid");
|
|
8139
|
-
}
|
|
8140
|
-
return BigInt(input.monotonic_ns);
|
|
8141
|
-
}
|
|
8142
|
-
function readRuntimeRecoveryBudget(db) {
|
|
8143
|
-
const row = sqliteGet(db, "SELECT tickets,ticket_id,ticket_boot_id,retry_at_ns,healthy_owner,healthy_boot_id,healthy_since_ns,healthy_last_ns FROM runtime_recovery_budget WHERE id=1");
|
|
8144
|
-
if (row === null || !Number.isSafeInteger(row.tickets) || row.tickets < 0 || row.tickets > 2 || row.tickets > 0 && (row.ticket_id === null || !isLowercaseUuid(row.ticket_id) || typeof row.ticket_boot_id !== "string" || !row.ticket_boot_id.length || row.retry_at_ns === null) || row.healthy_owner !== null && (!isLowercaseUuid(row.healthy_owner) || typeof row.healthy_boot_id !== "string" || !row.healthy_boot_id.length || row.healthy_since_ns === null || row.healthy_last_ns === null) || [row.retry_at_ns, row.healthy_since_ns, row.healthy_last_ns].some((value) => value !== null && !/^(0|[1-9]\d{0,24})$/.test(value))) {
|
|
8145
|
-
throw new ConfigRepositoryError("schema_corrupt", "runtime recovery budget is corrupt");
|
|
8146
|
-
}
|
|
8147
|
-
return Object.freeze({
|
|
8148
|
-
tickets: row.tickets,
|
|
8149
|
-
last_ticket_id: row.ticket_id,
|
|
8150
|
-
retry_boot_id: row.ticket_boot_id,
|
|
8151
|
-
retry_at_ns: row.retry_at_ns,
|
|
8152
|
-
healthy_owner: row.healthy_owner,
|
|
8153
|
-
healthy_boot_id: row.healthy_boot_id,
|
|
8154
|
-
healthy_since_ns: row.healthy_since_ns,
|
|
8155
|
-
healthy_last_ns: row.healthy_last_ns
|
|
8156
|
-
});
|
|
8157
|
-
}
|
|
8158
|
-
function consumeRuntimeRecoveryRestartTicket(db, ticketId, input) {
|
|
8159
|
-
const now = sample(input);
|
|
8160
|
-
if (!isLowercaseUuid(ticketId))
|
|
8161
|
-
throw new ConfigRepositoryError("invalid_operation", "runtime recovery ticket identity is invalid");
|
|
8162
|
-
const before = readRuntimeRecoveryBudget(db);
|
|
8163
|
-
const prior = sqliteGet(db, "SELECT owner,boot_id FROM runtime_recovery_tickets WHERE ticket_id=?", ticketId);
|
|
8164
|
-
if (prior !== null) {
|
|
8165
|
-
if (prior.owner !== input.owner || prior.boot_id !== input.boot_id) {
|
|
8166
|
-
throw new ConfigRepositoryError("invalid_operation", "runtime recovery ticket belongs to another owner or kernel boot");
|
|
8167
|
-
}
|
|
8168
|
-
return before;
|
|
8169
|
-
}
|
|
8170
|
-
if (before.tickets >= 2)
|
|
8171
|
-
throw new ConfigRepositoryError("attempts_exhausted", "runtime recovery restart budget is exhausted");
|
|
8172
|
-
if (before.retry_at_ns !== null && before.retry_boot_id === input.boot_id && now < BigInt(before.retry_at_ns)) {
|
|
8173
|
-
throw new ConfigRepositoryError("retry_not_due", "runtime recovery restart backoff has not elapsed");
|
|
8174
|
-
}
|
|
8175
|
-
const retry = now + BACKOFF_NS[before.tickets];
|
|
8176
|
-
db.run("INSERT INTO runtime_recovery_tickets(ticket_id,owner,boot_id,consumed_at_ns,retry_at_ns) VALUES(?,?,?,?,?)", [ticketId, input.owner, input.boot_id, now.toString(), retry.toString()]);
|
|
8177
|
-
db.run(`UPDATE runtime_recovery_budget SET tickets=tickets+1,ticket_id=?,ticket_boot_id=?,retry_at_ns=?,
|
|
8178
|
-
healthy_owner=NULL,healthy_boot_id=NULL,healthy_since_ns=NULL,healthy_last_ns=NULL WHERE id=1`, [ticketId, input.boot_id, retry.toString()]);
|
|
8179
|
-
return readRuntimeRecoveryBudget(db);
|
|
8180
|
-
}
|
|
8181
|
-
function readRuntimeRecoveryStartupGate(db, input) {
|
|
8182
|
-
const now = sample(input);
|
|
8183
|
-
const budget = readRuntimeRecoveryBudget(db);
|
|
8184
|
-
if (budget.retry_at_ns === null)
|
|
8185
|
-
return { kind: "ready", budget };
|
|
8186
|
-
if (budget.retry_boot_id !== input.boot_id)
|
|
8187
|
-
return { kind: "stopped", reason: "clock_domain_unknown", budget };
|
|
8188
|
-
const remaining = BigInt(budget.retry_at_ns) - now;
|
|
8189
|
-
if (remaining > 0n)
|
|
8190
|
-
return { kind: "waiting", remaining_ms: Number((remaining + 999999n) / 1000000n), budget };
|
|
8191
|
-
return { kind: "ready", budget };
|
|
8192
|
-
}
|
|
8193
|
-
function observeRuntimeRecoveryHealth(db, input, healthy) {
|
|
8194
|
-
const now = sample(input);
|
|
8195
|
-
const before = readRuntimeRecoveryBudget(db);
|
|
8196
|
-
if (typeof healthy !== "boolean")
|
|
8197
|
-
throw new ConfigRepositoryError("invalid_operation", "runtime health sample is invalid");
|
|
8198
|
-
if (!healthy) {
|
|
8199
|
-
db.run("UPDATE runtime_recovery_budget SET healthy_owner=NULL,healthy_boot_id=NULL,healthy_since_ns=NULL,healthy_last_ns=NULL WHERE id=1");
|
|
8200
|
-
return readRuntimeRecoveryBudget(db);
|
|
8201
|
-
}
|
|
8202
|
-
const continuous = before.healthy_owner === input.owner && before.healthy_boot_id === input.boot_id && before.healthy_since_ns !== null && before.healthy_last_ns !== null && now >= BigInt(before.healthy_last_ns) && now - BigInt(before.healthy_last_ns) <= MAX_HEALTH_SAMPLE_GAP_NS;
|
|
8203
|
-
const since = continuous ? BigInt(before.healthy_since_ns) : now;
|
|
8204
|
-
if (now - since >= HEALTHY_RESET_NS) {
|
|
8205
|
-
db.run(`UPDATE runtime_recovery_budget SET tickets=0,ticket_id=NULL,ticket_boot_id=NULL,retry_at_ns=NULL,
|
|
8206
|
-
healthy_owner=?,healthy_boot_id=?,healthy_since_ns=?,healthy_last_ns=? WHERE id=1`, [input.owner, input.boot_id, since.toString(), now.toString()]);
|
|
8207
|
-
} else {
|
|
8208
|
-
db.run("UPDATE runtime_recovery_budget SET healthy_owner=?,healthy_boot_id=?,healthy_since_ns=?,healthy_last_ns=? WHERE id=1", [input.owner, input.boot_id, since.toString(), now.toString()]);
|
|
8209
|
-
}
|
|
8210
|
-
return readRuntimeRecoveryBudget(db);
|
|
8211
|
-
}
|
|
8212
|
-
|
|
8213
8281
|
// src/config-storage/config-repository.ts
|
|
8214
8282
|
import { Database as Database3 } from "bun:sqlite";
|
|
8215
8283
|
import { mkdirSync } from "fs";
|
|
@@ -8411,7 +8479,7 @@ function readAllWorkers(db) {
|
|
|
8411
8479
|
|
|
8412
8480
|
// src/config-storage/worker-launch-store.ts
|
|
8413
8481
|
var INTENT_SELECT = `SELECT worker_instance_id,master_generation,worker_slot,
|
|
8414
|
-
allocation_mutation_id,allocation_worker_slot,allocation_attempt_no,guard_json,registered_at,
|
|
8482
|
+
allocation_mutation_id,allocation_worker_slot,allocation_attempt_no,guard_json,registered_at,runtime_epoch,
|
|
8415
8483
|
EXISTS (SELECT 1 FROM configuration_worker_launch_capacity_reclaims reclaim
|
|
8416
8484
|
WHERE reclaim.worker_instance_id=configuration_worker_launch_intents.worker_instance_id) AS capacity_reclaimed
|
|
8417
8485
|
FROM configuration_worker_launch_intents`;
|
|
@@ -8537,7 +8605,8 @@ function requireIntentRow(db, workerInstanceId) {
|
|
|
8537
8605
|
if (typeof workerInstanceId !== "string" || !isLowercaseUuid(workerInstanceId)) {
|
|
8538
8606
|
invalid3("worker launch instance identity is invalid");
|
|
8539
8607
|
}
|
|
8540
|
-
const row = sqliteGet(db, `${INTENT_SELECT} WHERE worker_instance_id
|
|
8608
|
+
const row = sqliteGet(db, `${INTENT_SELECT} WHERE worker_instance_id=?
|
|
8609
|
+
AND runtime_epoch=${CURRENT_RUNTIME_EPOCH}`, workerInstanceId);
|
|
8541
8610
|
if (row === null)
|
|
8542
8611
|
invalidOperation("worker launch intent was not registered");
|
|
8543
8612
|
return row;
|
|
@@ -8577,7 +8646,7 @@ function requireOpenAllocation(db, allocation, allowCancelled) {
|
|
|
8577
8646
|
const authority = sqliteGet(db, `SELECT o.state,o.cancel_requested,w.attempt_no
|
|
8578
8647
|
FROM configuration_operations o
|
|
8579
8648
|
JOIN configuration_operation_workers w ON w.mutation_id=o.mutation_id
|
|
8580
|
-
WHERE o.mutation_id=? AND w.worker_slot
|
|
8649
|
+
WHERE o.mutation_id=? AND w.worker_slot=? AND o.runtime_epoch=${CURRENT_RUNTIME_EPOCH}`, allocation.mutation_id, allocation.worker_slot);
|
|
8581
8650
|
if (authority === null || authority.state !== "committed" && authority.state !== "publishing" && authority.state !== "draining" || authority.attempt_no !== allocation.attempt_no || !allowCancelled && authority.cancel_requested === 1) {
|
|
8582
8651
|
invalidOperation("worker launch allocation is not the current open attempt");
|
|
8583
8652
|
}
|
|
@@ -8601,6 +8670,19 @@ function writeWorkerLaunchReservation(db, mutationId, workerSlot, attemptNo, upd
|
|
|
8601
8670
|
}
|
|
8602
8671
|
insertAllocationFact(db, "reserved", { mutation_id: mutationId, worker_slot: workerSlot, attempt_no: attemptNo }, updatedAt);
|
|
8603
8672
|
}
|
|
8673
|
+
function bindPreparedWorkerLaunch(db, identity, guard, allocation) {
|
|
8674
|
+
validateIdentity(identity);
|
|
8675
|
+
validateAllocation(allocation, identity);
|
|
8676
|
+
requireOpenAllocation(db, allocation, false);
|
|
8677
|
+
requireReservation(db, allocation);
|
|
8678
|
+
const row = requireIntentRow(db, identity.worker_instance_id);
|
|
8679
|
+
const launch = launchFromRow(db, row);
|
|
8680
|
+
if (launch.allocation !== null || launch.admitted || launch.not_started || launch.exited || row.master_generation !== identity.master_generation || row.worker_slot !== identity.worker_slot || guard === null || canonicalJson(launch.guard) !== canonicalJson(guard)) {
|
|
8681
|
+
invalidOperation("prepared worker launch does not match its live pre-fork intent");
|
|
8682
|
+
}
|
|
8683
|
+
db.run(`UPDATE configuration_worker_launch_intents
|
|
8684
|
+
SET allocation_mutation_id=?,allocation_worker_slot=?,allocation_attempt_no=? WHERE worker_instance_id=?`, [allocation.mutation_id, allocation.worker_slot, allocation.attempt_no, identity.worker_instance_id]);
|
|
8685
|
+
}
|
|
8604
8686
|
function fenceWorkerLaunchNotStarted(db, mutationId, workerSlot, attemptNo, updatedAt) {
|
|
8605
8687
|
const allocation = { mutation_id: mutationId, worker_slot: workerSlot, attempt_no: attemptNo };
|
|
8606
8688
|
if (typeof mutationId !== "string" || !validateMutationId(mutationId) || !natural2(workerSlot) || !natural2(attemptNo, 1)) {
|
|
@@ -8643,6 +8725,8 @@ function registerWorkerLaunch(db, identity, guard, allocation, updatedAt) {
|
|
|
8643
8725
|
}
|
|
8644
8726
|
const byInstance = sqliteGet(db, `${INTENT_SELECT} WHERE worker_instance_id=?`, identity.worker_instance_id);
|
|
8645
8727
|
if (byInstance !== null) {
|
|
8728
|
+
if (byInstance.runtime_epoch !== readRuntimeEpoch(db))
|
|
8729
|
+
invalidOperation("worker instance belongs to an archived runtime");
|
|
8646
8730
|
const existing = launchFromRow(db, byInstance);
|
|
8647
8731
|
if (sameAllocation(existing.allocation, allocation) && existing.identity.master_generation === identity.master_generation && existing.identity.worker_slot === identity.worker_slot && canonicalJson(existing.guard) === guardJson) {
|
|
8648
8732
|
return existing;
|
|
@@ -8651,7 +8735,7 @@ function registerWorkerLaunch(db, identity, guard, allocation, updatedAt) {
|
|
|
8651
8735
|
}
|
|
8652
8736
|
db.run(`INSERT INTO configuration_worker_launch_intents
|
|
8653
8737
|
(worker_instance_id,master_generation,worker_slot,allocation_mutation_id,allocation_worker_slot,
|
|
8654
|
-
allocation_attempt_no,guard_json,registered_at) VALUES (
|
|
8738
|
+
allocation_attempt_no,guard_json,registered_at,runtime_epoch) VALUES (?,?,?,?,?,?,?,?,${CURRENT_RUNTIME_EPOCH})`, [
|
|
8655
8739
|
identity.worker_instance_id,
|
|
8656
8740
|
identity.master_generation,
|
|
8657
8741
|
identity.worker_slot,
|
|
@@ -8819,8 +8903,9 @@ function assertPublicationLaunchDebtSettled(db, mutationId) {
|
|
|
8819
8903
|
function readWorkerLaunchInventory(db) {
|
|
8820
8904
|
const result = [];
|
|
8821
8905
|
const handled = new Set;
|
|
8822
|
-
const reservations = sqliteAll(db, `SELECT mutation_id,worker_slot,attempt_no,recorded_at FROM configuration_worker_launch_facts
|
|
8823
|
-
|
|
8906
|
+
const reservations = sqliteAll(db, `SELECT mutation_id,worker_slot,attempt_no,recorded_at FROM configuration_worker_launch_facts f
|
|
8907
|
+
JOIN configuration_operations o USING(mutation_id)
|
|
8908
|
+
WHERE f.kind='reserved' AND o.runtime_epoch=${CURRENT_RUNTIME_EPOCH} ORDER BY mutation_id,worker_slot,attempt_no`);
|
|
8824
8909
|
for (const reservation of reservations) {
|
|
8825
8910
|
const allocation = {
|
|
8826
8911
|
mutation_id: reservation.mutation_id,
|
|
@@ -8840,7 +8925,8 @@ function readWorkerLaunchInventory(db) {
|
|
|
8840
8925
|
continue;
|
|
8841
8926
|
result.push({ kind: "reservation", allocation });
|
|
8842
8927
|
}
|
|
8843
|
-
const intents = sqliteAll(db, `${INTENT_SELECT}
|
|
8928
|
+
const intents = sqliteAll(db, `${INTENT_SELECT} WHERE runtime_epoch=${CURRENT_RUNTIME_EPOCH}
|
|
8929
|
+
ORDER BY registered_at,worker_instance_id`);
|
|
8844
8930
|
for (const row of intents) {
|
|
8845
8931
|
const allocation = rowAllocation(row);
|
|
8846
8932
|
if (allocation !== null && handled.has(allocationKey(allocation)))
|
|
@@ -9336,6 +9422,13 @@ function readRecovery(db, recoveryId) {
|
|
|
9336
9422
|
const row = sqliteGet(db, `${RECOVERY_SELECT} WHERE recovery_id=?`, recoveryId);
|
|
9337
9423
|
return row === null ? null : recoveryFromRow(row);
|
|
9338
9424
|
}
|
|
9425
|
+
function requireCurrentRecovery(db, recoveryId) {
|
|
9426
|
+
const row = sqliteGet(db, `${RECOVERY_SELECT} WHERE recovery_id=?
|
|
9427
|
+
AND runtime_epoch=${CURRENT_RUNTIME_EPOCH}`, recoveryId);
|
|
9428
|
+
if (row === null)
|
|
9429
|
+
invalid5("recovery does not belong to the current runtime");
|
|
9430
|
+
return recoveryFromRow(row);
|
|
9431
|
+
}
|
|
9339
9432
|
function readRecoveryRows(db, sql, ...params) {
|
|
9340
9433
|
return sqliteAll(db, sql, ...params).map(recoveryFromRow);
|
|
9341
9434
|
}
|
|
@@ -9346,6 +9439,7 @@ function readPublicationRecoveryBarrier(db, excludeRecoveryId = null) {
|
|
|
9346
9439
|
return readRecoveryRows(db, `${RECOVERY_SELECT}
|
|
9347
9440
|
WHERE (state IN ('scheduled','running')
|
|
9348
9441
|
OR (state='stopped' AND final_reason_code='safety_outcome_unknown'))${exclusion}
|
|
9442
|
+
AND runtime_epoch=${CURRENT_RUNTIME_EPOCH}
|
|
9349
9443
|
ORDER BY CASE WHEN state IN ('scheduled','running') THEN 0 ELSE 1 END,
|
|
9350
9444
|
recovery_sequence DESC LIMIT 1`, ...excludeRecoveryId === null ? [] : [excludeRecoveryId])[0] ?? null;
|
|
9351
9445
|
}
|
|
@@ -9355,6 +9449,7 @@ function readLatestRecovery(db, targetRevision) {
|
|
|
9355
9449
|
}
|
|
9356
9450
|
function readCurrentRecovery(db) {
|
|
9357
9451
|
return readRecoveryRows(db, `${RECOVERY_SELECT}
|
|
9452
|
+
WHERE runtime_epoch=${CURRENT_RUNTIME_EPOCH}
|
|
9358
9453
|
ORDER BY CASE WHEN state IN ('scheduled','running') THEN 0 ELSE 1 END,
|
|
9359
9454
|
recovery_sequence DESC LIMIT 1`)[0] ?? null;
|
|
9360
9455
|
}
|
|
@@ -9413,7 +9508,7 @@ function requireSource(db, sourceMutationId) {
|
|
|
9413
9508
|
}
|
|
9414
9509
|
function requireNoActivePublication(db) {
|
|
9415
9510
|
const active = sqliteGet(db, `SELECT mutation_id FROM configuration_operations
|
|
9416
|
-
WHERE state IN ('committed','publishing','draining') LIMIT 1`);
|
|
9511
|
+
WHERE state IN ('committed','publishing','draining') AND runtime_epoch=${CURRENT_RUNTIME_EPOCH} LIMIT 1`);
|
|
9417
9512
|
if (active !== null)
|
|
9418
9513
|
invalid5("an active publication already exists");
|
|
9419
9514
|
}
|
|
@@ -9428,6 +9523,7 @@ function insertRecovery(db, recoveryId, sourceMutationId, targetRevision, trigge
|
|
|
9428
9523
|
return existing;
|
|
9429
9524
|
}
|
|
9430
9525
|
const active = readRecoveryRows(db, `${RECOVERY_SELECT} WHERE target_revision=? AND state IN ('scheduled','running')
|
|
9526
|
+
AND runtime_epoch=${CURRENT_RUNTIME_EPOCH}
|
|
9431
9527
|
ORDER BY recovery_sequence DESC LIMIT 1`, targetRevision)[0];
|
|
9432
9528
|
if (active !== undefined) {
|
|
9433
9529
|
throw new ConfigRepositoryError("recovery_in_progress", "target revision already has an active recovery", undefined, active);
|
|
@@ -9447,8 +9543,8 @@ function insertRecovery(db, recoveryId, sourceMutationId, targetRevision, trigge
|
|
|
9447
9543
|
requireDetail(initial.final_reason_detail);
|
|
9448
9544
|
db.run(`INSERT INTO configuration_recoveries
|
|
9449
9545
|
(recovery_id,source_mutation_id,target_revision,trigger,state,attempt_count,max_attempts,
|
|
9450
|
-
next_retry_at,final_reason_code,final_reason_detail,created_at,updated_at)
|
|
9451
|
-
VALUES (?,?,?, ?,?,0,6
|
|
9546
|
+
next_retry_at,final_reason_code,final_reason_detail,created_at,updated_at,runtime_epoch)
|
|
9547
|
+
VALUES (?,?,?, ?,?,0,6,?,?,?,?,?,${CURRENT_RUNTIME_EPOCH})`, [
|
|
9452
9548
|
recoveryId,
|
|
9453
9549
|
sourceMutationId,
|
|
9454
9550
|
targetRevision,
|
|
@@ -9495,9 +9591,7 @@ function createManualRecovery(db, recoveryId, sourceMutationId, expectedRevision
|
|
|
9495
9591
|
return insertRecovery(db, recoveryId, sourceMutationId, expectedRevision, "manual", now);
|
|
9496
9592
|
}
|
|
9497
9593
|
function claimRecoveryAttempt(db, recoveryId, previousAttemptCount, now) {
|
|
9498
|
-
const recovery =
|
|
9499
|
-
if (recovery === null)
|
|
9500
|
-
invalid5("recovery was not found");
|
|
9594
|
+
const recovery = requireCurrentRecovery(db, recoveryId);
|
|
9501
9595
|
requireNoActivePublication(db);
|
|
9502
9596
|
const barrier = readPublicationRecoveryBarrier(db, recoveryId);
|
|
9503
9597
|
if (barrier !== null) {
|
|
@@ -9528,9 +9622,7 @@ function claimRecoveryAttempt(db, recoveryId, previousAttemptCount, now) {
|
|
|
9528
9622
|
return claimed;
|
|
9529
9623
|
}
|
|
9530
9624
|
function scheduleRecoveryRetry(db, recoveryId, attemptCount, nextRetryAt, now) {
|
|
9531
|
-
const recovery =
|
|
9532
|
-
if (recovery === null)
|
|
9533
|
-
invalid5("recovery was not found");
|
|
9625
|
+
const recovery = requireCurrentRecovery(db, recoveryId);
|
|
9534
9626
|
requireAttempt(attemptCount);
|
|
9535
9627
|
requireNow(nextRetryAt);
|
|
9536
9628
|
if (recovery.state === "scheduled" && recovery.attempt_count === attemptCount && recovery.next_retry_at === nextRetryAt)
|
|
@@ -9553,9 +9645,7 @@ function scheduleRecoveryRetry(db, recoveryId, attemptCount, nextRetryAt, now) {
|
|
|
9553
9645
|
return scheduled;
|
|
9554
9646
|
}
|
|
9555
9647
|
function terminalTransition(db, recoveryId, attemptCount, state, finalReasonCode, finalReasonDetail, now) {
|
|
9556
|
-
const recovery =
|
|
9557
|
-
if (recovery === null)
|
|
9558
|
-
invalid5("recovery was not found");
|
|
9648
|
+
const recovery = requireCurrentRecovery(db, recoveryId);
|
|
9559
9649
|
requireAttempt(attemptCount);
|
|
9560
9650
|
validateTerminalMatrix(state, attemptCount, finalReasonCode, invalid5);
|
|
9561
9651
|
requireDetail(finalReasonDetail);
|
|
@@ -9584,9 +9674,7 @@ function stopRecovery(db, recoveryId, attemptCount, finalReasonCode, finalReason
|
|
|
9584
9674
|
return terminalTransition(db, recoveryId, attemptCount, "stopped", finalReasonCode, finalReasonDetail, now);
|
|
9585
9675
|
}
|
|
9586
9676
|
function requeueRecovery(db, recoveryId, attemptCount, now) {
|
|
9587
|
-
const recovery =
|
|
9588
|
-
if (recovery === null)
|
|
9589
|
-
invalid5("recovery was not found");
|
|
9677
|
+
const recovery = requireCurrentRecovery(db, recoveryId);
|
|
9590
9678
|
requireAttempt(attemptCount);
|
|
9591
9679
|
requireNow(now);
|
|
9592
9680
|
if (attemptCount >= recovery.max_attempts) {
|
|
@@ -9608,7 +9696,7 @@ function requeueRecovery(db, recoveryId, attemptCount, now) {
|
|
|
9608
9696
|
}
|
|
9609
9697
|
function verifyRecoveryIntegrity(db, _allowActiveRecoveryDrift = false) {
|
|
9610
9698
|
const rows = readRecoveryRows(db, `${RECOVERY_SELECT} ORDER BY recovery_sequence`);
|
|
9611
|
-
const sequences = sqliteAll(db, "SELECT recovery_sequence,created_at FROM configuration_recoveries ORDER BY recovery_sequence");
|
|
9699
|
+
const sequences = sqliteAll(db, "SELECT recovery_sequence,created_at,runtime_epoch FROM configuration_recoveries ORDER BY recovery_sequence");
|
|
9612
9700
|
if (sequences.length !== rows.length || sequences.some((row, index) => row.recovery_sequence !== index + 1) || sequences.some((row, index) => index > 0 && row.created_at < sequences[index - 1].created_at)) {
|
|
9613
9701
|
corrupt3("configuration recovery sequences are not contiguous");
|
|
9614
9702
|
}
|
|
@@ -9621,7 +9709,7 @@ function verifyRecoveryIntegrity(db, _allowActiveRecoveryDrift = false) {
|
|
|
9621
9709
|
const currentRevision = sqliteGet(db, "SELECT active_revision FROM configuration_state WHERE id=1")?.active_revision;
|
|
9622
9710
|
if (currentRevision === undefined)
|
|
9623
9711
|
corrupt3("configuration state is missing for recovery audit");
|
|
9624
|
-
for (const recovery of rows) {
|
|
9712
|
+
for (const [index, recovery] of rows.entries()) {
|
|
9625
9713
|
const source = sqliteGet(db, "SELECT state,error_code,committed_revision FROM configuration_operations WHERE mutation_id=?", recovery.source_mutation_id);
|
|
9626
9714
|
if (source === null || source.state !== "degraded" || source.committed_revision !== recovery.target_revision || source.error_code !== "replacement_convergence_failed" && source.error_code !== "control_readiness_failed") {
|
|
9627
9715
|
corrupt3("configuration recovery source metadata is incoherent");
|
|
@@ -9638,7 +9726,8 @@ function verifyRecoveryIntegrity(db, _allowActiveRecoveryDrift = false) {
|
|
|
9638
9726
|
const target = sqliteGet(db, "SELECT revision FROM configuration_revisions WHERE revision=?", recovery.target_revision);
|
|
9639
9727
|
if (target === null)
|
|
9640
9728
|
corrupt3("configuration recovery target revision is missing");
|
|
9641
|
-
|
|
9729
|
+
const epochTarget = `${sequences[index].runtime_epoch}:${recovery.target_revision}`;
|
|
9730
|
+
if ((recovery.state === "scheduled" || recovery.state === "running") && activeByTarget.has(epochTarget)) {
|
|
9642
9731
|
corrupt3("multiple active recoveries target one revision");
|
|
9643
9732
|
}
|
|
9644
9733
|
if (recovery.final_reason_code === "revision_superseded" && recovery.target_revision >= currentRevision) {
|
|
@@ -9648,7 +9737,7 @@ function verifyRecoveryIntegrity(db, _allowActiveRecoveryDrift = false) {
|
|
|
9648
9737
|
corrupt3("recovery target revision is newer than the active revision");
|
|
9649
9738
|
}
|
|
9650
9739
|
if (recovery.state === "scheduled" || recovery.state === "running")
|
|
9651
|
-
activeByTarget.add(
|
|
9740
|
+
activeByTarget.add(epochTarget);
|
|
9652
9741
|
}
|
|
9653
9742
|
}
|
|
9654
9743
|
|
|
@@ -9715,7 +9804,8 @@ var OWNER_STATES = `('committed','publishing','draining')`;
|
|
|
9715
9804
|
var SUPERSEDED_DETAIL = "revision was superseded before publication was claimed";
|
|
9716
9805
|
var CANCELLED_DETAIL = "publication candidate was cancelled before admission preparation";
|
|
9717
9806
|
function readPublicationOwner(db) {
|
|
9718
|
-
const rows = sqliteAll(db, `${OPERATION_SELECT} WHERE state IN ${OWNER_STATES}
|
|
9807
|
+
const rows = sqliteAll(db, `${OPERATION_SELECT} WHERE state IN ${OWNER_STATES}
|
|
9808
|
+
AND runtime_epoch=${CURRENT_RUNTIME_EPOCH}`);
|
|
9719
9809
|
if (rows.length > 1)
|
|
9720
9810
|
throw new ConfigRepositoryError("schema_corrupt", "multiple publication owners exist");
|
|
9721
9811
|
const row = rows[0];
|
|
@@ -9768,7 +9858,7 @@ function requireLatestAggregate(db, snapshot, revision) {
|
|
|
9768
9858
|
}
|
|
9769
9859
|
return snapshot.aggregate;
|
|
9770
9860
|
}
|
|
9771
|
-
function claimPublicationTarget(db, snapshot, pluginCatalogHash, updatedAt) {
|
|
9861
|
+
function claimPublicationTarget(db, snapshot, pluginCatalogHash, updatedAt, preparedInstances) {
|
|
9772
9862
|
if (!validateDigest(pluginCatalogHash)) {
|
|
9773
9863
|
throw new ConfigRepositoryError("invalid_command", "publication catalog identity is invalid");
|
|
9774
9864
|
}
|
|
@@ -9789,27 +9879,25 @@ function claimPublicationTarget(db, snapshot, pluginCatalogHash, updatedAt) {
|
|
|
9789
9879
|
if (recovery !== null) {
|
|
9790
9880
|
throw new ConfigRepositoryError("recovery_in_progress", "configuration application is blocked by an unresolved recovery", undefined, recovery);
|
|
9791
9881
|
}
|
|
9792
|
-
const retirement = sqliteGet(db,
|
|
9882
|
+
const retirement = sqliteGet(db, `SELECT r.mutation_id FROM configuration_retirements r JOIN configuration_operations o USING(mutation_id)
|
|
9883
|
+
WHERE r.state<>'released' AND o.runtime_epoch=${CURRENT_RUNTIME_EPOCH} LIMIT 1`);
|
|
9793
9884
|
if (retirement !== null) {
|
|
9794
9885
|
throw new ConfigRepositoryError("invalid_operation", "configuration application is blocked by unresolved worker retirement");
|
|
9795
9886
|
}
|
|
9796
|
-
if (readUnsettledWorkerLaunches(db).
|
|
9887
|
+
if (readUnsettledWorkerLaunches(db).some((entry) => entry.kind !== "launch" || entry.launch.allocation !== null || !preparedInstances?.has(entry.launch.identity.worker_instance_id))) {
|
|
9797
9888
|
throw new ConfigRepositoryError("invalid_operation", "configuration application is blocked by an unsettled worker launch");
|
|
9798
9889
|
}
|
|
9799
|
-
const
|
|
9890
|
+
const activeRevision = readActiveRevision(db);
|
|
9891
|
+
db.run(`UPDATE configuration_operations
|
|
9892
|
+
SET state='superseded',result_status=409,error_code='revision_superseded',error_detail=?,
|
|
9893
|
+
updated_at=max(?,updated_at)
|
|
9894
|
+
WHERE state='pending' AND committed_revision<?`, [SUPERSEDED_DETAIL, updatedAt, activeRevision]);
|
|
9895
|
+
const candidateRow = sqliteGet(db, `${OPERATION_SELECT} WHERE state='pending' AND committed_revision=?`, activeRevision);
|
|
9800
9896
|
if (candidateRow === null)
|
|
9801
9897
|
return null;
|
|
9802
9898
|
const candidate = operationFromRow(candidateRow);
|
|
9803
9899
|
if (candidate.state !== "pending")
|
|
9804
9900
|
throw new ConfigRepositoryError("schema_corrupt", "pending target state is invalid");
|
|
9805
|
-
const activeRevision = readActiveRevision(db);
|
|
9806
|
-
if (candidate.committed_revision !== activeRevision) {
|
|
9807
|
-
throw new ConfigRepositoryError("schema_corrupt", "pending target is not the latest revision");
|
|
9808
|
-
}
|
|
9809
|
-
const supersededAt = Math.max(updatedAt, candidate.created_at);
|
|
9810
|
-
db.run(`UPDATE configuration_operations
|
|
9811
|
-
SET state='superseded',result_status=409,error_code='revision_superseded',error_detail=?,updated_at=?
|
|
9812
|
-
WHERE state='pending' AND committed_revision<>?`, [SUPERSEDED_DETAIL, supersededAt, candidate.committed_revision]);
|
|
9813
9901
|
const aggregate = requireLatestAggregate(db, snapshot, candidate.committed_revision);
|
|
9814
9902
|
const revision = sqliteGet(db, "SELECT content_hash FROM configuration_revisions WHERE revision=?", candidate.committed_revision);
|
|
9815
9903
|
if (revision === null || hashConfigurationContent(aggregate) !== revision.content_hash) {
|
|
@@ -9821,8 +9909,8 @@ function claimPublicationTarget(db, snapshot, pluginCatalogHash, updatedAt) {
|
|
|
9821
9909
|
aggregate
|
|
9822
9910
|
}, pluginCatalogHash);
|
|
9823
9911
|
const claimed = db.run(`UPDATE configuration_operations
|
|
9824
|
-
SET state='committed',plugin_catalog_hash=?,updated_at
|
|
9825
|
-
WHERE mutation_id=? AND state='pending'`, [pluginCatalogHash,
|
|
9912
|
+
SET state='committed',plugin_catalog_hash=?,updated_at=?,runtime_epoch=${CURRENT_RUNTIME_EPOCH}
|
|
9913
|
+
WHERE mutation_id=? AND state='pending'`, [pluginCatalogHash, Math.max(updatedAt, candidate.updated_at), candidate.mutation_id]);
|
|
9826
9914
|
if (claimed.changes !== 1)
|
|
9827
9915
|
throw new ConfigRepositoryError("repository_failure", "publication claim lost its target");
|
|
9828
9916
|
const ownerAfter = readPublicationOwner(db);
|
|
@@ -10145,8 +10233,8 @@ function commitTransaction(db, prepared, options, snapshot, offlineManagement =
|
|
|
10145
10233
|
db.run(`INSERT INTO configuration_operations
|
|
10146
10234
|
(mutation_id,request_hash,expected_revision,committed_revision,kind,state,result_status,error_code,error_detail,
|
|
10147
10235
|
drain_recovery_generation,last_drain_recovery_previous_generation,plugin_catalog_hash,cancel_requested,
|
|
10148
|
-
prepare_started,target_worker_count,created_at,updated_at)
|
|
10149
|
-
VALUES (?,?,?,?,?,'pending',NULL,NULL,NULL,0,NULL,NULL,0,0
|
|
10236
|
+
prepare_started,target_worker_count,created_at,updated_at,runtime_epoch)
|
|
10237
|
+
VALUES (?,?,?,?,?,'pending',NULL,NULL,NULL,0,NULL,NULL,0,0,?,?,?,${CURRENT_RUNTIME_EPOCH})`, [
|
|
10150
10238
|
prepared.mutationId,
|
|
10151
10239
|
prepared.requestHash,
|
|
10152
10240
|
prepared.expectedRevision,
|
|
@@ -10399,6 +10487,7 @@ function auditConfigurationTables(db) {
|
|
|
10399
10487
|
requireSafeInteger(state.active_revision, "configuration_state.active_revision", 1);
|
|
10400
10488
|
requireSafeInteger(state.created_at, "configuration_state.created_at");
|
|
10401
10489
|
requireSafeInteger(state.updated_at, "configuration_state.updated_at", state.created_at);
|
|
10490
|
+
auditRuntimeCutovers(db, state.active_revision);
|
|
10402
10491
|
const revisions = sqliteAll(db, `SELECT revision,content_hash,kind,created_at
|
|
10403
10492
|
FROM configuration_revisions ORDER BY revision`);
|
|
10404
10493
|
if (revisions.length !== state.active_revision) {
|
|
@@ -10435,15 +10524,13 @@ function auditConfigurationTables(db) {
|
|
|
10435
10524
|
}
|
|
10436
10525
|
workersByMutation.set(worker.mutation_id, [...workersByMutation.get(worker.mutation_id) ?? [], worker]);
|
|
10437
10526
|
}
|
|
10438
|
-
|
|
10527
|
+
if (sqliteGet(db, `SELECT runtime_epoch FROM configuration_operations
|
|
10528
|
+
WHERE state IN ('committed','publishing','draining') GROUP BY runtime_epoch HAVING count(*)>1`) !== null) {
|
|
10529
|
+
throw new ConfigRepositoryError("schema_corrupt", "multiple publication owners exist for one runtime epoch");
|
|
10530
|
+
}
|
|
10439
10531
|
for (const operation of operations) {
|
|
10440
10532
|
const workers = workersByMutation.get(operation.mutation_id) ?? [];
|
|
10441
10533
|
validateOperationRelations(operation, workers);
|
|
10442
|
-
if (operation.state === "committed" || operation.state === "publishing" || operation.state === "draining") {
|
|
10443
|
-
if (owner !== undefined)
|
|
10444
|
-
throw new ConfigRepositoryError("schema_corrupt", "multiple publication owners exist");
|
|
10445
|
-
owner = operation;
|
|
10446
|
-
}
|
|
10447
10534
|
if (operation.state === "superseded" && operation.committed_revision === state.active_revision) {
|
|
10448
10535
|
throw new ConfigRepositoryError("schema_corrupt", "the latest revision cannot be superseded");
|
|
10449
10536
|
}
|
|
@@ -11207,8 +11294,62 @@ var WORKER_LAUNCH_CAPACITY_MIGRATION = {
|
|
|
11207
11294
|
}
|
|
11208
11295
|
};
|
|
11209
11296
|
|
|
11297
|
+
// src/config-storage/migrations/runtime-cutover.ts
|
|
11298
|
+
var RUNTIME_CUTOVER_MIGRATION = {
|
|
11299
|
+
version: 11,
|
|
11300
|
+
name: "stopped_instance_runtime_cutovers",
|
|
11301
|
+
up(db) {
|
|
11302
|
+
db.run(`CREATE TABLE runtime_cutovers (
|
|
11303
|
+
runtime_epoch INTEGER PRIMARY KEY CHECK(runtime_epoch BETWEEN 0 AND 9007199254740991),
|
|
11304
|
+
stopped_container_id TEXT UNIQUE,
|
|
11305
|
+
saved_revision INTEGER NOT NULL REFERENCES configuration_revisions(revision),
|
|
11306
|
+
confirmed_at INTEGER NOT NULL CHECK(confirmed_at BETWEEN 0 AND 9007199254740991),
|
|
11307
|
+
recovery_budget_json TEXT CHECK(recovery_budget_json IS NULL OR
|
|
11308
|
+
(json_valid(recovery_budget_json) AND json_type(recovery_budget_json)='object')),
|
|
11309
|
+
CHECK((runtime_epoch=0 AND stopped_container_id IS NULL AND saved_revision=1 AND confirmed_at=0
|
|
11310
|
+
AND recovery_budget_json IS NULL) OR (runtime_epoch>0 AND stopped_container_id IS NOT NULL
|
|
11311
|
+
AND length(stopped_container_id)=64 AND stopped_container_id NOT GLOB '*[^0-9a-f]*'
|
|
11312
|
+
AND recovery_budget_json IS NOT NULL))
|
|
11313
|
+
) STRICT`);
|
|
11314
|
+
db.run("INSERT INTO runtime_cutovers(runtime_epoch,saved_revision,confirmed_at) VALUES(0,1,0)");
|
|
11315
|
+
db.run(`CREATE TRIGGER runtime_cutovers_no_delete BEFORE DELETE ON runtime_cutovers
|
|
11316
|
+
BEGIN SELECT RAISE(ABORT,'runtime cutover history is immutable'); END`);
|
|
11317
|
+
db.run(`CREATE TRIGGER runtime_cutovers_no_update BEFORE UPDATE ON runtime_cutovers
|
|
11318
|
+
BEGIN SELECT RAISE(ABORT,'runtime cutover history is immutable'); END`);
|
|
11319
|
+
db.run(`CREATE TRIGGER runtime_cutovers_no_replace BEFORE INSERT ON runtime_cutovers
|
|
11320
|
+
WHEN EXISTS(SELECT 1 FROM runtime_cutovers WHERE runtime_epoch=NEW.runtime_epoch
|
|
11321
|
+
OR stopped_container_id=NEW.stopped_container_id)
|
|
11322
|
+
BEGIN SELECT RAISE(ABORT,'runtime cutover history is immutable'); END`);
|
|
11323
|
+
for (const table of ["configuration_operations", "configuration_recoveries", "configuration_worker_launch_intents"]) {
|
|
11324
|
+
db.run(`ALTER TABLE ${table} ADD COLUMN runtime_epoch INTEGER NOT NULL DEFAULT 0 REFERENCES runtime_cutovers(runtime_epoch)`);
|
|
11325
|
+
}
|
|
11326
|
+
db.run("DROP INDEX configuration_operations_single_owner");
|
|
11327
|
+
db.run(`CREATE UNIQUE INDEX configuration_operations_single_owner
|
|
11328
|
+
ON configuration_operations(runtime_epoch) WHERE state IN ('committed','publishing','draining')`);
|
|
11329
|
+
db.run("DROP INDEX configuration_recoveries_active_target_revision");
|
|
11330
|
+
db.run(`CREATE UNIQUE INDEX configuration_recoveries_active_target_revision
|
|
11331
|
+
ON configuration_recoveries(runtime_epoch,target_revision) WHERE state IN ('scheduled','running')`);
|
|
11332
|
+
}
|
|
11333
|
+
};
|
|
11334
|
+
|
|
11335
|
+
// src/config-storage/migrations/prepared-worker-allocation.ts
|
|
11336
|
+
var PREPARED_WORKER_ALLOCATION_MIGRATION = {
|
|
11337
|
+
version: 12,
|
|
11338
|
+
name: "prepared_worker_allocation",
|
|
11339
|
+
up(db) {
|
|
11340
|
+
db.run("DROP TRIGGER configuration_worker_launch_intents_no_update");
|
|
11341
|
+
db.run(`CREATE TRIGGER configuration_worker_launch_intents_no_update
|
|
11342
|
+
BEFORE UPDATE ON configuration_worker_launch_intents
|
|
11343
|
+
WHEN OLD.allocation_mutation_id IS NOT NULL OR NEW.allocation_mutation_id IS NULL
|
|
11344
|
+
OR NEW.worker_instance_id IS NOT OLD.worker_instance_id OR NEW.master_generation IS NOT OLD.master_generation
|
|
11345
|
+
OR NEW.worker_slot IS NOT OLD.worker_slot OR NEW.guard_json IS NOT OLD.guard_json
|
|
11346
|
+
OR NEW.registered_at IS NOT OLD.registered_at OR NEW.runtime_epoch IS NOT OLD.runtime_epoch
|
|
11347
|
+
BEGIN SELECT RAISE(ABORT,'worker launch intent is immutable'); END`);
|
|
11348
|
+
}
|
|
11349
|
+
};
|
|
11350
|
+
|
|
11210
11351
|
// src/config-storage/migrations/plan.ts
|
|
11211
|
-
var CONFIG_MIGRATIONS = [CONFIG_BASELINE, PUBLICATION_RETIREMENT_MIGRATION, UI_MENUS_MIGRATION, MANAGEMENT_PROTECTION_MIGRATION, SERVICE_REFERENCES_MIGRATION, WEBSOCKET_CONNECTIONS_MIGRATION, WEBSOCKET_MESSAGE_SIZE_MIGRATION, PUBLICATION_TARGET_MIGRATION, REQUEST_LOGS_DEFAULT_MIGRATION, WORKER_LAUNCH_CAPACITY_MIGRATION];
|
|
11352
|
+
var CONFIG_MIGRATIONS = [CONFIG_BASELINE, PUBLICATION_RETIREMENT_MIGRATION, UI_MENUS_MIGRATION, MANAGEMENT_PROTECTION_MIGRATION, SERVICE_REFERENCES_MIGRATION, WEBSOCKET_CONNECTIONS_MIGRATION, WEBSOCKET_MESSAGE_SIZE_MIGRATION, PUBLICATION_TARGET_MIGRATION, REQUEST_LOGS_DEFAULT_MIGRATION, WORKER_LAUNCH_CAPACITY_MIGRATION, RUNTIME_CUTOVER_MIGRATION, PREPARED_WORKER_ALLOCATION_MIGRATION];
|
|
11212
11353
|
var CONFIG_SCHEMA_VERSION = CONFIG_MIGRATIONS.at(-1).version;
|
|
11213
11354
|
|
|
11214
11355
|
// src/config-storage/schema-fingerprint.ts
|
|
@@ -11395,11 +11536,13 @@ function applyRequestLogsDefault(db, options, targetWorkerSlots) {
|
|
|
11395
11536
|
let settledRevision = snapshot.revision;
|
|
11396
11537
|
if (!snapshot.aggregate.plugin_activations.some((activation) => activation.plugin_name === PLUGIN)) {
|
|
11397
11538
|
const unfinished = sqliteGet(db, `SELECT 1 AS unfinished FROM configuration_operations
|
|
11398
|
-
WHERE state IN ('committed','publishing','draining')
|
|
11539
|
+
WHERE (state IN ('committed','publishing','draining') AND runtime_epoch=${CURRENT_RUNTIME_EPOCH})
|
|
11540
|
+
OR (state='pending' AND committed_revision=(
|
|
11399
11541
|
SELECT active_revision FROM configuration_state WHERE id=1))
|
|
11400
|
-
UNION ALL SELECT 1 FROM configuration_retirements
|
|
11542
|
+
UNION ALL SELECT 1 FROM configuration_retirements r JOIN configuration_operations o USING(mutation_id)
|
|
11543
|
+
WHERE r.state<>'released' AND o.runtime_epoch=${CURRENT_RUNTIME_EPOCH}
|
|
11401
11544
|
UNION ALL SELECT 1 FROM configuration_recoveries WHERE state='stopped' AND recovery_sequence=(
|
|
11402
|
-
SELECT max(recovery_sequence) FROM configuration_recoveries WHERE target_revision=(
|
|
11545
|
+
SELECT max(recovery_sequence) FROM configuration_recoveries WHERE runtime_epoch=${CURRENT_RUNTIME_EPOCH} AND target_revision=(
|
|
11403
11546
|
SELECT active_revision FROM configuration_state WHERE id=1))
|
|
11404
11547
|
LIMIT 1`);
|
|
11405
11548
|
if (unfinished !== null || readPublicationRecoveryBarrier(db) !== null || readUnsettledWorkerLaunches(db).length > 0)
|
|
@@ -11442,8 +11585,84 @@ function applyRequestLogsDefault(db, options, targetWorkerSlots) {
|
|
|
11442
11585
|
return settledRevision !== snapshot.revision;
|
|
11443
11586
|
}
|
|
11444
11587
|
|
|
11588
|
+
// src/supervision/state-repository.ts
|
|
11589
|
+
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
|
|
11590
|
+
function requireCommandUuid(value, field) {
|
|
11591
|
+
if (typeof value !== "string" || !isLowercaseUuid(value)) {
|
|
11592
|
+
throw new ConfigRepositoryError("invalid_command", `${field} must be a lowercase UUID`);
|
|
11593
|
+
}
|
|
11594
|
+
return value;
|
|
11595
|
+
}
|
|
11596
|
+
function requireCommandTimestamp(value) {
|
|
11597
|
+
if (!Number.isSafeInteger(value) || value < 0 || value >= MAX_SAFE_INTEGER) {
|
|
11598
|
+
throw new ConfigRepositoryError("invalid_command", "updated_at must be below Number.MAX_SAFE_INTEGER");
|
|
11599
|
+
}
|
|
11600
|
+
return value;
|
|
11601
|
+
}
|
|
11602
|
+
function readState(db) {
|
|
11603
|
+
const rows = sqliteAll(db, `
|
|
11604
|
+
SELECT id,instance_id,controller_epoch,current_controller_id,updated_at
|
|
11605
|
+
FROM supervision_state`);
|
|
11606
|
+
if (rows.length !== 1) {
|
|
11607
|
+
throw new ConfigRepositoryError("schema_corrupt", "supervision state must contain exactly one row");
|
|
11608
|
+
}
|
|
11609
|
+
const row = rows[0];
|
|
11610
|
+
if (row === undefined || row.id !== 1 || typeof row.instance_id !== "string" || typeof row.controller_epoch !== "number" || row.current_controller_id !== null && typeof row.current_controller_id !== "string" || typeof row.updated_at !== "number") {
|
|
11611
|
+
throw new ConfigRepositoryError("schema_corrupt", "supervision state contains invalid persisted values");
|
|
11612
|
+
}
|
|
11613
|
+
const instanceId = requireUuid(row.instance_id, "supervision_state.instance_id");
|
|
11614
|
+
const epoch = requireSafeInteger(row.controller_epoch, "supervision_state.controller_epoch");
|
|
11615
|
+
if (epoch >= MAX_SAFE_INTEGER) {
|
|
11616
|
+
throw new ConfigRepositoryError("schema_corrupt", "supervision_state.controller_epoch is out of range");
|
|
11617
|
+
}
|
|
11618
|
+
const updatedAt = requireSafeInteger(row.updated_at, "supervision_state.updated_at");
|
|
11619
|
+
if (updatedAt >= MAX_SAFE_INTEGER) {
|
|
11620
|
+
throw new ConfigRepositoryError("schema_corrupt", "supervision_state.updated_at is out of range");
|
|
11621
|
+
}
|
|
11622
|
+
const controllerId = row.current_controller_id === null ? null : requireUuid(row.current_controller_id, "supervision_state.current_controller_id");
|
|
11623
|
+
return {
|
|
11624
|
+
instance_id: instanceId,
|
|
11625
|
+
controller_epoch: epoch,
|
|
11626
|
+
current_controller_id: controllerId,
|
|
11627
|
+
updated_at: updatedAt
|
|
11628
|
+
};
|
|
11629
|
+
}
|
|
11630
|
+
|
|
11631
|
+
class SupervisionStateRepository {
|
|
11632
|
+
db;
|
|
11633
|
+
constructor(db) {
|
|
11634
|
+
this.db = db;
|
|
11635
|
+
}
|
|
11636
|
+
get() {
|
|
11637
|
+
return readState(this.db);
|
|
11638
|
+
}
|
|
11639
|
+
claim(controllerId, updatedAt) {
|
|
11640
|
+
const id = requireCommandUuid(controllerId, "controller_id");
|
|
11641
|
+
const timestamp = requireCommandTimestamp(updatedAt);
|
|
11642
|
+
return this.db.transaction(() => {
|
|
11643
|
+
const state = readState(this.db);
|
|
11644
|
+
if (state.controller_epoch >= MAX_SAFE_INTEGER - 1) {
|
|
11645
|
+
throw new ConfigRepositoryError("repository_failure", "supervision controller epoch is exhausted");
|
|
11646
|
+
}
|
|
11647
|
+
const effectiveUpdatedAt = Math.max(timestamp, state.updated_at);
|
|
11648
|
+
const result = this.db.run(`UPDATE supervision_state
|
|
11649
|
+
SET controller_epoch=controller_epoch+1,current_controller_id=?,updated_at=?`, [id, effectiveUpdatedAt]);
|
|
11650
|
+
if (result.changes !== 1) {
|
|
11651
|
+
throw new ConfigRepositoryError("schema_corrupt", "supervision state singleton update failed");
|
|
11652
|
+
}
|
|
11653
|
+
return readState(this.db);
|
|
11654
|
+
}).immediate();
|
|
11655
|
+
}
|
|
11656
|
+
}
|
|
11657
|
+
function readSupervisionState(db) {
|
|
11658
|
+
return readState(db);
|
|
11659
|
+
}
|
|
11660
|
+
|
|
11445
11661
|
// src/config-storage/migrations/index.ts
|
|
11446
11662
|
function migrateConfigurationDatabase(db, plan = CONFIG_MIGRATIONS, options = {}) {
|
|
11663
|
+
migrate(db, plan, options);
|
|
11664
|
+
}
|
|
11665
|
+
function migrate(db, plan, options, cutover) {
|
|
11447
11666
|
if (db.inTransaction)
|
|
11448
11667
|
throw new ConfigRepositoryError("migration_failed", "configuration migration must not nest in a transaction");
|
|
11449
11668
|
db.run("PRAGMA foreign_keys = OFF");
|
|
@@ -11451,16 +11670,21 @@ function migrateConfigurationDatabase(db, plan = CONFIG_MIGRATIONS, options = {}
|
|
|
11451
11670
|
if (db.query("PRAGMA foreign_keys").get()?.foreign_keys !== 0) {
|
|
11452
11671
|
throw new ConfigRepositoryError("migration_failed", "configuration migration could not disable foreign keys");
|
|
11453
11672
|
}
|
|
11454
|
-
db.transaction(() => {
|
|
11673
|
+
return db.transaction(() => {
|
|
11455
11674
|
if (!plan.length || plan[0] !== CONFIG_MIGRATIONS[0] || plan.some((m, i) => i > 0 && m.version !== plan[i - 1].version + 1) || new Set(plan.map((m) => m.name)).size !== plan.length)
|
|
11456
11675
|
throw new ConfigRepositoryError("migration_failed", "invalid configuration migration plan");
|
|
11457
11676
|
const count = db.query("SELECT count(*) AS count FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'").get().count;
|
|
11677
|
+
if (cutover !== undefined && count === 0) {
|
|
11678
|
+
throw new ConfigRepositoryError("schema_corrupt", "runtime cutover requires an existing configuration database");
|
|
11679
|
+
}
|
|
11458
11680
|
let applied = [];
|
|
11459
11681
|
if (count > 0) {
|
|
11460
11682
|
applied = db.query("SELECT version,name FROM schema_migrations ORDER BY version").all();
|
|
11461
11683
|
if (!applied.length || applied.length > plan.length || applied.some((r, i) => r.version !== plan[i]?.version || r.name !== plan[i]?.name))
|
|
11462
11684
|
throw new ConfigRepositoryError("schema_corrupt", "configuration migration history is not an exact baseline prefix");
|
|
11463
11685
|
verifySchemaFingerprint(db, applied.at(-1).version, plan);
|
|
11686
|
+
if (cutover !== undefined)
|
|
11687
|
+
readActiveRevision(db);
|
|
11464
11688
|
}
|
|
11465
11689
|
for (const migration of plan.slice(applied.length)) {
|
|
11466
11690
|
migration.up(db);
|
|
@@ -11470,11 +11694,22 @@ function migrateConfigurationDatabase(db, plan = CONFIG_MIGRATIONS, options = {}
|
|
|
11470
11694
|
if (plan === CONFIG_MIGRATIONS && applied.length > 0 && applied.at(-1).version < 5) {
|
|
11471
11695
|
convertServiceReferenceRevision(db, options);
|
|
11472
11696
|
}
|
|
11473
|
-
if (plan === CONFIG_MIGRATIONS)
|
|
11697
|
+
if (plan === CONFIG_MIGRATIONS) {
|
|
11698
|
+
verifyRuntimeCutoverCatalog(db, options.compileOptions?.availablePlugins);
|
|
11474
11699
|
applyRequestLogsDefault(db, options);
|
|
11700
|
+
}
|
|
11475
11701
|
if (plan.length > applied.length && db.query("PRAGMA foreign_key_check").all().length > 0) {
|
|
11476
11702
|
throw new ConfigRepositoryError("schema_corrupt", "configuration migration left invalid references");
|
|
11477
11703
|
}
|
|
11704
|
+
if (cutover === undefined)
|
|
11705
|
+
return;
|
|
11706
|
+
readActivePublication(db);
|
|
11707
|
+
const result = recordRuntimeCutover(db, cutover.stoppedContainerId, cutover.now);
|
|
11708
|
+
verifyRepositoryIntegrity(db);
|
|
11709
|
+
readRepositorySnapshot(db);
|
|
11710
|
+
readMenuLayout(db);
|
|
11711
|
+
readSupervisionState(db);
|
|
11712
|
+
return result;
|
|
11478
11713
|
}).immediate();
|
|
11479
11714
|
} catch (error) {
|
|
11480
11715
|
if (error instanceof ConfigRepositoryError)
|
|
@@ -11535,76 +11770,6 @@ function readSqliteVersion(db) {
|
|
|
11535
11770
|
return row.v;
|
|
11536
11771
|
}
|
|
11537
11772
|
|
|
11538
|
-
// src/supervision/state-repository.ts
|
|
11539
|
-
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
|
|
11540
|
-
function requireCommandUuid(value, field) {
|
|
11541
|
-
if (typeof value !== "string" || !isLowercaseUuid(value)) {
|
|
11542
|
-
throw new ConfigRepositoryError("invalid_command", `${field} must be a lowercase UUID`);
|
|
11543
|
-
}
|
|
11544
|
-
return value;
|
|
11545
|
-
}
|
|
11546
|
-
function requireCommandTimestamp(value) {
|
|
11547
|
-
if (!Number.isSafeInteger(value) || value < 0 || value >= MAX_SAFE_INTEGER) {
|
|
11548
|
-
throw new ConfigRepositoryError("invalid_command", "updated_at must be below Number.MAX_SAFE_INTEGER");
|
|
11549
|
-
}
|
|
11550
|
-
return value;
|
|
11551
|
-
}
|
|
11552
|
-
function readState(db) {
|
|
11553
|
-
const rows = sqliteAll(db, `
|
|
11554
|
-
SELECT id,instance_id,controller_epoch,current_controller_id,updated_at
|
|
11555
|
-
FROM supervision_state`);
|
|
11556
|
-
if (rows.length !== 1) {
|
|
11557
|
-
throw new ConfigRepositoryError("schema_corrupt", "supervision state must contain exactly one row");
|
|
11558
|
-
}
|
|
11559
|
-
const row = rows[0];
|
|
11560
|
-
if (row === undefined || row.id !== 1 || typeof row.instance_id !== "string" || typeof row.controller_epoch !== "number" || row.current_controller_id !== null && typeof row.current_controller_id !== "string" || typeof row.updated_at !== "number") {
|
|
11561
|
-
throw new ConfigRepositoryError("schema_corrupt", "supervision state contains invalid persisted values");
|
|
11562
|
-
}
|
|
11563
|
-
const instanceId = requireUuid(row.instance_id, "supervision_state.instance_id");
|
|
11564
|
-
const epoch = requireSafeInteger(row.controller_epoch, "supervision_state.controller_epoch");
|
|
11565
|
-
if (epoch >= MAX_SAFE_INTEGER) {
|
|
11566
|
-
throw new ConfigRepositoryError("schema_corrupt", "supervision_state.controller_epoch is out of range");
|
|
11567
|
-
}
|
|
11568
|
-
const updatedAt = requireSafeInteger(row.updated_at, "supervision_state.updated_at");
|
|
11569
|
-
if (updatedAt >= MAX_SAFE_INTEGER) {
|
|
11570
|
-
throw new ConfigRepositoryError("schema_corrupt", "supervision_state.updated_at is out of range");
|
|
11571
|
-
}
|
|
11572
|
-
const controllerId = row.current_controller_id === null ? null : requireUuid(row.current_controller_id, "supervision_state.current_controller_id");
|
|
11573
|
-
return {
|
|
11574
|
-
instance_id: instanceId,
|
|
11575
|
-
controller_epoch: epoch,
|
|
11576
|
-
current_controller_id: controllerId,
|
|
11577
|
-
updated_at: updatedAt
|
|
11578
|
-
};
|
|
11579
|
-
}
|
|
11580
|
-
|
|
11581
|
-
class SupervisionStateRepository {
|
|
11582
|
-
db;
|
|
11583
|
-
constructor(db) {
|
|
11584
|
-
this.db = db;
|
|
11585
|
-
}
|
|
11586
|
-
get() {
|
|
11587
|
-
return readState(this.db);
|
|
11588
|
-
}
|
|
11589
|
-
claim(controllerId, updatedAt) {
|
|
11590
|
-
const id = requireCommandUuid(controllerId, "controller_id");
|
|
11591
|
-
const timestamp = requireCommandTimestamp(updatedAt);
|
|
11592
|
-
return this.db.transaction(() => {
|
|
11593
|
-
const state = readState(this.db);
|
|
11594
|
-
if (state.controller_epoch >= MAX_SAFE_INTEGER - 1) {
|
|
11595
|
-
throw new ConfigRepositoryError("repository_failure", "supervision controller epoch is exhausted");
|
|
11596
|
-
}
|
|
11597
|
-
const effectiveUpdatedAt = Math.max(timestamp, state.updated_at);
|
|
11598
|
-
const result = this.db.run(`UPDATE supervision_state
|
|
11599
|
-
SET controller_epoch=controller_epoch+1,current_controller_id=?,updated_at=?`, [id, effectiveUpdatedAt]);
|
|
11600
|
-
if (result.changes !== 1) {
|
|
11601
|
-
throw new ConfigRepositoryError("schema_corrupt", "supervision state singleton update failed");
|
|
11602
|
-
}
|
|
11603
|
-
return readState(this.db);
|
|
11604
|
-
}).immediate();
|
|
11605
|
-
}
|
|
11606
|
-
}
|
|
11607
|
-
|
|
11608
11773
|
// src/master-runtime/instance-lock.ts
|
|
11609
11774
|
import { constants as sqliteConstants, Database as Database2 } from "bun:sqlite";
|
|
11610
11775
|
var SQLITE_OPEN_READWRITE_NOFOLLOW = sqliteConstants.SQLITE_OPEN_READWRITE | sqliteConstants.SQLITE_OPEN_NOFOLLOW;
|
|
@@ -11859,6 +12024,9 @@ class ConfigRepository {
|
|
|
11859
12024
|
getSnapshot() {
|
|
11860
12025
|
return this.snapshot;
|
|
11861
12026
|
}
|
|
12027
|
+
getRuntimeEpoch() {
|
|
12028
|
+
return runRepositoryAction(() => readRuntimeEpoch(this.db));
|
|
12029
|
+
}
|
|
11862
12030
|
getMenuLayout() {
|
|
11863
12031
|
return runRepositoryAction(() => withConsistentRead(this.db, () => readMenuLayout(this.db)));
|
|
11864
12032
|
}
|
|
@@ -11905,12 +12073,17 @@ class ConfigRepository {
|
|
|
11905
12073
|
const applied = this.mutationTransaction(() => applyRequestLogsDefault(this.db, this.options, targetWorkerSlots));
|
|
11906
12074
|
return applied ? this.getControlProjection() : null;
|
|
11907
12075
|
}
|
|
11908
|
-
commitPrepared(prepared) {
|
|
12076
|
+
commitPrepared(prepared, publication) {
|
|
11909
12077
|
try {
|
|
11910
12078
|
const decision = this.mutationTransaction(() => {
|
|
11911
|
-
|
|
11912
|
-
if (result.kind === "committed")
|
|
11913
|
-
|
|
12079
|
+
let result = commitTransaction(this.db, prepared, this.options, this.snapshot);
|
|
12080
|
+
if (result.kind === "committed") {
|
|
12081
|
+
const { committed_revision: revision } = result.operation;
|
|
12082
|
+
settleRequestLogsDefault(this.db, this.options, revision);
|
|
12083
|
+
if (publication !== undefined) {
|
|
12084
|
+
result = { kind: "committed", operation: this.bindPreparedPublication(prepared, revision, publication) };
|
|
12085
|
+
}
|
|
12086
|
+
}
|
|
11914
12087
|
readManagementProtection(this.db);
|
|
11915
12088
|
return result;
|
|
11916
12089
|
});
|
|
@@ -11929,6 +12102,31 @@ class ConfigRepository {
|
|
|
11929
12102
|
throw new ConfigRepositoryError("repository_failure", "configuration commit transaction failed", error);
|
|
11930
12103
|
}
|
|
11931
12104
|
}
|
|
12105
|
+
bindPreparedPublication(command, revision, publication) {
|
|
12106
|
+
const { mutationId, createdAt, contentHash, aggregate, targetSlots } = command;
|
|
12107
|
+
const { pluginCatalogHash, workers, retired } = publication;
|
|
12108
|
+
if (workers.length === 0 || workers.length !== targetSlots.length || workers.some((worker, index) => worker.identity.worker_slot !== targetSlots[index] || worker.revision !== revision || worker.content_hash !== contentHash || worker.plugin_catalog_hash !== pluginCatalogHash || worker.publication?.mutation_id !== mutationId || worker.publication.attempt_no !== 1 || worker.publication.drain_recovery_generation !== 0)) {
|
|
12109
|
+
throw new ConfigRepositoryError("invalid_operation", "prepared worker evidence does not match configuration commit");
|
|
12110
|
+
}
|
|
12111
|
+
const instances = new Set(workers.map((worker) => worker.identity.worker_instance_id));
|
|
12112
|
+
const owner = claimPublicationTarget(this.db, { revision, content_hash: contentHash, aggregate }, pluginCatalogHash, createdAt, instances);
|
|
12113
|
+
if (owner?.operation.mutation_id !== mutationId) {
|
|
12114
|
+
throw new ConfigRepositoryError("invalid_operation", "prepared configuration could not claim publication");
|
|
12115
|
+
}
|
|
12116
|
+
beginPublication(this.db, mutationId, createdAt);
|
|
12117
|
+
for (const worker of workers) {
|
|
12118
|
+
const slot = worker.identity.worker_slot;
|
|
12119
|
+
beginWorkerAttempt(this.db, mutationId, slot, 0, "initial", createdAt);
|
|
12120
|
+
bindPreparedWorkerLaunch(this.db, worker.identity, worker.guard, { mutation_id: mutationId, worker_slot: slot, attempt_no: 1 });
|
|
12121
|
+
recordWorkerResult(this.db, mutationId, slot, { kind: "converged", attempt_no: 1, applied_revision: revision }, createdAt);
|
|
12122
|
+
}
|
|
12123
|
+
const decision = enterPublicationPrepare(this.db, mutationId, revision, createdAt);
|
|
12124
|
+
if (decision.kind !== "granted")
|
|
12125
|
+
throw new ConfigRepositoryError("invalid_operation", "prepared configuration lost publication authority");
|
|
12126
|
+
freezePublicationServingSet(this.db, mutationId, 0, workers);
|
|
12127
|
+
freezePublicationRetirement(this.db, mutationId, 0, retired, createdAt);
|
|
12128
|
+
return decision.operation;
|
|
12129
|
+
}
|
|
11932
12130
|
getOperation(mutationId) {
|
|
11933
12131
|
return runRepositoryAction(() => withConsistentRead(this.db, () => {
|
|
11934
12132
|
return getOperation(this.db, mutationId);
|
|
@@ -12002,7 +12200,8 @@ class ConfigRepository {
|
|
|
12002
12200
|
getCurrentOperationState() {
|
|
12003
12201
|
return runRepositoryAction(() => withConsistentRead(this.db, () => {
|
|
12004
12202
|
const revision = readActiveRevision(this.db);
|
|
12005
|
-
const row = sqliteGet(this.db, `${OPERATION_SELECT} WHERE committed_revision
|
|
12203
|
+
const row = sqliteGet(this.db, `${OPERATION_SELECT} WHERE committed_revision=?
|
|
12204
|
+
AND (state='pending' OR runtime_epoch=${CURRENT_RUNTIME_EPOCH})`, revision);
|
|
12006
12205
|
const operation = row === null ? null : operationFromRow(row);
|
|
12007
12206
|
if (operation === null)
|
|
12008
12207
|
return null;
|
|
@@ -12143,11 +12342,7 @@ class ConfigRepository {
|
|
|
12143
12342
|
return runRepositoryAction(() => withConsistentRead(this.db, () => readPublicationRetirementRetry(this.db, ...args)));
|
|
12144
12343
|
}
|
|
12145
12344
|
requestPublicationRetirementRetry(...args) {
|
|
12146
|
-
return runRepositoryAction(() => this.mutationTransaction(() =>
|
|
12147
|
-
if (this.snapshot.revision !== args[2])
|
|
12148
|
-
throw new ConfigRepositoryError("cas_conflict", "retirement retry revision changed");
|
|
12149
|
-
return requestPublicationRetirementRetry(this.db, ...args);
|
|
12150
|
-
}));
|
|
12345
|
+
return runRepositoryAction(() => this.mutationTransaction(() => requestPublicationRetirementRetry(this.db, ...args)));
|
|
12151
12346
|
}
|
|
12152
12347
|
markPublicationRetirementReleased(...args) {
|
|
12153
12348
|
return runRepositoryAction(() => this.mutationTransaction(() => markPublicationRetirementReleased(this.db, ...args)));
|
|
@@ -12210,6 +12405,7 @@ class ConfigRepository {
|
|
|
12210
12405
|
|
|
12211
12406
|
// src/config-storage/storage-protocol.ts
|
|
12212
12407
|
var STORAGE_METHODS = [
|
|
12408
|
+
"getRuntimeEpoch",
|
|
12213
12409
|
"getMenuLayout",
|
|
12214
12410
|
"putMenuLayout",
|
|
12215
12411
|
"getPublicationRetirementRetry",
|
|
@@ -12275,6 +12471,7 @@ var STORAGE_METHODS = [
|
|
|
12275
12471
|
"observeRuntimeRecoveryHealth"
|
|
12276
12472
|
];
|
|
12277
12473
|
var READ_METHODS = new Set([
|
|
12474
|
+
"getRuntimeEpoch",
|
|
12278
12475
|
"getControlProjection",
|
|
12279
12476
|
"getMenuLayout",
|
|
12280
12477
|
"getPublicationRetirementRetry",
|