Skip to content

An open-source, faster Devin alternative

TypeScript

token-billing (review P1): one-active-key-per-org guard for enable

Igor Zalutski6e71d2a89321
diff --git a/cloudflare-workers/api-edge/src/model_billing.ts b/cloudflare-workers/api-edge/src/model_billing.ts
index 2a1957b4..a14d5571 100644
--- a/cloudflare-workers/api-edge/src/model_billing.ts
+++ b/cloudflare-workers/api-edge/src/model_billing.ts
@@ -293,12 +293,19 @@ export async function enableManagedBilling(env: ModelBillingEnv, orgId: string):
let row = await getResumableRow(env, orgId);
if (!row) {
- row = await insertRow(env, {
- id: newRowId(),
- orgId,
- operationId: newOperationId(),
- createdAt: Math.floor(Date.now() / 1000),
- });
+ try {
+ row = await insertRow(env, {
+ id: newRowId(),
+ orgId,
+ operationId: newOperationId(),
+ createdAt: Math.floor(Date.now() / 1000),
+ });
+ } catch (e) {
+ // Lost a concurrent enable race — the unique "one active key per org" index
+ // (schema_phase9) rejected this insert. Adopt the row the winner created.
+ row = await getResumableRow(env, orgId);
+ if (!row) throw e;
+ }
}
return driveProvisioning(env, org, row);
}
diff --git a/cloudflare-workers/schema_phase9_model_billing.sql b/cloudflare-workers/schema_phase9_model_billing.sql
index 05fb2449..7d2ebf9a 100644
--- a/cloudflare-workers/schema_phase9_model_billing.sql
+++ b/cloudflare-workers/schema_phase9_model_billing.sql
@@ -65,3 +65,10 @@ CREATE TABLE IF NOT EXISTS managed_model_keys (
-- superseded/deleting keys (poll until quiesced).
CREATE INDEX IF NOT EXISTS idx_managed_model_keys_org_status
ON managed_model_keys(org_id, status);
+
+-- AT MOST ONE active key per org. Without this, two concurrent enable calls/retries
+-- (getResumableRow → insertRow with no txn) could mint two active OR keys + two
+-- managed credentials. The unique partial index makes the losing insert fail; the
+-- provisioning driver catches it and adopts the winner.
+CREATE UNIQUE INDEX IF NOT EXISTS idx_managed_model_keys_one_active
+ ON managed_model_keys(org_id) WHERE status = 'active';