OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[feature]:PathLock handoff-adopt 持续续约/ PathLock Leases Refreshed Between Handoff and Adopt

Open baojun-zhang opened this issue 3 months ago • 0 comments

本 issue 为双语版本(英文 + 中文)。中文版在前,英文版在后。 This issue is bilingual (English + Chinese). Chinese version first, English version below.


中文版 / Chinese Version

Problem Statement

当前 Rust PathLockManager 通过后台 refresh loop 自动续约 LeaseRegistry.entries 中的 lease,刷新周期为 lock_expire_secs / 3。lease 只要仍在 registry 中,就会持续刷新 fencing token。

现有异步转交流程为:

to_handoff() -> enqueue(handoff_ref) -> handoff() -> dequeue -> adopt()

其中:

  • to_handoff() 生成可持久化的转交凭证;
  • handoff() 直接调用 LeaseRegistry::remove() 删除 lease;
  • adopt() 根据 handoff_ref 校验 token,并为消费者创建新的 owned lease。

lease 从 registry 删除后,handoff -> adopt 期间没有组件继续刷新 token。若 QueueFS 积压时间超过 lock_expire_secs,其他任务可以将该 token 判定为 stale,清理后获取同一路径的锁。

当前 adopt 失败后的 reacquire 只能保证任务最终继续执行,不能保证 handoff 前后的连续隔离。在原任务重新加锁前,其他任务可能已经修改受保护文件。

该问题影响携带 lock_handoff 的 durable queue 场景,包括:

  • SemanticMsg
  • AddResourceMsg
  • summarizer 后续处理

Proposed Solution

1. 在 LeaseEntry 增加 pending_handoff

struct LeaseEntry {
    lease: PathLockLease,
    ownership_ref: String,
    pending_handoff: bool,
    lock_kinds: HashMap<String, PathLockKind>,
    last_active_at: Instant,
}

字段语义:

pending_handoff 含义 capability 操作 自动续约
false 当前调用方持有 lease ownership_ref 匹配时允许 是
true 消息已入队,等待消费者接管 拒绝旧 ownership_ref 是

所有 owned capability 校验必须同时满足:

!entry.pending_handoff && entry.ownership_ref == ownership_ref

pending_handoff == true 时,lease 仍保留在 registry 中并由 refresh loop 自动续约,但生产者的旧 ownership_ref 不能继续执行 refresh、release、borrow 或受 lease 保护的业务操作。

adopt() 成功后将 pending_handoff 恢复为 false,并覆盖 ownership_ref,使生产者保存的旧值永久失效。

本方案只增加一个布尔字段,不引入额外状态枚举、时间戳或清理字段。

2. 保留现有两步 handoff 调用

调用顺序保持不变:

handoff_ref = pathlock_to_handoff(owned_lease_ref)
await queue.enqueue(message_with(handoff_ref))
await pathlock_handoff(owned_lease_ref)

两个方法继续承担不同职责:

  1. pathlock_to_handoff() 只生成转交凭证,不修改 LeaseEntry。
  2. QueueFS enqueue 成功后,pathlock_handoff() 才将 pending_handoff 设为 true。

这样可以保证消息可靠入队后再交出 lease。若 enqueue 失败,pending_handoff 仍为 false,生产者可按现有逻辑 release,不会产生无人接管的 handoff。

3. 在 PathLockHandoffRef 增加 lease_ref

struct PathLockHandoffRef {
    #[serde(default)]
    lease_ref: Option<String>,
    owner_id: String,
    lock_paths: Vec<String>,
    #[serde(default)]
    covered_paths: Vec<PathLockRequest>,
}

字段用途:

字段 用途
lease_ref 唯一定位原 LeaseEntry
owner_id 校验 fencing token owner
lock_paths 实际锁文件路径,用于读取和刷新 token
covered_paths 原始业务路径及 Exact / Tree 类型,用于覆盖关系校验

handoff_ref 是 owned lease 的降权投影,不包含 ownership_ref,只能用于 adopt(),不能执行 refresh、release 或 handoff。

新生成的 payload 必须携带 lease_ref。Rust 字段使用 Option<String> 是为了兼容历史 QueueFS 消息:

  • QueueFS 默认使用 SQLite,未 ACK 消息会跨重启保留并在启动时恢复;
  • Redis backend 同样会持久化消息;
  • 只有显式使用 memory backend 时,重启才会清空队列。

因此,升级后仍可能消费不含 lease_ref 的旧 lock_handoff,除非发布流程明确要求先 drain 或清空 QueueFS。

4. 修改 handoff() 的内部语义

handoff() 不再从 registry 删除 lease,而是在校验 lease_ref + ownership_ref 后:

  1. 确认 pending_handoff == false;
  2. 将 pending_handoff 设为 true;
  3. 保留 registry entry 和 token 引用;
  4. 由现有 refresh loop 继续续约。

5. adopt() 一次完成接管

接口契约保持不变:

pathlock_adopt(handoff_ref) -> owned_lease_ref

本地快速路径在同一个 registry write guard 内完成:

  1. 通过 handoff_ref.lease_ref 定位 entry;
  2. 校验 owner_id、lock_paths、covered_paths 与 entry 一致;
  3. 校验 pending_handoff == true;
  4. 将 pending_handoff 设为 false;
  5. 生成并写入新的 ownership_ref;
  6. 直接返回新的 OwnedPathLockLease。

消费者不会获得 pending_handoff == true 的 lease,也不需要额外调用。该快速路径只修改进程内 registry,不执行存储层 CAS。

6. 处理 enqueue 与 handoff 的竞态

handoff_ref 在 enqueue 前生成,而 handoff() 在 enqueue 成功后执行。因此消息可能先被消费者取出,此时本地 entry 的 pending_handoff 仍为 false。

adopt() 执行单次检查:

  • pending_handoff == true:立即接管;
  • pending_handoff == false:立即返回 handoff failure;
  • QueueFS 沿用现有错误路径重新入队;
  • 生产者完成 handoff() 后,下一次 adopt() 即可成功。

该处理不在 Rust 内 sleep,也不增加超时或轮询参数。

7. 保留 token fallback

以下情况继续执行现有 token fallback:

  • 历史 payload 没有 lease_ref;
  • 本地 registry 中不存在对应 entry;
  • 进程重启后 registry 已丢失;
  • 消费者与生产者不共享 PathLockManager。

fallback 继续按 owner_id + lock_paths + covered_paths 校验并刷新 token。token 已失效时,维持现有 adopt 失败及上层 reacquire 行为。

正常流程如下:

sequenceDiagram
    participant P as Producer
    participant M as PathLockManager
    participant Q as QueueFS
    participant C as Consumer

    P->>M: acquire()
    M-->>P: owned lease
    P->>M: to_handoff(owned lease)
    M-->>P: handoff_ref
    P->>Q: enqueue(handoff_ref)
    Q-->>P: enqueue success
    P->>M: handoff(owned lease)
    M->>M: pending_handoff = true

    loop lock_expire_secs / 3
        M->>M: refresh token
    end

    Q-->>C: dequeue(handoff_ref)
    C->>M: adopt(handoff_ref)
    M->>M: pending_handoff = false
    M->>M: replace ownership_ref
    M-->>C: owned lease

8. 适用边界

pending_handoff 是 PathLockManager 的进程内字段。本地快速接管要求生产者和消费者共享同一个 PathLockManager。

消费者位于另一进程或实例时,本地 entry 不可见,只能走 token fallback。该路径无法清除生产者进程中的 pending_handoff,因此本方案不提供跨进程无缝接管保证。

实施前需要确认目标 QueueFS handoff 主路径满足同进程前提。进程重启和跨实例场景继续使用现有恢复语义,不保证锁连续性。

Alternatives Considered

  1. 将全局 lock_expire_secs 保持为较大值
  • 可以扩大 handoff 的无续约窗口;
  • 但会让实例崩溃后遗留锁的 stale 清理同样变慢;
  • 不能从根本上解决 handoff 期间无人续约的问题。
  1. 仅依赖 adopt 失败后的 reacquire
  • 可以保证队列任务最终继续执行;
  • 但不能保证 handoff 前后的锁连续性;
  • 其他写任务可能在原任务重新加锁前修改同一路径。

Feature Area

Core (Client/Engine)

Use Case

资源导入或语义处理先在生产者阶段持有 PathLock,再通过 QueueFS 将后续处理交给消费者。即使队列等待超过默认 lock_expire_secs,只要生产者和消费者共享同一个 PathLockManager,锁也应持续续约,避免其他任务在 handoff 期间修改受保护路径。

Additional Context

  • lock_paths 表示底层实际锁文件路径,用于读写 fencing token。
  • covered_paths 表示调用方申请的逻辑业务路径及 Exact / Tree 类型。
  • owned_lease_ref 包含 lifecycle capability ownership_ref。
  • handoff_ref 不包含 ownership_ref,只能用于接管。
  • adopt() 当前已经返回 owned_lease_ref,本方案不改变其外部接口。

Contribution

  • [x] I am willing to contribute to implementing this feature


English Version / 英文版

Problem Statement

The Rust PathLockManager automatically refreshes leases stored in LeaseRegistry.entries every lock_expire_secs / 3. A lease continues to refresh only while its entry remains in the registry.

The current asynchronous transfer flow is:

to_handoff() -> enqueue(handoff_ref) -> handoff() -> dequeue -> adopt()

In this flow:

  • to_handoff() creates a serializable transfer reference;
  • handoff() directly removes the lease through LeaseRegistry::remove();
  • adopt() validates the token from handoff_ref and creates a new owned lease for the consumer.

After the entry is removed, no component refreshes the token between handoff and adopt. If QueueFS backlog exceeds lock_expire_secs, another task may treat the token as stale, remove it, and acquire the same path.

Falling back to reacquire after an adopt failure preserves liveness but not continuous isolation. Another task may modify the protected files before the original task reacquires the lock.

This affects durable queue flows carrying lock_handoff, including:

  • SemanticMsg
  • AddResourceMsg
  • summarizer post-processing

Proposed Solution

1. Add pending_handoff to LeaseEntry

struct LeaseEntry {
    lease: PathLockLease,
    ownership_ref: String,
    pending_handoff: bool,
    lock_kinds: HashMap<String, PathLockKind>,
    last_active_at: Instant,
}

Field semantics:

pending_handoff Meaning Capability operations Auto refresh
false The current caller owns the lease Allowed when ownership_ref matches Yes
true The message is queued and waiting for adoption Reject the old ownership_ref Yes

All owned capability checks must require:

!entry.pending_handoff && entry.ownership_ref == ownership_ref

When pending_handoff == true, the lease remains in the registry and continues to refresh, while the producer's old ownership_ref can no longer perform refresh, release, borrow, or protected business operations.

After a successful adopt(), pending_handoff is reset to false and ownership_ref is replaced, permanently invalidating the producer's old value.

This proposal adds only one boolean field, with no additional state enum, timestamp, or cleanup field.

2. Keep the existing two-step handoff calls

The current call order remains unchanged:

handoff_ref = pathlock_to_handoff(owned_lease_ref)
await queue.enqueue(message_with(handoff_ref))
await pathlock_handoff(owned_lease_ref)

The two methods retain separate responsibilities:

  1. pathlock_to_handoff() only creates the transfer reference and does not modify LeaseEntry.
  2. pathlock_handoff() sets pending_handoff to true only after QueueFS enqueue succeeds.

This ensures that the producer transfers the lease only after the message is durably queued. If enqueue fails, pending_handoff remains false, allowing the producer to release the lease normally.

3. Add lease_ref to PathLockHandoffRef

struct PathLockHandoffRef {
    #[serde(default)]
    lease_ref: Option<String>,
    owner_id: String,
    lock_paths: Vec<String>,
    #[serde(default)]
    covered_paths: Vec<PathLockRequest>,
}

Field purposes:

Field Purpose
lease_ref Uniquely locate the original LeaseEntry
owner_id Validate the fencing token owner
lock_paths Physical lock-file paths used to read and refresh tokens
covered_paths Original business paths and Exact / Tree kinds used for coverage validation

handoff_ref is a reduced-privilege projection of the owned lease. It does not include ownership_ref, can only be used for adopt(), and cannot perform refresh, release, or handoff.

New payloads must include lease_ref. The Rust field remains Option<String> to support historical QueueFS messages:

  • QueueFS uses SQLite by default, and unacknowledged messages survive restarts and are recovered at startup;
  • the Redis backend also persists messages;
  • only the explicit memory backend clears messages on restart.

Therefore, an upgraded deployment may still consume an old lock_handoff without lease_ref, unless rollout explicitly drains or clears QueueFS first.

4. Change the internal behavior of handoff()

Instead of removing the lease from the registry, handoff() validates lease_ref + ownership_ref and then:

  1. verifies that pending_handoff == false;
  2. sets pending_handoff to true;
  3. preserves the registry entry and token references;
  4. lets the existing refresh loop continue renewing the token.

5. Complete adoption in one adopt() call

The external contract remains unchanged:

pathlock_adopt(handoff_ref) -> owned_lease_ref

The local fast path completes under one registry write guard:

  1. locate the entry through handoff_ref.lease_ref;
  2. validate that owner_id, lock_paths, and covered_paths match the entry;
  3. require pending_handoff == true;
  4. set pending_handoff to false;
  5. generate and store a new ownership_ref;
  6. return the new OwnedPathLockLease directly.

The consumer never receives a lease with pending_handoff == true and does not need an additional call. This fast path only mutates the in-process registry and does not perform a storage CAS.

6. Handle the enqueue/handoff race

handoff_ref is created before enqueue, while handoff() runs only after enqueue succeeds. The consumer may therefore dequeue the message while the local entry still has pending_handoff == false.

adopt() performs one check:

  • if pending_handoff == true, adopt immediately;
  • if pending_handoff == false, fail immediately with the existing handoff failure;
  • QueueFS follows the existing error path and re-enqueues the message;
  • after the producer completes handoff(), the next adopt() succeeds.

No sleeping, timeout, or polling configuration is added in Rust.

7. Preserve token fallback

The existing token fallback remains for:

  • historical payloads without lease_ref;
  • missing local registry entries;
  • registry loss after process restart;
  • consumers that do not share the producer's PathLockManager.

The fallback continues to validate and refresh the token using owner_id + lock_paths + covered_paths. If the token has expired, adopt fails and the upper layer keeps the existing reacquire behavior.

Normal flow:

sequenceDiagram
    participant P as Producer
    participant M as PathLockManager
    participant Q as QueueFS
    participant C as Consumer

    P->>M: acquire()
    M-->>P: owned lease
    P->>M: to_handoff(owned lease)
    M-->>P: handoff_ref
    P->>Q: enqueue(handoff_ref)
    Q-->>P: enqueue success
    P->>M: handoff(owned lease)
    M->>M: pending_handoff = true

    loop lock_expire_secs / 3
        M->>M: refresh token
    end

    Q-->>C: dequeue(handoff_ref)
    C->>M: adopt(handoff_ref)
    M->>M: pending_handoff = false
    M->>M: replace ownership_ref
    M-->>C: owned lease

8. Scope and boundaries

pending_handoff is an in-process field of PathLockManager. The local fast path requires the producer and consumer to share the same PathLockManager.

When the consumer runs in another process or instance, the local entry is not visible and only token fallback is available. That path cannot clear pending_handoff in the producer process, so this proposal does not provide seamless cross-process adoption.

Before implementation, the target QueueFS handoff path must be confirmed to satisfy the same-process requirement. Process restart and cross-instance cases continue to use the existing recovery semantics without continuous-lock guarantees.

Alternatives Considered

  1. Keep a large global lock_expire_secs
  • This enlarges the unrefreshed handoff window;
  • but it also delays stale-lock cleanup after an instance crashes;
  • and it does not solve the lack of a refresher during handoff.
  1. Rely only on reacquire after adopt failure
  • This preserves eventual task execution;
  • but it does not preserve lock continuity across handoff;
  • another writer may modify the same path before the original task reacquires it.

Feature Area

Core (Client/Engine)

Use Case

Resource ingestion or semantic processing first holds a PathLock in the producer stage and then transfers follow-up work to a QueueFS consumer. Even when queue wait time exceeds the default lock_expire_secs, the lock should continue refreshing while producer and consumer share the same PathLockManager, preventing another task from modifying the protected path during handoff.

Additional Context

  • lock_paths are the physical lock-file paths used to read and write fencing tokens.
  • covered_paths are the logical business paths and Exact / Tree kinds requested by the caller.
  • owned_lease_ref contains the lifecycle capability ownership_ref.
  • handoff_ref excludes ownership_ref and can only be used for adoption.
  • adopt() already returns owned_lease_ref; this proposal does not change its external API.

Contribution

  • [x] I am willing to contribute to implementing this feature

baojun-zhang avatar Aug 08 '26 04:08 baojun-zhang