Skip to content

Commit 480b8e1

Browse files
author
hzq
committed
Reset API key usage in bounded settlement slices
Fence new work on the resetting key while draining terminal accounting. Commit the quota and zeroed usage together with a receipt, and verify uncertain commits before publishing either change.
1 parent e4581ff commit 480b8e1

17 files changed

Lines changed: 709 additions & 69 deletions

‎docs/operations.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,8 @@ Creating a run commits its initial event, key usage, any platform hold and its w
178178

179179
On `GET /metrics`, `oaa_run_outcomes_total{agent,status}` is the counter for completion and failure rates. It counts transitions into terminal states and survives history pruning and restarts. At first upgrade it starts from the terminal runs still retained, not already-deleted history. The older `oaa_runs_total`, `oaa_run_errors_total`, `oaa_run_tokens_total` and `oaa_tokens_total` series retain their names and snapshot values, but are gauges: do not apply `rate()` to them.
180180

181+
Resetting an API key through `POST /v1/keys/{id}/quota` with `reset_usage: true` settles its pending terminal runs in short batches before clearing its usage. During the reset, new runs and resumes for that key, and other quota changes to it, return `503 key_quota_busy`. Other keys are not paused. Runs that are still active at the reset boundary remain active and can accrue usage afterward. On `409 effect_outcome_unknown`, inspect the current quota and usage before retrying; the final write is checked in the background, not replayed.
182+
181183
Nothing is deleted automatically unless you ask for it. `oaa prune [--older-than 30d] [--dry-run] [--vacuum]` deletes finished runs older than the given age with their events, steps, artifacts and webhook approval announcements, plus uploads (including stored image inputs) and session workspaces that no kept run uses. Queued, running, waiting and `interrupted` runs are never touched, nor is a run whose developer-platform ledger line is still unsettled. Ledger lines, key usage totals, memories and webhook delivery logs are records and stay. To prune on a schedule, set `"retention": {"runsDays": 30}` in `config.json`; `oaa doctor` and `oaa status` warn when the database grows past `retention.warnDatabaseMb` (default 1024).
182184

183185
Before a schema migration the gateway copies the database to `backups/state-v<old>-before-subjects-<time>.sqlite`; only the newest 3 copies per source version are kept. Details, measured soak results and crash-recovery semantics: [stability.md](stability.md).

‎docs/protocol.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,7 @@ Error codes and response shapes do not depend on language; only the text of `mes
727727
| `rate_limited` | 429 | The key exceeded its requests per minute (600 by default) |
728728
| `concurrency_limit` | 429 | The owner has too many active requests |
729729
| `admission_busy` | 503 | No run was created: the database writer wait expired or the admission queue was full. Respect `Retry-After` and reuse the same idempotency key. |
730+
| `key_quota_busy` | 503 | The API key is undergoing a quota reset, or the reset cannot currently acquire the database writer. Respect `Retry-After`. |
730731
| `upload_busy` | 503 | The upload exhausted its wait budget, its previous quota reader has not released the scan, or repeated changes prevented a consistent count. No new file was accepted; respect `Retry-After`. |
731732
| `file_commit_unconfirmed` | 409 | The file metadata commit could not be confirmed or read back. Inspect the supplied `file_id` before uploading again; do not assume that no file exists. |
732733
| `subject_concurrency_limit` | 429 | The same caller (subject) reached `maxActiveRunsPerSubject` unfinished requests |

‎docs/zh-CN/protocol.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -751,6 +751,7 @@ HTTP 错误响应默认使用形状 `{"error":{"code":"…","message":"…","typ
751751
| `rate_limited` | 429 | 超出该密钥每分钟请求数(默认 600) |
752752
| `concurrency_limit` | 429 | owner 的活跃请求过多 |
753753
| `admission_busy` | 503 | 尚未创建运行:数据库写锁等待超时或准入等待队列已满。请遵守 `Retry-After` 并沿用同一幂等键。 |
754+
| `key_quota_busy` | 503 | 该密钥正在重置额度,或重置暂时无法取得数据库写锁。请遵守 `Retry-After`。 |
754755
| `upload_busy` | 503 | 上传等待超出预算、原读取尚未交回,或文件记录持续变化而无法确认配额。未接受新的文件;请遵守 `Retry-After`。 |
755756
| `file_commit_unconfirmed` | 409 | 文件提交应答丢失且无法回读。按返回的 `file_id` 查询,不要假定文件未保存而自动重传。 |
756757
| `subject_concurrency_limit` | 429 | 同一调用方(subject)的未完成请求达到 `maxActiveRunsPerSubject` |

‎src/core/errors-en.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export const ERROR_EN: Readonly<Record<string, readonly [string, string?]>> = {
1818
rate_limited: ['This key exceeded its requests-per-minute limit (600 by default).', 'Retry later, or ask the owner to raise this key\'s per-minute limit.'],
1919
concurrency_limit: ['The owner has too many active requests.', 'Retry after some in-flight requests finish.'],
2020
admission_busy: ['The gateway could not acquire the run admission writer in time or the wait queue is full.', 'Retry later with the same idempotency key.'],
21+
key_quota_busy: ['The API key is undergoing a quota reset, or the reset could not acquire the writer.', 'Retry after the current operation finishes.'],
2122
upload_busy:['File publication did not obtain the database writer within its wait budget.','Retry the upload later.'],
2223
file_commit_unconfirmed:['The file publication outcome is unconfirmed.','Inspect the returned file ID before uploading again.'],
2324
subject_concurrency_limit: ['This caller has reached its limit of unfinished requests.', 'Retry after some in-flight requests finish.'],

‎src/core/errors.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const ROWS: Row[] = [
7676
['rate_limited', 429, 'request', R, '超出该密钥每分钟请求数(默认 600)', '稍后重试,或请 owner 调高该密钥的每分钟请求数'],
7777
['concurrency_limit', 429, 'request', R, 'owner 的活跃请求过多', '等待已有请求完成后重试'],
7878
['admission_busy', 503, 'request', R, '运行尚未创建,数据库写入准入等待超时或已满', '稍后使用相同的幂等键重试'],
79+
['key_quota_busy', 503, 'request', R, '密钥额度正在重置,或重置暂时无法取得写锁', '等待当前操作完成后再试'],
7980
['upload_busy',503,'request',R,'文件尚未发布,上传写锁等待超时或已满','稍后重试上传'],
8081
['file_commit_unconfirmed',409,'request',_,'文件可能已经提交,暂时无法回读确认','先查询返回的文件编号,不要盲目重传'],
8182
['subject_concurrency_limit', 429, 'request', R, '同一调用方的未完成请求数已达上限', '等待已有请求完成后重试'],

‎src/gateway/auth.ts‎

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { Fault, RetryLaterFault, id, safeEqual, secret, sha } from '../core/util
2222
import { permits } from '../fabric/network.js';
2323
import { KeyUsage, type KeyUsageView } from './key-usage.js';
2424
import { generateApiKey, invalidKey, missingKey } from './api-key.js';
25+
import { prepareKeyQuota } from './key-quota.js';
2526

2627
import type { StoredKey, AccountKeyView, AccountKeyPolicy } from './key-types.js';
2728
export type { AccountKeyView, AccountKeyPolicy } from './key-types.js';
@@ -167,6 +168,7 @@ export class Auth {
167168
return this.usage.keyUsage(keyId);
168169
}
169170
checkQuotaForRun(p: Principal, agent?: string): void {
171+
this.accounting.assertQuotaWritable(p.keyId);
170172
if (p.quota?.expiresAt && Date.now() >= p.quota.expiresAt) {
171173
throw new Fault('key_expired', 'API key has expired.', 401);
172174
}
@@ -280,9 +282,10 @@ export class Auth {
280282
)
281283
.all(p.owner)
282284
.flatMap((row) => {
283-
const { hash, ...key } = JSON.parse(row.payload as string) as StoredKey;
285+
const stored = JSON.parse(row.payload as string) as StoredKey;
284286
// Account keys are managed separately; revoked keys are not listed.
285-
if (key.accountId || key.revoked) return [];
287+
if (stored.accountId || stored.revoked) return [];
288+
const { hash, ...key } = this.managedByHash.get(stored.hash) ?? stored;
286289
return [{ ...key, managed: true, usage: this.usage.listedUsage(key.id, row) }];
287290
});
288291
return [
@@ -433,40 +436,37 @@ export class Auth {
433436
this.indexAccountKey(key, accountId);
434437
this.store.authorizationChanged(owner);
435438
}
436-
updateQuota(
437-
p: Principal,
438-
keyId: string,
439-
quota: KeyQuota | undefined,
440-
resetUsage = false,
441-
): Record<string, unknown> {
439+
updateQuota(p: Principal, keyId: string, quota: KeyQuota | undefined): Record<string, unknown> {
442440
this.require(p, 'admin');
443-
if (resetUsage) this.accounting.beforeReset(p.owner, keyId);
444-
const row = this.store.db
445-
.prepare('SELECT payload FROM api_keys WHERE id=? AND owner=?')
446-
.get(keyId, p.owner);
447-
if (row) {
448-
const key = JSON.parse(row.payload as string) as StoredKey;
449-
if (quota && Object.keys(quota).length) key.quota = quota;
450-
else delete key.quota;
451-
this.store.db
452-
.prepare('UPDATE api_keys SET payload=? WHERE id=?')
453-
.run(JSON.stringify(key), keyId);
454-
if (!key.revoked) this.managedByHash.set(key.hash, key);
455-
} else {
456-
const cfg = this.configured.find(
457-
(k) =>
458-
k.principal.owner === p.owner &&
459-
(k.principal.keyId === keyId || `config:${k.principal.name}` === keyId),
460-
);
461-
if (!cfg) throw new Fault('key_not_found', 'API key was not found for this owner.', 404);
462-
if (quota && Object.keys(quota).length) cfg.principal.quota = quota;
463-
else delete cfg.principal.quota;
464-
}
465-
if (resetUsage) this.usage.reset(keyId, p.owner);
441+
const stage = this.quotaUpdate(p, keyId, quota, false);
442+
this.accounting.assertQuotaWritable(keyId);
443+
stage()();
444+
return this.quotaResult(keyId, quota);
445+
}
446+
async resetQuota(p: Principal, keyId: string, quota: KeyQuota | undefined, check: () => void) {
447+
this.require(p, 'admin');
448+
const usage = await this.accounting.resetQuota(p.owner, keyId, () => {
449+
check();
450+
return this.quotaUpdate(p, keyId, quota, true);
451+
});
452+
return this.quotaResult(keyId, quota, usage);
453+
}
454+
private quotaUpdate(p: Principal, keyId: string, quota: KeyQuota | undefined, active: boolean) {
455+
return prepareKeyQuota(
456+
this.store,
457+
this.configured,
458+
this.managedByHash,
459+
p,
460+
keyId,
461+
quota,
462+
active,
463+
);
464+
}
465+
private quotaResult(keyId: string, quota: KeyQuota | undefined, usage = this.keyUsage(keyId)) {
466466
return {
467467
id: keyId,
468468
quota: quota && Object.keys(quota).length ? quota : null,
469-
usage: this.keyUsage(keyId),
469+
usage,
470470
};
471471
}
472472
revoke(p: Principal, keyId: string): void {

‎src/gateway/key-accounting.ts‎

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@ import type { UsagePublication } from '../kernel/types.js';
66
import { isWriteUnavailable } from '../store/checkpoint.js';
77
import { UnconfirmedRunCommit, type UnconfirmedAdmissionCommit } from '../store/run-creation.js';
88
import { withSavepoint } from '../store/savepoint.js';
9+
import { runSqliteWrite } from '../store/sqlite-write.js';
910
import type { Store } from '../store/store.js';
11+
import { KeyQuotaResets, type StageQuota } from './key-quota-resets.js';
1012
import type { AccountKeyPolicy } from './key-types.js';
1113
import type { KeyUsage } from './key-usage.js';
12-
import { keySettlements, keySettlementsForKey } from './key-settlement-candidates.js';
14+
import { keySettlements } from './key-settlement-candidates.js';
1315

1416
const RECOVERY_PAGE = 64;
1517

@@ -49,12 +51,21 @@ export class KeyAccounting {
4951
private retrySweep = false;
5052
private readonly held = new Map<string, HeldSettlement>();
5153
private readonly admissions = new Map<string, HeldAdmission>();
54+
private readonly resets: KeyQuotaResets;
5255
constructor(
5356
private store: Store,
5457
private usage: KeyUsage,
5558
private accounts: ReadonlyMap<string, string>,
5659
private platform: () => AccountKeyPolicy | undefined,
57-
) {}
60+
) {
61+
this.resets = new KeyQuotaResets(
62+
store,
63+
usage,
64+
(owner, key) => this.assertResettable(owner, key),
65+
(owner, key, run, total, status) => this.settle(key, owner, run, total, status),
66+
() => this.schedule(5000),
67+
);
68+
}
5869

5970
checkInterruptedResume(own: Principal, run: Pick<Run, 'id' | 'agentId'>, self: boolean): void {
6071
if (own.quota?.expiresAt && Date.now() >= own.quota.expiresAt)
@@ -66,11 +77,13 @@ export class KeyAccounting {
6677
!(own.scopes.includes('invoke') || own.scopes.includes('admin'))
6778
)
6879
throw new Fault('scope_denied', "The response's API key no longer grants this agent.", 403);
80+
this.assertQuotaWritable(own.keyId);
6981
if (own.accountId) this.platform()?.checkRun(own.accountId, run.agentId);
7082
this.usage.checkQuota(own, run.id);
7183
}
7284

7385
prepareQueuedRecovery(principal: Principal, run: Run, keyId: string): () => void {
86+
this.assertQuotaWritable(keyId);
7487
this.usage.assertConfirmed(keyId);
7588
if (
7689
!this.store
@@ -87,6 +100,7 @@ export class KeyAccounting {
87100

88101
stage(keyId: string | undefined, owner: string, run: string, agent?: string) {
89102
if (!keyId) return;
103+
this.assertQuotaWritable(keyId);
90104
this.requireSettled(keyId, owner);
91105
const account = this.accounts.get(keyId);
92106
if (account && agent !== undefined) this.platform()?.beginRun(account, run, agent);
@@ -147,6 +161,7 @@ export class KeyAccounting {
147161
}
148162
stageRejoin(keyId: string | undefined, run: string) {
149163
if (!keyId) return;
164+
this.assertQuotaWritable(keyId);
150165
this.requireSettled(keyId);
151166
this.usage.assertConfirmed(keyId);
152167
this.usage.markPending(keyId, run);
@@ -260,9 +275,20 @@ export class KeyAccounting {
260275
receipt ? { id: receipt, previous } : undefined,
261276
);
262277
if (done) {
263-
this.store
264-
.prepare('DELETE FROM api_key_pending_runs WHERE run_id=? AND owner=? AND key_id=?')
265-
.run(run, owner, keyId);
278+
const removed = runSqliteWrite(
279+
this.store.prepare(
280+
'DELETE FROM api_key_pending_runs WHERE run_id=? AND owner=? AND key_id=?',
281+
),
282+
run,
283+
owner,
284+
keyId,
285+
);
286+
if (old?.pendingKey != null && Number(removed.changes) !== 1)
287+
throw new Fault(
288+
'persistence_failed',
289+
'The run accounting journal was not cleared.',
290+
500,
291+
);
266292
if (receipt && old) {
267293
const counted = previous?.tokens ?? 0;
268294
ticket = {
@@ -301,7 +327,9 @@ export class KeyAccounting {
301327
publish!();
302328
}
303329
recover(): void {
330+
let pendingResets = false;
304331
try {
332+
pendingResets = this.resets.recover();
305333
this.recoverAdmissions();
306334
for (let n = Math.min(this.held.size, RECOVERY_PAGE); n > 0; n--) {
307335
const [key, ticket] = this.held.entries().next().value!;
@@ -343,20 +371,23 @@ export class KeyAccounting {
343371
this.retrySweep = true;
344372
}
345373
this.recoveryAfter = '0';
346-
if (this.retrySweep || this.held.size || this.admissions.size) this.schedule(5000);
374+
if (this.retrySweep || this.held.size || this.admissions.size || pendingResets)
375+
this.schedule(5000);
347376
else this.warned = false;
348377
this.retrySweep = false;
349378
}
350-
beforeReset(owner: string, keyId: string): void {
379+
assertResettable(owner: string, keyId: string): void {
351380
this.requireSettled(keyId, owner);
352381
this.usage.assertConfirmed(keyId, owner);
353-
// A delayed pre-reset charge must not appear in the freshly reset totals.
354-
for (;;) {
355-
const rows = keySettlementsForKey(this.store, owner, keyId, RECOVERY_PAGE);
356-
for (const r of rows)
357-
this.settle(keyId, owner, String(r.run_id), Number(r.total_tokens), r.status as RunStatus);
358-
if (rows.length < RECOVERY_PAGE) return;
359-
}
382+
}
383+
assertQuotaWritable(keyId?: string): void {
384+
this.resets.assertIdle(keyId);
385+
}
386+
resetQuota(owner: string, keyId: string, prepare: () => StageQuota) {
387+
return this.resets.reset(owner, keyId, prepare);
388+
}
389+
stopResets(): void {
390+
this.resets.stop();
360391
}
361392
private requestSweep() {
362393
// A newly terminal run may be behind a page cursor while another sweep is already queued.
@@ -378,6 +409,7 @@ export class KeyAccounting {
378409
}, delay).unref();
379410
}
380411
close() {
412+
this.stopResets();
381413
clearTimeout(this.timer);
382414
this.timer = undefined;
383415
for (const ticket of this.held.values()) this.store.accountingReadbacks.delete(ticket.run);

0 commit comments

Comments
 (0)