Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions docs/en/rfcs/1515_artifact_processing_supervisor.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,138 @@ On OceanBase, a logical Supervisor may have multiple candidate instances, but on
uses one Runtime host process; `dedicated` organizes multiple Supervisors within that process without adding support
for multiprocess SQLite deployments.

## Distributed consumption and ownership handoff

Distributed consumption is optional. The default `all`/`global` or `dedicated` Runtime keeps a single process, local
in-memory queues and no external broker. A deployment may explicitly run independently scalable background worker
nodes that share durable storage and consume the same configured Families. Each worker still owns a normal local
Worker budget; distribution changes discovery and delivery, not processor business rules.

### Durable handoff

`pc_artifact_processing_intents` remains the authority for accepted work. The transaction that advances
`requested_generation` also inserts a row into `pc_artifact_processing_outbox`:

| Column | Meaning |
|---|---|
| `task_id` | Stable UUID for one notification attempt lineage; consumers deduplicate on it |
| `binding_name`, `scope_id` | Existing processing key; no business input is placed in the message |
| `request_generation` | Generation that was accepted; never inferred from the broker |
| `state`, `available_at`, `attempts`, `lease_expires_at` | Relay/visibility state for publication retry |
| `published_at`, `last_error_code` | Publication evidence outside the business transaction |

The outbox relay publishes a versioned envelope containing `task_id`, `(binding_name, scope_id)`,
`request_generation` and envelope version. It marks `published_at` only after the adapter accepts the publish. A crash
before publish leaves the row pending; a crash after broker acceptance but before `published_at` republishes the same
`task_id`; a broker outage becomes visible outbox backlog. Publication never makes a second accepted invocation and is
never part of the processor's business transaction.

A delivery is a hint. On claim, a worker re-reads the intent and executes only when
`requested_generation > handled_generation`; duplicate, stale or older-generation messages are no-ops. A broker
redelivery therefore cannot skip pending work, regress a cursor or acknowledge a newer invocation.

### Per-key ownership and fencing

The existing Supervisor Lease fences discovery. Execution ownership is separate and keyed by
`(binding_name, scope_id)`, because different Scopes of one Family must execute on different nodes while each key has at
most one valid owner:

| Column | Meaning |
|---|---|
| `binding_name`, `scope_id` | Processing key, primary key |
| `holder_id` | Random worker/process identity |
| `ownership_generation` | Monotonic generation; increments on every successful claim, not on renewal |
| `request_generation` | The invocation generation this owner claimed |
| `lease_expires_at`, `updated_at` | Database-time lease and last renewal |

A worker claims in one database transaction using database time: insert when absent, or update when the lease has
expired plus a handoff grace, or when `holder_id` matches its own renewal. The grace covers clock skew and heartbeat
jitter. A successful claim increments `ownership_generation`; renewal does not.

The processor receives `(binding_name, scope_id, ownership_generation, claimed_request_generation)`. Every durable
processor transaction that advances a cursor, records progress, publishes an Artifact or completes the intent validates
the ownership row with the same holder and generation in that transaction. The check and write must share the
transaction; a read-then-write in a separate transaction is insufficient. A stale worker cannot advance a cursor,
publish, or acknowledge a newer invocation regardless of whether it still holds an old broker message.

### Handoff while a model call is in flight

A worker that misses a heartbeat is not presumed stopped. Another worker may claim only after the database lease and
handoff grace have both expired. The old worker may finish its model call, but its subsequent fence check fails, so it
cannot commit, publish or acknowledge. If it resumes after a new owner has completed the invocation, it verifies
`handled_generation >= claimed_request_generation` and may acknowledge idempotently; it never writes the newer
generation.

The new owner may repeat a model call only when the invocation/step has no durable completion. If the old worker
committed the step before takeover, the new owner observes that progress and skips the call. If the old commit arrives
after the new claim, the ownership fence rejects it. External model calls are at-least-once: an in-flight call may be
repeated and may incur duplicate provider cost or side effects. Processors must checkpoint durable step results and
must not perform non-idempotent external publication inside the call path. The design does not claim exactly-once model
calls merely because database writes are fenced.

### Acknowledgment and recovery

Completion order is: business commit and intent `handled_generation` update with the ownership fence, then outbox or
broker acknowledgment. Acknowledging first is forbidden.

| Failure | Recovery |
|---|---|
| Worker stops before execution | Lease expires; another worker claims and executes |
| Worker stops during processing | No durable completion; new owner resumes from processor progress |
| Business commit succeeds, ack is lost | Intent already shows `handled_generation >= claimed_request_generation`; the new owner sees completion and acknowledges without republishing |
| Duplicate or stale delivery | Generation comparison makes it a no-op; no cursor regression or duplicate publication |
| Broker disconnect | Outbox remains pending; relay retries with bounded backoff; accepted intent is not lost |
| Poison invocation | Bounded retry/backoff, then quarantine with the intent still pending and observable; unrelated Scopes continue |

A processor that commits in multiple short transactions must expose its own progress so a new owner can continue
without replaying a completed step; the scheduling layer cannot infer domain progress from message delivery.

### Adapters and configuration

One broker-neutral contract defines envelope versions and the operations `publish`, `claim`/visibility, `heartbeat`,
`ack`, `nack`/retry and ownership-loss notification. Adapters normalize transport semantics without promising identical
ordering, partition ownership or visibility. The local adapter is the in-process mailbox and imports no MQ SDK. The
distributed mode is explicit configuration, for example:

~~~dotenv
POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_EXECUTION_MODE=local
# distributed:
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_EXECUTION_MODE=distributed
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_QUEUE_BACKEND=redis-streams
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_QUEUE_URL=...
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_OWNERSHIP_LEASE_SECONDS=60
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_HANDOFF_GRACE_SECONDS=15
~~~

The initial external pair for the design is Redis Streams and NATS JetStream; the first implementation PR may ship the
contract, local adapter and one external adapter, with the second adapter completing the two-backend acceptance. A
different concrete pair may be selected during implementation review without changing the envelope or ownership
contract.
The configuration names above are the proposed surface; implementation review may rename them while keeping the
execution-mode, backend, lease and grace semantics.

### Observability and limits

Deployment backlog is read from durable state: oldest pending age, pending/retry/quarantined counts per binding, and
outbox publication lag. These are shared totals and must not be summed per replica. Each worker also exposes its
node-local running/owned count and worker budget. Existing local-mode queue metrics, schedules, timeouts and Worker
limits keep their meanings. A deployment-wide concurrency limit is enforced by ownership claims; node-local limits
remain node-local and are documented as such.

### Migration and rollout

The outbox and ownership tables are additive. Existing intents, pending work, cursors, generations, schedules and local
mode must remain valid without backfill. The implementation must register the new tables in the supported migration
chain and refresh the managed persistence digest. Distributed mode requires every background worker to run the same
distributed contract; local mode remains unchanged. Mixed-mode operation between local and distributed workers on one
deployment is not supported for the first release. A mode change follows the coordinated shutdown rules in §9, keeps
accepted work and processor progress, and does not reset generations or schedules.

Acceptance must include two real worker nodes processing different Scopes of the same Family against shared OceanBase,
ownership takeover with a late old worker, commit-before-ack, broker publication failure and disconnect, poison retry,
and deployment backlog versus node-local counts. In-process fakes and mocked acknowledgments do not establish real
multi-node or broker acceptance.

## Artifact type first, then Scope

Each scheduling check follows this sequence:
Expand Down
118 changes: 118 additions & 0 deletions docs/zh/rfcs/1515_artifact_processing_supervisor.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,124 @@ Lease、任期和调度循环都按制品拆开:每种已注册制品对应一
OceanBase 的一个逻辑 Supervisor 可以有多个候选实例,但同一时刻只有一个有效 Leader。SQLite 使用单个
Runtime 宿主进程;`dedicated` 在该进程内组织多个 Supervisor,不增加 SQLite 多进程部署能力。

## 分布式消费与所有权交接

分布式消费是可选项。默认的 `all`/`global` 或 `dedicated` Runtime 仍使用单进程、本地内存队列,不引入外部
broker。部署可以显式增加独立伸缩的后台 worker 节点,它们共享持久化存储并消费相同配置的制品族。每个 worker
仍使用自己的本地 Worker 额度和超时;分布式只改变发现和投递,不改变处理器业务规则。

### 可靠交接

`pc_artifact_processing_intents` 仍是已接受工作的权威。推进 `requested_generation` 的同一事务同时写入
`pc_artifact_processing_outbox`:

| 列 | 含义 |
|---|---|
| `task_id` | 一条通知链路的稳定 UUID,消费者据此去重 |
| `binding_name`、`scope_id` | 现有处理键;消息中不携带业务输入 |
| `request_generation` | 本次接受的 generation,不能从 broker 推断 |
| `state`、`available_at`、`attempts`、`lease_expires_at` | 发布重试和可见性状态 |
| `published_at`、`last_error_code` | 业务事务之外的发布证据 |

outbox relay 发布带版本的 envelope,只包含 `task_id`、`(binding_name, scope_id)`、`request_generation` 和
envelope 版本。adapter 接受发布后才写 `published_at`。发布前进程退出,行保持 pending;broker 已接收但
`published_at` 未写,relay 用同一 `task_id` 重发,消费者去重;broker 故障表现为 outbox backlog。发布不产生
第二次已接受调用,也不进入处理器的业务事务。

投递只是提示。claim 时 worker 重新读取 intent,只有 `requested_generation > handled_generation` 才执行;
重复、过期或较旧 generation 的消息都是 no-op。因此 broker 重投不会跳过 pending 工作、回退 cursor 或确认更新的
invocation。

### 按处理键的所有权和 fencing

现有 Supervisor Lease 只用于发现和选主。执行所有权独立,按 `(binding_name, scope_id)` 记录,使同一制品族的不同
Scope 可以在不同节点执行,同时每个键最多只有一个有效 owner:

| 列 | 含义 |
|---|---|
| `binding_name`、`scope_id` | 处理键,联合主键 |
| `holder_id` | 随机 worker/process 身份 |
| `ownership_generation` | 单调递增;每次成功 claim 加一,续租不加 |
| `request_generation` | 本次 owner 认领的 invocation generation |
| `lease_expires_at`、`updated_at` | 数据库时间的租约和最后续租 |

worker 在一个数据库事务内、使用数据库时间 claim:不存在则插入;租约已过期且超过 handoff grace,或
`holder_id` 等于自己续租时更新。grace 覆盖时钟偏差和心跳抖动。成功 claim 增加 `ownership_generation`;普通
续租不增加。

处理器接收 `(binding_name, scope_id, ownership_generation, claimed_request_generation)`。每个推进 cursor、记录
进度、发布制品或完成 intent 的持久化事务,都必须在**同一事务**内校验 holder 和 generation。先读后另开事务写
不构成 fencing。失去所有权的旧 worker 即使仍持有旧消息,也不能推进 cursor、发布或确认更新 generation。

### model call 进行中的交接

错过一次心跳不能推定 worker 已停止。另一个 worker 只有在数据库租约和 handoff grace 都过期后才能 claim。旧
worker 可以跑完 model call,但后续 fence 会失败,不能提交、发布或确认。如果它在新的 owner 已完成 invocation 后
恢复,应校验 `handled_generation >= claimed_request_generation`,最多做幂等确认,不能写入更新的 generation。

新 owner 只有在本次 invocation/step 还没有 durable completion 时才可以重复 model call。若旧 worker 在接管前已
提交该 step,新 owner 应看到进度并跳过。若旧 worker 的提交晚于新 claim,所有权 fence 会拒绝。外部 model call
只能保证 at-least-once:进行中的调用可能被重复,可能产生重复的 provider 费用或副作用。处理器必须持久化 step
结果,且不要在 model call 路径里执行非幂等的外部发布。本设计不会因为数据库写入有 fence 就声称 model call
exactly-once。

### 确认与恢复

完成顺序必须是:带所有权 fence 的业务提交和 intent `handled_generation` 更新,然后才确认 outbox/broker。禁止
先确认后提交。

| 故障 | 恢复 |
|---|---|
| 执行前 worker 退出 | 租约过期,另一个 worker claim 并执行 |
| 处理中退出 | 没有 durable completion;新 owner 从处理器进度继续 |
| 业务提交成功但 ack 丢失 | intent 已显示 `handled_generation >= claimed_request_generation`;新 owner 识别为完成,幂等确认,不重复发布 |
| 重复/过期投递 | generation 比较使其成为 no-op;不回退 cursor,不重复发布 |
| broker 断连 | outbox 保持 pending,relay 有界退避重试;已接受 intent 不丢失 |
| 毒 invocation | 有界重试/退避后 quarantine,intent 仍 pending 且可观测;其他 Scope 继续 |

处理器若用多个短事务提交,必须暴露自己的进度,让新 owner 在已完成 step 之后继续;调度层不能从消息投递推断
领域进度。

### Adapter 与配置

broker-neutral 契约定义 envelope 版本以及 `publish`、`claim`/visibility、`heartbeat`、`ack`、`nack`/retry 和
ownership-loss 通知。adapter 只归一化传输语义,不承诺相同的顺序、分区所有权或可见性。local adapter 是进程内
mailbox,不导入 MQ SDK。分布式模式必须显式配置,例如:

~~~dotenv
POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_EXECUTION_MODE=local
# distributed:
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_EXECUTION_MODE=distributed
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_QUEUE_BACKEND=redis-streams
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_QUEUE_URL=...
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_OWNERSHIP_LEASE_SECONDS=60
# POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_HANDOFF_GRACE_SECONDS=15
~~~

设计阶段建议的首批外部 adapter 为 Redis Streams 和 NATS JetStream;第一个实现 PR 可以先交付契约、local adapter
和一个外部 adapter,第二个外部 adapter 完成双后端验收。实现评审时可以在不改变 envelope 和所有权契约的前提下
选择其他具体后端。
以上配置名是设计建议;实现评审可以重命名,但 execution mode、backend、lease 和 grace 的语义保持不变。

### 可观测性和限额

部署级 backlog 从持久化状态读取:最老 pending 时长、每种 binding 的 pending/retry/quarantined 数量、outbox
发布延迟。这些是共享总量,不能按副本相加。每个 worker 另外暴露节点本地 running/owned 数量和 Worker 额度。
local 模式现有队列指标、周期、超时和 Worker 限额保持原义。部署级并发上限由 ownership claim 保证;
节点本地限额仍是节点本地,并在文档中明确。

### 迁移和滚动升级

outbox 与 ownership 表是增量表。现有 intent、pending 工作、cursor、generation、周期和 local 模式必须无需回填
即可继续有效。实现必须在受支持的 migration 链中注册新表,并刷新 managed persistence digest。distributed 模式
要求所有后台 worker 使用相同的 distributed 契约;local 模式不变。首个版本不支持同一部署中 local 与
distributed worker 混跑。模式切换遵循第 9 节的协调关闭规则,保留已接受工作和处理器进度,不重置 generation
或周期。

验收必须包含两个真实 worker 节点在共享 OceanBase 上并发处理同一制品族的不同 Scope、旧 worker 延迟恢复后的
接管、commit-before-ack、broker 发布失败/断连、毒消息重试,以及部署 backlog 与节点本地计数的区分。进程内 fake
和 mock ack 不能作为真实多节点或 broker 验收。

## 先制品类型,再 Scope

一次调度检查遵循:
Expand Down