diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 28c3643c..00000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,258 +0,0 @@ -name: CI - -on: - push: - branches: [main, master] - pull_request: - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: ci-${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - COMM_REPOSITORY: ${{ vars.LINKERBOT_COMM_REPOSITORY || format('{0}/linkerbot-transport-cpp', github.repository_owner) }} - # Transport v0.3.4 release commit; keep checkout instructions in sync. - COMM_REF: 0e190032d65ed0b315337b45b3779cf4f650ed68 - -jobs: - build-and-test: - name: GCC 13 / ${{ matrix.build_type }} - runs-on: ubuntu-24.04 - timeout-minutes: 30 - env: - CC: gcc-13 - CXX: g++-13 - strategy: - fail-fast: false - matrix: - build_type: [Debug, Release] - - steps: - - name: Set offline configuration directory - run: echo "XDG_CONFIG_HOME=${RUNNER_TEMP}/xdg-config" >> "$GITHUB_ENV" - - - name: Check out hand SDK - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: hand-cpp - - - name: Check documentation and analysis helpers - working-directory: hand-cpp - run: | - python3 validation/check_docs.py - python3 -m unittest discover -s validation -p 'test_quality_tools.py' - python3 -m unittest discover -s validation -p 'test_transport_provider.py' - python3 -m unittest discover -s validation -p 'test_release*.py' - - - name: Check out communication library - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: ${{ env.COMM_REPOSITORY }} - ref: ${{ env.COMM_REF }} - path: linkerbot-transport-cpp - token: ${{ secrets.LINKERBOT_COMM_TOKEN || github.token }} - - - name: Install build tools - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends \ - cmake ninja-build gcc-13 g++-13 python3 - - - name: Configure - working-directory: hand-cpp - run: | - cmake -S . -B build -G Ninja \ - -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \ - -DCMAKE_INSTALL_PREFIX="${RUNNER_TEMP}/linkerbot-sdk" \ - -DLINKERBOT_COMM_SOURCE_DIR="${GITHUB_WORKSPACE}/linkerbot-transport-cpp" \ - -DLINKERBOT_BUILD_EXAMPLES=OFF \ - -DLINKERBOT_BUILD_TESTS=ON \ - -DLINKERBOT_BUILD_TOOLS=ON \ - -DLINKERBOT_COMM_BUILD_TESTS=OFF - - - name: Build SDK and offline test targets - working-directory: hand-cpp - run: | - cmake --build build --parallel 4 --target \ - linkerbot-cpp-sdk l6_read_version l6_frequency_benchmark \ - tests protocol-tests - - - name: Run offline tests - working-directory: hand-cpp - run: ctest --test-dir build --output-on-failure --timeout 120 - - - name: Check protocol boundaries - if: matrix.build_type == 'Release' - working-directory: hand-cpp - run: | - python3 validation/check_protocol_boundary.py \ - --source . \ - --comm-include "${GITHUB_WORKSPACE}/linkerbot-transport-cpp/include" \ - --compiler g++-13 - python3 validation/l6/check_boundary.py \ - --comm-include "${GITHUB_WORKSPACE}/linkerbot-transport-cpp/include" \ - --compiler g++-13 - - - name: Install SDK for public header checks - if: matrix.build_type == 'Release' && github.event_name != 'pull_request' - working-directory: hand-cpp - run: | - cmake --build build --parallel 4 - cmake --install build - - - name: Check installed public headers - if: matrix.build_type == 'Release' && github.event_name != 'pull_request' - working-directory: hand-cpp - run: | - python3 validation/check_headers.py \ - --include "${RUNNER_TEMP}/linkerbot-sdk/include" \ - --compiler g++-13 \ - --jobs 4 \ - --output "${RUNNER_TEMP}/header-check.json" - - - name: Compile documented asynchronous examples - if: matrix.build_type == 'Release' && github.event_name != 'pull_request' - working-directory: hand-cpp - run: | - python3 validation/check_documented_examples.py \ - --prefix "${RUNNER_TEMP}/linkerbot-sdk" \ - --build-dir build-documented-examples - - - name: Check package and source dependency versions - if: matrix.build_type == 'Release' && github.event_name != 'pull_request' - working-directory: hand-cpp/build - run: | - cmake -DHAND_PREFIX="${RUNNER_TEMP}/linkerbot-sdk" \ - -P ../validation/check_package_compatibility.cmake - - - name: Build and run installed consumer without optional drivers - if: matrix.build_type == 'Release' && github.event_name != 'pull_request' - working-directory: hand-cpp - run: | - cmake -S validation/installed-consumer \ - -B build-installed-consumer -G Ninja \ - -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_PREFIX_PATH="${RUNNER_TEMP}/linkerbot-sdk" - cmake --build build-installed-consumer --parallel 4 - ctest --test-dir build-installed-consumer \ - --output-on-failure --timeout 120 - - windows-discovery: - name: Windows x64 / ${{ matrix.configuration }} - runs-on: windows-2022 - timeout-minutes: 50 - strategy: - fail-fast: false - matrix: - configuration: [Debug, Release] - defaults: - run: - shell: pwsh - env: - PYTHONUTF8: '1' - - steps: - - name: Check out hand SDK - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: hand-cpp - - - name: Check out fixed communication library - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: ${{ env.COMM_REPOSITORY }} - ref: ${{ env.COMM_REF }} - path: linkerbot-transport-cpp - token: ${{ secrets.LINKERBOT_COMM_TOKEN || github.token }} - - - name: Install fixed CMake and record Windows tools - run: ./hand-cpp/validation/setup_windows.ps1 - - # Both suites share these build trees. PRs stop after tests; pushes to the - # main branch retain full installation and release-package acceptance. - - name: Check transport selection including Windows source paths - run: python -m unittest discover -s hand-cpp/validation -p 'test_transport_provider.py' - - - name: Build once and validate both test suites - run: | - $QuickArgs = @() - if ('${{ github.event_name }}' -eq 'pull_request') { $QuickArgs += '--quick' } - python hand-cpp/validation/run_release_validation.py ` - --comm-source linkerbot-transport-cpp ` - --work-dir "${{ runner.temp }}/windows-${{ matrix.configuration }}" ` - --config ${{ matrix.configuration }} --suite all ` - --generator 'Visual Studio 17 2022' --architecture x64 --toolset 'v143,version=14.44' ` - --comm-sha '${{ env.COMM_REF }}' --hand-sha '${{ github.sha }}' --allow-downloads @QuickArgs - if ($LASTEXITCODE -ne 0) { throw 'Windows release validation failed' } - - - name: Save build, test, consumer and package evidence - if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: windows-x64-${{ matrix.configuration }} - if-no-files-found: error - path: | - ${{ runner.temp }}/windows-${{ matrix.configuration }}/evidence/ - ${{ runner.temp }}/windows-${{ matrix.configuration }}/packages/*/*.zip - ${{ runner.temp }}/windows-${{ matrix.configuration }}/packages/*/*.sha256 - - sanitizers: - name: ASan and UBSan - runs-on: ubuntu-24.04 - timeout-minutes: 30 - env: - CC: gcc-13 - CXX: g++-13 - ASAN_OPTIONS: detect_leaks=0:halt_on_error=1:strict_string_checks=1 - UBSAN_OPTIONS: print_stacktrace=1:halt_on_error=1 - - steps: - - name: Set offline configuration directory - run: echo "XDG_CONFIG_HOME=${RUNNER_TEMP}/xdg-config" >> "$GITHUB_ENV" - - - name: Check out hand SDK - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: hand-cpp - - - name: Check out communication library - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: ${{ env.COMM_REPOSITORY }} - ref: ${{ env.COMM_REF }} - path: linkerbot-transport-cpp - token: ${{ secrets.LINKERBOT_COMM_TOKEN || github.token }} - - - name: Install build tools - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends \ - cmake ninja-build gcc-13 g++-13 - - - name: Configure sanitizer build - working-directory: hand-cpp - run: | - cmake -S . -B build-sanitized -G Ninja \ - -DCMAKE_BUILD_TYPE=Debug \ - -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" \ - -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" \ - -DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=address,undefined" \ - -DLINKERBOT_COMM_SOURCE_DIR="${GITHUB_WORKSPACE}/linkerbot-transport-cpp" \ - -DLINKERBOT_BUILD_EXAMPLES=OFF \ - -DLINKERBOT_BUILD_TESTS=ON \ - -DLINKERBOT_BUILD_TOOLS=ON \ - -DLINKERBOT_COMM_BUILD_TESTS=OFF - - - name: Build sanitizer test targets - working-directory: hand-cpp - run: | - cmake --build build-sanitized --parallel 4 --target \ - tests protocol-tests l6_read_version l6_frequency_benchmark - - - name: Run sanitizer tests - working-directory: hand-cpp - run: ctest --test-dir build-sanitized --output-on-failure --timeout 180 diff --git a/.github/workflows/release-packages.yml b/.github/workflows/release-packages.yml index 58f88877..3f131552 100644 --- a/.github/workflows/release-packages.yml +++ b/.github/workflows/release-packages.yml @@ -4,7 +4,7 @@ name: Release packages pull_request: paths: - '.github/workflows/release-packages.yml' - - '.github/workflows/ci.yml' + - '.github/workflows/sanitizers.yml' - 'CMakeLists.txt' - 'cmake/**' - 'src/**' @@ -26,7 +26,7 @@ name: Release packages expected_version: description: 'Hand SDK version (transport may use a compatible newer patch)' required: true - default: '0.3.11' + default: '0.3.12' permissions: contents: read diff --git a/.github/workflows/sanitizers.yml b/.github/workflows/sanitizers.yml new file mode 100644 index 00000000..26e920c0 --- /dev/null +++ b/.github/workflows/sanitizers.yml @@ -0,0 +1,119 @@ +name: Sanitizers + +on: + push: + branches: [main, master] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + COMM_REPOSITORY: ${{ vars.LINKERBOT_COMM_REPOSITORY || format('{0}/linkerbot-transport-cpp', github.repository_owner) }} + # Transport v0.3.4 release commit; keep checkout instructions in sync. + COMM_REF: 0e190032d65ed0b315337b45b3779cf4f650ed68 + +jobs: + validation: + name: Validation + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - name: Check out hand SDK + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: hand-cpp + + - name: Check documentation and analysis helpers + working-directory: hand-cpp + run: | + python3 validation/check_docs.py + python3 -m unittest discover -s validation -p 'test_quality_tools.py' + python3 -m unittest discover -s validation -p 'test_transport_provider.py' + python3 -m unittest discover -s validation -p 'test_release*.py' + + - name: Check out communication library + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ env.COMM_REPOSITORY }} + ref: ${{ env.COMM_REF }} + path: linkerbot-transport-cpp + token: ${{ secrets.LINKERBOT_COMM_TOKEN || github.token }} + + - name: Install boundary check compiler + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends g++-13 + + - name: Check protocol boundaries + working-directory: hand-cpp + run: | + python3 validation/check_protocol_boundary.py \ + --source . \ + --comm-include "${GITHUB_WORKSPACE}/linkerbot-transport-cpp/include" \ + --compiler g++-13 + python3 validation/l6/check_boundary.py \ + --comm-include "${GITHUB_WORKSPACE}/linkerbot-transport-cpp/include" \ + --compiler g++-13 + + sanitizers: + name: ASan and UBSan + runs-on: ubuntu-24.04 + timeout-minutes: 30 + env: + CC: gcc-13 + CXX: g++-13 + ASAN_OPTIONS: detect_leaks=0:halt_on_error=1:strict_string_checks=1 + UBSAN_OPTIONS: print_stacktrace=1:halt_on_error=1 + + steps: + - name: Set offline configuration directory + run: echo "XDG_CONFIG_HOME=${RUNNER_TEMP}/xdg-config" >> "$GITHUB_ENV" + + - name: Check out hand SDK + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: hand-cpp + + - name: Check out communication library + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ env.COMM_REPOSITORY }} + ref: ${{ env.COMM_REF }} + path: linkerbot-transport-cpp + token: ${{ secrets.LINKERBOT_COMM_TOKEN || github.token }} + + - name: Install build tools + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + cmake ninja-build gcc-13 g++-13 + + - name: Configure sanitizer build + working-directory: hand-cpp + run: | + cmake -S . -B build-sanitized -G Ninja \ + -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" \ + -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" \ + -DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=address,undefined" \ + -DLINKERBOT_COMM_SOURCE_DIR="${GITHUB_WORKSPACE}/linkerbot-transport-cpp" \ + -DLINKERBOT_BUILD_EXAMPLES=OFF \ + -DLINKERBOT_BUILD_TESTS=ON \ + -DLINKERBOT_BUILD_TOOLS=ON \ + -DLINKERBOT_COMM_BUILD_TESTS=OFF + + - name: Build sanitizer test targets + working-directory: hand-cpp + run: | + cmake --build build-sanitized --parallel 4 --target \ + tests protocol-tests l6_read_version l6_frequency_benchmark + + - name: Run sanitizer tests + working-directory: hand-cpp + run: ctest --test-dir build-sanitized --output-on-failure --timeout 180 diff --git a/CHANGELOG.md b/CHANGELOG.md index db580a85..2f8e375c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ [English](CHANGELOG.md) | [简体中文](CHANGELOG.zh-CN.md) +## 0.3.12 + +- Schedule angle commands and queries at complete tactile-stage boundaries under explicit `RuntimeBehavior::kPython`, covering Classic L6/O6/L20Lite/L20 and O30 HOP V25. L30 retains its existing no-yield behavior. +- Align query-only, command-feedback-only and adaptive sampling; preserve active-reader coalescing and pending-target replacement. Limit each boundary to four logical angle transactions, alternate ready work and retain finite execution deadlines. +- Add regressions for incomplete stages, continuous load, nested failures, timeouts, polling changes, close/reopen, recovery and shared-Session isolation. Preserve public C++ APIs, Native defaults, the existing sender and transport v0.3.4 minimum; exclude O20 and hand/arm integration. +- Read the runtime connection generation directly after unified telemetry reads, avoiding full diagnostic-report construction while preserving explicit health reports. +- Record revision-specific O6, L20 and O30 scheduling hardware results and untested topologies/fault timing. See [release notes](RELEASE_NOTES.md#0312). + ## 0.3.11 - Release L20 dispatch-only write reply reservations under the explicit Python policy. diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index fac9249c..eaa57b0a 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -2,6 +2,14 @@ [English](CHANGELOG.md) | [简体中文](CHANGELOG.zh-CN.md) +## 0.3.12 + +- 显式 `RuntimeBehavior::kPython` 下,在完整触觉阶段边界调度角度命令和查询,覆盖 Classic L6/O6/L20Lite/L20 与 O30 HOP V25;L30 保留原有不让出行为。 +- 对齐独立查询、仅命令反馈和自适应采样,保留主动读取合并及待执行目标替换;每边界最多四个逻辑角度事务,就绪任务交替服务,保留有限执行总期限。 +- 增加不完整阶段、持续负载、嵌套失败、超时、轮询变更、关闭重开、恢复及共享 Session 隔离回归。保持公开 C++ API、Native 默认值、既有发送器及 transport v0.3.4 最低依赖,不涉及 O20 或 hand/arm 接入。 +- 统一遥测读取完成后直接读取运行时连接编号,避免构建完整诊断报告;显式健康报告保持原有行为。 +- 记录固定源码版本的 O6、L20 和 O30 调度实机结果,以及未测拓扑和故障时序。见[发行说明](RELEASE_NOTES.md#0312)。 + ## 0.3.11 - 显式 Python 策略下,L20 仅发送写入不再保留可选回复及读取匹配资源。 diff --git a/CMakeLists.txt b/CMakeLists.txt index f60942b8..9ec43cf3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.16) project(linkerbot-hand-cpp - VERSION 0.3.11 + VERSION 0.3.12 DESCRIPTION "LinkerBot dexterous hand C++ SDK" LANGUAGES CXX ) diff --git a/README.en.md b/README.en.md index 5e1b1f37..fa986c98 100644 --- a/README.en.md +++ b/README.en.md @@ -38,7 +38,7 @@ The validated Linux baseline is Ubuntu 24.04 / GCC 13. ### 1. Get and build the SDK Keep both repositories in the same parent directory. The transport revision below matches CI. -Use paired `0.3.x` versions; the transport version must be at least the hand SDK version. +The SDK versions are independent: hand 0.3.12 requires transport `0.3.x` at version 0.3.4 or newer. ```bash mkdir sdk-build && cd sdk-build @@ -60,7 +60,7 @@ This installs the SDK and communication library into the local `install/` direct Catch2 and vendor development packages are not required. Run the remaining commands from this repository's root directory. -Hand SDK 0.3.11 requires transport 0.3.4 or newer in the 0.3 minor line, +Hand SDK 0.3.12 requires transport 0.3.4 or newer in the 0.3 minor line, for source builds, prebuilt packages and installed consumers. To reuse a prebuilt transport v0.3.4 SDK, configure with diff --git a/README.md b/README.md index 5e1b1f37..fa986c98 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ The validated Linux baseline is Ubuntu 24.04 / GCC 13. ### 1. Get and build the SDK Keep both repositories in the same parent directory. The transport revision below matches CI. -Use paired `0.3.x` versions; the transport version must be at least the hand SDK version. +The SDK versions are independent: hand 0.3.12 requires transport `0.3.x` at version 0.3.4 or newer. ```bash mkdir sdk-build && cd sdk-build @@ -60,7 +60,7 @@ This installs the SDK and communication library into the local `install/` direct Catch2 and vendor development packages are not required. Run the remaining commands from this repository's root directory. -Hand SDK 0.3.11 requires transport 0.3.4 or newer in the 0.3 minor line, +Hand SDK 0.3.12 requires transport 0.3.4 or newer in the 0.3 minor line, for source builds, prebuilt packages and installed consumers. To reuse a prebuilt transport v0.3.4 SDK, configure with diff --git a/README.zh-CN.md b/README.zh-CN.md index 44748ec2..3970976c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -34,8 +34,8 @@ L6 默认使用 Classic CAN;支持 CAN FD 的设备可显式选择[可选 HOP ### 1. 获取并构建 -两个仓库放在同一级目录。transport 使用与当前 CI 一致的提交;两库须配套使用 -`0.3.x`,transport 版本不得低于 hand 版本。 +两个仓库放在同一级目录。transport 使用与当前 CI 一致的提交;两库版本独立, +hand 0.3.12 要求 transport `0.3.x` 且不低于 0.3.4。 ```bash mkdir sdk-build && cd sdk-build @@ -56,7 +56,7 @@ cmake --install build --prefix "$PWD/install" 这会将 SDK 和配套通信库安装到当前目录的 `install/`,不需要 Catch2 或厂商开发包。 后续命令均从 `linkerbot-hand-cpp` 源码根目录执行。 -hand SDK 0.3.4 的源码、预构建及安装消费者均要求 transport 0.3.x 且不低于 0.3.4。 +hand SDK 0.3.12 的源码、预构建及安装消费者均要求 transport 0.3.x 且不低于 0.3.4。 也可直接使用 transport v0.3.4 的预构建 SDK,省去 transport 编译; 使用 `cmake --preset prebuilt -DLINKERBOT_COMM_PREBUILT_PREFIX=/absolute/path/to/comm-sdk`。 diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index eac56106..84fd4a27 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,5 +1,83 @@ # Release notes +## 0.3.12 + +This patch extends the explicit Python runtime policy with angle scheduling at safe +tactile-stage boundaries and removes full health-report construction from unified +telemetry read completion. It builds on v0.3.11. + +### Behavior and compatibility + +- Under explicit `RuntimeBehavior::kPython`, service angle commands and queries between complete tactile protocol stages. Classic L6/O6/L20Lite/L20 yield between complete fingers; O30 HOP 0.0.4 with explicit V25 yields between complete sensor transactions. Never insert into incomplete rows, reply fragments or a multi-frame angle batch. L30 retains its no-yield behavior; L6 HOP and O30 Mounted V36 remain unsupported by this policy. +- Apply query-only, command-feedback-only and adaptive polling rules to the inserted work. Preserve active reads, read coalescing, latest-target replacement, actual-state feedback validation and plan-specific counters. +- Limit each boundary to four logical angle transactions. Alternate ready commands and queries except when eligible command feedback can satisfy polling demand. Preserve a fixed wait horizon, finite recovery deadlines and each stage's response window. The bound and existing operation arbitration provide progress under continuous demand, not hard real-time guarantees. +- Keep inner protocol/response failures local while the connection remains valid. Transport failure, close or invalid connection generation aborts later stages. Preserve complete cached evidence, real dispatch results, bounded shutdown, old-work isolation and no motion replay after recovery. Add nested lifecycle and shared-Session isolation regressions. +- After unified telemetry reads, obtain the runtime connection generation without constructing a full health report. Explicit `get_health()` still computes the complete diagnostic report; statistics collection and generation handling remain in place. This optimization also applies to the existing Native read path. + +Public C++ APIs, enum values and Native scheduling/defaults remain compatible. All +physical sends use the existing Session writer; no send queue is added. O20, Python +bindings, automatic reconnect and hand/arm integration are outside this update. +The minimum and paired transport remain v0.3.4 +(`0e190032d65ed0b315337b45b3779cf4f650ed68`). Rebuild the SDK and consumers with matching +headers and libraries. Details are in the [Python behavior baseline](docs/en/guides/python-behavior-baseline.md#tactile-stage-angle-scheduling-0312). + +### Recorded local validation + +| Evidence | Recorded result / revision scope | +| --- | --- | +| Tactile-stage regressions | 24 cases, 453 assertions passed on the source later committed as `05bc5b0`; covers the applicable models, all policies, bounds, fairness, failures, lifecycle and shared-Session isolation | +| Regression after the generation-read optimization | Release CTest 20/20 and Debug ASan+UBSan 10/10 passed on `05bc5b0` plus the patch now committed as `74aeceb` | +| macOS arm64 / AppleClang 21 / C++17 release validation | SOURCE/PREBUILT, installed/extracted consumers, public headers, documentation examples and ZIP audits passed before the performance patch; this is not final release-matrix evidence | +| O6 performance diagnosis | Before/after 10-second tight-loop reads: unified Native 965.03 to 1512.64 Hz; explicit Python 909.42 to 1448.92 Hz. These are diagnosis points, not sustained frequency limits | + +These records describe the tested implementation revisions and local configurations. +They do not certify other platforms or the final release artifacts. The +[release guide](docs/en/guides/releases.md) describes the Report Card and twelve-target +package gates; CI and artifact verification provide release-level evidence. + +### Hardware scope, 2026-11-12 to 2026-11-13 + +All three devices were tested separately on Ubuntu 24.04 x86_64, Linux SocketCAN, +Release builds and transport v0.3.4. Control commands repeated the initial measured +pose; no movement trajectory or mechanical tracking accuracy was tested. + +| Device | Identity and connection | Tactile sample | Saturation result | +| --- | --- | --- | --- | +| O6 left | ID `0x28`; firmware V1.3.2, hardware V0.0.3; PCAN USB / `pcan_usb`, Classic 1 Mbps | Five 10×4 matrices, 200 bytes | 300.02 s, 12,349 complete acquisitions, maximum four inserted angle transactions per boundary | +| L20 right | ID `0x27`; firmware V3.0.6, hardware V4.0.1; PCAN USB / `pcan_usb`, Classic 1 Mbps | Five 12×6 matrices, 360 bytes | 300.057 s, 2,126 complete acquisitions, maximum four inserted transactions; each angle batch contains five frames | +| O30 right, V25 in all modes | Request/reply `0x001` / `0x401`; firmware 1.1.0, hardware V0.9.0, HOP 0.0.4; `gs_usb`, FD 1/5 Mbps without BRS | Five TSSP_JZG sensors, each 72 bytes with a 10×7 tactile matrix | 300.141 s, 733 complete acquisitions, maximum four inserted angle transactions per boundary | + +Each device also passed query-only, command-feedback-only and adaptive groups of +30 seconds each, plus a 30-second Native control. Each of those groups completed +300 tactile acquisitions. Command-feedback-only generated no independent angle +queries; adaptive resumed queries after commands stopped. Native inserted no angle +sends within a tactile acquisition. Python framing/completion checks, tactile +integrity and continuing progress passed, with zero recorded API errors, protocol +violations or capture drops. Native retains dispatch semantics; Python's single +outstanding angle-response rule was not imposed on it. + +**The five O30 scheduling hardware groups passed.** The tested path reads each +72-byte sensor payload through separate range requests; every observed HOP request +received one reply frame. Separate offline regressions cover multi-reply reassembly, +including a 72-byte object returned as 61+11 bytes, out-of-order fragments and +conflicting duplicates. Multi-reply reassembly coverage is offline; the physical +firmware exercised single-frame replies for each individual range request. + +O6 used clean `05bc5b07bce9cebd937c9f791b6e6c3ec2f305f2`. L20/O30 used that commit +plus the generation-read patch, SHA256 +`dfdd98b1384e0a3ad762ce717b5f5941f1f8a7ecf18e65f79df545f414fa51b4`. +The patch has been checked byte-for-byte against the `05bc5b0..74aeceb` diff, so those +two runs exercised the implementation now committed as `74aeceb`. They were not new +runs of a release tag or PR merge commit. Detailed reports, programs and raw evidence +remain in the development workspace's separate `benchmark/` archive (`results/`, +`l20-stage/` and `o30-stage/`); this repository contains the scope summary, not the captures. + +Hardware validation limits: + +- No new L6/L20Lite scheduling hardware acceptance; L6 identity discovery alone is not scheduling acceptance. +- No physical shared-Session multi-device acceptance, multi-device sustained run, close/recovery or injected malformed/missing/late-response timing tests. The current two-hand setup uses separate CAN interfaces. Offline regressions do not substitute for these hardware cases. +- Host receive timestamps are not hardware timestamps. These scheduling runs establish neither frequency maxima, dynamic motion accuracy, other firmware/driver combinations nor Windows hardware behavior. Active raw SocketCAN benchmarking was excluded; observation was passive. + ## 0.3.11 - Under the explicit Python runtime policy, L20 speed, current-limit and fault-clear writes end at physical dispatch without retaining Native optional reply decoders or read-key reservations. Subsequent reads do not wait for an unused reply window. diff --git a/docs/en/connections/prepare-interface.md b/docs/en/connections/prepare-interface.md index 7f067fec..102766d8 100644 --- a/docs/en/connections/prepare-interface.md +++ b/docs/en/connections/prepare-interface.md @@ -5,7 +5,7 @@ This guide is for the C++ SDK. Build and install the SDK first, then prepare the ## Build and link prerequisites You need a C++17 compiler, CMake 3.16+, and a `linkerbot-transport-cpp` version compatible with the hand SDK. -Use compatible `0.3.x` versions of hand and transport; the transport version must not be older than the hand version. +Hand and transport versions are independent. Hand 0.3.12 requires transport `0.3.x` at version 0.3.4 or newer. For build and installation steps, see the [Project quick start](../../../README.md); for Windows, see the [Windows guide](../guides/windows.md). Save a complete program from this directory as your application's `main.cpp`. After installing the SDK, use this minimal `CMakeLists.txt`: diff --git a/docs/en/guides/python-behavior-baseline.md b/docs/en/guides/python-behavior-baseline.md index d5050899..652f8f77 100644 --- a/docs/en/guides/python-behavior-baseline.md +++ b/docs/en/guides/python-behavior-baseline.md @@ -1,10 +1,107 @@ # Python behavior baseline +[中文](../../zh/guides/python-behavior-baseline.md) · [Documentation index](../README.md) + The reference source is `linkerbot-hand-python-sdk` commit `3a63e723b9a0046e9a60a58339b9f064ef5b70fd` (source version 2.0.0). This document records native SDK preparation for a future Python migration. -It does not claim that a Python binding, a hand/arm migration, or hardware -acceptance has been completed. O20 is outside this change. +A Python binding and hand/arm integration remain outside this change, as does O20. +The 0.3.12 scheduling update has limited hardware evidence documented in the +[release notes](../../../RELEASE_NOTES.md#0312); earlier batches retain their original validation scope. + +## Tactile-stage angle scheduling (0.3.12) + +This update builds on v0.3.11 and the pinned Python actor/transaction-runner behavior. +Only explicit `RuntimeBehavior::kPython` enables the new stage scheduler. Existing +public C++ APIs, enum values and Native defaults remain available. The minimum and +paired transport remain v0.3.4. Rebuild the SDK and downstream consumers with matching +headers and libraries. This is a behavior comparison, not complete cross-language equivalence. + +### Protocol boundaries + +| Model / protocol | Eligible boundary | Must remain uninterrupted | +| --- | --- | --- | +| L6 / O6 Classic | After a complete finger response, before the next finger request; four boundaries per acquisition | All rows of the current finger, including duplicate/conflict validation | +| L20Lite / L20 Classic | The same complete-finger boundary; Python reads fingers sequentially and publishes only the complete hand | Current finger assembly and each multi-frame angle batch; Native retains its existing request pattern | +| O30 HOP 0.0.4, explicit `O30Layout::kPythonV25` | After a complete sensor-selection echo, metadata read or sensor-data range, when a subsequent tactile stage exists | Every reply fragment covering the current HOP request; no insertion before the first request or after the final stage | +| L30 | No new yield boundary: the pinned Python tactile transaction does not enable yielding | Existing tactile operation | +| L6 HOP / O30 Mounted V36 | Not supported by the explicit Python policy; existing validation rejects these combinations | No new scheduling contract | + +An idle gap between frames is not a safe boundary. Missing rows, conflicting payloads +and incomplete HOP ranges cannot trigger angle insertion or publish a partial hand. +Classic L6/L20Lite/L20 require 12 rows of 6 values per finger; O6 requires 10 rows of 4. + +### Feedback, ordering and bounds + +| Angle polling policy | Behavior at an eligible boundary | +| --- | --- | +| `kQueryOnly` | Serve due queries; command feedback does not postpone the query deadline | +| `kCommandFeedbackOnly` | Use verified actual-state command feedback; do not create a poll query or resend a target to obtain feedback | +| `kAdaptive` | Reuse sufficiently fresh actual-state command feedback, otherwise serve the due query | + +Explicit angle getters remain active demand under every polling policy. Only feedback +declared to contain measured state can satisfy polling; target echoes and successful +physical sends are not measurements. O30 V25 declares its complete angle write response +as actual state; the Mounted V36 declaration is unchanged. + +Each eligible boundary permits at most **four logical angle transactions**, including +ordinary failed attempts. A multi-frame angle batch counts once and remains atomic. +New arrivals and target replacement do not reset the count; the next boundary does. +Pending commands retain the existing latest-target replacement and receipt semantics. + +An eligible command may run first when its actual-state feedback can satisfy pending +or due polling demand under the selected policy. Otherwise, simultaneously ready +commands and queries alternate, retaining the preference across boundaries. Queries +join the existing ReadCoordinator and coalesce with active readers. Removing poll-only +demand does not cancel those readers. A boundary may wait for an already-queued command +due within the next stage's estimate; its wait horizon does not grow with new arrivals. + +The next-stage estimates are L6 11 ms, O6 2.4 ms, L20Lite/L20 4 ms and O30 3 ms. +For a finite recovery execution deadline, insertion requires strictly more remaining +time than that estimate; equality or insufficient time continues tactile work. The +deadline is never restarted. Ordinary getter caller waits remain independent of the +shared operation; each protocol stage retains its response window starting after +physical dispatch. Estimates are admission checks, not worst-case timing guarantees. + +The four-transaction bound lets tactile work progress during continuous angle demand. +The existing execution gate continues to arbitrate between complete operations so +other reads and commands can progress. Stage work borrows the current device's logical +execution lease, without recursively acquiring it. All sends use the existing Session +writer; no additional send queue or physical writer is added. Waiting for replies does +not hold the physical send lock. This does not establish a hard real-time latency bound. + +### Failure, lifecycle and device isolation + +An inner angle protocol error or response timeout completes that inner task with its +own failure; tactile work can continue while the connection remains valid, matching +the Python reference. A transport error, closure or invalid connection generation +stops later stages and fails the outer operation. A failed acquisition never replaces +the previous complete tactile evidence with partial data; closed/faulted retained +snapshots still follow the existing unavailable-metadata contract. + +Missing or malformed optional command feedback does not rewrite a real physical +`Dispatched` result as an unsent command. Logical success/latency accounting remains +separate from dispatch and does not count an unsuccessful inner task as successful. +Caller wait timeouts do not cancel shared work or duplicate completion statistics. + +Stopping polling removes poll intent while preserving coalesced active readers. +Replacing a plan fences old-plan counters without discarding a successful underlying +sample. Close stops later stage admission and releases waiters while retaining the +real result of an already-claimed physical batch. Recovery/reopen invalidates old work, +does not replay motion targets, and resumes scheduling only after initialization. + +Devices passed the same Session retain separate scheduling, cancellation, reply routes, +caches and statistics. Closing one HandDevice does not close an externally supplied +Session or cancel a peer's work. Physical Session recovery remains channel-wide and +must follow the existing shared-generation contract; it is not promised to be invisible +to peers. Separate SocketCAN interfaces are not automatically combined into one Session. +Classic protocols without transaction identifiers retain same-opcode late-reply ambiguity. + +Offline coverage in [the scheduling regressions](../../../tests/hand/device/test_python_tactile_scheduling.cpp) +exercises the applicable models, all policies, incomplete stages, insertion bounds, +continuous demand, nested failures, timeouts, stop/replace, close/reopen, recovery, +shared-Session isolation and Native controls. Recorded validation and hardware coverage +are described in the [release notes](../../../RELEASE_NOTES.md#0312). ## Added native capabilities @@ -72,8 +169,9 @@ Still required before replacing the accepted Python implementation: - Multi-device hand/arm integration demonstrating one shared channel Runtime and independent device lifecycles. The current change does not integrate SDKs. - Hardware acceptance on the deployed OS, adapter/driver, CAN backend, firmware - and channel topology. No new hardware validation is claimed here, including - persistence, calibration, torque-mode transitions and V25 device behavior. + and channel topology. The initial capability batches did not add hardware acceptance + for persistence, calibration or torque-mode transitions; the 0.3.12 scheduling + checks above do not establish those behaviors. V25 requires an explicit side. Default request IDs are right `0x001` and left `0x002`, matching Python; `address` explicitly overrides them. The native mounted default is unchanged. diff --git a/docs/en/guides/releases.md b/docs/en/guides/releases.md index 3cfb85b1..623c20ef 100644 --- a/docs/en/guides/releases.md +++ b/docs/en/guides/releases.md @@ -2,6 +2,13 @@ [中文](../../zh/guides/releases.md) · [Documentation index](../README.md) +## 0.3.12 scheduling update + +Version 0.3.12 adds angle scheduling at safe tactile-stage boundaries under the +explicit Python runtime policy while retaining Native defaults and existing C++ APIs. +The [release notes](../../../RELEASE_NOTES.md#0312) describe compatibility, recorded +validation, O6/L20/O30 hardware results and the untested shared-Session/fault timing scope. + ## Targets aligned with transport The Hand release workflow uses the transport v0.3.4 target matrix: @@ -16,22 +23,24 @@ availability of proprietary ARM64 drivers. Hand SDK packages contain both hand and paired transport static libraries, headers, CMake packages, documentation and read-only command-line examples. Test executables and proprietary drivers/libraries -are excluded. Versions remain independent. Hand 0.3.11 requires transport 0.3.4 or newer in +are excluded. Versions remain independent. Hand 0.3.12 requires transport 0.3.4 or newer in the 0.3 minor line in source, prebuilt and installed-consumer builds. The paired source pin and prebuilt downloads use the same v0.3.4 release. Rebuild hand and downstream consumers with matching transport headers and libraries; -public transport structures have grown. No new physical hardware acceptance is claimed. Transport archives now use the `linkerbot-transport-` prefix. +public transport structures have grown. Dependency pairing itself adds no hardware +acceptance; the 0.3.12 scheduling evidence has the limited scope linked above. +Transport archives now use the `linkerbot-transport-` prefix. Hand continues to consume the supported `linkerbot-comm` CMake package and CAN target aliases. ## Names and checksums -Examples use hand version `0.3.0`; compiler versions reflect the actual build: +Examples use hand version `0.3.12`; compiler versions reflect the actual build: ```text -linkerbot-hand-cpp-0.3.0-Linux-aarch64-ubuntu24.04-GNU13.3.0-libstdcxx-abi1-Release.tar.gz -linkerbot-hand-cpp-0.3.0-Windows-ARM64-msvc143-19.44.35229.0-Debug-MDd.zip +linkerbot-hand-cpp-0.3.12-Linux-aarch64-ubuntu24.04-GNU13.3.0-libstdcxx-abi1-Release.tar.gz +linkerbot-hand-cpp-0.3.12-Windows-ARM64-msvc143-19.44.35229.0-Debug-MDd.zip ``` Each archive has an adjacent `.sha256` file. The complete set also contains `release-manifest.json` diff --git a/docs/en/guides/validation.md b/docs/en/guides/validation.md index dbb73bd0..784137e7 100644 --- a/docs/en/guides/validation.md +++ b/docs/en/guides/validation.md @@ -14,7 +14,7 @@ A parent-provided `linkerbot::comm` target is reused and version-checked. The legacy empty `LINKERBOT_COMM_SOURCE_DIR=` still selects package discovery through `CMAKE_PREFIX_PATH` in AUTO mode. Configure logs identify the selected dependency. Use separate build directories when switching dependencies to avoid stale CMake caches. -Hand 0.3.10 requires transport 0.3.4 or newer in the 0.3 minor line. Source, +Hand 0.3.12 requires transport 0.3.4 or newer in the 0.3 minor line. Source, prebuilt and installed-consumer checks reject older patches and other minor lines. For paired development, keep the source commit pinned in README and CI; record the actual revision and configuration in test reports. diff --git a/docs/en/reference/compatibility.md b/docs/en/reference/compatibility.md index dedddbfe..23fa8c3e 100644 --- a/docs/en/reference/compatibility.md +++ b/docs/en/reference/compatibility.md @@ -1,12 +1,35 @@ # Platform and hardware validation scope -The unreleased 0.3.0 API has removed O30 motion-time and torque-limit read/write APIs, model entry points, samples, events, and snapshot fields. -Remove old calls and rebuild; actual torque reads and current-limit reads/writes remain available, with surviving public enum values unchanged. -Historical hardware acceptance refers to the SDK revision recorded in each report, not the API inventory after these removals. +[中文](../../zh/reference/compatibility.md) · [Documentation index](../README.md) -L6 position Kp, position Kd, and torque Kd are available only through native `l6::L6` Managers. -The corresponding unified read/write methods, samples, snapshot fields, events, and capabilities have been removed. Migrate to the Managers' -`set_values()`, `get_blocking()`, and `get_snapshot()` and rebuild. Native protocol and raw-value semantics remain unchanged. +## 0.3.12 compatibility and scheduling validation + +Existing public C++ APIs and Native defaults remain available. The tactile-stage +scheduler requires explicit `RuntimeBehavior::kPython`; the +[Python behavior baseline](../guides/python-behavior-baseline.md#tactile-stage-angle-scheduling-0312) +records supported protocols and scheduling rules. Hand 0.3.12 requires transport +0.3.4 or newer in the 0.3 minor line. Rebuild consumers with matching headers and libraries. + +L6 position Kp/Kd and torque Kd are available through both the unified API and +native Managers. O30 unified torque-limit and motion-time methods require explicit +`O30Layout::kPythonV25`; native Managers retain the mounted V36 layout. See the +[API guide](../guides/usage.md#features-unified-through-handdevice) for entry points. Earlier 0.3.0 +API-removal notes do not describe the current interface inventory. + +O6 left, L20 right and O30 right (explicit V25) passed query-only, +command-feedback-only, adaptive, five-minute saturation and Native-control scheduling +groups on Ubuntu 24.04 x86_64 / SocketCAN / Release. Firmware, adapters, tested +revisions and per-device results are recorded in the +[0.3.12 release notes](../../../RELEASE_NOTES.md#0312). +No new L6/L20Lite scheduling hardware acceptance or physical shared-Session, +close/recovery and injected abnormal-reply timing acceptance is claimed. Offline +regressions cover these lifecycle and isolation rules independently. The scheduling +runs do not establish frequency maxima or dynamic motion accuracy. + +## Historical common-feature hardware baseline + +Historical hardware acceptance applies to the SDK revision and configuration recorded +in each report. It does not automatically validate changes in later releases. The `0.3.0` validation baseline is Ubuntu 24.04 x86_64 / GCC 13 / C++17 and Windows 11 x64 / Visual Studio 2022 / MSVC v143 14.44 / C++17. Other operating systems, architectures, toolchains, and driver versions diff --git a/docs/zh/connections/prepare-interface.md b/docs/zh/connections/prepare-interface.md index 7efb342d..2ba2c221 100644 --- a/docs/zh/connections/prepare-interface.md +++ b/docs/zh/connections/prepare-interface.md @@ -5,7 +5,7 @@ ## 编译与链接前提 需要 C++17 编译器、CMake 3.16+,以及与 hand SDK 配套的 `linkerbot-transport-cpp`。 -hand 与 transport 使用兼容的 `0.3.x` 版本,transport 版本不得低于 hand。 +hand 与 transport 版本独立;hand 0.3.12 要求 transport `0.3.x` 且不低于 0.3.4。 构建和安装步骤见[项目快速开始](../../../README.zh-CN.md);Windows 见[Windows 使用指南](../guides/windows.md)。 本目录的完整程序可保存为应用的 `main.cpp`。SDK 安装后,最小 `CMakeLists.txt` 为: diff --git a/docs/zh/guides/python-behavior-baseline.md b/docs/zh/guides/python-behavior-baseline.md index 80c5bd68..9ed64b09 100644 --- a/docs/zh/guides/python-behavior-baseline.md +++ b/docs/zh/guides/python-behavior-baseline.md @@ -1,9 +1,78 @@ # Python 行为基准 +[English](../../en/guides/python-behavior-baseline.md) · [文档索引](../README.md) + 参考源码为 `linkerbot-hand-python-sdk` 提交 `3a63e723b9a0046e9a60a58339b9f064ef5b70fd`,源码版本为 2.0.0。 -本文记录未来 Python 迁移所需的原生 SDK 准备,不代表 Python 绑定、hand/arm 接入或实机验收已经完成。 -本次不包含 O20。 +本文记录未来 Python 迁移所需的原生 SDK 准备,不包含 Python 绑定、hand/arm 接入或 O20。 +0.3.12 的阶段调度更新已有有限范围的实机证据,见[发行说明](../../../RELEASE_NOTES.md#0312);历史批次保留各自原有的验证范围。 + +## 触觉阶段角度调度(0.3.12) + +本批基于 v0.3.11,以固定 Python actor 和 transaction runner 的行为为参考。 +只有显式 `RuntimeBehavior::kPython` 启用新的阶段调度,现有公开 C++ API、枚举值和 Native 默认行为保持兼容。 +最低及配套 transport 仍为 v0.3.4,需使用匹配的头文件和库重新编译 SDK 及下游消费者。 +这里描述行为对照,不宣称所有操作与 Python 完全等价。 + +### 协议阶段边界 + +| 型号 / 协议 | 允许插入的位置 | 不可打断的部分 | +| --- | --- | --- | +| L6 / O6 Classic | 完整收到当前手指后、下一指请求前;每轮四个边界 | 当前手指的全部数据行及重复、冲突校验 | +| L20Lite / L20 Classic | 同样在完整指间插入;Python 路径逐指读取,仅在整手完整后发布 | 当前手指拼装及每个多帧角度批次;Native 保留原请求方式 | +| O30 HOP 0.0.4,显式 `O30Layout::kPythonV25` | 完整的传感器选择回显、元数据或传感器数据区间事务后,且存在下一触觉阶段 | 当前 HOP 请求覆盖范围的全部回复分片;首个请求前及最终阶段后不插入 | +| L30 | 不增加让出边界:固定 Python 触觉事务未启用让出 | 原有触觉操作 | +| L6 HOP / O30 Mounted V36 | 显式 Python 策略不支持,既有配置校验拒绝 | 不新增调度约定 | + +帧间空隙不等于安全边界。缺行、冲突数据或未收齐的 HOP 区间不能触发角度插入,也不能发布部分整手触觉。 +Classic L6/L20Lite/L20 每指需要 12 行、每行 6 个值;O6 每指需要 10 行、每行 4 个值。 + +### 反馈策略、选择顺序和上限 + +| 角度轮询策略 | 安全边界内的行为 | +| --- | --- | +| `kQueryOnly` | 服务到期查询,命令反馈不推迟查询期限 | +| `kCommandFeedbackOnly` | 仅使用确认有效的实际状态命令反馈;不为轮询补查询或重发目标来获取反馈 | +| `kAdaptive` | 复用足够新的实际状态命令反馈,否则服务到期查询 | + +显式角度 getter 在所有轮询策略下都保留主动读取需求。只有能力声明为实际测量状态的反馈才能满足轮询;目标回显或发送成功不能冒充测量。 +O30 V25 的完整角度写回复声明为实际状态,Mounted V36 声明不变。 + +每个安全边界最多执行 **4 个逻辑角度事务**,普通失败同样占用一次额度。一次多帧角度批次计一次,批次保持完整。 +新任务到达及目标替换不重置计数,进入下一边界才重置;待执行命令仍使用既有 latest 目标替换和回执语义。 + +当命令反馈能按所选策略满足待执行或到期轮询需求时,可优先执行该命令;其他情况下,同时就绪的命令与查询交替服务,偏好跨边界保留。 +查询复用原 ReadCoordinator,与主动读取合并;撤销纯轮询需求不取消合并的主动读者。 +边界可以等待已经排队、且将在下一阶段估时范围内到期的命令,等待终点固定,不随新任务到达不断延长。 + +下一阶段估时分别为 L6 11 ms、O6 2.4 ms、L20Lite/L20 4 ms、O30 3 ms。 +存在有限恢复执行总期限时,剩余时间必须严格大于下一阶段估时才准入角度任务;相等或不足则继续触觉,不重置总期限。 +普通 getter 的调用者等待期限独立于共享底层事务,各协议阶段仍从物理发送完成后使用各自响应窗口。 +估时只是准入条件,不是设备响应的最坏耗时保证。 + +每边界四次上限使连续角度需求下的触觉仍能推进,整轮之间继续由原 ExecutionGate 仲裁,使其他读取和命令取得进展。 +阶段任务借用当前设备的逻辑执行权,不重复获取执行权;所有发送仍走既有 Session writer,不增加发送队列或第二套物理发送器。 +等待回复不持有物理发送锁;这些规则不构成硬实时延迟保证。 + +### 失败、生命周期及设备隔离 + +内层角度协议错误或响应超时由内层任务承担,连接仍有效时继续后续触觉阶段,与 Python 基准一致。 +传输错误、关闭或连接编号失效会停止后续阶段并使外层失败。失败读取不能用部分触觉替换上一份完整证据;关闭或故障后的历史快照仍按原契约标为不可用。 + +缺失或畸形的可选命令反馈不改写真实物理发送的 `Dispatched` 结果。逻辑成功、延迟与发送结果分开统计,失败内层不能计为成功。 +调用者等待超时不取消共享工作,也不能造成重复完成或统计。 + +停止轮询撤销轮询意图,保留合并的主动读者;替换计划隔离旧计划计数,但保留底层成功取得的样本。 +关闭阻止后续阶段准入并释放等待者,保留已领取物理批次的真实结果。 +恢复或重开使旧任务失效,不重放运动目标,初始化成功后才继续调度。 + +传入同一个 Session 的设备分别维护调度、取消、回复路由、缓存和统计。 +关闭一个 HandDevice 不关闭外部传入的 Session,也不取消其他设备的工作。 +物理 Session 恢复仍影响整个通道,按既有共享连接编号契约处理,不承诺其他设备完全无感。 +不同 SocketCAN 接口不会自动合并成同一个 Session。Classic 协议缺少事务编号时,同操作码迟到回复的歧义仍存在。 + +[阶段调度离线回归](../../../tests/hand/device/test_python_tactile_scheduling.cpp)覆盖适用型号、三种策略、不完整阶段、插入上限、持续需求、嵌套失败、超时、停止和替换计划、关闭重开、恢复、共享 Session 隔离及 Native 对照。 +验证记录及实机覆盖范围见[发行说明](../../../RELEASE_NOTES.md#0312)。 ## 新增原生能力 @@ -45,7 +114,7 @@ - Python 绑定验证:包装或分配失败不丢回执,GIL、回调、析构及解释器退出安全,异常与墙上时间转换正确。 原生单调时间戳不能直接当 Unix 时间。 - 多手、多臂接入证明共用通道 Runtime,且设备生命周期相互独立;本次不接入 hand/arm。 -- 在部署 OS、适配器及驱动、CAN 后端、固件和拓扑上实机验收。本次不新增实机验证结论;参数持久化、校准、扭矩模式切换和 V25 行为均单独待验证。 +- 在部署 OS、适配器及驱动、CAN 后端、固件和拓扑上实机验收。最初能力批次未新增参数持久化、校准和扭矩模式切换的实机验收;本次阶段调度测试也不证明这些行为。 V25 要求显式指定左右手;默认请求 ID 为右手 `0x001`、左手 `0x002`,与 Python 一致;`address` 可显式覆盖。原生挂载路径的默认地址不变。 diff --git a/docs/zh/guides/releases.md b/docs/zh/guides/releases.md index 59a04d4b..e403e0d8 100644 --- a/docs/zh/guides/releases.md +++ b/docs/zh/guides/releases.md @@ -2,6 +2,11 @@ [English](../../en/guides/releases.md) · [文档索引](../README.md) +## 0.3.12 阶段调度更新 + +0.3.12 在显式 Python 运行时策略下增加触觉安全阶段边界的角度调度,保留 Native 默认行为及现有 C++ API。 +[发行说明](../../../RELEASE_NOTES.md#0312)记录兼容性、验证结果、O6/L20/O30 实机证据及共享 Session、故障时序等未测范围。 + ## 与 transport 对齐的目标 Hand 发布工作流使用与 transport v0.3.4 相同的目标矩阵: @@ -15,21 +20,21 @@ libstdc++ ABI1 和 C++17。Windows 使用原生架构 runner 与 v143 14.44 工 产物是开发 SDK,Hand 包包含 hand 与配套 transport 静态库、头文件、CMake 包和文档, 保留只读命令行示例;不包含测试程序、厂商驱动或厂商库。 -两个项目版本独立。hand 0.3.11 的源码、预构建及安装消费者均要求 transport 0.3.x 且不低于 0.3.4。 +两个项目版本独立。hand 0.3.12 的源码、预构建及安装消费者均要求 transport 0.3.x 且不低于 0.3.4。 配套源码固定提交和预构建下载统一使用 v0.3.4 发行版。transport 公共结构有新增字段, -须使用匹配的头文件和库重新编译 hand 及下游应用。本次更新不计为新增实机验收。 +须使用匹配的头文件和库重新编译 hand 及下游应用。依赖配对本身不计为新增实机验收;0.3.12 阶段调度测试仅覆盖上文链接中记录的范围。 transport 归档名现以 `linkerbot-transport-` 开头;Hand 继续使用受支持的 `linkerbot-comm` CMake 包及 CAN 目标别名。 ## 命名与校验 -以下示例中的 hand 版本为 `0.3.0`,编译器版本以实际构建结果为准: +以下示例中的 hand 版本为 `0.3.12`,编译器版本以实际构建结果为准: ```text -linkerbot-hand-cpp-0.3.0-Linux-aarch64-ubuntu24.04-GNU13.3.0-libstdcxx-abi1-Release.tar.gz -linkerbot-hand-cpp-0.3.0-Windows-ARM64-msvc143-19.44.35229.0-Debug-MDd.zip +linkerbot-hand-cpp-0.3.12-Linux-aarch64-ubuntu24.04-GNU13.3.0-libstdcxx-abi1-Release.tar.gz +linkerbot-hand-cpp-0.3.12-Windows-ARM64-msvc143-19.44.35229.0-Debug-MDd.zip ``` 每份归档旁有 `.sha256`;完整集合另有 `release-manifest.json` 和 `SHA256SUMS.txt`, diff --git a/docs/zh/guides/validation.md b/docs/zh/guides/validation.md index 1a4759d6..55f4d131 100644 --- a/docs/zh/guides/validation.md +++ b/docs/zh/guides/validation.md @@ -13,7 +13,7 @@ 父项目已经提供 `linkerbot::comm` 时,复用父项目的目标,并检查版本。 显式设置旧参数 `LINKERBOT_COMM_SOURCE_DIR=` 仍可在 AUTO 下通过 `CMAKE_PREFIX_PATH` 使用安装包。配置日志会显示实际选择的依赖;切换依赖时使用独立构建目录,避免旧 CMake 缓存。 -hand 0.3.10 要求 transport 0.3.x 且不低于 0.3.4。源码、预构建及安装消费者测试均拒绝更低补丁版本和其他 minor 版本。 +hand 0.3.12 要求 transport 0.3.x 且不低于 0.3.4。源码、预构建及安装消费者测试均拒绝更低补丁版本和其他 minor 版本。 源码开发继续使用 README 与 CI 固定的提交,并在测试报告中记录实际版本和构建配置。 ### 从源码构建 diff --git a/docs/zh/reference/compatibility.md b/docs/zh/reference/compatibility.md index b40f5a0d..1fc526f6 100644 --- a/docs/zh/reference/compatibility.md +++ b/docs/zh/reference/compatibility.md @@ -1,12 +1,27 @@ # 平台与硬件验证范围 -未发布的 0.3.0 已删除 O30 运动时间和扭矩上限的读写接口、型号入口、样本、事件及快照字段。 -旧调用须移除并重新编译;实际扭矩读取与电流上限读写保留,其余公开枚举编号保持不变。 -历史实机验收以各报告记录的 SDK 版本为准,不代表删除后的接口清单。 +[English](../../en/reference/compatibility.md) · [文档索引](../README.md) -L6 位置 Kp、位置 Kd、扭矩 Kd 仅通过 `l6::L6` 的专有 Manager 提供。 -对应的统一读写方法、样本、快照字段、事件及能力描述已删除;调用方须迁移到 Manager 的 -`set_values()`、`get_blocking()`、`get_snapshot()` 并重新编译。原生协议及原始值语义保持不变。 +## 0.3.12 兼容性与调度验证 + +现有公开 C++ API 和 Native 默认行为保持可用。触觉阶段调度须显式设置 +`RuntimeBehavior::kPython`;支持的协议及调度规则见 +[Python 行为基准](../guides/python-behavior-baseline.md#触觉阶段角度调度0312)。 +hand 0.3.12 要求 transport 0.3.x 且不低于 0.3.4;消费者须使用匹配的头文件和库重新编译。 + +L6 位置 Kp/Kd 和扭矩 Kd 已同时提供统一接口及原生 Manager 入口。 +O30 统一扭矩上限和运动时间方法须显式选择 `O30Layout::kPythonV25`,原生 Manager 保留挂载 V36 布局。 +具体入口见[API 指南](../guides/usage.md#已通过-handdevice-统一的能力)。早期 0.3.0 的接口删除说明不代表当前接口清单。 + +O6 左手、L20 右手和 O30 右手(显式 V25)已在 Ubuntu 24.04 x86_64 / SocketCAN / Release 下 +通过独立查询、仅命令反馈、自适应、五分钟饱和负载及 Native 对照五组调度验证。 +固件、适配器、实测源码版本和逐设备结果见[0.3.12 发行说明](../../../RELEASE_NOTES.md#0312)。 +本次未新增 L6/L20Lite 调度实机验收,也未实机执行共享 Session、关闭恢复及异常回复时序测试; +生命周期和隔离规则另有离线回归覆盖。这些调度测试不证明频率上限或动态运动精度。 + +## 历史常用功能实机基线 + +历史实机验收仅对应各报告记录的 SDK 版本和配置,不自动覆盖后续版本的改动。 `0.3.0` 验证基线为 Ubuntu 24.04 x86_64 / GCC 13 / C++17,以及 Windows 11 x64 / Visual Studio 2022 / MSVC v143 14.44 / C++17。其他系统、架构、工具链及驱动版本不在 diff --git a/src/hand/capabilities/o30.cpp b/src/hand/capabilities/o30.cpp index e43211e5..9adca9b5 100644 --- a/src/hand/capabilities/o30.cpp +++ b/src/hand/capabilities/o30.cpp @@ -36,7 +36,7 @@ namespace linkerbot::hand::capabilities_detail { profile.operations.read_device_info = true; profile.joints = joints; profile.commands = { - angle_command(joints, encoding, AckSupport::kRequired, false), + angle_command(joints, encoding, AckSupport::kRequired, true), command(CommandSemantic::kSpeeds, names, u8, encoding, "count", std::nullopt, Confidence::kUnknown, AckSupport::kRequired), command(CommandSemantic::kAccelerations, names, u8, encoding, "count", std::nullopt, diff --git a/src/hand/detail/failure_kind.hpp b/src/hand/detail/failure_kind.hpp index d480a7a9..633b3dbf 100644 --- a/src/hand/detail/failure_kind.hpp +++ b/src/hand/detail/failure_kind.hpp @@ -4,6 +4,25 @@ #include namespace linkerbot::hand::detail { + // Nested protocol failures belong to their own waiter/handle. Connection + // and generation failures must also stop an enclosing staged transaction. + inline void rethrow_nested_connection_failure(const std::exception_ptr &error) { + if (!error) { + return; + } + try { + std::rethrow_exception(error); + } catch (const TransportError &) { + throw; + } catch (const DeviceNotReadyError &) { + throw; + } catch (const ClosedError &) { + throw; + } catch (...) { + // The inner operation has already retained its ordinary failure. + return; + } + } enum class FailureKind { timeout, lifecycle, closed, other }; inline FailureKind failure_kind(std::exception_ptr error) noexcept { if (!error) { diff --git a/src/hand/l20/force_sensor.cpp b/src/hand/l20/force_sensor.cpp index 0cc7e770..258b3892 100644 --- a/src/hand/l20/force_sensor.cpp +++ b/src/hand/l20/force_sensor.cpp @@ -1,4 +1,5 @@ #include "linkerbot/hand/l20/force_sensor.hpp" +#include "../unified/detail/runtime_access.hpp" #include #include #include @@ -114,16 +115,28 @@ namespace linkerbot::hand::l20 { channel_.stop(true); } - // One transaction, one absolute deadline, transaction-local 5-finger - // assembler (see protocol::read_force_sensor_all): the aggregate is - // published only when all 5 fingers' 12 rows arrive intact, so a - // partial/timed-out batch never overwrites the last complete snapshot - // and there is only ever one Request in flight (nothing to cancel on - // partial failure by construction). + // Native retains the aggregate transaction. Python response-window scopes + // read complete fingers sequentially and yield only between them. In both + // cases publish the aggregate only after every finger has succeeded. AllFingersData ForceSensorManager::get_blocking(std::chrono::milliseconds timeout_ms) { if (timeout_ms.count() <= 0) { throw ValidationError("timeout_ms must be positive"); } + if (unified_detail::RuntimeAccess::uses_response_windows(*runtime_)) { + const auto call = channel_.enter(); + const auto deadline = runtime::deadline_after(timeout_ms); + auto operation = runtime_->operation("python.tactile.batch", deadline); + std::array values{}; + for (size_t index = 0; index < kFingerNames.size(); ++index) { + if (index != 0) { + unified_detail::RuntimeAccess::stage_boundary(*runtime_); + } + values[index] = fingers_.at(kFingerNames[index])->get_blocking(runtime::remaining(deadline)); + } + AllFingersData data{values[0], values[1], values[2], values[3], values[4]}; + return detail::Channel::project( + runtime_->publish("force_sensor_all", std::move(data), runtime_->response_provenance())); + } return channel_.get(protocol_.make_read("force_sensor_all"), runtime::deadline_after(timeout_ms)); } diff --git a/src/hand/l20lite/force_sensor.cpp b/src/hand/l20lite/force_sensor.cpp index dd1a299c..e6c1029b 100644 --- a/src/hand/l20lite/force_sensor.cpp +++ b/src/hand/l20lite/force_sensor.cpp @@ -1,4 +1,5 @@ #include "linkerbot/hand/l20lite/force_sensor.hpp" +#include "../unified/detail/runtime_access.hpp" #include #include #include @@ -115,16 +116,28 @@ namespace linkerbot::hand::l20lite { channel_.stop(); } - // One transaction, one absolute deadline, transaction-local 5-finger - // assembler (see protocol::read_force_sensor_all): the aggregate is - // published only when all 5 fingers' 12 rows arrive intact, so a - // partial/timed-out batch never overwrites the last complete snapshot - // and there is only ever one Request in flight (nothing to cancel on - // partial failure by construction). + // Native retains the aggregate transaction. Python response-window scopes + // read complete fingers sequentially and yield only between them. In both + // cases publish the aggregate only after every finger has succeeded. AllFingersData ForceSensorManager::get_blocking(std::chrono::milliseconds timeout_ms) { if (timeout_ms.count() <= 0) { throw ValidationError("timeout_ms must be positive"); } + if (unified_detail::RuntimeAccess::uses_response_windows(*runtime_)) { + const auto call = channel_.enter(); + const auto deadline = runtime::deadline_after(timeout_ms); + auto operation = runtime_->operation("python.tactile.batch", deadline); + std::array values{}; + for (size_t index = 0; index < kFingerNames.size(); ++index) { + if (index != 0) { + unified_detail::RuntimeAccess::stage_boundary(*runtime_); + } + values[index] = fingers_.at(kFingerNames[index])->get_blocking(runtime::remaining(deadline)); + } + AllFingersData data{values[0], values[1], values[2], values[3], values[4]}; + return detail::Channel::project( + runtime_->publish("force_sensor_all", std::move(data), runtime_->response_provenance())); + } return channel_.get(protocol_.make_read("force_sensor_all"), runtime::deadline_after(timeout_ms)); } diff --git a/src/hand/l6/force_sensor.cpp b/src/hand/l6/force_sensor.cpp index 205409c9..771cc50b 100644 --- a/src/hand/l6/force_sensor.cpp +++ b/src/hand/l6/force_sensor.cpp @@ -1,3 +1,4 @@ +#include "../unified/detail/runtime_access.hpp" #include #include #include @@ -145,6 +146,9 @@ namespace linkerbot::hand::l6 { try { for (size_t i = 0; i < fingers.size(); ++i) { token.throw_if_cancelled(); + if (i != 0) { + unified_detail::RuntimeAccess::stage_boundary(*core); + } if (before_finger) { before_finger(i, deadline); } diff --git a/src/hand/o30/client.cpp b/src/hand/o30/client.cpp index 7e548bb8..8849f7d6 100644 --- a/src/hand/o30/client.cpp +++ b/src/hand/o30/client.cpp @@ -1,3 +1,4 @@ +#include "../unified/detail/runtime_access.hpp" #include #include #include @@ -118,6 +119,9 @@ namespace linkerbot::hand::o30 { } auto call = calls_.hold(); auto operation = runtime_->operation(deadline); + if (mi >= protocol::kMiSensorInfo && mi <= protocol::kMiSensorCh1 + 2) { + unified_detail::RuntimeAccess::stage_boundary(*runtime_); + } const auto old_response = response_id_.load(); if (next_id && protocol::expected_response_id(*next_id) != old_response) { runtime_->set_routes({{old_response, false}, {protocol::expected_response_id(*next_id), false}}); diff --git a/src/hand/o6/force_sensor.cpp b/src/hand/o6/force_sensor.cpp index d38ba477..02342845 100644 --- a/src/hand/o6/force_sensor.cpp +++ b/src/hand/o6/force_sensor.cpp @@ -1,4 +1,5 @@ #include "linkerbot/hand/o6/force_sensor.hpp" +#include "../unified/detail/runtime_access.hpp" #include #include #include @@ -124,6 +125,9 @@ namespace linkerbot::hand::o6 { auto operation = runtime_->operation("o6.tactile.batch", deadline); std::array values{}; for (size_t index = 0; index < kFingerNames.size(); ++index) { + if (index != 0) { + unified_detail::RuntimeAccess::stage_boundary(*runtime_); + } const auto remaining = runtime::remaining(deadline); if (remaining.count() <= 0) { throw internal::DataRelayTimeout("O6 tactile batch deadline expired"); diff --git a/src/hand/runtime/device_runtime.cpp b/src/hand/runtime/device_runtime.cpp index 15e007a2..96f8cfae 100644 --- a/src/hand/runtime/device_runtime.cpp +++ b/src/hand/runtime/device_runtime.cpp @@ -352,6 +352,7 @@ namespace linkerbot::hand::runtime { unified_detail::RuntimeAccess::TimingCapture timing; }; thread_local std::map response_policies; + thread_local std::map stage_boundaries; } struct Request::State { mutable std::mutex mutex; @@ -3030,3 +3031,52 @@ void linkerbot::hand::unified_detail::RuntimeAccess::logical_transaction_succeed device.impl_->consecutive_errors = 0; } } + +void linkerbot::hand::unified_detail::RuntimeAccess::with_stage_boundaries(StageBoundary boundary, + runtime::DeviceRuntime &device, + const std::function &execute) { + auto previous = runtime::stage_boundaries.extract(&device); + const auto restore = [&] { + runtime::stage_boundaries.erase(&device); + if (!previous.empty()) { + runtime::stage_boundaries.insert(std::move(previous)); + } + }; + try { + runtime::stage_boundaries.emplace(&device, std::move(boundary)); + execute(); + } catch (...) { + restore(); + throw; + } + restore(); +} + +void linkerbot::hand::unified_detail::RuntimeAccess::stage_boundary(runtime::DeviceRuntime &device) { + const auto found = runtime::stage_boundaries.find(&device); + if (found != runtime::stage_boundaries.end()) { + // Nested angle work cannot recursively open another tactile boundary. + auto boundary = found->second; + with_stage_boundaries([] {}, device, boundary); + } +} + +void linkerbot::hand::unified_detail::RuntimeAccess::fault_nested_transaction(runtime::DeviceRuntime &device, + std::exception_ptr error) { + auto &p = *device.impl_; + const std::lock_guard lock(p.mutex); + if (p.health.state != runtime::DeviceState::ready) { + return; + } + // Match a fatal polling failure even if the boundary, rather than the + // poll worker, claimed the query. Never fault the shared physical Session. + p.health.state = runtime::DeviceState::faulted; + p.polling_cancel.cancel(); + p.polling_request_cancel.cancel(); + p.invalidate_locked(); + const auto pending = p.pending; + for (const auto &request : pending) { + p.finish_locked(request, error, true); + } + p.cv.notify_all(); +} diff --git a/src/hand/unified/backend.cpp b/src/hand/unified/backend.cpp index 1d982564..503b859c 100644 --- a/src/hand/unified/backend.cpp +++ b/src/hand/unified/backend.cpp @@ -3,6 +3,7 @@ #include "detail/connection_initializer.hpp" #include "detail/force.hpp" #include "detail/o30_v25.hpp" +#include "detail/python_stage_scheduling.hpp" #include "detail/python_state.hpp" #include "detail/python_transactions.hpp" #include "detail/read_coordinator.hpp" @@ -99,6 +100,11 @@ namespace linkerbot::hand::unified_detail { }); } + void set_angle_dispatch(AngleReady ready, RunAngle run) override { + angle_ready_ = std::move(ready); + run_angle_ = std::move(run); + } + ~ModelBackend() override { if (python_) { python_->stop(); @@ -514,6 +520,10 @@ namespace linkerbot::hand::unified_detail { } } + [[nodiscard]] uint64_t connection_generation() const override { + return device_->runtime()->runtime_health().device_generation; + } + [[nodiscard]] HandHealth health() const override { auto health = device_->health(); auto current = snapshot(Model::kUnknown, HandSide::kUnknown, capabilities_); @@ -641,9 +651,20 @@ namespace linkerbot::hand::unified_detail { task.period = std::chrono::milliseconds{1}; task.next = [state = python_] { return state->next_poll(); }; task.run = [this](runtime::CancellationToken token) { - const auto ticket = python_->take_poll(); - if (!ticket || token.cancelled()) { - return; + std::optional ticket; + { + // Transfer a due sampling intent atomically with respect + // to tactile boundary dispatch. Never wait for I/O here. + const std::lock_guard lock(poll_dispatch_mutex_); + ticket = python_->take_poll(); + if (!ticket || token.cancelled()) { + return; + } + const auto valid = read_generation(); + reads_->request_poll( + static_cast(ticket->semantic), scheduled_read(ticket->semantic, valid), + [state = python_, selected = *ticket] { return state->poll_needed(selected); }, + prepare_read(valid)); } try { (void)coordinated_read( @@ -794,6 +815,90 @@ namespace linkerbot::hand::unified_detail { } private: + using ReadValue = std::variant; + typename ReadCoordinator::Prepare prepare_read(const std::function &valid) { + return [this, valid](const std::function &demand) { + return execution_gate_->acquire(false, runtime::Deadline::max(), {}, + [valid, demand] { return valid() && demand(); }); + }; + } + typename ReadCoordinator::Execute scheduled_read(TelemetrySemantic semantic, + const std::function &valid) { + return [this, semantic, valid](const std::shared_ptr &lane) -> ReadValue { + ReadValue result; + auto capture = std::make_shared>(0); + const auto before = RuntimeAccess::error_revision(*device_->runtime()); + with_python_read_windows( + [&] { + result = python_read(semantic, reads_->claimed_by_poll(), valid, lane, capture, before); + }, + valid, capture); + return result; + }; + } + void service_angle_boundary(const std::function &valid, const std::shared_ptr &lane) { + const auto key = static_cast(TelemetrySemantic::kAngles); + const auto next_stage = python_next_tactile_stage(config_.model); + unsigned dispatched = 0; + while (dispatched < kMaxInterstageAngleTransactions) { + if (!valid() || device_->runtime()->runtime_health().state != runtime::DeviceState::ready) { + throw ClosedError("read generation ended at tactile boundary"); + } + const auto deadline = runtime::Deadline{ + runtime::Clock::duration{execution_deadline_.load(std::memory_order_acquire)}}; + const auto now = runtime::Clock::now(); + if (!python_stage_has_budget(now, deadline, next_stage)) { + return; + } + const auto command_at = angle_ready_ ? angle_ready_() : std::nullopt; + const bool command_ready = command_at && *command_at <= now; + bool feedback_first = false; + { + const std::lock_guard lock(poll_dispatch_mutex_); + feedback_first = + command_ready && python_->angle_command_fulfills_due(reads_->has_pending_poll(key)); + if (feedback_first) { + reads_->cancel_pending_poll(key); + } else if (const auto ticket = python_->take_poll(TelemetrySemantic::kAngles)) { + reads_->request_poll( + key, scheduled_read(TelemetrySemantic::kAngles, valid), + [state = python_, ticket = *ticket] { return state->poll_needed(ticket); }, + prepare_read(valid)); + } + } + if (feedback_first && run_angle_(lane)) { + prefer_angle_read_ = true; + ++dispatched; + continue; + } + const bool read_ready = reads_->has_pending(key); + if (read_ready && (!command_ready || prefer_angle_read_) && reads_->serve_pending(key, lane)) { + prefer_angle_read_ = false; + ++dispatched; + continue; + } + if (command_ready && run_angle_(lane)) { + prefer_angle_read_ = true; + ++dispatched; + continue; + } + if (read_ready && reads_->serve_pending(key, lane)) { + prefer_angle_read_ = false; + ++dispatched; + continue; + } + // Wait only for an already queued target due before the next + // stage would finish. The horizon never moves with wakeups. + const auto horizon = std::min(deadline, now + next_stage); + if (!command_at || *command_at > horizon) { + return; + } + device_->runtime()->wait_until(*command_at); + } + if (!valid() || device_->runtime()->runtime_health().state != runtime::DeviceState::ready) { + throw ClosedError("read generation ended during angle work"); + } + } TelemetrySample python_read(TelemetrySemantic semantic, bool polling, const std::function &valid, const std::shared_ptr &lane, const RuntimeAccess::ErrorCapture &capture, uint64_t before) { @@ -801,8 +906,29 @@ namespace linkerbot::hand::unified_detail { throw UnsupportedFirmwareError("optional telemetry is disabled for this generation"); } const auto sent = device_->runtime()->runtime_health().sent_frames; + const auto poll_revision = python_->poll_revision(); try { - (void)read_direct(semantic, config_.transaction_timeout, valid, lane); + if (semantic == TelemetrySemantic::kForce && config_.model != Model::kL30) { + bool first_o30_stage = true; + RuntimeAccess::with_stage_boundaries( + [&] { + if (config_.model == Model::kO30 && first_o30_stage) { + first_o30_stage = false; + return; + } + try { + service_angle_boundary(valid, lane); + } catch (const TransportError &) { + RuntimeAccess::fault_nested_transaction(*device_->runtime(), + std::current_exception()); + throw; + } + }, + *device_->runtime(), + [&] { (void)read_direct(semantic, config_.transaction_timeout, valid, lane); }); + } else { + (void)read_direct(semantic, config_.transaction_timeout, valid, lane); + } auto result = telemetry_sample(snapshot(config_.model, config_.side, capabilities_), semantic); if (auto *force = std::get_if(&result)) { force->fields.erase( @@ -829,12 +955,12 @@ namespace linkerbot::hand::unified_detail { if (const auto *force = std::get_if(&result)) { python_->observe_force(*force); } - python_->read_succeeded(semantic, polling); + python_->read_succeeded(semantic, polling, poll_revision); return result; } catch (const HandError &error) { try { python_->read_failed(semantic, device_->runtime()->runtime_health().sent_frames > sent, error, - polling); + polling, poll_revision); } catch (const UnsupportedFirmwareError &downgraded) { RuntimeAccess::promote_error(*device_->runtime(), capture->load(std::memory_order_acquire), downgraded, before); @@ -843,7 +969,6 @@ namespace linkerbot::hand::unified_detail { throw; } } - using ReadValue = std::variant; std::function read_generation() { const auto epoch = read_epoch_.load(std::memory_order_acquire); return [this, epoch] { @@ -871,6 +996,10 @@ namespace linkerbot::hand::unified_detail { runtime::Deadline{runtime::Clock::duration{execution_deadline_.load(std::memory_order_acquire)}}, valid, identity, python_->health_metrics()); } + std::mutex poll_dispatch_mutex_; + AngleReady angle_ready_; + RunAngle run_angle_; + bool prefer_angle_read_ = false; HandDeviceConfig config_; DeviceCapabilities capabilities_; std::unique_ptr device_; diff --git a/src/hand/unified/command_scheduler.cpp b/src/hand/unified/command_scheduler.cpp index 2a82fb5b..34e0fa2e 100644 --- a/src/hand/unified/command_scheduler.cpp +++ b/src/hand/unified/command_scheduler.cpp @@ -320,7 +320,7 @@ namespace linkerbot::hand::unified_detail { while (!stop_) { auto now = now_(); expire(now); - if (!pending_size()) { + if (active_ || !pending_size()) { changed_.wait(lock); continue; } @@ -391,50 +391,87 @@ namespace linkerbot::hand::unified_detail { auto &m = metrics_.at(job.handle.family()); sample(m.queue_times, now - job.accepted); next_start_ = now + interval_; - lock.unlock(); - std::optional result; - std::exception_ptr error; - try { - // The absolute admission deadline also travels with the request; - // this rounded duration is only for native API compatibility. - if (!python_behavior_) { - job.request.timeout = runtime::remaining(job.deadline); - } - result = job.execute(job.request); - } catch (...) { - error = classify_exception(std::current_exception(), job.context, ErrorCode::kInternal); - } - lock.lock(); - // Leave a full interval after completion as well. Arbitration may - // delay the physical start; this prevents catch-up bursts thereafter. + execute_active(lock, now); + } + } + + std::exception_ptr CommandScheduler::execute_active(std::unique_lock &lock, Clock::time_point started) { + auto &job = ::linkerbot::hand::detail::checked_value(active_, "missing active command"); + auto &m = metrics_.at(job.handle.family()); + lock.unlock(); + std::optional result; + std::exception_ptr error; + try { + // The absolute admission deadline also travels with the request; + // this rounded duration is only for native API compatibility. if (!python_behavior_) { - next_start_ = now_() + interval_; + job.request.timeout = runtime::remaining(job.deadline); } - sample(m.execution_times, now_() - now); - if (!job.handle.done()) { - --m.value.pending; + result = job.execute(job.request); + } catch (...) { + error = classify_exception(std::current_exception(), job.context, ErrorCode::kInternal); + } + lock.lock(); + // Leave a full interval after completion as well. Arbitration may + // delay the physical start; this prevents catch-up bursts thereafter. + if (!python_behavior_) { + next_start_ = now_() + interval_; + } + sample(m.execution_times, now_() - started); + if (!job.handle.done()) { + --m.value.pending; + } + // A no-ACK receipt is terminal. Optional feedback can subsequently + // fail, but cannot change successful delivery into another terminal. + if (error && !job.handle.done()) { + fail(job, error); + } else { + // Internal scheduler tests/adapters may return a distinct handle. + // Production backend updates the accepted handle from receipts. + if (result && !job.handle.done() && job.handle.stage() == CommandStage::kAccepted) { + command_detail::CommandHandleAccess::mark_dispatched(job.handle, result->sent_frames()); + ++m.value.dispatched; } - // A no-ACK receipt is terminal. Optional feedback can subsequently - // fail, but cannot change successful delivery into another terminal. - if (error && !job.handle.done()) { - fail(job, error); - } else { - // Internal scheduler tests/adapters may return a distinct handle. - // Production backend updates the accepted handle from receipts. - if (result && !job.handle.done() && job.handle.stage() == CommandStage::kAccepted) { - command_detail::CommandHandleAccess::mark_dispatched(job.handle, result->sent_frames()); - ++m.value.dispatched; - } - if (result && result->stage() == CommandStage::kAcknowledged) { - if (!job.handle.done()) { - command_detail::CommandHandleAccess::mark_acknowledged(job.handle); - ++m.value.acknowledged; - } + if (result && result->stage() == CommandStage::kAcknowledged) { + if (!job.handle.done()) { + command_detail::CommandHandleAccess::mark_acknowledged(job.handle); + ++m.value.acknowledged; } } - active_.reset(); - changed_.notify_all(); } + active_.reset(); + changed_.notify_all(); + return error; + } + + std::optional CommandScheduler::pending_angle_at() { + const std::lock_guard lock(mutex_); + expire(now_()); + if (!python_behavior_ || active_ || latest_.count(CommandFamily::kAngleTarget) == 0) { + return {}; + } + return next_start_; + } + + bool CommandScheduler::run_angle(const std::shared_ptr &lane) { + std::unique_lock lock(mutex_); + const auto now = now_(); + expire(now); + auto found = latest_.find(CommandFamily::kAngleTarget); + if (!python_behavior_ || stop_ || active_ || now < next_start_ || found == latest_.end()) { + return false; + } + active_.emplace(std::move(found->second)); + latest_.erase(found); + auto &job = *active_; + job.request.execution_lease = lane; + removed(job, false); + sample(metrics_.at(job.handle.family()).queue_times, now - job.accepted); + next_start_ = now + interval_; + const auto error = execute_active(lock, now); + lock.unlock(); + ::linkerbot::hand::detail::rethrow_nested_connection_failure(error); + return true; } std::vector CommandScheduler::metrics() const { diff --git a/src/hand/unified/detail/backend.hpp b/src/hand/unified/detail/backend.hpp index b12fd11a..b048bf33 100644 --- a/src/hand/unified/detail/backend.hpp +++ b/src/hand/unified/detail/backend.hpp @@ -40,6 +40,9 @@ namespace linkerbot::hand::unified_detail { class DeviceBackend { public: virtual ~DeviceBackend() = default; + using AngleReady = std::function()>; + using RunAngle = std::function &)>; + virtual void set_angle_dispatch(AngleReady, RunAngle) {} virtual void stop_admission() {} virtual void resume_admission() {} virtual DeviceCapabilities observed_capabilities(DeviceCapabilities value) const { return value; } @@ -65,6 +68,8 @@ namespace linkerbot::hand::unified_detail { [[nodiscard]] virtual HandSnapshot snapshot(Model model, HandSide side, const DeviceCapabilities &capabilities) const = 0; [[nodiscard]] virtual HandHealth health() const = 0; + // Read completion needs only the epoch, not a full diagnostic snapshot. + [[nodiscard]] virtual uint64_t connection_generation() const { return health().connection_generation; } [[nodiscard]] virtual DeviceIdentity verify_identity(HandSide side, std::chrono::milliseconds timeout) = 0; virtual TelemetrySample initialize_read(TelemetrySemantic semantic, std::chrono::milliseconds timeout) { return read(semantic, timeout); diff --git a/src/hand/unified/detail/command_scheduler.hpp b/src/hand/unified/detail/command_scheduler.hpp index d646b6e9..271ac67d 100644 --- a/src/hand/unified/detail/command_scheduler.hpp +++ b/src/hand/unified/detail/command_scheduler.hpp @@ -35,6 +35,9 @@ namespace linkerbot::hand::unified_detail { // Production retains steady_clock and timed CV waits. This seam controls // queue expiry/throttling, not native protocol response clocks. void notify_clock_advanced(); + // Called only while the backend owns the device lane at a safe boundary. + std::optional pending_angle_at(); + bool run_angle(const std::shared_ptr &lane); private: struct ConstructorTag {}; @@ -67,6 +70,7 @@ namespace linkerbot::hand::unified_detail { size_t pending_size() const; void removed(Job &job, bool dropped); void run(); + std::exception_ptr execute_active(std::unique_lock &lock, Clock::time_point started); void watch_deadlines(); const Clock::duration interval_; diff --git a/src/hand/unified/detail/python_stage_scheduling.hpp b/src/hand/unified/detail/python_stage_scheduling.hpp new file mode 100644 index 00000000..7dc0bf6a --- /dev/null +++ b/src/hand/unified/detail/python_stage_scheduling.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +namespace linkerbot::hand::unified_detail { + // Fixed Python actor bound, counted in logical transactions per boundary, + // including failed nested transactions, not in physical frames. + inline constexpr unsigned kMaxInterstageAngleTransactions = 4; + + inline std::chrono::microseconds python_next_tactile_stage(Model model) { + using namespace std::chrono_literals; + // Python FORCE estimated_transaction_s / 5; O30's dynamic HOP stage. + switch (model) { + case Model::kL6: + return 11000us; + case Model::kO6: + return 2400us; + case Model::kL20Lite: + case Model::kL20: + return 4000us; + case Model::kO30: + return 3000us; + default: + return 0us; // No yielding contract (including L30 and L6 HOP). + } + } + + inline bool python_stage_has_budget(runtime::Deadline now, runtime::Deadline deadline, + std::chrono::microseconds next_stage) { + // Ordinary Python reads have independent response windows and no total + // caller budget. A finite recovery execution deadline is never extended. + return next_stage.count() > 0 && now < deadline && deadline - now > next_stage; + } +} diff --git a/src/hand/unified/detail/python_state.hpp b/src/hand/unified/detail/python_state.hpp index bf60483c..19361a2d 100644 --- a/src/hand/unified/detail/python_state.hpp +++ b/src/hand/unified/detail/python_state.hpp @@ -19,7 +19,8 @@ namespace linkerbot::hand::unified_detail { std::map metadata; uint64_t sequence = 0; }; - explicit PythonState(const HandDeviceConfig &config); + using Now = std::function; + explicit PythonState(const HandDeviceConfig &config, Now now = {}); void set_health(const std::shared_ptr &metrics); void configure(const DeviceCapabilities &capabilities); PythonHealthMetrics &health_metrics() const { return *health_; } @@ -34,8 +35,10 @@ namespace linkerbot::hand::unified_detail { void initialized(); DeviceCapabilities capabilities(DeviceCapabilities value) const; bool disabled(TelemetrySemantic semantic) const; - void read_succeeded(TelemetrySemantic semantic, bool polling); - void read_failed(TelemetrySemantic semantic, bool sent, const HandError &error, bool polling); + uint64_t poll_revision() const; + void read_succeeded(TelemetrySemantic semantic, bool polling, std::optional revision = {}); + void read_failed(TelemetrySemantic semantic, bool sent, const HandError &error, bool polling, + std::optional revision = {}); bool replace(const PollingPlan &plan); void stop_polling(); std::optional next_poll() const; @@ -44,7 +47,8 @@ namespace linkerbot::hand::unified_detail { uint64_t feedback; uint64_t plan; }; - std::optional take_poll(); + std::optional take_poll(std::optional only = {}); + bool angle_command_fulfills_due(bool pending_poll = false) const; bool poll_needed(const PollTicket &ticket) const; void project_health(HandHealth &health) const; std::string domain(TelemetrySemantic semantic) const; @@ -66,6 +70,7 @@ namespace linkerbot::hand::unified_detail { void disable_locked(TelemetrySemantic semantic); void visible_locked(bool command_feedback); DeviceCapabilities capabilities_locked(DeviceCapabilities value) const; + const Now now_; HandDeviceConfig config_; DeviceCapabilities base_capabilities_; std::map domains_; diff --git a/src/hand/unified/detail/python_transactions.hpp b/src/hand/unified/detail/python_transactions.hpp index 4ceee692..3a642c69 100644 --- a/src/hand/unified/detail/python_transactions.hpp +++ b/src/hand/unified/detail/python_transactions.hpp @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include namespace linkerbot::hand::unified_detail { @@ -55,6 +57,29 @@ namespace linkerbot::hand::unified_detail { // classic_management}.py and each model's tactile/identity transactions. inline protocol::TransactionPlan python_transaction(protocol::TransactionPlan plan, const HandDeviceConfig &config) { + if (config.model == Model::kO6 && !plan.consume && plan.command_family == "angle" && plan.frames.size() == 1 && + plan.frames.front().data[0] == 1 && plan.frames.front().dlc == 7) { + // The native O6 setter is dispatch-only. The explicit Python policy + // collects its declared current-state feedback, including interstage writes. + std::array raw{}; + std::copy_n(plan.frames.front().data.begin() + 1, raw.size(), raw.begin()); + plan.consume = o6::protocol::command_angle_feedback(plan.frames.front().id, raw).consume; + plan.optional_response_window = std::chrono::milliseconds{50}; + plan.supersede_optional_feedback = true; + } + if (config.model == Model::kL20Lite && !plan.consume && plan.command_family == "angle" && + plan.frames.size() == 2 && plan.frames.front().data[0] == 1 && plan.frames.front().dlc == 7) { + // Correlate both banks before returning to adaptive polling. An + // unsolicited observer alone can publish after the next poll was admitted. + auto decode = l20lite::protocol::read_angle(plan.frames.front().id).consume; + plan.consume = [decode = std::move(decode)](const can::Message &message) mutable { + auto progress = decode(message); + progress.origin = protocol::Origin::command_feedback; + return progress; + }; + plan.optional_response_window = std::chrono::milliseconds{100}; + plan.supersede_optional_feedback = true; + } if (!plan.consume) { return plan; } diff --git a/src/hand/unified/detail/read_coordinator.hpp b/src/hand/unified/detail/read_coordinator.hpp index a5683bd7..d1c803e6 100644 --- a/src/hand/unified/detail/read_coordinator.hpp +++ b/src/hand/unified/detail/read_coordinator.hpp @@ -1,6 +1,7 @@ #pragma once #include "../../detail/checked_optional.hpp" +#include "../../detail/failure_kind.hpp" #include #include #include @@ -129,6 +130,101 @@ namespace linkerbot::hand::unified_detail { } return ::linkerbot::hand::detail::checked_value(entry->value, "read completed without a value"); } + // Only the coordinator worker may service queued reads reentrantly, while + // retaining its outer device lease. No extra worker or send queue exists. + void request_poll(unsigned key, Execute execute, std::function demand, Prepare prepare = {}) { + const std::lock_guard lock(mutex_); + if (!accepting_ || !demand()) { + return; + } + auto found = entries_.find(key); + if (found == entries_.end()) { + auto entry = std::make_shared(); + entry->execute = std::move(execute); + entry->prepare = std::move(prepare); + entry->generation = generation_; + queue_.push_back({key, entry}); + try { + found = entries_.emplace(key, entry).first; + } catch (...) { + queue_.pop_back(); + throw; + } + } + found->second->requested_by_poll = true; + found->second->poll_demand = std::move(demand); + found->second->poll_cancel = {}; + changed_.notify_all(); + } + bool has_pending_poll(unsigned key) { + const std::lock_guard lock(mutex_); + const auto found = entries_.find(key); + return found != entries_.end() && !found->second->claimed && found->second->requested_by_poll && + !found->second->poll_cancel.cancelled() && + (!found->second->poll_demand || found->second->poll_demand()); + } + void cancel_pending_poll(unsigned key) { + const std::lock_guard lock(mutex_); + const auto found = entries_.find(key); + if (found != entries_.end() && !found->second->claimed) { + // Active readers remain attached even when feedback satisfies a poll. + found->second->requested_by_poll = false; + changed_.notify_all(); + } + } + bool has_pending(unsigned key) { + const std::lock_guard lock(mutex_); + const auto found = entries_.find(key); + return found != entries_.end() && !found->second->claimed && demand_locked(*found->second); + } + bool serve_pending(unsigned key, const std::shared_ptr &lane) { + std::unique_lock lock(mutex_); + const auto found = entries_.find(key); + if (found == entries_.end() || found->second->claimed || !demand_locked(*found->second)) { + return false; + } + auto entry = found->second; + entry->claimed = true; + const auto previous_poll = current_poll_; + const auto previous_active_poll = active_poll_; + current_poll_ = entry->requested_by_poll && !entry->poll_cancel.cancelled() && + (!entry->poll_demand || entry->poll_demand()); + active_poll_ = active_poll_ || current_poll_; + for (auto it = queue_.begin(); it != queue_.end(); ++it) { + if (it->second == entry) { + queue_.erase(it); + break; + } + } + lock.unlock(); + std::optional value; + std::exception_ptr error; + try { + value.emplace(entry->execute(lane)); + } catch (...) { + error = std::current_exception(); + } + lock.lock(); + if (!entry->done) { + try { + entry->value = std::move(value); + entry->error = error; + } catch (...) { + entry->error = std::current_exception(); + } + entry->completed_at = Clock::now(); + entry->done = true; + } + if (const auto it = entries_.find(key); it != entries_.end() && it->second == entry) { + entries_.erase(it); + } + current_poll_ = previous_poll; + active_poll_ = previous_active_poll; + changed_.notify_all(); + lock.unlock(); + ::linkerbot::hand::detail::rethrow_nested_connection_failure(error); + return true; + } // Must precede runtime cancellation/draining. No late result can complete // a waiter from an invalidated generation. void invalidate() { @@ -162,7 +258,7 @@ namespace linkerbot::hand::unified_detail { } bool claimed_by_poll() { const std::lock_guard lock(mutex_); - return active_poll_; + return current_poll_; } size_t waiter_count() { const std::lock_guard lock(mutex_); @@ -266,6 +362,7 @@ namespace linkerbot::hand::unified_detail { } active_poll_ = entry->requested_by_poll && !entry->poll_cancel.cancelled() && (!entry->poll_demand || entry->poll_demand()); + current_poll_ = active_poll_; entry->claimed = true; } value.emplace(entry->execute(lease)); @@ -291,6 +388,7 @@ namespace linkerbot::hand::unified_detail { } active_ = false; active_poll_ = false; + current_poll_ = false; changed_.notify_all(); } } @@ -305,6 +403,7 @@ namespace linkerbot::hand::unified_detail { bool accepting_ = true; bool active_ = false; bool active_poll_ = false; + bool current_poll_ = false; bool stopping_ = false; std::thread worker_; }; diff --git a/src/hand/unified/detail/runtime_access.hpp b/src/hand/unified/detail/runtime_access.hpp index 941c6581..bd39cdce 100644 --- a/src/hand/unified/detail/runtime_access.hpp +++ b/src/hand/unified/detail/runtime_access.hpp @@ -43,6 +43,10 @@ namespace linkerbot::hand::unified_detail { static void set_polling_gate(runtime::DeviceRuntime &runtime, PollingGate gate); static void wait_endpoint_quiet(runtime::DeviceRuntime &runtime, std::chrono::milliseconds quiet, runtime::Deadline deadline, const std::function &cancelled); + using StageBoundary = std::function; + static void with_stage_boundaries(StageBoundary, runtime::DeviceRuntime &, const std::function &); + static void stage_boundary(runtime::DeviceRuntime &); + static void fault_nested_transaction(runtime::DeviceRuntime &, std::exception_ptr); using PlanTransform = std::function; static void with_response_windows(runtime::DeviceRuntime &runtime, PlanTransform transform, const std::function &execute, diff --git a/src/hand/unified/device.cpp b/src/hand/unified/device.cpp index cd64e75a..65b577b7 100644 --- a/src/hand/unified/device.cpp +++ b/src/hand/unified/device.cpp @@ -305,8 +305,12 @@ namespace linkerbot::hand { [[nodiscard]] std::unique_ptr create_backend() { if (python_health_) { - return unified_detail::make_backend_with_python_health(config_, transport_factory_, shared_session_, - python_health_); + auto backend = unified_detail::make_backend_with_python_health(config_, transport_factory_, + shared_session_, python_health_); + backend->set_angle_dispatch( + [this] { return scheduler_->pending_angle_at(); }, + [this](const std::shared_ptr &lane) { return scheduler_->run_angle(lane); }); + return backend; } return unified_detail::make_backend(config_, transport_factory_, shared_session_); } @@ -606,7 +610,7 @@ namespace linkerbot::hand { } auto lease = begin_io(context, operation); auto sample = complete_io(context, operation, [&] { return context.backend->read(semantic, timeout); }); - auto generation = context.backend->health().connection_generation; + auto generation = context.backend->connection_generation(); finish_io(context, operation); if (config_.runtime_behavior == RuntimeBehavior::kPython) { const std::lock_guard lock(mutex_); diff --git a/src/hand/unified/python_state.cpp b/src/hand/unified/python_state.cpp index aebeb3aa..bd738d3e 100644 --- a/src/hand/unified/python_state.cpp +++ b/src/hand/unified/python_state.cpp @@ -33,8 +33,9 @@ namespace linkerbot::hand::unified_detail { } } - PythonState::PythonState(const HandDeviceConfig &config) - : config_(config), base_capabilities_(declared_capabilities(config)) { + PythonState::PythonState(const HandDeviceConfig &config, Now now) + : now_(now ? std::move(now) : Now{runtime::Clock::now}), config_(config), + base_capabilities_(declared_capabilities(config)) { const auto caps = declared_capabilities(config); for (const auto &channel : caps.telemetry) { domains_.emplace(domain(channel.semantic), channel.semantic); @@ -127,6 +128,13 @@ namespace linkerbot::hand::unified_detail { if (found == domains_.end() && !identity) { return; } + if (found != domains_.end() && found->second == S::kAngles && + sample.origin == protocol::Origin::command_feedback) { + const auto *command = base_capabilities_.command(CommandSemantic::kAngles); + if (!command || !command->returns_current_state) { + return; // A target echo is not a measurement or sampling evidence. + } + } // Keep only complete, declared channels. Partial assembler domains and // externally published names cannot grow the retained view. current_.samples[name] = sample; @@ -153,7 +161,7 @@ namespace linkerbot::hand::unified_detail { ++state.commands; if (state.channel.angle_feedback != AngleFeedbackPolicy::kQueryOnly) { ++state.feedback; - state.next = std::max(state.next, runtime::Clock::now() + state.channel.interval); + state.next = std::max(state.next, now_() + state.channel.interval); } } } @@ -237,27 +245,34 @@ namespace linkerbot::hand::unified_detail { } visible_locked(false); } - void PythonState::read_succeeded(S semantic, bool polling) { + uint64_t PythonState::poll_revision() const { + const std::lock_guard lock(mutex_); + return plan_sequence_; + } + void PythonState::read_succeeded(S semantic, bool polling, std::optional revision) { const std::lock_guard lock(mutex_); if (optional(semantic)) { failures_.erase(semantic); verified_.insert(semantic); } + if (revision && *revision != plan_sequence_) { + return; // Completion from an earlier plan cannot enter the new window. + } if (auto poll = polls_.find(semantic); poll != polls_.end()) { ++poll->second.reads; if (!(semantic == S::kAngles && poll->second.channel.angle_feedback == AngleFeedbackPolicy::kCommandFeedbackOnly)) { ++poll->second.feedback; if (!polling) { - poll->second.next = - std::max(poll->second.next, runtime::Clock::now() + poll->second.channel.interval); + poll->second.next = std::max(poll->second.next, now_() + poll->second.channel.interval); } } } } - void PythonState::read_failed(S semantic, bool sent, const HandError &error, bool polling) { + void PythonState::read_failed(S semantic, bool sent, const HandError &error, bool polling, + std::optional revision) { const std::lock_guard lock(mutex_); - if (polling) { + if (polling && (!revision || *revision == plan_sequence_)) { if (auto poll = polls_.find(semantic); poll != polls_.end()) { ++poll->second.timeouts; } @@ -309,7 +324,7 @@ namespace linkerbot::hand::unified_detail { } auto retained = plan; std::map next; - const auto now = runtime::Clock::now(); + const auto now = now_(); for (const auto &channel : resolved.queries) { next.emplace(channel.semantic, Poll{channel, @@ -343,12 +358,20 @@ namespace linkerbot::hand::unified_detail { } return result; } - std::optional PythonState::take_poll() { + bool PythonState::angle_command_fulfills_due(bool pending_poll) const { + const std::lock_guard lock(mutex_); + const auto found = polls_.find(S::kAngles); + const auto *command = base_capabilities_.command(CommandSemantic::kAngles); + return command && command->returns_current_state && !stopped_ && found != polls_.end() && + found->second.enabled && found->second.channel.angle_feedback != AngleFeedbackPolicy::kQueryOnly && + (pending_poll || found->second.next <= now_()); + } + std::optional PythonState::take_poll(std::optional only) { const std::lock_guard lock(mutex_); - const auto now = runtime::Clock::now(); + const auto now = now_(); auto selected = polls_.end(); for (auto it = polls_.begin(); it != polls_.end(); ++it) { - if (it->second.enabled && it->second.next <= now && + if ((!only || it->first == *only) && it->second.enabled && it->second.next <= now && (selected == polls_.end() || it->second.next < selected->second.next)) { selected = it; } @@ -373,7 +396,7 @@ namespace linkerbot::hand::unified_detail { } void PythonState::project_health(HandHealth &health) const { const std::lock_guard lock(mutex_); - const auto now = runtime::Clock::now(); + const auto now = now_(); const auto caps = capabilities_locked(base_capabilities_); health.channels.clear(); health.force_fields.clear(); @@ -450,14 +473,14 @@ namespace linkerbot::hand::unified_detail { sample->meta = found->second; sample->meta.origin = origin; sample->meta.within_declared_range = range; - complete_freshness(sample->meta, caps.telemetry_channel(semantic), runtime::Clock::now()); + complete_freshness(sample->meta, caps.telemetry_channel(semantic), now_()); } }); if (const auto identity = view.samples.find("python/identity"); identity != view.samples.end()) { snapshot.device_info = std::any_cast(identity->second.value); // Identity owns its logical sequence, independently of native queries. snapshot.device_info->meta.connection_generation = identity->second.device_generation; - complete_freshness(snapshot.device_info->meta, nullptr, runtime::Clock::now()); + complete_freshness(snapshot.device_info->meta, nullptr, now_()); } std::vector> scalars; for (const auto semantic : {S::kForceFns, S::kForceFts, S::kForceFds, S::kForcePx}) { @@ -509,7 +532,7 @@ namespace linkerbot::hand::unified_detail { } } complete_force_meta(*snapshot.force, snapshot.force->meta.connection_generation, caps); - complete_freshness(snapshot.force->meta, caps.telemetry_channel(S::kForce), runtime::Clock::now()); + complete_freshness(snapshot.force->meta, caps.telemetry_channel(S::kForce), now_()); } } } diff --git a/tests/hand/device/test_python_tactile_scheduling.cpp b/tests/hand/device/test_python_tactile_scheduling.cpp new file mode 100644 index 00000000..c9b0094e --- /dev/null +++ b/tests/hand/device/test_python_tactile_scheduling.cpp @@ -0,0 +1,1050 @@ +#include "../../../src/hand/unified/detail/python_stage_scheduling.hpp" +#include "../../../src/hand/unified/detail/python_state.hpp" +#include "../../../src/hand/unified/detail/python_transactions.hpp" +#include "../../../src/hand/unified/detail/read_coordinator.hpp" +#include "../../../validation/fake_classic_hand.hpp" +#include "hand/l30/comm_helpers.hpp" +#include "hand/o30/comm_helpers.hpp" +#include "hand/support/optional_value.hpp" +#include +#include +#include +#include +#include +#include + +using namespace linkerbot::hand; +using namespace std::chrono_literals; +namespace { + using Message = linkerbot::can::Message; + struct Script { + std::promise first_finger; + std::promise resume; + std::shared_future release = resume.get_future().share(); + std::atomic gate{false}; + std::atomic slow_angles{false}; + std::atomic bad_angles{false}; + std::atomic missing_row{false}; + std::atomic held_finger{0}; + std::atomic hold_angle{false}; + std::atomic feedback_mode{0}; // actual / missing / malformed / transport failure + std::atomic angle_queries{0}; + std::atomic angle_writes{0}; + std::atomic finger_requests{0}; + std::function on_angle; + Model model; + explicit Script(Model value) : model(value) {} + std::vector reply(const Message &request) { + const auto opcode = request.data[0]; + if (opcode >= 0xB1 && opcode <= 0xB5) { + ++finger_requests; + if (held_finger == opcode) { + return {}; + } + if (opcode == 0xB1 && gate.exchange(false)) { + first_finger.set_value(); + release.wait(); + } + std::vector rows; + const size_t count = model == Model::kO6 ? 10 : 12; + for (size_t row = 0; row < count; ++row) { + if (missing_row && opcode == 0xB1 && row == count - 1) { + continue; + } + auto frame = request; + frame.dlc = model == Model::kO6 ? 6 : 8; + frame.data[1] = static_cast(row); + std::fill(frame.data.begin() + 2, frame.data.begin() + frame.dlc, opcode); + rows.push_back(frame); + } + return rows; + } + if (opcode == 0xC0) { + const std::string code = model == Model::kL6 ? "LHL6-1-123-L" + : model == Model::kO6 ? "LHO6-1-123-L" + : model == Model::kL20 ? "LHT20-1-123-L" + : "LHT10-1-123-L"; + std::vector frames; + for (size_t chunk = 0; chunk < 4; ++chunk) { + auto frame = request; + frame.dlc = 8; + frame.data[1] = static_cast(model == Model::kL20Lite ? chunk * 6 : chunk); + for (size_t index = 0; index < 6; ++index) { + const auto offset = chunk * 6 + index; + frame.data[index + 2] = offset < code.size() ? static_cast(code[offset]) : 0; + } + frames.push_back(frame); + } + return frames; + } + if (opcode == 0xC1 || opcode == 0xC2 || opcode == 0xC4) { + auto frame = request; + frame.dlc = model == Model::kL6 && opcode == 0xC1 ? 5 : 4; + frame.data[1] = 1; + frame.data[2] = 2; + frame.data[3] = 3; + return {frame}; + } + if (opcode == 1 && request.dlc == 1) { + ++angle_queries; + if (on_angle) { + on_angle(request); + } + if (hold_angle) { + return {}; + } + } + if (opcode == 1 && request.dlc > 1) { + ++angle_writes; + if (on_angle) { + on_angle(request); + } + if (feedback_mode == 3) { + throw linkerbot::can::TransportIOError("nested angle physical send failed"); + } + if (feedback_mode == 1) { + return {}; + } + if (feedback_mode == 2) { + auto bad = request; + bad.dlc = 2; + return {bad}; + } + } + if (slow_angles && request.dlc == 1) { + std::this_thread::sleep_for(3ms); + } + auto frame = request; + frame.dlc = bad_angles && request.dlc == 1 ? 2 + : model == Model::kL20Lite ? (opcode == 1 ? 7 + : opcode == 4 ? 5 + : 6) + : 7; + for (size_t index = 1; index < frame.dlc; ++index) { + frame.data[index] = request.dlc > 1 ? request.data[index] : 64; + } + return {frame}; + } + }; + struct Device { + std::shared_ptr