From 10bd39f87ba37f972c4333af2c5c1a2be3e01633 Mon Sep 17 00:00:00 2001 From: ouyangshun <1246787391@qq.com> Date: Wed, 11 Nov 2026 16:52:18 +0800 Subject: [PATCH 01/10] feat(runtime): expose safe tactile stage boundaries Add scoped, nonrecursive callbacks between complete tactile stages. Read Python L20 and L20Lite fingers sequentially while publishing only complete whole-hand samples; preserve the Native aggregate path. --- src/hand/l20/force_sensor.cpp | 25 +++++++++++++----- src/hand/l20lite/force_sensor.cpp | 25 +++++++++++++----- src/hand/l6/force_sensor.cpp | 4 +++ src/hand/o30/client.cpp | 4 +++ src/hand/o6/force_sensor.cpp | 4 +++ src/hand/runtime/device_runtime.cpp | 30 ++++++++++++++++++++++ src/hand/unified/detail/runtime_access.hpp | 3 +++ 7 files changed, 83 insertions(+), 12 deletions(-) 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..fd9ecd6d 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,32 @@ void linkerbot::hand::unified_detail::RuntimeAccess::logical_transaction_succeed device.impl_->consecutive_errors = 0; } } + +void linkerbot::hand::unified_detail::RuntimeAccess::with_stage_boundaries(runtime::DeviceRuntime &device, + StageBoundary boundary, + 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); + } +} diff --git a/src/hand/unified/detail/runtime_access.hpp b/src/hand/unified/detail/runtime_access.hpp index 941c6581..d28d79a8 100644 --- a/src/hand/unified/detail/runtime_access.hpp +++ b/src/hand/unified/detail/runtime_access.hpp @@ -43,6 +43,9 @@ 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(runtime::DeviceRuntime &, StageBoundary, const std::function &); + static void stage_boundary(runtime::DeviceRuntime &); using PlanTransform = std::function; static void with_response_windows(runtime::DeviceRuntime &runtime, PlanTransform transform, const std::function &execute, From 687a5a42b298ca959740cc9304c4e5c0e7ae7da6 Mon Sep 17 00:00:00 2001 From: ouyangshun <1246787391@qq.com> Date: Wed, 11 Nov 2026 16:52:18 +0800 Subject: [PATCH 02/10] fix(python): align angle feedback and polling plan accounting Accept only declared current-state feedback as angle sampling evidence. Correct the O30 V25 capability and collect optional O6 angle feedback. Fence read completion counters by polling plan revision and provide an internal clock seam for exact deadline regression tests. --- src/hand/capabilities/o30.cpp | 2 +- src/hand/unified/detail/python_state.hpp | 13 +++-- .../unified/detail/python_transactions.hpp | 11 ++++ src/hand/unified/python_state.cpp | 55 +++++++++++++------ 4 files changed, 60 insertions(+), 21 deletions(-) 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/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..5653a3e8 100644 --- a/src/hand/unified/detail/python_transactions.hpp +++ b/src/hand/unified/detail/python_transactions.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace linkerbot::hand::unified_detail { @@ -55,6 +56,16 @@ 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 (!plan.consume) { return plan; } 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_()); } } } From bf4266efedb3aa7ecca727832e437ee6de4eebbe Mon Sep 17 00:00:00 2001 From: ouyangshun <1246787391@qq.com> Date: Wed, 11 Nov 2026 16:52:18 +0800 Subject: [PATCH 03/10] feat(python): schedule bounded angle work between tactile stages Reuse the active device lease for pending angle targets and merged reads. Limit each boundary to four logical transactions, alternate reads and writes, and preserve finite execution budgets and actual send receipts. Propagate nested connection failures while retaining ordinary inner errors and isolate poll ownership during reentrant reads. --- src/hand/detail/failure_kind.hpp | 18 +++ src/hand/unified/backend.cpp | 133 +++++++++++++++++- src/hand/unified/command_scheduler.cpp | 115 ++++++++++----- src/hand/unified/detail/backend.hpp | 3 + src/hand/unified/detail/command_scheduler.hpp | 4 + .../detail/python_stage_scheduling.hpp | 35 +++++ src/hand/unified/detail/read_coordinator.hpp | 101 ++++++++++++- src/hand/unified/device.cpp | 8 +- 8 files changed, 368 insertions(+), 49 deletions(-) create mode 100644 src/hand/unified/detail/python_stage_scheduling.hpp diff --git a/src/hand/detail/failure_kind.hpp b/src/hand/detail/failure_kind.hpp index d480a7a9..54f6d10e 100644 --- a/src/hand/detail/failure_kind.hpp +++ b/src/hand/detail/failure_kind.hpp @@ -4,6 +4,24 @@ #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. + } + } enum class FailureKind { timeout, lifecycle, closed, other }; inline FailureKind failure_kind(std::exception_ptr error) noexcept { if (!error) { diff --git a/src/hand/unified/backend.cpp b/src/hand/unified/backend.cpp index 1d982564..c07359a9 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(); @@ -641,9 +647,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 +811,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 +902,23 @@ 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( + *device_->runtime(), + [&] { + if (config_.model == Model::kO30 && first_o30_stage) { + first_o30_stage = false; + return; + } + service_angle_boundary(valid, lane); + }, + [&] { (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 +945,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 +959,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 +986,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..51fd7bc1 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; } 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/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/device.cpp b/src/hand/unified/device.cpp index cd64e75a..3243d7f0 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_); } From 5ca5bef20ffd0d5626bcb28b04464b15de9e5449 Mon Sep 17 00:00:00 2001 From: ouyangshun <1246787391@qq.com> Date: Wed, 11 Nov 2026 16:52:18 +0800 Subject: [PATCH 04/10] test(python): cover tactile scheduling and lifecycle boundaries Cover feedback policies, complete protocol boundaries, bounded mixed loads, nested failures, polling replacement, close, recovery, and shared Session isolation with FakeTransport and controlled synchronization. Validation: 24 tactile scheduling cases and 450 assertions passed. Full offline CTest passed all 10 groups on macOS arm64 with C++17 and SOURCE transport v0.3.4. No new hardware validation was performed. --- .../device/test_python_tactile_scheduling.cpp | 1007 +++++++++++++++++ 1 file changed, 1007 insertions(+) create mode 100644 tests/hand/device/test_python_tactile_scheduling.cpp 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..4af8d76b --- /dev/null +++ b/tests/hand/device/test_python_tactile_scheduling.cpp @@ -0,0 +1,1007 @@ +#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 + +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