Skip to content

Reserve, settle, and release

Follow the concurrency-safe quota lifecycle before provider dispatch and through every streaming terminal state.

Updated View as Markdown
Audience: application-backendPlane: dataAuth: inference-keyStatus: beta

Outcome

你可以判断请求在何时占用、扣除或归还 Units,并验证普通响应、Streaming、失败和断开最终只产生一个结算结果。

                        ┌─ actual usage ─────→ SETTLED
request → ACTIVE reserve├─ no delivered usage → RELEASED
                        └─ recovery timeout ──→ EXPIRED

三个终态都不可返回 ACTIVE,也不能互相切换。

Reserve before the Provider

Gateway 先估算 Input,并用 Period Snapshot 的安全输出上限计算 reserveUnits。PostgreSQL 事务锁定当前 QuotaPeriod,校验 Available Units,创建 ACTIVE QuotaReservation,再增加 reservedUnits

只有事务提交后,Gateway 才获得可调度的 ProviderConnection。额度不足、Access 无效或数据库不可用时,Provider 不会被调用。

Settle with actual usage

响应或 Stream 提供可证明 Usage 后,Settlement 使用 Reserve 时保存的倍率快照计算 Actual Units:

reservedUnits -= reservation.heldUnits
consumedUnits += actualUnits
reservation.status = SETTLED
append immutable UsageEvent

Cached Token 在 Reserve 前通常未知;Settle 按真实 Cached Usage 重新计算并释放差额。

Release when nothing was delivered

请求在 Provider 前失败,或 Provider 完全失败且没有向用户交付可计量结果时,Release 归还全部 Held Units,并把 Reservation 标为 RELEASED。Provider Attempt 的错误或成本观察事实仍可保留。

Streaming and cancellation

  • 正常 Stream 结束:按末尾 Usage 或可证明计量结果 Settle。
  • 客户端断开:取消向上游传播,按已交付或 Provider 返回的可证明 Usage Settle,其余释放。
  • Provider 超时或错误:根据是否有有效交付选择 Settle 或 Release。
  • 进程中断:Worker 查找过期 ACTIVE Reservation,并按幂等规则恢复到确定终态。

Idempotency is mandatory

Reserve、Settle、Release、Recovery 和 UsageEvent 都使用稳定 Idempotency Key。重复完成事件不能重复扣量,重复 Release 不能增加 Available Units,迟到事件不能覆盖已经确定的终态。

Check your work

  • 每个 Invocation 最多有一条 ACTIVE Reservation,并最终进入一个终态。
  • reservedUnits + consumedUnits 从不超过 grantedUnits
  • 被 Quota 拒绝的请求没有 Provider Attempt。
  • Request ID 可以关联 Invocation、Reservation、UsageEvent 和 Audit。

Next steps

Navigation

Type to search…

↑↓ navigate↵ selectEsc close