Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ English · [简体中文](CHANGELOG.md)

## Unreleased

- Add shared runtime channel ownership, device rebind and coordinated recovery, owned-operation close permits, per-device pacing and failure limits, masked routes and bounded discovery observation. Keep legacy C++ defaults and use the existing Session writer. Add lifecycle, allocation rollback and installed-consumer regression coverage.

- Add logical device handles with owned inboxes, generation-bound submission and retryable endpoint drain on the existing Session writer. Add shared admission domains and opt-in endpoint-local age checks; preserve legacy defaults.

- Add opt-in Session scheduling for SDK bindings: weighted FIFO and separate latest capacity, endpoint FIFO/fair selection, generation/age admission, start-only deadlines, native per-frame pacing and a consecutive-send-failure threshold. Preserve existing signatures and defaults.
- Add atomic conditional latest replacement, endpoint admission/drain gates and value-returning terminal receipt waits. Existing cancellation and throwing waits retain their behavior.
- Add coalesced state-change signals, route-key extraction with original frame preservation, shared claim/RX event ordering and queue/route diagnostics. Document the single-writer integration boundary and add offline regressions; no Python binding or hardware acceptance is included.
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

## 未发布

- 补齐 Runtime 共享连接、设备 rebind 与协调恢复、已登记操作收尾、设备节拍与错误阈值、掩码路由及有界发现观察;复用 Session writer,保留旧 C++ 默认行为,增加生命周期、分配失败回滚及安装消费者回归。

- 新增逻辑设备句柄,拥有独立 inbox、绑定 generation 的发送入口及可重试排空,复用原 Session writer;新增共享准入额度域及可选 endpoint 局部队龄检查,保留旧默认行为。

- 为 SDK 绑定新增可选 Session 调度:FIFO 容量计量与独立 latest 限制、同 endpoint FIFO 和公平选择、generation/年龄准入、开始前 deadline、原生逐帧周期及连续发送失败阈值。保留原有签名和默认值。
- 新增原子的条件 latest 替换、endpoint 准入/排空及返回终态值的回执等待;原取消和抛异常等待接口保持行为。
- 新增可合并状态通知、保留原帧的路由 key 提取、共享领取/RX 事件顺序和队列/路由诊断。说明唯一 writer 接入边界并增加离线回归;不包含 Python 绑定或实机验收。
Expand Down
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ add_library(linkerbot-can STATIC
src/vendor_canfd_transport.cpp
src/vendor_canfd_loader.cpp
src/session.cpp
src/runtime.cpp
src/pcan_transport.cpp
src/pcan_loader.cpp
src/slcan_transport.cpp
Expand Down Expand Up @@ -153,6 +154,7 @@ if(LINKERBOT_TRANSPORT_BUILD_TESTS)
tests/test_session.cpp
tests/test_session_receive_compat.cpp
tests/test_session_tx_compat.cpp
tests/test_transport_runtime.cpp
tests/test_session_tx_edges.cpp
tests/test_session_physical_compat.cpp
tests/test_session_review.cpp
Expand Down
55 changes: 55 additions & 0 deletions docs/en/device-sessions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Logical device sessions

`Session::attach_device(identity, DeviceOptions)` creates a logical device on the existing Session writer. Attach devices before legacy sends or route registration. Raw Session sends are rejected after the first device attaches. Existing Session constructors, default scheduling, receipt methods and deadline policies retain their behavior.

A device binds its endpoint and physical generation to submissions. Callers cannot override these fields. A closed handle stays closed; attaching the same identity creates a new registration. Recovery invalidates previous handles. `channel_instance` distinguishes connections recreated with the same backend generation.

## Shared physical ownership

Include `<linkerbot/transport/runtime.hpp>` to use `TransportRuntime`. Runtime instances in the same linked library share a channel registry and `SharedCANBusPool`. Each channel owns one physical pool lease and one Session; logical devices hold counted leases on that owner.

`open_device(ChannelSpec, DeviceSpec, factory)` requires an explicit configuration fingerprint for backend settings not represented by `CANBusKey`. Reusing a channel requires identical fingerprints and Session scheduling options. The pool also checks incompatible physical modes. Factories execute outside the registry lock; concurrent first opens share initialization, and cyclic initialization is rejected.

Closing one device leaves its peers connected. The last device closes the Session and releases the physical lease. Explicit close failures retain the registration and connection owner for retry. Destructor cleanup is best effort and uses the existing physical lease cleanup mechanism; applications should explicitly close and handle errors.

`recover_channel(key, observed_generation)` coordinates physical recovery. Concurrent callers join an in-progress attempt; successful recovery is reused for an older observed generation. Failed attempts may be retried. Existing handles remain invalid and unfinished work is not replayed. A device registered with `ChannelResetPolicy::kRequireDetach` prevents physical reset until it detaches. This supports SDKs whose recovery requires rebuilding their device state.

`rebind_device(key, previous, replacement, deadline)` pins the connection, closes the old logical registration, and attaches a replacement without reopening the backend. SDK identity checks, cache invalidation and initialization remain the caller's responsibility. This operation does not replace the existing Python hand recovery behavior, which requests physical recovery.

## Admission and scheduling

An `AdmissionDomain` is immutable accounting identity, not another queue. Share a domain object among devices sharing a budget and set it in `DeviceOptions::admission_domain`. FIFO capacity counts batches or frames; latest capacity counts waiting slots. Claimed work does not consume waiting capacity. Both domain and Session limits apply. Failed replacement admission leaves the previous latest job intact. Reusing a domain on separate physical Sessions does not combine their accounting.

`SessionOptions::domain_round_robin` selects an eligible domain by least recent service before ranking its jobs. It is opt-in for mixed deployments. FIFO work retains device ordering. `max_batch_frames` bounds a claimed atomic batch; zero retains the legacy unlimited batch size. Deployment configuration must choose aggregate budgets and batch limits explicitly.

Device pending-age checks default to the device endpoint and include queued, writing and final-cooldown work. `PendingAgeScope::kAdmissionDomain` explicitly checks the shared domain. Legacy Session submissions retain the whole-Session default.

Device `send_period` measures each successful frame from dispatch attempt entry. It disables native batch merging, retains the atomic boundary within a batch, and releases the writer during the final cooldown so another device can send. The same Job remains owned until completion; drain and pending-age accounting include it. Device and legacy Session periods cannot be combined.

`max_consecutive_send_errors` faults only that device. A successful frame resets its streak; peer success does not. Reaching the threshold fails its waiting jobs and closes its inboxes with a fault reason. It does not directly fault the physical Session.

The Python source baselines use a shared hand domain of 256 request batches and 64 latest slots with 50 ms aging, and an arm domain of 2000 frames per arm with a 300 microsecond period and error threshold 10. These values are not new C++ defaults. Applications must provide resolved deployment profiles and provenance before treating them as original-business configuration.

## Deadlines and progress

`DeadlinePolicy::kDispatchStart` records claim, then checks the deadline once at dispatch entry. Expiry produces zero transmitted frames with claim metadata. Once dispatch begins, that queue deadline does not truncate physical lock waiting or the batch suffix. Explicit cancellation and physical failure still apply. Existing `kExecution` and `kStartOnly` retain their previous boundaries. Caller receipt waits have independent deadlines and do not cancel work.

`sent_frames` reports the known backend-accepted prefix. `dispatch_completed_frames` separately exposes the prefix whose pacing has completed. Pending final cooldown may therefore show full physical acceptance with incomplete dispatch progress. Ending final cooldown during close preserves a known dispatched result.

## Device close and owned operations

`begin_operation()` registers thread-bound SDK work before close begins. The move-only `DeviceOperation` permits that owner to submit restoration work after the public device gate closes. It creates no worker or payload queue. Other threads cannot submit through the operation, and its owning thread cannot synchronously close the device while still holding it.

`close_until(deadline)` closes public admission, waits for registered operations, cancels waiting jobs, drains claimed work without truncating it, closes device inboxes, and releases the logical channel lease. Timeout retains the registration for retry. Backend close calls can exceed the waiting deadline. Close itself sends no motion, disable, calibration or brake commands; model-specific restoration remains in the SDK.

## Routes and diagnostics

`subscribe_routes()` owns exact ID/format pairs. `subscribe_rules()` owns masked ID/format ranges, including extended A7 Lite routing. Rules preserve the original frame and record their logical key separately. Overlap is rejected using actual wire ranges, including exact-versus-masked conflicts. Group registration rolls back after allocation failure. Masked routes cannot use the legacy global extractor.

`observe_rules(rules, capacity)` provides bounded read-only discovery observation. It does not take route ownership or ordinary receive-budget slots; a full observer drops its own copy. Normal owners receive their frame first. Discovery requests still use the same device writer. Observation inbox health records its own backlog and drops.

`max_route_keys` bounds registered rules including observations; `max_pending_rx` bounds the ordinary receive backlog. Zero preserves legacy unlimited behavior. Inbox overflow drops the new frame. `compatibility_sequence` increments after matching and before queue offer, so overflow leaves gaps; it resets on physical invalidation. The existing C++ sequence remains unchanged. Device fault reasons are retained by inboxes; legacy inbox close exceptions retain their existing contract.

Channel health includes route count, receive backlog/high-water mark, routed frames, stale frames, registration quota rejections and close drops. Device health reports admission state, generation, instance, registered operations, send-error streak, queued FIFO frames/latest slots, in-flight jobs and oldest owned work.

This transport implementation does not provide Python bindings, Python Future execution, protocol transactions, SDK migration or motor safety policy. Hardware timestamps and arbitrary Python backend plugins are not provided by these APIs. Software tests do not establish hardware or firmware compatibility; deployments need the device/driver/topology acceptance checks described in the migration plan.
53 changes: 53 additions & 0 deletions docs/zh/device-sessions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# 逻辑设备会话

`Session::attach_device(identity, DeviceOptions)` 在既有 Session writer 上注册设备。必须在旧式发送和路由注册前接入;进入设备模式后,原始 Session 发送被拒绝。现有 C++ 构造入口、默认调度、回执等待和截止时间策略保持兼容。

设备句柄为提交绑定独立 endpoint 和物理 generation,调用方不能覆盖。关闭后重新注册同名设备会获得新 endpoint,旧句柄始终关闭。物理恢复使旧句柄失效;`channel_instance` 区分底层 generation 相同但已经重新创建的连接。

## 共享连接与恢复

`<linkerbot/transport/runtime.hpp>` 提供 `TransportRuntime`。同一链接库内的 Runtime 实例共享通道注册表和 `SharedCANBusPool`,每个通道持有一个物理租约和一个 Session,设备持有逻辑租约。

`open_device(ChannelSpec, DeviceSpec, factory)` 要求明确提供配置 fingerprint,覆盖 `CANBusKey` 之外的后端参数。共享连接必须使用一致的 fingerprint 和 Session 调度配置。池同时检查物理模式冲突。factory 在注册表锁外执行;并发首次打开合并初始化,循环等待被拒绝。

关闭一个设备保留其他设备通信;最后一个设备关闭 Session 并释放物理租约。显式关闭失败保留注册和连接所有者,允许重试。析构只尽力清理,底层失败资源沿用物理租约的保留机制。应用应显式关闭并处理异常。

`recover_channel(key, observed_generation)` 协调物理恢复:并发请求复用在途尝试,成功结果按旧 generation 复用,失败后允许再次尝试。旧句柄失效,未完成工作不重放。`ChannelResetPolicy::kRequireDetach` 阻止活跃设备期间的通道重置,适用于需要重建 SDK 状态的设备。

`rebind_device(key, previous, replacement, deadline)` 先保留连接租约,再关闭旧注册并接入替代设备,不重开后端。SDK 仍负责身份核对、缓存失效和初始化。它不替代 Python hand 既有的物理 recover 行为。

## 同一队列内的设备政策

`AdmissionDomain` 是不可变额度身份,不是额外队列。共享预算的设备使用同一个对象,并通过 `DeviceOptions::admission_domain` 绑定。FIFO 可按批次或帧计费,latest 按等待槽计费,claimed 工作不占等待额度。domain 与 Session 限制同时生效。latest 替换准入失败不影响旧任务。跨物理 Session 使用同一 domain 不合并额度。

`domain_round_robin` 为混合通道提供显式跨 domain 轮转,再执行域内排序。设备 FIFO 保持顺序。`max_batch_frames` 限制单个原子批次,零保留旧式不限制行为。部署必须明确给出总容量、批次上限和拓扑。

设备默认队龄检查只包含自身 queued、writing 和最终 cooldown;显式 `kAdmissionDomain` 检查共享额度域。旧 Session 提交保留全 Session 默认作用域。

设备 `send_period` 从每帧 dispatch attempt 入口计时,禁用原生批次合并,批次内部保持原子边界。最终帧 cooldown 释放 writer,使其他设备可发送;同一个 Job 仍由原生层保留,排空和队龄统计继续计入。设备周期不能与旧 Session 周期同时配置。

`max_consecutive_send_errors` 只使相应设备 fault。成功帧清除本设备错误连续计数,邻居发送成功不清除它。达到阈值时终结其等待任务并以 fault 原因关闭 inbox,不直接终止物理 Session。

已核对的 Python 源码基准为:hand 共享 FIFO 256 个请求批次、latest 64 槽、aging 50 ms;arm 每臂 FIFO 2000 帧、成功帧周期 300 μs、错误阈值 10。这些不是新的 C++ 默认值。部署需提供展开配置及来源,才能标记为原始业务配置。

## 时间、进度与关闭

新增 `DeadlinePolicy::kDispatchStart` 先记录 claim,再在 dispatch 入口检查一次截止时间。过期时零帧发送并保留 claim 元数据;开始后不再用该期限截断物理锁等待或发送后缀。取消和物理故障仍生效。旧 `kExecution`、`kStartOnly` 边界不变。调用方等待期限独立,等待超时不取消任务。

`sent_frames` 为已知后端接受前缀,`dispatch_completed_frames` 为完成节拍的前缀。最终 cooldown 中可能已经全部物理发送,但 dispatch 尚未完成。关闭唤醒最终等待时保留已知 dispatched 结果。

SDK 在关闭前用 `begin_operation()` 登记已有工作。可移动的 `DeviceOperation` 绑定创建线程,允许所属工作在公开准入关闭后发送恢复命令,不创建 worker 或载荷队列。其他线程不能借用它发送;持有操作的线程不能同步等待自身关闭。

`close_until(deadline)` 依次关闭公开准入、等待已登记操作、取消等待任务、排空 claimed 批次、关闭设备 inbox、释放逻辑租约。超时保留注册以便重试。底层关闭调用可能超过等待期限。transport 不自动发送运动、失能、标定或抱闸命令;不同型号的收尾规则仍由 SDK 执行。

## 路由、发现与诊断

`subscribe_routes()` 注册精确 ID 和帧格式,`subscribe_rules()` 注册掩码范围,支持 A7 Lite 扩展 ID。始终交付原始帧,逻辑 key 单独记录。按实际 wire 范围拒绝精确与掩码的重叠,整组注册在分配失败后回滚。掩码规则不能与旧全局 extractor 混用。

`observe_rules(rules, capacity)` 提供显式、有界、只读的发现观察。它不占用普通路由所有权或普通接收总容量,原始 owner 优先收到自己的帧;观察流满时仅丢弃其观察副本。发现请求发送仍使用设备的同一 writer。观察 inbox 的容量与丢弃情况通过自身 health 查看。

`max_route_keys` 限制注册规则总数,包含观察规则;`max_pending_rx` 限制普通路由总积压。零保留旧无限制行为。溢出丢弃新帧。`compatibility_sequence` 在匹配后、offer 前递增,因此溢出保留间隙;物理失效后重置。原 C++ sequence 不改变。相同报文的普通交付和观察副本共用原生事件顺序。

通道 health 包含路由数、普通接收积压与高水位、已路由帧、过期帧、额度拒绝和关闭丢弃。设备 health 包含准入、generation、instance、已登记操作、错误连续计数、等待 FIFO 帧/latest 槽、in-flight Job 和最老工作。设备故障原因由 inbox 保留,旧式 inbox 的关闭异常约定不变。

本次不交付 Python 绑定、Future 执行、协议事务、hand/arm SDK 接入或电机安全政策。硬件时间戳和任意 Python 插件后端仍需各自兼容实现。软件 fake 测试不代表实机、固件与驱动已验收;部署继续遵循迁移方案的型号、驱动和拓扑验收要求。
Loading
Loading