Layer 4–6 — Reasoning, Safety, Observability
Part of the OpenRAL public-symbol inventory. Hand-curated;
(LNN)markers are refreshed bytools/refresh_methods_linenos.py.
Layer 6 (Observability) is fully shipped — traces + metrics + structlog→OTLP log bridge, with W3C TraceContext propagation helpers for cross-process correlation (Python ↔ ROS 2 ↔ C++ safety kernel). Layer 4 (Reasoner) ships the live ReasonerCore direct-dispatch loop below; Layer 5 (C++ safety kernel) is still planned.
python/reasoner/src/openral_reasoner/tool_use.py
Typed LLM tool-use clients (direct-dispatch surface); the ReasonerToolCall union is the sole planner output.
- module constant
LIFECYCLE_PEER_NOTES: dict[str, str](L380) — What driving a well-known lifecycle peer does (todayopenral_estimated_depth_provider: deactivate stops the estimated world-collision cloud, the kernel's world check then stops arm motion, no VRAM freed; activate resumes it), appended to thelifecycle_transitiontool description by_tool_palette_to_anthropic_toolsfor each peer inpalette.node_ids(leading/ignored); the schema'snodeenum alone gives bare names. - module constant
DEFAULT_SYSTEM_PROMPT: str— Base S2 system prompt: one-tool-per-tick, safe skill selection, never bypass e-stop, exact field names,waitwhile a skill runs. Deployments may override. (L105) - module constants
ANTHROPIC_BASE_URL/OPENAI_BASE_URL/OPENROUTER_BASE_URL/OLLAMA_BASE_URL/OLLAMA_CLOUD_BASE_URL/VLLM_BASE_URL/GEMINI_BASE_URL/XAI_BASE_URL/DEEPSEEK_BASE_URL/HUGGINGFACE_BASE_URL: str— Named-endpoint base URLs; canonical copy now lives inopenral_core.schemas, re-exported here unchanged. - module constant
_ENDPOINT_PRESETS: dict[str, ReasonerEndpointPreset]— Back-compat alias ofopenral_core.REASONER_ENDPOINT_PRESETS: per-endpointurl/dialect/auth_required/timeout_s/tool_choicefor eachOPENRAL_REASONER_ENDPOINTname. The curated model-first path takes only the endpoint properties from it; the uncurated path takes all five. (L989) - module constant
SYSTEM_PROMPT_ENV_VAR: str = "OPENRAL_REASONER_SYSTEM_PROMPT"(L502) — env var that overrides the base operating brief; honoured byresolve_reasoner_system_prompt. render_robot_context_prompt(capabilities: RobotCapabilities | None, *, base_prompt=DEFAULT_SYSTEM_PROMPT) -> str(L391) — Appends a deterministic## THIS ROBOTbody-awareness block (embodiment, locomotion, manipulation/sensing, payload, control modes) to the prompt;Nonereturnsbase_promptunchanged. No cell geometry is listed: place surfaces are measured, not surveyed.resolve_reasoner_system_prompt(capabilities: RobotCapabilities | None, *, env=None) -> str(L505) — Composes the full reasoner system prompt (env override or default base brief +## THIS ROBOTblock).envis injectable for tests; called fromReasonerNode.on_configure.class ToolUseClient(Protocol)(L552) — LLM tool-use client contract:model_id, optionallast_prompt_tokens. RaisesROSReasonerInvalidPlanon a bad/mismatched tool call,ROSPlanningErroron transport failure.select_tool(self, *, context_text, palette, system_prompt=DEFAULT_SYSTEM_PROMPT) -> ReasonerToolCall(L574) — Pick exactly oneReasonerToolCallforcontext_text.describe_image(self, *, image_jpeg, question) -> str(L606) — Ask the model a free-text question about a single camera frame.class OpenAICompatibleToolUseClient— OpenAI-compatible tool-use client.tool_choice='auto'covers endpoints that reject'required'(nudges once on a prose reply, then raisesROSReasonerInvalidPlan);max_tokensoptionally caps completion tokens, else the endpoint default applies;max_tokens_paramnames the cap field, switched tomax_completion_tokensat runtime when the endpoint asks for it.- module constant
REASONER_MODEL_ENV: str = "OPENRAL_REASONER_MODEL"(L640) - module constant
REASONER_ENDPOINT_ENV: str = "OPENRAL_REASONER_ENDPOINT"(L641) - module constant
REASONER_API_KEY_ENV: str = "OPENRAL_REASONER_API_KEY"(L642) - module constant
REASONER_DIALECT_ENV: str = "OPENRAL_REASONER_DIALECT"(L643) - module constant
REASONER_MAX_TOKENS_ENV: str = "OPENRAL_REASONER_MAX_TOKENS"(L644) - module constant
REASONER_TIMEOUT_ENV: str = "OPENRAL_REASONER_TIMEOUT_S"(L645) — model-first env names (ADR-0088). - module constant
DEFAULT_FIRST_CALL_TIMEOUT_S: float = 120.0(L653) — default ofOPENRAL_REASONER_FIRST_CALL_TIMEOUT_S. - module constant
REASONER_FIRST_CALL_TIMEOUT_ENV: str = "OPENRAL_REASONER_FIRST_CALL_TIMEOUT_S"(L652) — #665: the timeout of an openai-dialect client's requests until its endpoint first replies (a cold local model's load). The factory's_first_call_timeout_s(known_cloud=…)reads it (finite, ≥ 0, elseROSConfigError), defaulting toDEFAULT_FIRST_CALL_TIMEOUT_Sunless the endpoint is a known cloud one (a named endpoint that takes a key, or a curated cloud model's registry endpoint), and passes it asOpenAICompatibleToolUseClient(first_call_timeout_s=…);_sendapplies it as the read timeout of each request until the first reply, and again after anAPITimeoutError(a model the server unloaded reloads on the next request); logged asreasoner.llm.first_call_timeout. At or belowtimeout_sit does nothing; the class default is0.0(off). - module constant
REASONER_TOOL_CHOICE_ENV: str = "OPENRAL_REASONER_TOOL_CHOICE"(L664) —auto/requiredoverride for an uncurated model on a bare-URLopenaiendpoint or on theanthropicdialect (required→ Anthropicany); validated on every path viaopenral_core.parse_reasoner_tool_choice, and ignored with areasoner.tool_choice_ignoredwarning for curated models and namedopenaiendpoints. - module constant
_ANTHROPIC_UNCURATED_MAX_TOKENS: int = 16000— completion cap for an uncuratedanthropicmodel with noOPENRAL_REASONER_MAX_TOKENS(thinking counts against it). - module constant
_NO_TOOL_CALL_NUDGE: str— the one-shot follow-up sent when atool_choice='auto'model answers in prose. _rejects_forced_tool_choice(exc) -> bool— True for a provider HTTP 400 worded as a forced-tool-use refusal (Claude 5's"any"refusal, thinking-mode gateways, the HF router, thinking-with-forced-tool), not any 400 that merely mentionstool_choiceor itsdisable_parallel_tool_usesub-field; triggers the runtimerequired→autoretry._rejects_max_tokens(exc) -> bool— True for an OpenAI 400 asking formax_completion_tokens._prose_reply_error(text, *, model_id) -> ROSReasonerInvalidPlan— The error for anautoreply with no tool call after the nudge (#522): quotes the text (whitespace-collapsed, ≤300 chars) so the node feeds it back into## EXECUTION; loggedreasoner.no_tool_call. Not await, which is retry-cap exempt and sends no hint back._log_tool_choice_downgrade(model_id, exc) -> None— The onereasoner.tool_choice_downgradedlog both clients emit after a successfulautoretry._sum_prompt_tokens(*counts) -> int | None— Prompt tokens over a tick's calls (the nudge is a second billed call).- module constant
_FORCED_TOOL_CHOICE_REFUSALS: tuple[re.Pattern[str], ...]— Provider wordings of a forced-tool-use refusal that_rejects_forced_tool_choicematches. _openai_tool_calls(choices) -> list/_openai_may_nudge(choices) -> bool— First choice's tool calls; whether a tool-less reply is nudge-worthy (notlength/content_filter)._anthropic_tool_use_block(response)/_anthropic_may_nudge(response) -> bool— Firsttool_useblock orNone; whether a tool-less reply is nudge-worthy (notrefusal/max_tokens).- module constant
REASONER_MAX_SKILL_TOOLS_ENV: str = "OPENRAL_REASONER_MAX_SKILL_TOOLS"(L655) — per-tick skill-tool cap override read byresolve_max_skill_tools;0= no cap. resolve_max_skill_tools(client) -> int | None(L1088) — The per-tick skill-tool cap for the modelclienttalks to (#494):OPENRAL_REASONER_MAX_SKILL_TOOLSwhen set (0→None, negative / non-integer →ROSConfigError), else themax_skill_toolsof the curatedReasonerModelwhoseserved_model_idisclient.model_id, elseNone. Keyed on the built (or injected) client so the two cannot disagree;ReasonerNode.on_configureresolves it right after building the client, before any resource opens.build_tool_use_client_from_env() -> ToolUseClient— Model-first client factory:OPENRAL_REASONER_MODELresolvesopenral_core.REASONER_MODELSfor dialect/endpoint/auth/hosting/tool-choice/token-cap;OPENRAL_REASONER_ENDPOINToverrides location (a named preset, a bare URL, ormanaged);API_KEY/MAX_TOKENS/TIMEOUT_Soverride the rest. With no endpoint set, a registry default that is a named endpoint's URL brings that preset's properties (a curated Ollama model gets Ollama's 60 s timeout andauto).DIALECTis needed only for a bare URL and always wins when set. No hidden model default. On an Ollama reply (system_fingerprintfp_ollama)OpenAICompatibleToolUseClient.select_toolraisesROSPlanningErrorwhen the reported prompt tokens show the server truncated the prompt to its context window. (L1007)class AnthropicToolUseClient(L2132) — Anthropic SDK-backed client; builds/reuses one client/HTTP pool and marks the static system/tools prefix cacheable.tool_choicerequired(sent asany) orauto; a forced-tool-use refusal downgrades toautofor the client's life once anautoretry succeeds (reasoner.tool_choice_downgraded)._create(self, client, **kwargs)—messages.createwith the currenttool_choice, retried once asautoon a forced-tool-use refusal; the downgrade is kept only if that retry succeeds._wire_tool_choice(self) -> dict—{"type": "any"|"auto", "disable_parallel_tool_use": True}.select_tool(self, *, context_text, palette, system_prompt=DEFAULT_SYSTEM_PROMPT) -> ReasonerToolCall(L2260) — Call Anthropic and decode the resulting tool payload; underautoa prose reply is nudged once, then raisesROSReasonerInvalidPlan; a refusal ormax_tokenscut-off raisesROSPlanningError.last_prompt_tokenssums both calls.describe_image(self, *, image_jpeg, question) -> str(L2337) — Ask the Anthropic model a free-text question about a camera frame._anthropic_response_text(response) -> str— Concatenate all text blocks so thinking-enabled responses do not lose an answer after a leading thinking block.class OpenAICompatibleToolUseClient(L2384) — OpenAI-compatible client with cached SDK/HTTP pool, endpoint/tool-choice/token-cap configuration, and image-description support.select_tool(self, *, context_text, palette, system_prompt=DEFAULT_SYSTEM_PROMPT) -> ReasonerToolCall(L2537) — Call the OpenAI-compatible endpoint and decode the tool call; underautoa prose reply is nudged once, then raisesROSReasonerInvalidPlan; alength/content_filterfinish raisesROSPlanningError.last_prompt_tokenssums both calls._complete(self, client, messages, tools) -> tuple[list, Any]— Onechat.completions.create, adapting at runtime to a forced-tool-use refusal (→auto) and amax_completion_tokens400; each adaptation is logged and kept only after a call made with it succeeds.describe_image(self, *, image_jpeg, question) -> str(L2677) — Ask an OpenAI-compatible model a free-text question about a frame.class OpenAIResponsesToolUseClient(OpenAICompatibleToolUseClient)(L2738) —ToolUseClientover OpenAI's Responses API (/v1/responses), built for theopenaiendpoint: OpenAI's reasoning models take function tools only there. Same tick contract as the Chat Completions client (forced call, runtimeautodowngrade, one nudge thenROSReasonerInvalidPlan, refusal /max_output_tokenscut-off →ROSPlanningError);store=False,parallel_tool_calls=False, reasoning left at the model default,max_tokenssent asmax_output_tokens._respond(self, client, instructions, inputs, tools)— Oneresponses.create, retried once asautoon a forced-tool-use refusal.select_tool(self, *, context_text, palette, system_prompt=DEFAULT_SYSTEM_PROMPT) -> ReasonerToolCall(L2804) — Call the Responses API and decode thefunction_calloutput item.describe_image(self, *, image_jpeg, question) -> str(L2847) — Frame question asinput_text+input_imageover the Responses API._openai_client_cls(preset, base_url) -> type[OpenAICompatibleToolUseClient]— Responses client for OpenAI's own API (preset.wire_api == "responses", or its URL spelled out), Chat Completions client for every other openai-dialect endpoint._decode_function_call(name, raw_arguments, palette) -> ReasonerToolCall— Shared JSON-arguments check (malformed / non-object →ROSReasonerInvalidPlan) then_decode_tool_payload, for both OpenAI wire APIs._tool_palette_to_responses_tools(palette) -> list[dict]— The palette as flat Responses-API function tools withstrict: False._responses_function_call(response)/_responses_text(response) -> str/_responses_refusal(response) -> str | None/_responses_may_nudge(response) -> bool— Responses output readers: firstfunction_callitem; concatenatedoutput_text; refusal text; whether a tool-less reply is nudge-worthy (complete, not refused, no error)._tool_palette_to_anthropic_tools(palette) -> list[dict]— Render the closed palette, includingWaitTool; per-skill names use collision-resistantexecute_rskill__<slug>_<sha1-8>.lifecycle_transition'snodecarriesenum: sorted(palette.node_ids)(the decoder refuses anything else); with no peers its description says every call is refused._tool_palette_to_openai_tools(palette) -> list[dict]— Convert the same surface to OpenAI function shape without leaking the Anthropic-onlyinput_schemakey._decode_tool_payload(*, tool_name, arguments, palette) -> ReasonerToolCall— Validate provider output against the union + palette; per-skill names resolve through the same hashed mapping used to render them. Alifecycle_transitionwhosenodeis not inpalette.node_idsraisesROSReasonerInvalidPlan.- module constant
_PER_SKILL_TOOL_PREFIX: str = "execute_rskill__"— prefix the decoder matches on to identify per-skill tool calls. (L1494) - module constant
_LLM_TOOL_NAME_MAX_LEN: int = 64— Anthropic + OpenAI tool-name regex limit; long HF Hub ids are sha1-suffix-truncated to fit. (L1497) _skill_id_to_tool_name(rskill_id: str) -> str— Map a<owner>/<repo>id into a collision-resistant 64-char-maxexecute_rskill__<slug>_<sha1-8>name. (L1500)_format_skill_tool_description(entry: RSkillToolEntry) -> str— Render the skill's id + description + actions + objects + scenes into the NL string the LLM scores, plus the object-tracking target rule whenentry.object_targetis set (_GRASP_TARGET_REQUIRED/_GRASP_TARGET_AND_HAND_REQUIRED/_OBJECT_TARGETS_NOT_APPLICABLE). (L1517)_llm_schema(model: type[BaseModel]) -> dict[str, Any]—model_json_schema(schema_generator=_LLMSchemaGenerator), which emits notitles and no model/enum docstrings; built once per class, cached as a JSON string and returned as a fresh dict; field descriptions are kept and are the LLM's only field guidance, so every reasoner tool field must have one (#440). (L1609)class _LLMSchemaGenerator(GenerateJsonSchema)— Pydantic schema generator behind_llm_schema: drops the auto-generatedtitleof every field/model/enum and model/enum docstringdescriptions (an explicitField(title=...)and dataclass/TypedDict schemas keep theirs). (L1574)_llm_schema_json(model: type[BaseModel]) -> str—functools.cached JSON string of the stripped schema, one per class;_llm_schemaparses a fresh dict from it. (L1604)AnthropicToolUseClient._tools(palette)/OpenAICompatibleToolUseClient._tools(palette)— The provider tool list, rendered once per palette object (a registry refresh installs a new palette) instead of every tick; the Anthropic one carries the prompt-cache breakpoint. Each returns the list it rendered or read, never a re-read of the shared cache, so overlapping calls cannot swap palettes. (L2199)_drop_property(schema: dict, name: str) -> dict— Return a copy of a JSON Schema dict withnamestripped from bothpropertiesandrequired. Used to droprskill_idfrom per-skillExecuteRskillToolschemas. (L1998)- module constant
_TOOL_ADAPTER: TypeAdapter[ReasonerToolCall](L375) — cachedTypeAdapter(ReasonerToolCall)used to validate a decoded tool payload against the discriminated union.
python/reasoner/src/openral_reasoner/cosmos3.py
NVIDIA Cosmos 3 reasoner backend (OPENRAL_REASONER_MODEL=cosmos3-edge), the physical-AI-native S2 planner. Runs the on-device 4B Edge tier behind an OpenAI-compatible endpoint, so the typed tool-use contract is unchanged. Companion boot helper: tools/cosmos3_reasoner_sidecar.py.
- module constant
COSMOS3_BASE_URL: str—http://127.0.0.1:8901/v1; dedicated port so the sidecar never collides with a user-runvllm serveon :8000. (L68) - module constant
DEFAULT_COSMOS3_MODEL: str—nvidia/Cosmos3-Edge, served id of the curatedcosmos3-edgeregistry entry. (L74) - module constants
AUTOSTART_ENV/BOOT_TIMEOUT_ENV/SIDECAR_SCRIPT_ENV/DEFAULT_BOOT_TIMEOUT_S— env knobs:OPENRAL_COSMOS3_AUTOSTART(0disables managed spawn),OPENRAL_COSMOS3_BOOT_TIMEOUT_S(first boot provisions a venv + downloads weights; default 1800 s),OPENRAL_COSMOS3_SIDECAR(boot-helper path override). (L79) - module constant
BOOT_TIMEOUT_ENV: str = "OPENRAL_COSMOS3_BOOT_TIMEOUT_S"(L80) - module constant
SIDECAR_SCRIPT_ENV: str = "OPENRAL_COSMOS3_SIDECAR"(L81) - module constant
DEFAULT_BOOT_TIMEOUT_S: float = 1800.0(L82) — default boot timeout in seconds. - module constant
_LOOPBACK_HOSTS: frozenset[str](L87) —{"localhost", "127.0.0.1", "::1", "0.0.0.0"}, hostnames_managed_porttreats as loopback (a client URL may name0.0.0.0; the server never binds it). _bind_host(hostname: str) -> str(L90) — The address the autostarted sidecar binds for a_LOOPBACK_HOSTSname:::1stays::1, everything else (0.0.0.0,localhost) is127.0.0.1, so the unauthenticated vLLM is never exposed on every interface. Used by_spawn_argv.find_cosmos3_sidecar_script() -> Path— Locatetools/cosmos3_reasoner_sidecar.py(env override or repo-parent walk); raisesROSConfigErrorwhen an explicit override path is missing or the walk finds nothing. (L104)_managed_port(base_url) -> int | None— Explicit port of a loopback base URL, orNone(unmanaged, e.g. a portless reverse proxy). Autostart needs an explicit loopback port so spawn and readiness probe agree. (L136)class Cosmos3ToolUseClient(OpenAICompatibleToolUseClient)— Managed local sidecar client over the inherited OpenAI-compatible wire path; adds probe/spawn/readiness/teardown.warm()letsReasonerNode.on_configurestart the sidecar at bringup instead of on the first tick, overlapping the model load with other startup work. Idempotent: reuses a still-booting child instead of duplicate-spawning. (L172)warm(self) -> None(L363) — Start the managed sidecar now instead of on the first tick.select_tool(self, *, context_text, palette, system_prompt=DEFAULT_SYSTEM_PROMPT) -> ReasonerToolCall(L382) — Ensure the managed server is up, then run the OpenAI-compatible path.describe_image(self, *, image_jpeg, question) -> str(L397) — Ensure the managed server is up, then run the OpenAI-compatible path.close(self) -> None(L349) — Terminate the server child if (and only if) we spawned it.
python/reasoner/src/openral_reasoner/palette.py
Closed-set ToolPalette + builder. Three tool variants (reload_gst_pipeline / lifecycle_transition / emit_prompt) are always available; execute_skill is gated by the installed-rSkill registry filtered by RobotCapabilities + license posture.
class RSkillToolEntry(BaseModel)(L244) — Frozen per-skill record surfaced to the LLM as one tool:rskill_id,description,actions,objects,scenes,goal_params_schema, mirrored from the matchingRSkillManifestat palette-build time, plusquantization_dtype(the manifest'squantization.dtype; not shown to the LLM, read by the skill-subset precision tie-break),result_only(a wrapped ROS action/service with noresult_trajectory_field:ReasonerCorekeeps no backstop live while it is in flight on an unchanged context),completes_task_on_success(mirrorsRosIntegration.completes_task_on_success: the node completes the active mission task when the goal succeeds) andmax_execution_s(the manifest'slatency_budget.max_execution_s, sizinginflight_backstop_s); none is shown to the LLM.object_target("grasp_required"/"grasp_and_hand_required"/"not_applicable"/None, set bybuild_tool_palette(object_tracking=True, grasp_hand_required=...)fromRSkillManifest.actuates_manipulator) is:_format_skill_tool_descriptionappends the matching sentence (grasp_target required for an arm / gripper skill, its contact_links left unset because the deployment supplies the hand — or named, on a multi-hand robot with no declared hand; neither target applies to a base-only one).class ContinuousDetectorEntry(BaseModel)(L114) — Frozen coverage record for amode: continuousdetector, surfaced to the LLM as coverage (not a tool) so it can read tracked objects from world state and reservelocate_in_viewfor the long tail.class OnDemandDetectorEntry(BaseModel)(L221) — Frozen record for amode: on_demandopen-vocab locator, surfaced as a selectablelocate_in_viewoption — a read-only prompt-able tool, never an ExecuteRskill policy.detector_alias(rskill_name) -> str(L142) — Short LLM-/operator-facing detector id: strips theOpenRAL/org +rskill-kind prefixes. Single source of truth for the alias the reasoner routes on.detector_service_segment(alias) -> str(L155) — ROS-safe service-namespace segment for an alias (hyphens → underscores), so the locate service lives at/openral/perception/<segment>/locate_in_view.locate_in_view_service(detector, *, default="") -> str(L204) — Resolves thelocate_in_viewservice for a (possibly empty) selector: empty →default; unresolved alias → the legacy single-detector service; else the namespaced service.resolve_locate_in_view_detector(detector, *, known_aliases) -> str(L166) — Normalizes an LLM-supplieddetectorvalue to""when it names no configured on-demand locator, so an unrecognised alias degrades to the deployment default instead of a service that never existed.class ToolPalette(BaseModel)(L311) — Frozen palette presented to the LLM each tick: primaryskills, back-compatexecute_rskill_ids(auto-derived), sensor/node ids,continuous_detectors(coverage), and availability flags gating the read-only tools —spatial_memory_available(recall_object/resolve_place),detector_available(locate_in_view, withon_demand_detectorsas its options),scene_query_available(query_scene, independent of detection),memory_available(memory_write/memory_search). A cross-validator rejectsskills/execute_rskill_idspassed with disagreeing ids.skill(self, rskill_id: str | None) -> RSkillToolEntry | None— the entry forrskill_id, orNone(absent, or a palette without per-skill metadata). (L408)build_tool_palette(*, installed_skills, robot_capabilities, sensor_ids=(), node_ids=(), commercial_deployment=False, spatial_memory_available=False, detector_available=False, scene_query_available=False, task_progress_available=False, memory_available=False, object_tracking=False, grasp_hand_required=False, allowed_rskill_ids=None) -> ToolPalette(L465) — Builds the palette: a skill qualifies whenopenral_core.rskill_matches_robotadmits it (not the scaffold,kindinEXECUTE_RSKILL_KINDS, embodiment/capability/license checks) — the predicate the robot manifest'sskill:*actions share (ADR-0129). Acontinuousdetector becomes coverage only;on_demandbecomes alocate_in_viewoption;segmenteris dropped and surfaced nowhere. Output is id-sorted for a deterministic tool schema.object_tracking(the deploy'sobject_trackingis notoff; the reasoner node passes it) sets each entry'sobject_target;grasp_hand_required(several hands, nograsp_contact_links) picks the variant that asks for the hand.allowed_rskill_ids(the robot's curated list,OPENRAL_RSKILLS) admits only the listed actuating skills; detectors are not filtered.task_space_disagreement(manifest, description, hal_mode, legacy_ok) -> str | None(L56) — Warn-only shadow gate: compares the canonicaltask_space_compatibleverdict against the caller'slegacy_ok, returning a warning string only on disagreement (Noneotherwise, including for non-actuating skills). Surfaces cross-layer mismatches without changing the drop/publish decision.
python/reasoner/src/openral_reasoner/skill_subset.py
Top-k skill subset per mission task (#440, #494): small reasoner models (Cosmos3-Edge) emit runaway tool calls once they see many near-identical skill tools, so ReasonerCore offers only the best-matching few. Keyword overlap, deterministic and replayable from the trace; no new dependency. Pure, ROS-free.
- module constant
PRECISION_RANK: dict[QuantizationDtype, int](L58) — Tie-break rank of a skill's run dtype, lower first: fp32/bf16/fp16 0, fp8 1, int8 2, int4/nvfp4 3. A coarse prior, not a measurement. - module constant
SUPPORT_ACTIONS: frozenset[RSkillAction](L49) —{look, navigate}: the actions of the skills the system prompt's workflow uses around any object task (APPROACH / FRAME); the best skill of each action not already kept gets a slot, never the last free one. mission_keywords(text) -> frozenset[str](L153) — Case-folded content words oftextin any script (_/-split), short stopword list removed.query_keywords(text) -> frozenset[str](L190) —mission_keywordsplus theRSkillActionvalue an everyday verb names (put→place,point→look,move→reach, …); query side only.score_skill(entry, keywords) -> float(L234) — Relevance of oneRSkillToolEntry: each keyword counts once at the weight of the strongest field sharing one of its inflected forms (plurals,-ing,-ed; objects / actions 3, scenes / description / id 1).class SkillSubset(BaseModel)(L263) — Frozen result: the narrowedpalette,scoresfor every skill (best first, in tie-break order),query, the ids kept assticky/focused(top operator prompt's best match) /support, thetriedids demoted among ties, andk.offered(self) -> tuple[str, ...](L290) — Offered ids in palette order (sorted for an id-only palette).max_score(self) -> float(L297) — Best score;0.0means the query matched nothing and the pick falls to the tie-breaks.select_skill_subset(palette, *, query, k, sticky=(), focus="", recent=(), tried=()) -> SkillSubset(L334) — Fills at mostkslots in order: in-palettestickyids (in flight), the best match forfocus(with one skill in flight, anyk≥ 2 leaves it a slot),recentids (last dispatch), the bestSUPPORT_ACTIONSskill per action not already covered by a kept id (never the last free slot), then by score — so at least one ranked skill (the best untried substitute) is offered whenever a slot remains. Every pick (focus, support, ranked) orders by score, then not-in-tried, thenPRECISION_RANKofRSkillToolEntry.quantization_dtype, thenrskill_id. Query verbs map to actions through their inflected forms (dropped→place). Keeps the full palette's order and every non-skill field; an id-only palette is capped and focused on its ids. A palette with ≤kskills is returned as the same object;k< 1 raisesValueError.
python/reasoner/src/openral_reasoner/grounding.py
Grounds an ExecuteRskillTool's named targets into the goal's declarations (real pick-and-place design §2.2-2.3): the reasoner names, perception grounds, the producer measures. Pure, ROS-free; never supplies a region. A place target is an optional hint: the real producer measures the surface under the carried payload without one.
DECLARATION_TIMEOUT_MARGIN_S = GraspDeclaration.TIMEOUT_MARGIN_S(10 s) (L63) — Seconds a grounded declaration'stimeout_sexceeds the goal's patience ceiling (then capped at the declaration'sMAX_TIMEOUT_S).gripper_hands— re-exported fromopenral_core.gripper_hands(moved there so the HAL's approach-armed grasp target groups hands without importing the reasoner; seedocs/methods/00-core-schemas.md).ground_grasp_target(ref, *, live_objects, scene_graph, base_frame, default_contact_links, patience_s, pad_m, object_tracking=False, hand=None, declared_hand=()) -> GraspDeclaration(L240) —ref.object_idset → that spatial-memory node'sbbox_3d; else the single live lifted detection whose label equalsref.label(case-insensitive). The box, padded bypad_mon every side (downward too, so the support layer is inside it: a search hint with no support semantics; the producer measures the support) and gravity-aligned (identity quaternion inbase_frame), becomessearch_box;target_id="obj:<label or node_id>",region=None. RaisesROSReasonerInvalidPlanon no match, more than one match withoutobject_id, an unknown node id, a missing box, a box in a frame other thanbase_frame(no tf2 here: a fixed-base cell's lift must run in its base frame), no gripper joint, nocontact_linksnamed on a robot with more than one hand (defaulting would exempt every hand), named links that are not gripper child links of ONE hand, or only part of one hand's links (that would exempt one finger and the kernel would stop the grasp; the refusal lists the whole hand). Named links are accepted in any order and the declaration carries the hand's links in manifest order.default_contact_linksisgripper_hands(...)(a barestrelement is a one-link hand); an emptyref.contact_linksdefaults to the hand of a single-hand robot. Withobject_tracking(issue #418) it also carriestarget_queries=(ObjectQuery(ref.label, count, TARGET, hand),),count="all"when several live detections carry the label — which then grounds withsearch_box=None(target_id="obj:<label>") instead of being refused; a label no live detection carries grounds too (count="one",search_box=None: the tracker's standing query keeps looking and escalates to EXHAUSTED itself, Addendum G — tracking off still refuses); one match keeps itssearch_boxunchanged (side by side).handis a hint (openral_core.hand_joint).declared_hand(the deployment's declared grasping hand, the reasoner'sgrasp_contact_linksfrom the scene's grasp declaration) is used whenrefnames nocontact_links, under the same one-whole-hand rule; empty on a multi-hand robot, an unnamed hand is refused as before. Withobject_trackinga matching detection / memory node outsidebase_frame(the lift'smap), or with nobbox_3d, grounds with nosearch_box(loggedreasoner.grounding_seed_dropped; no tf2 in the reasoner) instead of refusing;ground_place_targetthe same; without tracking it still refuses. Withobject_trackingandref.object_idthe TARGET query'sseedis that node's box padded bypad_min the node's own frame (around its pose with nobbox_3d; not logged as a dropped seed): the tracker scopes the query to the one instance through tf2 (issue #631). A node whose padded box exceeds a region's bound refuses (ROSReasonerInvalidPlan);ground_place_targetnever builds the scope.ground_place_target(ref, *, live_objects, scene_graph, base_frame, patience_s, pad_m, object_tracking=False) -> PlaceDeclaration(L387) — The mirror ofground_grasp_targetfor an OPTIONAL named surface:ref.object_id/ref.place_node_idset → that spatial-memory node'sbbox_3d; else the single live lifted detection whose label equalsref.label. The padded, gravity-aligned box becomessearch_box(a hint the producer refuses a patch outside of);target_id="surface:<label or node_id>",region=None. RaisesROSReasonerInvalidPlanon no match (incl. no detector), more than one match without a node id, an unknown node id (incl. no spatial memory), a missing box or one outsidebase_frame— the hint is optional, but a supplied one that does not ground refuses the goal (message: "the place hint could not be grounded…" + omitplace_targetto place on the measured surface), never a fall-back to placing anywhere. Withobject_tracking(issue #418) it also carriesdestination_query=ObjectQuery(ref.label, "one", DESTINATION), and several matches — or none (Addendum G: the standing query keeps looking) — ground with nosearch_boxinstead of refusing.hand_joint— re-exported fromopenral_core.hand_joint(seedocs/methods/00-core-schemas.md).placement_queries(placements) -> tuple[ObjectQuery, ...](L486) — The standing queries a scene task names (issue #418):(object, destination object | None)pairs (an Isaacplacement_successtask viaIsaacPlacementSuccess.placements_for) → oneTARGETquery per class (instance suffix_<n>dropped,_read as a space — a non-class prim name such asstock_object/carton_bneedsIsaacPlacement.label; placed more than once →count="all"), then at most oneDESTINATIONquery (a fixed region such as a shelf slot gives none). RaisesROSConfigErroron no placement or several destination objects. Used byopenral deploy sim(_object_queries_json).ground_workspace(source, destination, *, anchor_xyz, base_frame, pad_m, headroom_m, evidence_ref) -> PlaceRegion(L542) — AGraspDeclaration.workspace_boxfrom boxes: the gravity-aligned hull of the source fixture and the destination, padded, plusheadroom_mon top; an axis wider than twiceMAX_WORKSPACE_HALF_EXTENT_Mis cut to that window aroundanchor_xyz(the target). RaisesROSReasonerInvalidPlanpast the volume cap. Fed by sim ground truth (tools/derive_scene_inputs.py) or, on a real cell, scene-graph surface boxes.
python/reasoner/src/openral_reasoner/spatial_query.py
Read-only spatial-memory query bridge: maps a RecallObjectTool / ResolvePlaceTool to a query, runs it against an injected backend, and renders an LLM-readable result. Layer-4 module; backend is duck-typed, not imported from openral_world_state.
class SpatialMemoryQuerier(Protocol)(L55) — Read-only query surface; structurally satisfied byopenral_world_state.SpatialMemory.recall_object(self, query, *, now_ns) -> RecallObjectResult(L58) — Recall objects matchingquery(empty result = not found).resolve_place(self, query, *, from_node_id=None) -> ResolvePlaceResult(L62) — Resolve a place/room/agent reference (raisesROSObjectNotInMemoryon miss).to_scene_graph(self) -> SceneGraph(L68) — Immutable snapshot of the current graph (for telemetry / dashboard).SpatialQueryTool: TypeAlias—RecallObjectTool | ResolvePlaceTool(the read-only ReasonerToolCall variants this bridge dispatches).recall_object_tool_to_query(call) -> RecallObjectQuery(L73) — tool → query mapper.resolve_place_tool_to_query(call) -> ResolvePlaceQuery(L78) — tool → query mapper.format_recall_object_result(query_text, result, *, blocked_node_ids=frozenset()) -> str(L87) — Render results as LLM-readable text; a miss is reported as text, never a fabricated pose.blocked_node_idsrenders a match whose approach failed grid refinement as BLOCKED instead of a pose.format_resolve_place_result(reference, result) -> str(L135) — render aResolvePlaceResultas an LLM-readable text block.nav_goal_places(goals, stamp_ns=0) -> list[SpatialNode](L279) — One declared spatial-memoryPLACEnode perNavGoal(node_idnav_goal:<name>, label = name, typedaliasesanddescription), soresolve_placematches a name or alias exactly;format_resolve_place_resultthen gives the heading (yaw and quaternion).ContextRenderer._render_nav_goalslists the declared places one per line with their quaternion and a how-to header;ToolPalette.places_onlyhidesrecall_objectwhen declared places are the memory's only content.run_spatial_query_detailed(call, querier, *, now_ns, from_node_id=None, refine_approach=None) -> SpatialQueryOutcome(L175) — Execute a read-only tool call; render text and report whether the query matched, so a miss can be escalated without re-parsing the rendered text.class SpatialQueryOutcome(NamedTuple)(L158) —(text, found, ambiguous=False).foundisTruewhenrecall_objecthad ≥1 match (even if grid-BLOCKED) orresolve_placeresolved; drives the reasoner's recall→locate_in_viewescalation.ambiguous:resolve_placematched several nodes (ROSObjectNotInMemory.candidates, named intext) — never escalated as a miss.run_spatial_query(call, querier, *, now_ns, from_node_id=None, refine_approach=None) -> str(L256) — Execute a read-only tool call and render the result;ROSObjectNotInMemory→ "not in memory".refine_approach(duck-typed, so this L4 module never imports L0) adjusts eachrecall_objectmatch's approach viewpoint;Nonemarks it BLOCKED. Thin wrapper returning only.text.ApproachRefiner(TypeAlias =Callable[[ApproachViewpoint, tuple[float, float, float]], ApproachViewpoint | None]) — occupancy-grid refinement callback contract; the reasoner node wiresrefine_approach_poseover its latched/mapsubscription.
python/reasoner/src/openral_reasoner/active_search.py
Bounded active object search over the scene graph (pure-Python, openral_core only).
class SearchBudget(BaseModel)(L35) — frozen;max_candidates(1–50),max_attempts(1–50). The bound.class SearchCandidate(BaseModel)(L49) —place_node_id, goal: Pose6D, open_container_id: str | None, reason, rank ∈ [0,1].plan_active_search(graph, *, target_text, budget) -> list[SearchCandidate](L70) — Ranked frontier of places to check (occluding containers, then containers, then places), truncated tobudget.max_candidates;[]when nowhere to search (hands off to a human). The LLM prioritizes among candidates.class ObjectQueryStep(BaseModel)— Bounded object-query action —rung(recover|blocked),label, last refusalreason, and a reflection carrying workspace and recent observation evidence. (L172)object_query_step(evidence, *, failures, max_attempts=DEFAULT_MAX_ATTEMPTS) -> ObjectQueryStep— Returnrecoveronly while the active mission task's persisted failed dispatch count (TaskState.failures, counting the goal this query fails) is belowmax_attempts; earlier successful dispatches (an approach drive, a look-at) spend none of it (#562). Otherwise, or with no budget to read (failures=None: no mission, or the goal's task is no longer active),blockeduntil a new operator goal. Recovery requires re-observing and re-grounding the object and workspace before manipulation. (L190)object_query_matches_invocation(evidence, *, active_invocation_id) -> bool— Accept only exact equality between ObjectQueryEvidence's action UUID and the current ExecuteRskill dispatch UUID; missing or stale IDs are rejected. (L271)object_query_task_is_current(*, dispatch_task_id, dispatch_mission_generation, current_task_id, current_mission_generation) -> bool— Distinguishes missions that reuse task ids such ast1; a delayed result can only recover or block the mission generation that dispatched it. (L280)class SearchProgress(L124) — attempt counter against aSearchBudget. The runaway bound.attempts(self) -> int(L138) — Number of search steps consumed so far.exhausted(self) -> bool(L143) — True once the attempt budget is spent (hands off to a human).record_attempt(self) -> bool(L147) — Consume one attempt;Truewhile budget remains, elseFalse.reset(self) -> None(L152) — Reset the counter (e.g. on a fresh operator goal).format_search_frontier(candidates, target_text) -> str(L157) — LLM-readable frontier text (empty → "hand off to a human").
python/reasoner/src/openral_reasoner/completion.py
VLM adjudication helpers (pure, no rclpy). Importable and testable without a ROS install.
- COMPLETION_QUESTION: str (L165) — prompt template for the ambiguous reward band, formatted with task=active.text.
- module constant _NEGATIONS: tuple[str, ...] (L169) — negation tokens parse_yes_no checks for.
- module constant _AFFIRMATIVES: tuple[str, ...] (L187) — affirmative tokens parse_yes_no checks for.
- parse_yes_no(answer: str) -> bool (L200) — Parse a VLM free-text answer: True iff it contains an affirmative token without a negation token. Token-based, not substring, to avoid false-completing on "No. It is done." or "abandoned" (contains "done"); typographic apostrophes fold to ASCII first. False on empty or ambiguous input.
- image_msg_to_jpeg(*, data: bytes, height: int, width: int, encoding: str, flip_180: bool = False) -> bytes (L257) — Convert a raw sensor_msgs/Image payload to JPEG via numpy + PIL (no cv_bridge); supports "rgb8"/"bgr8". flip_180 rotates 180° before encoding to match bottom-up LIBERO/MuJoCo frames. Raises ValueError on unsupported encoding.
- is_frame_fresh(*, age_s: float, max_age_s: float) -> bool (L26) — Whether a cached completion frame is recent enough to adjudicate: True iff max_age_s <= 0 or age_s <= max_age_s. A stale frame degrades to "cannot adjudicate", never a false verdict.
- is_reward_wake(*, source: str, severity: int, severity_fail: int) -> bool (L133) — Classify a FailureTrigger as a reward-watcher wake: True iff source == "critic" and severity >= severity_fail. Used to cancel an in-flight execute_rskill goal on the reward signal rather than waiting for deadline_s.
- tiled_jpeg(images: list[tuple[bytes, int, int, str]], *, flip_180=False) -> bytes (L404) — flip_180 rotates every view upright first (image_msg_to_jpeg; LIBERO/MuJoCo publish bottom-up). Raw camera images (data, height, width, encoding) side by side, each scaled to the first one's height, as one JPEG: every view in one single-image describe_image call (the completion check's reasoner judge). Raises ValueError before any decode when the canvas would exceed _MAX_TILED_PIXELS (32 Mpx).
- class CompletionTrigger(success_threshold=0.6, cooldown_s=3.0, release_rechecks=3) (L321) — When completion_check_node asks the VLM (2026-10-22): fire(now_s, *, success=None, released=False) -> str | None returns "release" / "success" (a success-head score at/above the bar) at most once per cooldown_s, else None; a non-firing call starts no cooldown. A reward model's success head alone is no completion signal (Spark R221-R223: it peaked mid-carry as often as at the placement). A release is asked again release_rechecks times, one cooldown apart, while the hand stays empty ("release_recheck"; a hold ends them): Spark R329's judge said "no" as the gripper opened over a banana lying in the bowl.
- fire(now_s, *, success=None, released=False, holding=False) -> str | None (L364) — The trigger's reason if a check is due (a release, or success >= success_threshold), at most once per cooldown_s, never while holding; a release is remembered (while holding or cooling down) and fires next.
- mark_released() -> None (L360) — Remember a release seen while a check was running.
- resolve_band_edges(*, contract_threshold: float | None, contract_floor: float | None, fallback_threshold: float, fallback_floor: float) -> tuple[float, float] (L54) — Three-tier verdict band edges: the active reward model's (success_threshold, check_floor) when both present, else the system fallback (never mixed).
- resolve_patience_s(*, override: float | None, contract_default: float | None, legacy_deadline_s: float) -> float (L97) — Patience ceiling for a dispatch: LLM patience_s override > reward model's default_patience_s > legacy deadline_s (0.0 → runner resolves its own ceiling).
python/reasoner/src/openral_reasoner/mission.py
Typed sequential task queue for multi-task deploy goals. Reasoner-internal bookkeeping (no rclpy/Pydantic); the node drives transitions, the ContextRenderer renders the ## MISSION ledger.
- TaskStatus (TypeAlias = Literal["pending","active","verifying","done","abandoned"]) — subtask lifecycle; done/abandoned terminal (never re-queued).
- VerdictAction (TypeAlias = Literal["complete","abandon","retry","vlm_check"]) — the reward-gate decision: complete (auto-pass), vlm_check (ambiguous band — caller adjudicates via describe_image), abandon (ladder exhausted), retry.
- DEFAULT_MAX_ATTEMPTS: int = 3 (L50) — default per-task cap on failed dispatches (TaskState.failures) before abandon + hand-off; every per-task ladder counts failures, not dispatches: the reward gate, the no-reward-monitor cap and object-query recovery (#562).
- DEFAULT_MAX_TASK_DISPATCHES: int = 10 (L60) — hard per-task bound on dispatches of any outcome: a task that keeps succeeding but is never completed (no verifier, an unscored reply, or a final_step=False step re-sent) still ends in the abandon path. ReasonerNode._dispatch_execute_rskill checks it before sending a goal, so it holds on every result path, a reward verdict that never comes included.
- DEFAULT_MAX_SUBDIVIDE_DEPTH: int = 2 (L72) — max re-decomposition depth; a task already at this depth is refused subdivision, terminating the ladder in human-handoff.
- DEFAULT_MAX_TASK_LOCATE_ATTEMPTS: int = 3 (L83) — per-task locate_in_view cycle budget before abandonment. Distinct from SearchProgress's miss budget, which resets on a hit and so cannot bound a hit-looping search.
- module constant _ACTIVE_STATES: frozenset[TaskStatus] (L280) — {"active", "verifying"}.
- module constant _TERMINAL_STATES: frozenset[TaskStatus] (L281) — {"done", "abandoned"}.
- evaluate_task_verdict(*, ok: bool, progress_now: float, success_threshold: float, check_floor: float, failures: int, max_attempts=DEFAULT_MAX_ATTEMPTS, success_now: float | None = None) -> tuple[VerdictAction, str] (L176) — Three-tier reward gate. Gates on the PROGRESS head, not the (compressed) success head: progress_now >= success_threshold → "complete"; check_floor <= progress_now < success_threshold → "vlm_check"; below floor → failure ladder ("abandon" once failures >= max_attempts, else "retry"). failures counts the task's failed dispatches including this one should the gate not complete it: a failed dispatch is counted when it returns, a successful one the node adds and keeps only on a ladder verdict, so a final_step=False step the gate never judged spends nothing (#562). ok=False always goes to the ladder. success_now is an optional secondary signal in the verdict text, never overriding the progress band.
- class TaskLocateBudget (dataclass, slots) (L95) — per-task locate_in_view cycle budget. Held by reasoner_node as _task_locate_budget.
- task_id(self) -> str | None (L148) — the task the budget is currently tracking (for persistence).
- count(self) -> int (L124) — locate cycles charged against the current task so far.
- reset(self) -> None (L128) — clear the budget (new task / real progress).
- restore(self, task_id, count) -> None (L133) — restore a persisted counter (reasoner restart resume).
- charge(self, task_id) -> bool (L152) — Count one locate cycle for the active task (auto-resets on task_id change); True once the count exceeds DEFAULT_MAX_TASK_LOCATE_ATTEMPTS.
- reason(self, query) -> str (L164) — specific abandonment reason for the ledger, e.g. could not confirm 'teapot' in view after 3 locate attempts without a skill dispatch.
- class TaskState (dataclass, slots) (L285) — one subtask: fields task_id, text, status=pending, attempts=0, failures=0, last_rskill_id, tried_rskill_ids=(), last_trace_id, last_verdict, depth=0, steps=[] (steps = one {rskill_id, prompt, outcome} per dispatch at the task, outcome a StepOutcome, display only; failures = failed dispatches, the count every per-task ladder caps: the ones that came back aborted / patience- or reward-cancelled, the successes a reward gate scored not done, and the ones whose object query failed; depth = re-decomposition level; tried_rskill_ids = every skill dispatched for the task, first-try order, persisted in the ladder state and demoted among ties by the skill subset).
- settle_step(self, outcome, *, overwrite=False) -> None (L331) — set the last step's StepOutcome; only a running one unless overwrite (the node's _count_failure overwrites with failed so the step row agrees with the ladder).
- class SplitRecord (TypedDict) (L273) — a task MissionState.subdivide_active replaced: text and the steps it ran before the split.
- class MissionState (L337) — ordered queue, ≤1 task active/verifying.
- from_prompt(cls, text) -> MissionState (L390) — seeds the operator goal as a single active task and as goal; the LLM decomposes via decompose_mission.
- tasks(self) -> tuple[TaskState, ...] (L406) — snapshot of every task, in order.
- active(self) -> TaskState | None (L414) — the currently active or verifying task, or None.
- is_empty(self) -> bool (L418) — True when the mission carries no tasks (empty/whitespace prompt).
- is_complete(self) -> bool (L422) — True when every task is terminal (done/abandoned).
- has_started(self) -> bool (L430) — True when any task is terminal or the active task has been attempted; gates a safe decompose_mission populate-replace.
- record_attempt(self, *, rskill_id, trace_id=None, prompt="") -> None (L454) — note a dispatch against the active task (increments attempts, sets last_rskill_id, appends a new id to tried_rskill_ids, closes a still-running step as interrupted and opens a running one).
- settle_step(self, outcome, *, task_id=None, overwrite=False) -> None (L474) — set the last step outcome of task task_id (default the active task); display only.
- mark_verifying(self) -> None (L502) — move the active task active → verifying (a skill returned; gating).
- complete_active(self, verdict) -> TaskState | None (L508) — mark the active task done and activate the next pending task.
- abandon_active(self, reason) -> TaskState | None (L515) — mark the active task abandoned (ladder exhausted / unverifiable).
- rearm_active(self) -> TaskState | None (L522) — move the active task verifying → active so dispatch/subdivide resumes after a subdivision offer.
- subdivide_active(self, subtasks, *, max_depth=DEFAULT_MAX_SUBDIVIDE_DEPTH) -> TaskState | None (L544) — Flat-splice the blocked active task in place with finer children t<n>.1, t<n>.2, … at depth+1, activate the first; the parent's text and steps go to the split map (to_summary()["splits"]); returns None (caller falls back to abandon_active) with no active task, empty subtasks, or the depth bound reached.
- to_state_dict(self) -> dict[str, object] (L614) — Full round-trippable snapshot (every TaskState field) for crash-safe ladder persistence, unlike the lossy to_summary.
- from_state_dict(cls, state) -> MissionState (L655) — rebuild a mission from to_state_dict output (exact resume); raises ValueError on malformed input.
- to_summary(self) -> dict[str, object] (L699) — JSON-able snapshot stamped on the reasoner.tick span as reasoner.mission_json for the dashboard Mission card: max_attempts, max_dispatches, reward_gated (the node sets it and the per-task pending from MissionState.reward_gated / pending_verdicts before each tick; None / 0 otherwise) and per task id/text/status/attempts/failures/pending/verdict/rskill_id/depth/steps, plus goal (the operator goal, kept across a populate) and splits ({task_id: {text, steps}} for every subdivided task); a task's budget is failures + pending (successes awaiting a reward verdict) of max_attempts and attempts of max_dispatches (steps only when reward_gated) (attempts over max_attempts reads "5/3" on a healthy task); children carry dotted ids t<n>.1 for indenting under their parent.
- render(self) -> str (L752) — the ## MISSION ledger: done ✓ / active ▶ / verifying ? / abandoned ✗ + pending count; children indented by depth.
python/reasoner/src/openral_reasoner/node_policy.py
Pure prompt-handling policy for the reasoner node (no rclpy) — the two consequential _on_prompt decisions, single-sourced and unit-testable without a ROS install.
- module constant
CASCADE_PROMPT_SOURCES: frozenset[str](L44) — the six frame_ids of the reasoner's own cascade re-prompts (spatial_memory,detector,scene_vlm,reward_monitor,memory,mission). Both the search-bound/streak reset guard and the mission-rebuild guard key off this one set. - module constant
OPERATOR_PROMPT_TOPIC = "/openral/prompt"(L51) — Where the reasoner speaks to its operator (EmitPromptTool, the hand-off); its other prompt topic, the router's/openral/prompt_in/auto, is the machine cascade. - module constant
CORRELATION_ID_RE: re.Pattern[str](L70) —openral_core.robot_ui.CORRELATION_ID_PATTERNcompiled;prompt_correlation_idfull-matches it. prompt_correlation_id(metadata_json) -> str | None(L73) — The caller'scorrelation_idin a prompt's metadata when it is well formed (openral_core.robot_ui.CORRELATION_ID_PATTERN), elseNone._on_promptputs it on the mission the prompt starts (MissionState.correlation_id, kept bydecompose_missionand across a resume, shown inreasoner.mission_json); a prompt taken as a reply to a mission in progress starts none, so that mission keeps its own id (#658).is_operator_prompt(source) -> bool(L54) — Whether a prompt fromsourceis a person's or their program's: not one ofCASCADE_PROMPT_SOURCESand not the machine cascadeauto._on_promptclearsContextRenderer.awaiting_operatoron one. That field holds what the reasoner last said to its operator (anemit_promptonOPERATOR_PROMPT_TOPIC, or_handoff_to_operator) until an operator prompt answers; each tick span carries it asreasoner.awaiting_operatorand, where free text may leave the host,reasoner.operator_question(_stamp_awaiting_operator), andmission_viewserves both asawaiting_operator/question(#660).judged_prompt_is_task(prompt, task_text) -> bool(L201) — Whether a goal's prompt is the mission task's own text (case and spacing aside): a judged success (scene grade, declaredSuccessCondition) completes the task only then, never on a sub-step's success.asks_completion_after_budget(*, budget_ended, judged, reward_available, final_step) -> bool(L222) — Whether a returning goal asks the reasoner's model if the task is done: a final step that ran out its budget unjudged with no reward monitor.forgets_conversation(*, previous, asked, metadata_json) -> bool(L100) — Onceshould_rebuild_missionsaid yes: whether the new mission also drops the old goal's conversation (ContextRenderer.forget_conversation: queued prompts but the new one, the(emit_prompt)lines of## EXECUTION,awaiting_operator; skill outcomes and failures stay). Yes when there was a previous goal, unless the reasoner had asked its operator something and the prompt is notnew_goal: a not-yet-started mission is replaced by any prompt, and a reply means nothing without its question (#661).should_rebuild_mission(source, metadata_json, mission, *, active_succeeded_unverified=False, answers_question=False) -> bool(L124) — Whether an inbound prompt replaces the mission queue: cascade → never; no/empty/finished/not-yet-started mission → yes; a genuinely in-progress mission → only with top-level"new_goal": truemetadata (an operator reply must not silently discard the in-flight queue), or whenactive_succeeded_unverifiedand no task is queued after the active one (its last dispatch succeeded and no reward monitor can judge it — the next prompt is a new goal; the node clears the flag once the reasoner prompts the operator, so a reply stays a reply). Withanswers_question(the reasoner had asked its operator something and this is an operator prompt), a prompt withoutnew_goalis the answer and keeps any unfinished mission, started or not (#661).judged_prompt_is_task(prompt, task_text) -> bool— Whether a goal's prompt is the mission task's own text (case and spacing aside): a judged success completes the task only then, so a sub-step's success never closes it.asks_completion_after_budget(*, budget_ended, judged, reward_available, final_step) -> bool— A goal that ran out its budget with nothing judging it and no reward monitor, on the task's final step: the reasoner node asks its model once (_adjudicate_completion_async,COMPLETION_QUESTIONon the completion-camera frame) whether the task is done; yes completes it, anything else settles it astask_step_without_verifiersays.task_step_without_verifier(*, succeeded, completes_task_on_success, reward_available, attempts, failures, final_step=True, judged_success=False, max_attempts=DEFAULT_MAX_ATTEMPTS, max_dispatches=DEFAULT_MAX_TASK_DISPATCHES) -> tuple[Literal["complete", "step", "abandon"], str] | None— What settles the active task after a dispatch returns where no reward verdict does:completewhen the run's outcome is a judged success (judged_success: the scene's grade or a declaredSuccessCondition) on the task'sfinal_step, or when the skill succeeded, its manifest opts in (RosIntegration.completes_task_on_success, reward monitor or not) and the goal was the task'sfinal_step;abandonatmax_dispatchesdispatches of any outcome when no reward gate will judge this result (no reward monitor, or a step), or with no reward monitor oncefailuresreachmax_attempts(a success nobody can judge is not a failure, #562);stepwhen an opted-in skill succeeded as a non-final step (the task stays active, no reward query, the node forces a tick for the next step); elseNone. The per-skill tool schema offersfinal_steponly on skills withcompletes_task_on_success, and the system prompt's approach rule tells the LLM to send the approach drive withfinal_step=false. (L251)
python/reasoner/src/openral_reasoner/persistence.py
Crash-safe ladder persistence (pure, no rclpy): the mission ledger + every replanning-ladder bound snapshotted after each mutation and reloaded at configure, so a restart resumes the ladder instead of resetting every cap mid-mission.
- module constant
_SCHEMA_VERSION: Literal["0.1"](L33) — on-disk schema version stamped into every snapshot;load_ladder_staterefuses a mismatch. class ReasonerLadderState(Pydantic v2, extra-forbid) (L36) — versioned on-disk boundary carrying everything a restarted reasoner needs:mission: MissionState | None,subdivide_offered: set[str],collective_nudges: dict[str, int],locate_task_id: str | None,locate_count: int,object_query_blocked_task_id: str | None.save_ladder_state(path, state) -> None(L98) — atomic JSON write (tmp +os.replace; a crash mid-write leaves the previous snapshot intact). Versioned (schema_version: "0.1").load_ladder_state(path) -> ReasonerLadderState | None(L120) —Noneon absent / corrupt / version-mismatched snapshot; caller starts fresh and logs rather than resuming from a bad snapshot.
python/reasoner/src/openral_reasoner/memory.py
The self-maintained MEMORY.md file model: persistent semantic memory (preferences, lessons, home facts, object-location log, open tasks). Summarized inline in context.py's entry above; this is the file's own symbol inventory.
- module constant
_SECTION_TITLES: dict[MemorySection, str](L28) — the five section headings ("Home Map / Places","User Preferences","Learned Lessons / Corrections","Object-Location Log","Open Tasks / Commitments") MEMORY.md is organized under. - module constant
_TITLE_TO_SECTION: dict[str, MemorySection](L35) — reverse of_SECTION_TITLES, for parsingfrom_markdown. - module constant
_ENTRY_RE(L38) — regex matching one round-trip-stable MEMORY.md entry line (- [imp:<float> ts:<iso> st:<status>] <content>). - module constant
_SCHEMA_VERSION: str = "0.1"(L40) — on-disk MEMORY.md schema marker. class MemoryEntry(L53) — One remembered fact in aMemoryStore.render_line(self) -> str(L62) — Render the entry as one round-trip-stable MEMORY.md line.class MemoryStore(L68) — Ordered set ofMemoryEntryrendered to / parsed fromMEMORY.md.from_markdown(cls, text) -> MemoryStore(L78) — Parse aMEMORY.mdbody. Unrecognized lines are ignored (lenient).to_markdown(self) -> str(L113) — The full on-diskMEMORY.md(title + schema marker + sections).to_context_block(self, *, cap=None) -> str(L132) — The## MEMORYblock the reasoner injects into its context;caprenders only the top-capentries by importance then recency.consolidate(self) -> list[MemoryEntry](L157) — Merge exact-duplicate facts, keeping the best; return the removed entries for archiving.entries(self) -> tuple[MemoryEntry, ...](L180) — A snapshot of the current entries, in order.apply(self, *, op, section, content, importance, target, now) -> MemoryEntry | None(L186) — Apply one explicitadd/update/supersede/deleteedit. Returns an entry to archive (orNone).search(archive, *, query, section, limit) -> list[MemoryEntry](L232) — Rank archived entries by a keyword match.
python/reasoner/src/openral_reasoner/context.py
ContextRenderer builds the structured text snapshot the LLM consumes per tick (no pixels in v1).
- module constant
DEFAULT_BUFFER_SIZE: int = 8— Rolling buffer capacity per category. (L81) - module constant
DEFAULT_PROMPT_PRIORITY: int = 10(L86) — Default operator-prompt priority, matchingopenral_prompt_router.DEFAULT_SOURCES; human sources stamp 100 so they drain first. - module constant
_FAILURE_ADAPTER: TypeAdapter[FailureEvidence](L122) — cachedTypeAdapter(FailureEvidence)used to decode a failure buffer entry'sevidence_json. - module constant
_PERCEPTION_ADAPTER: TypeAdapter[PerceptionEventMetadata](L123) — cachedTypeAdapter(PerceptionEventMetadata)used to decode a perception buffer entry'smetadata_json. class FailureEventRecord(frozen dataclass) (L127) — Failure-buffer entry; fieldssource, kind, severity, evidence_json, rskill_id, trace_id, stamp_ns. Rendered withkind/severitynames (kind=COLLISION severity=ABORT) and itsage.const SAFETY_STATUS_LIVENESS_S: float = 3.0— a/openral/safety_statusstamp older than this renders## SAFETYas UNKNOWN, never "clear" (HZ-0096-1). (L90)failure_kind_name(kind: int) -> str—FailureTrigger/SafetyStatusKIND_*number → name without the prefix ("KIND_<n>"if unknown), built from theopenral_observability.failure_busIDL mirror. (L112)class SafetyStateRecord(BaseModel)(frozen Pydantic,extra="forbid") — Latest/openral/safety_statusas the LLM sees it:latched,reason(drop_reasonname,""when clear),stamp_ns. Set viaContextRenderer.set_safety_status; rendered as## SAFETY(clear / dropping / LATCHED / UNKNOWN). (L202)class PerceptionEventRecord(frozen dataclass) (L144) — Perception-buffer entry; fieldskind, text, metadata_json, stamp_ns.class PromptRecord(frozen dataclass) (L154) — Operator-prompt-buffer entry; fieldstext, metadata_json, stamp_ns, priority=DEFAULT_PROMPT_PRIORITY.priorityis filled byappend_promptfrommetadata_json["priority"]when constructed with the default sentinel.render_robot_self_model(description: RobotDescription) -> str(L753) — Deterministic static self-model block (embodiment, dof, end-effectors, locomotion, payload, capability flags, cameras with FOV, control modes, configured joint aliases and link graph) so the LLM can judge reach/view feasibility before dispatch. Set viaContextRenderer.set_robot_model; rendered as## ROBOT.render_playbooks_block(entries: list[tuple[str, str]]) -> str(L714) — Renders the## PLAYBOOKSsystem-prompt block from(name—trigger, PLAYBOOK.md body)entries;""when none match. Playbooks guide decisions only — every motion still goes throughexecute_rskill+ the safety kernel.class MemoryEntry/class MemoryStore(openral_reasoner.memory, own section below) — The self-maintainedMEMORY.mdsemantic-memory model (complementary to the geometric scene graph), advisory only. Round-trips the file; renders a capped## MEMORYcontext block; applies explicit add/update/supersede/delete edits; consolidates duplicates; searches the archive. Loaded at configure byreasoner_node._maybe_load_memory.class ExecutionEventRecord(frozen dataclass) (L182) — Execution-feedback buffer entry (skill outcomes, and(<tool>)lines for non-skill tool outcomes the node records); fieldsrskill_id, outcome ("ok"|"failed"|"stopped"), summary, reflection (failures only), stamp_ns, evidence_json=""(the result'sFailureEvidence, rendered as anevidence=…summary on the line).class RewardStateRecord(frozen dataclass) (L230) — Latest two-head reward assessment surfaced to the LLM:progress(closeness, the gated head),success(done-confidence, compressed, secondary),progress_trend,success_trend,task,stamp_ns. Rendered as## REWARDviaset_reward_state/_render_reward.reflect_on_failure(outcome_state, detail, *, timed_out: bool | None = None, failure_kind: str | None = None, evidence_json: str = "") -> str(L443) — Deterministic one-line strategy hint (no LLM call) turning a raw failure into a "change approach" cue.timed_outcomes from the typedExecuteRskill.Result.failure_kindwhen the caller has it;Nonefalls back to a deprecated substring probe over the prose.failure_kind(anExecuteRskill.ResultFAILURE_*name) selects a kind-specific hint from_FAILURE_KIND_REFLECTIONS(stale perception → retry the same skill; config/capability → another skill; …);FAILURE_SAFETY_ESTOPpicks collision-vs-other-kernel-stop-vs-operator-e-stop fromevidence_json.reflect_on_reward_plateau(progress_now) -> str(L596) — Reward-plateau hint (policy ran clean but progress says not done): the move is to change tactic, not to subdivide or re-issue the same instruction.task_outcome_judged(task_outcome_json) -> bool(L541) — True when the scene (scene) or a declaredSuccessCondition(success_condition) judged the run, whatever the verdict; a skill's or checker's word,noneand an unreadable payload are not. Feedsasks_completion_after_budget(judged=...).task_outcome_judged_success(task_outcome_json) -> bool(L514) — True when the run'sTaskOutcomeis a succeeded verdict judged by the scene (scene) or a declaredSuccessCondition(success_condition); a skill's or checker's own "done", and an unreadable payload, are not. Feedstask_step_without_verifier(judged_success=...).task_outcome_text(task_outcome_json) -> str(L564) — Issue #635: the## EXECUTIONphrase forExecuteRskill.Result.task_outcome_json,task_outcome=<verdict> (<source>): <reason>;""when the runner sent none or nothing judged the run (source: none); a payload that does not decode readstask_outcome=unknown (unreadable task_outcome_json). The reasoner node appends it to the[ok]and[failed]lines of a dispatched skill.reflect_on_grasp_miss(hand, target_id, short_of_command, *, consecutive_misses=1) -> str(L626) — Issue #353: hint for aKIND_GRASP_OUTCOMEmiss — names the hand (jaw link), the declared target and the jaw's shortfall, and points at the leversexecute_rskillalready has (a re-groundedgrasp_target.object_id, the other hand viagrasp_target.contact_links, a different skill), never an identical re-issue; a run of misses (the HAL's per-hand, per-target count) is called out, and abandonment is keyed on that target. Decides nothing: the ladder's caps still bound what follows.reflect_on_invalid_plan(detail) -> str(L678) — Strategy hint feeding a decode error back so a model that emitted malformed JSON arguments fixes its call instead of re-issuing it verbatim.reflect_on_retry_cap(tool, cap) -> str(L702) — Strategy hint whenReasonerCore's per-kind retry ladder is exhausted fortool.class ContextRenderer(L827) — Stateful renderer.ContextRenderer(*, buffer_size=8, robot_model=None, now_ns=None): with anow_nsclock every event line, the in-flight line,## REWARDand the world-state stamp carry theirage.set_robot_model(self, robot_model) -> None(L953) — Sets/clears the static## ROBOTself-model; does NOT bumpseq.set_memory_block(self, memory_block) -> None(L968) — Sets/clears the## MEMORYblock from the MEMORY.md store; does NOT bumpseq.set_mission(self, mission) -> None(L1009) — Sets/clears the active task queue rendered as## MISSION; a new goal is an event so it DOES bumpseq.set_spatial_memory(self, graph) -> None(L976) — Sets/clears the spatial-memory snapshot whose OBJECT nodes render asmemory_objects[<frame>]: <label> id=<node_id>@(x,y,z) size=(…)— the idsgrasp_target.object_idtakes; does NOT bumpseq(ingest jitter).set_in_view(self, objects) -> None(L1025) — Sets/clears the latest continuous-detector enumeration rendered asin_view[<camera>]in## WORLD_STATE; bumpsseqonly when the rendered enumeration actually changes.set_inflight_skill(self, rskill_id, *, stamp_ns=0, state='running') -> None(L1045) — Records (or clears) the in-flightexecute_rskillgoal with its phase ("dispatching"until accept, then"running"), rendered as the leadingin_flight:line in## EXECUTION; state changes bumpseq.set_inflight_feedback(self, text) -> None— LatestExecuteRskillfeedback of the in-flight goal, shown on thein_flight:line; never bumpsseq; cleared when the in-flight skill changes. (L1065)set_safety_status(self, status) -> None— Sets theSafetyStateRecordrendered as## SAFETY; bumpsseqwhenlatchedorreasonchanges or a status arrives after the last one went stale (the 1 Hz refresh of a live, unchanged state is not an event). Without anow_nsclock the section always reads UNKNOWN, never clear. (L1074)safety_latched(self) -> bool— True while the last safety status was latched; read byReasonerCore'ssafety_latchedgate (which holds a beat only while the context is unchanged). (L1131)inflight_skill(self) -> str | None(L1136) —rskill_idof the goal currently in flight, orNone; also read byReasonerCore's in-flight backstop gate.inflight_state(self) -> str | None(L1141) — Phase of the in-flight goal ("dispatching"/"running"), orNone.note_located(self, objects) -> None(L1148) — Folds open-vocablocate_in_viewhits into a stickylocated[<camera>]line (latest-wins, capped) that survives the continuous detector's per-frame clobber, keeping a mislabelled goal noun grounded for decompose/dispatch; bumpsseq.clear_located(self) -> None(L1192) — Drops the sticky open-vocab grounding on a new operator goal; bumpsseqwhen non-empty.set_reward_state(self, reward) -> None(L1206) — Sets/clears the two-head reward assessment rendered as## REWARD; bumpsseq.mission(self) -> MissionState | None(L1235) — the activeMissionState, orNone; the node mutates it in place for non-waking bookkeeping (record_attempt/mark_verifying).advance_mission(self, *, done, verdict) -> TaskState | None(L1245) —complete_active/abandon_activethe active task + activate the next, bumpsseq;Nonewhen the mission is finished or unset.append_failure(self, record) -> None(L1269) — pushes a failure event onto the rolling buffer; bumpsseq. AGraspOutcomeEvidencepayload (issue #353) also opens (miss, latest per hand) or closes (attach, whichever hand's ATTACH ended the run) that hand's open grasp miss, rendered as a[grasp_miss] hand=<jaw link> target=<id|-> misses=<n> — reflect: <reflect_on_grasp_miss>line at the end of## EXECUTION. Open misses also drop onclear_failures,advance_missionand aset_missionwith a different mission object (re-setting the same one, as the subdivide path does, keeps them); capped atbuffer_size.append_execution(self, record, *, wake=True) -> None(L1288) — Pushes a skill execution outcome onto the rolling buffer; bumpsseqso feedback wakes an idle heartbeat.wake=Falserecords something the model already knows (what it said to the operator) without bumpingseq.clear_failures(self) -> None(L1347) — drops stale failure/execution context (and the open grasp misses) after/openral/estop_clearedso the next prompt is not poisoned by a resolved e-stop.append_perception(self, record) -> None(L1301) — pushes a perception event onto the rolling buffer; bumpsseq. A record repeating the newest one of itskind(same text) is dropped with noseqbump (the detector's every-period"N objects").append_prompt(self, record) -> None(L1363) — priority-ordered insert; buffer-evicts the lowest-priority oldest entry on overflow; bumpsseq.forget_conversation(self, *, keep=None) -> None(L1318) — Drop the previous goal's operator exchange when a new goal replaces it (#661): every queued prompt butkeep, the(emit_prompt)lines in## EXECUTION, andawaiting_operator. Skill outcomes and failures stay.render(self, *, world_state) -> str(L1407) — Returns the deterministic text snapshot for one LLM tick.## WORLD_STATEcovers joint_state/ee_poses/battery/diagnostics plus a 3Dscene_objects[<frame>]line (one entry per instance — label, centre, size, track — never deduped by label; arepeated_labels:line flags labels a bare name cannot ground), thememory_objects[<frame>]node-id line, and a depth-free, pixel-spacein_view[<camera>]line (so grounding still works with RGB-only / no octomap);note_locatedhits render as a stickylocated[<camera>]line distinct fromin_view.## REWARD(when set) carries both reward heads distinctly labelled so the LLM never blurs progress (persist-vs-replan) with success (done-ness).## WORLD_STATEalso rendersbase_poseand aholding:line fromattached_objects(released ones,released_by_linkset, excluded);## SAFETYsits before## REWARDonce a status arrived.failures(self) -> tuple[FailureEventRecord, ...](L1782) — snapshot of the failure buffer (oldest first).perception_events(self) -> tuple[PerceptionEventRecord, ...](L1792) — snapshot of the perception buffer (oldest first).executions(self) -> tuple[ExecutionEventRecord, ...](L1787) — snapshot of the execution-feedback buffer (oldest first).prompts(self) -> tuple[PromptRecord, ...](L1797) — snapshot of the prompt buffer (oldest first).seq(self) -> int(L1802) — monotonic mutation counterReasonerCoreuses to short-circuit a heartbeat tick when nothing has changed since the last successful tick.refresh_clock_state(self) -> None— Folds time-dependent context intoseq: a safety status crossingSAFETY_STATUS_LIVENESS_Seither way bumps it.ReasonerCore.prepare_tickcalls it once per tick before its gates and the render;## SAFETYrenders the freshness evaluated here, so readingseqor rendering never changes the renderer. (L1094)drain_prompts(self, *, seen=None) -> tuple[PromptRecord, ...](L1819) — Pull-once, priority-desc + arrival-asc order; does NOT bumpseq.seendrains only those records by identity, so a prompt that arrived mid-LLM-call and was never rendered survives for the next tick.- module constant
_PROMPT_EXCLUDED_FIELDS: frozenset[str](L1883) — evidence fields_summarise_evidence_jsondrops by role rather than length (currently{"joint_positions_rad", "joint_names"}: replay data, useless to a planner). - module constant
_PROMPT_FIELD_BUDGET: int = 48(L1889) — char backstop past which_summarise_evidence_jsondrops a field and discloses it as+<field>[<n>]. - module constant
_COLLISION_BASE_FRAME_KEYS: Final[Mapping[str, str]](L1897) — read-only (MappingProxyType) prompt names for a collision's voxel coordinates, rendered as<key>[<frame>]like every other framed prompt line:world_cell_center_m→cell_center_m[<base_frame>],world_grid_origin_m→grid_origin_m[<base_frame>], where<base_frame>is the robot manifest'sbase_frame(the kernel's grid frame, never the map), orrobot base frame(_UNKNOWN_BASE_FRAME) when no manifest is loaded. Wire/schema names are unchanged. _decode_evidence(payload) -> FailureEvidence | None(L1964) — Decode aFailureTrigger.evidence_jsonthrough the union;Nonefor an empty or rejected payload (the failure line still shows it raw). Used byappend_failure._summarise_evidence_json(payload, *, base_frame=None) -> str— Decode the FailureEvidence union and produce a one-line, 120-char-truncated summary; a field named in_PROMPT_EXCLUDED_FIELDSor past the_PROMPT_FIELD_BUDGETbackstop is dropped and disclosed as+<field>[<n>]. Exclusion is by role, not length, so identity fields survive truncation instead of noise fields. A collision summary is not truncated and renames its voxel coordinates per_COLLISION_BASE_FRAME_KEYSso the reasoner reads them as base-frame, not map, positions. (L1978)_extract_priority(metadata_json) -> int— Parse a top-levelpriorityfield out of a PromptStamped's metadata; returnsDEFAULT_PROMPT_PRIORITYon missing / malformed / non-int payload.
python/reasoner/src/openral_reasoner/core.py
ReasonerCore, the transport-agnostic orchestrator. The ROS-side reasoner_node wraps this with rclpy.
class ReasonerTickResult(frozen dataclass) (L219) — Tick outcome; fieldstool_call,error,elapsed_s,suppressed_reason("","min_interval","safety_latched","llm_error_backoff","retry_cap_hold","mission_finished","wait_hold","backstop_not_due","heartbeat_idle","no_goal","retry_cap","palette_empty"),trigger(the tick'sPreparedTick.trigger,""when suppressed before the LLM),traceparent(Nonewhen no realTracerProvideris installed).const BACKSTOP_MIN_S: float = 15.0— lower clamp of the in-flight backstop (issue #620). (L118)const BACKSTOP_MAX_S: float = 30.0— upper clamp of the in-flight backstop. (L119)const LLM_ERROR_BACKOFF_S: tuple[float, ...] = (5.0, 10.0, 20.0)— delays before re-trying an LLM call that failed in transport; after the last,ReasonerCore.llm_gave_up. (L124)const QUIET_SUPPRESSIONS: frozenset[str]— every timer-beat suppression reason (min_interval,safety_latched,llm_error_backoff,retry_cap_hold,mission_finished,wait_hold,backstop_not_due,heartbeat_idle,no_goal,llm_gave_up); the node logs these at DEBUG and keeps its retry-cap warn latch across them. (L129)inflight_backstop_s(max_execution_s: float | None) -> float— Heartbeat period while a skill is in flight:clamp(max_execution_s / 4, BACKSTOP_MIN_S, BACKSTOP_MAX_S),BACKSTOP_MIN_Swithout a budget. (L145)_call_identity(call) -> str— Canonical retry-cap identity of a tool call: the full argument payload minusrationale(rephrasing rationale between identical retries must not dodge the cap), JSON-serialised with sorted keys.class PreparedTick(dataclass) (L174) — In-flight state of a phased tick betweenprepare_tickandfinish_tick: LLM inputs (context_text,palette,system_prompt) plus prepare-time snapshots (started,seq,prompts, an unattached OTelspan,renderer,force,tier,trigger,coalesced). Theseq/promptssnapshots boundfinish_tickto only what the model actually saw.llm_s/prompt_tokensare the only fields the LLM phase writes back, so tick latency can be attributed to the provider vs. reasoner-side overhead.- module constant
_RETRY_CAP_EXEMPT_TOOLS: frozenset[str](L110) —{"recall_object", "resolve_place", "locate_in_view", "wait"}, the tool kinds transparent to the retry cap (seeReasonerCorebelow). class ReasonerCore(L253) — Orchestrator.max_skill_tools(self) -> int | None(L386) — the configured per-tick skill-tool cap, orNone(read-only).llm_gave_up(self) -> bool— True once everyLLM_ERROR_BACKOFF_Sretry failed in a row; cleared by the next good call. The node hands off to the operator when it flips. (L372)wait_hold(self) -> tuple[str, float] | None—(until, monotonic deadline)of the model's activewait, orNone. (L381)offered_palette(self, palette, renderer) -> ToolPalette(L390) — The palette the LLM sees this tick:palettenarrowed byselect_skill_subsettomax_skill_toolsskills, ranked against the active mission task plus every pending prompt (when both are empty — mission finished, prompt drained — the last non-empty query is kept rather than ranking on nothing). The in-flight skill issticky; the newest prompt of the top-priority band is thefocus(offered on the tick it arrives, beforefinish_tickdrains it); the task's last dispatched skill isrecent(outside a mission, the lastExecuteRskillToolthis core returned); the task'stried_rskill_idsare demoted among equal scores. Recomputed only when the palette object, query or sticky / tried ids change, reusing the previous palette object while the offered set is unchanged so the clients' per-palette tool render and the provider prefix cache hold. Each recompute logsreasoner.skill_subset(query, every score, kept and tried ids,max_score); with a cap set,prepare_tickstampsreasoner.offered_skillson every tick span (absent without a cap). Without a cap, returnspaletteunchanged.retry_cap(self) -> int(L471) — the configured consecutive-identical-call cap (read-only).streak_tool(self) -> str(L476) — tool kind of the current consecutive-call streak (""when none).reset_kind_streak(self) -> None(L480) — reset the consecutive-call counter used by the retry-cap gate.tick(self, *, world_state, renderer, palette, force=False, tier='heartbeat', trigger='heartbeat') -> ReasonerTickResult(L491) — Synchronous composition of the phased API (prepare → off-thread LLM call → finish) so the executor is never starved. Enforces the min-interval and retry cap (search tools +waitare exempt); short-circuits on a finished mission or idle heartbeat.force=Truebypasses every gate but the retry cap. Wraps the tick in areasoner.tickOTel span.prepare_tick(self, *, world_state, renderer, palette, force=False, tier='heartbeat', trigger='heartbeat', coalesced=()) -> PreparedTick | ReasonerTickResult(L664) — Phase 1 of a tick: run the suppression gates and render the context; must run on the owning/executor thread. A forced tick ends anywait. A timer beat reaches the LLM only asllm_error_retry,wait_timeout,backstop(skill in flight,inflight_backstop_ssince the last call) orcontext_changed(nothing in flight, mission or prompt pending); the trigger, coalesced triggers and beats skipped since the last call land on the span.run_prepared_llm(self, prep) -> ReasonerToolCall(L795) — Phase 2 of a tick: the blockingselect_toolround-trip; the ONLY phase safe off-thread.finish_tick(self, prep, *, call=None, error=None) -> ReasonerTickResult(L871) — Phase 3 of a tick: retry-cap ladder + bookkeeping + span close, back on the owning thread. AWaitToolarms the wait hold (reasoner.wait.*on the span); a transportROSPlanningErrorleaves the context unseen and arms theLLM_ERROR_BACKOFF_Sretry (marked seen once they run out);ROSReasonerInvalidPlanmarks it seen.
python/reasoner/src/openral_reasoner/critic_watchdog.py
Tier-C critic progress-stall / success watchdog — default decision core for the reserved /openral/failure/critic source. Pure logic, import-safe (no rclpy). Source-agnostic: any reward model emitting a higher-is-better scalar drives the same watchdog; the critic producer node routes samples through CriticWatchdogGroup and publishes to the failure bus on a fire. Fires on stall OR success, waking the reasoner promptly when an attempt is likely done.
class CriticWatchdog(L62) — Progress-stall / success state machine; raisesValueErroronstall_patience < 1ormin_delta < 0. Fires oneCriticEvidencein two mutually exclusive, one-shot-per-streak cases: success (score crosses threshold) or stall (stall_patienceconsecutive non-improving observations). Success takes precedence when both would fire on the same sample.critic_id(self) -> str(L131) — Identifier of the upstream critic stamped onto emitted evidence.threshold(self) -> float(L136) — Pass threshold; observations at or above it are recoveries.stall_patience(self) -> int(L141) — Consecutive stalled observations required to fire.min_delta(self) -> float(L146) — Minimum strict improvement over the running best to count as progress.observe(self, score) -> CriticEvidence | None(L150) — Feed one progress/critic score and decide whether to fire.reset(self) -> None(L220) — Clears running best, stall counter, and both latches (call on a reasoner context shift).class CriticWatchdogGroup(L234) — Multiplexer keying oneCriticWatchdogpercritic_idso several reward models share the/openral/failure/criticsource independently.stall_patience(self) -> int(L293) — Consecutive stalled observations each watchdog requires to fire.min_delta(self) -> float(L298) — Minimum strict improvement each watchdog counts as progress.observe(self, *, critic_id, score, threshold) -> CriticEvidence | None(L302) — Lazily creates a watchdog percritic_id(threshold bound on first sight) and delegates.known_critics(self) -> frozenset[str](L328) — Return thecritic_idset seen since construction / last reset.reset(self, critic_id=None) -> None(L332) — drop one critic's watchdog (rebinds its threshold) or all.
packages/openral_safety/openral_safety/supervisor_node.py
Day-1 Python safety envelope: candidate_action → safe_action pass-through with real per-control-mode envelope checks, the estop latch/reset pair, and the latched SafetyStatus topic. Reserves the node name and topic surface for the future C++ kernel; any addition of enforcement beyond this file requires safety-WG sign-off.
class SafetyPassthroughNode(LifecycleNode)(L151) — Owns/openral/candidate_action → /openral/safe_actionplus the estop latch/reset pair and theSafetyStatustopic. Refuses (nonfinite) a candidate whoseflatholds any non-finite value before the per-mode bounds run (NaN passes every ordered comparison).__init__(node_name="openral_safety") -> None(L172)on_configure(state) -> TransitionCallbackReturn(L238) — Opens the publishers, subscriptions, service, and diagnostics heartbeat.on_activate(state) -> TransitionCallbackReturn(L328)on_deactivate(state) -> TransitionCallbackReturn(L360)on_cleanup(state) -> TransitionCallbackReturn(L370)on_shutdown(state) -> TransitionCallbackReturn(L402)_on_candidate_action(msg) -> None(L408) — Subscribes/openral/candidate_action. Drops the candidate and re-fires/openral/estopon an envelope violation; drops silently while already latched; otherwise forwards unchanged on/openral/safe_action. Emits asafety.checkOTel span per candidate._envelope_violation(msg) -> tuple[str | None, str](L465) — Dispatches oncontrol_mode: joint modes get the position-limit check; Cartesian/twist/gripper modes each get their own bound check. Every bound parameter defaults to-1.0(no enforcement declared, skip)._handle_violation(msg, *, kind, reason) -> None(L733) — Drops the chunk, latches the estop, publishesstd_msgs/Emptyon/openral/estop, and updates the latchedSafetyStatus._on_external_estop(_msg) -> None(L762) — Subscribes/openral/estop(defense in depth): any external estop publication latches this node too, independent of its own checks._on_estop_reset(request, response) -> object(L789) — Exposes/openral/estop_reset(std_srvs/Trigger); clears the latch only onceestop_reset_cooldown_s(default 0.5 s) has elapsed since the last estop.SafetySupervisorNode(L873) — Back-compat alias ofSafetyPassthroughNode, not a separate skeleton.SAFETY_STATUS_TOPIC: str(L72) —/openral/safety_status, the latched current-safety-state topic (RELIABLE + TRANSIENT_LOCAL + KEEP_LAST=1), published alongside — never instead of —/openral/estop. Same contract the C++ kernel publishes.SAFETY_STATUS_HEARTBEAT_S: float(L79) — 1.0 s liveness refresh;header.stampis re-stamped at this cadence even when nothing changed, so a durable value can be told apart from a dead publisher's leftover state.main(args=None) -> int(L876) — Entry point forros2 run openral_safety supervisor_node.- module constant
_KERNEL_LABEL_PASSTHROUGH: str = "passthrough"(L57) —safety.kernelspan/log label this Python passthrough stamps (vs. the future C++ kernel's own label). - module constant
_WORKSPACE_VIOLATION_KINDS: frozenset[str](L96) —{"workspace", "gripper_range"}, envelope-violation kinds_envelope_violationcan return. - module constant
_RATE_VIOLATION_KINDS: frozenset[str](L97) —{"cartesian_step", "cartesian_step_rot", "ee_linear_speed", "ee_angular_speed", "base_linear_speed", "base_angular_speed"}, the rate/speed-bound violation kinds. - module constant
DEFAULT_ESTOP_RESET_COOLDOWN_S: float = 0.5(L85) — default cooldown_on_estop_resetenforces since the last estop before clearing the latch.
cpp/openral_safety_kernel/include/openral_safety_kernel/lifecycle_kernel.hpp
C++ (Layer 5). Node-side caps on the world-voxel freshness parameters (hazard log Entries 033/034).
kMaxWorldVoxelDeadlineMs = 2000.0,kMaxWorldVoxelDataAgeBudgetMs = 3000.0,kDefaultWorldVoxelDataAgeBudgetMs = 1500.0— Withworld_voxel_enabled,on_configurereturns FAILURE for aworld_voxel_deadline_msoutside (0, 2000] or aworld_voxel_data_age_budget_msoutside (0, 3000]; the budget defaults to 1500 and 0 does not disable it. Deliberate mirror ofDeployRuntime's caps, pinned bytests/unit/test_perception_caps_mirror.py.- External-torque observer params (#373) —
force_observer_enabled(default false) +force_observer_{gain_per_s, coulomb_velocity_rad_s, limit_margin_rad, gravity, link_mass, link_com, link_inertia, joint_armature, joint_viscous, joint_coulomb, joint_offset}(per-link arrays parallel to the collision links) and the envelope's per-dofjoint_external_torque_max(0 = unmonitored).on_configurereturns FAILURE on a ceiling with the observer off, a malformed model,collision_base_dofs, or a ceiling on a dof no joint drives. Each/joint_statesmessage runs one sample (run_force_observer); stale position/velocity/effort or a monitored joint inside its limit margin resets the estimate (an invalid estimate stops nothing). Over a ceiling: latch +FailureTrigger(KIND_FORCE)ForceEvidence{unit:"Nm"}+SafetyStatus.KIND_FORCE+/openral/estop. Publishes the estimate on/openral/safety/external_torque(sensor_msgs/JointState.effort, 50 Hz, sensor QoS); diagnosticsforce_observer/force_peak_ratio./openral/estop_resetrestarts the estimate. - Workspace contact params (#349) —
workspace_contact_enabled(default false; requiresgrasp_allowance_enabled),workspace_contact_links(each a collision link, non-empty),workspace_contact_max_speed_mpsandworkspace_contact_control_period_s(finite > 0),workspace_contact_max_lead_m(finite, > 0, ≤kMaxWorkspaceContactLeadM),workspace_contact_jaw_joints(each acollision_joint_namesentry; default empty),workspace_contact_brake_enabled(default false; requires the rule: a JOINT_POSITION chunk whose only reasons to stop are the measured hand speed and/or lead becomes a hold at each commanded joint's hold anchor — the row of the last command the kernel published for it that is due now (record_workspace_holdkeeps up tokWorkspaceHoldMaxRowsrows on every accept and hold, whoever owns the rules;workspace_hold_qreturns the last row due at or before now, never a later one), usable untilkWorkspaceHoldFreshPeriodsperiods past the last row's due time, within the lead bound and passing the relaxed check, else the measured value — jaws keep their command, no latch, WARNsafety.workspace_brake ... anchor=command|measured anchor_why=—-when anchored, else why the measured pose:no_command/early/stale/past_rows/no_period(workspace_hold_q(d, now_ns, why)),lead/collides(the anchor failed the lead bound / relaxed check),at_measured,uncommanded),workspace_contact_hold_max_consecutive(default 0; needs the brake: a command the relaxed check still refuses while the hold passes is held, up to that many chunks in a row, then the latched stop) — no default the node would use:on_configurereturns FAILURE otherwise and WARNs the rule (both bounds, the freshness window) when on. The node ingestsGraspDeclaration.workspace_regionnext to the grasp region (ingest_workspace_contact, same frame/measurement-age/backstop/stream-freshness rules — a retirement ends the grasp region, not the workspace,safety.workspace_region_armed/_dropped/_rejected,safety.workspace_contact_summaryon drop), sets the hand speed of a JOINT_POSITION candidate from the MEASURED velocity (measured_velocity_fresh(now_ns): every FK dof has a finite/joint_statesvelocity at mostcollision_state_deadline_msold —on_joint_statestores it per dof indq_meas_, a message naming a joint without one forgets it; thenworkspace_hand_speedof FK(q_meas + dq_meas · period) vs FK(q_meas), once per candidate, every row), else the commanded-speed fallback per row (workspace_hand_speed: max over hand links oflink_displacement_bound(prev row, row)/ period; row 0's previous row is, per commanded joint, its previously accepted command whileworkspace_command_fresh— held, due ≤kWorkspaceCommandFreshPeriodsperiods ago — else the measured state; the tick-partner check the same, partner joints at their committed targets) and the hand lead (workspace_hand_lead: max over hand links oflink_displacement_bound(measured, row)with the jaw joints held at measured, not divided by the period); unknown →+inffor every other mode or a stale measured state. Held commands are recorded on accept and forgotten (clear_workspace_commands) on any refused chunk, an external E-stop, a reset, configure/activate/cleanup, and a workspace armed/dropped; the hold anchor survives a refused chunk and a brake (ResetReason::kRefusal/kOther), not the rest, and an accepted arm chunk that records none (velocity / Cartesian / torque / a position chunk outside the geometry checks; not gripper / dex-hand / composite) forgets it too. WARNssafety.workspace_contact(speed +speed_source=measured|commanded, and lead) ≤ 1 Hz per link, and addsworkspace_gate_active=(the stop line's key; theFailureTrigger'sworkspace_contact_activestays the in-tree rule) /hand_speed_mps=/hand_lead_m=/hand_speed_source=/workspace_denied=/workspace_gate=(in_tree/provider/none: under an ADR-0121 provider the provider's verdict region, whichworkspace_gate_active=andworkspace_denied=then report too) tosafety.collision,safety.workspace_contact_active/safety.workspace_gate/_pairs/_max_depth_m/safety.workspace_hand_speed_mps/safety.workspace_hand_speed_source/safety.workspace_hand_lead_mspan attributes and max speed (+max_speed_source) + max lead tosafety.workspace_contact_summary. kMaxRegionMeasurementAgeS = 4.0(2 ×kMaxWorldVoxelDeadlineMs) — Cap ongrasp_region_max_age_s/place_region_max_age_s, how old a producer-measured region'sstamp_nsmay be and still exempt anything.0(default) resolves to 2 ×world_voxel_deadline_ms;on_configurereturns FAILURE for a resolved value outside (0, 4] while the matching allowance (grasp_allowance_enabled/attached_collision_enabled) is on. A stale or future-stamped region is dropped (reason=region_stale) at ingest and per candidate; not applied to a grasp box latched at handover.kDefaultStationTranslationM = 0.02,kDefaultStationRotationRad = 0.02,kMaxStationTranslationM = 0.05,kMaxStationRotationRad = 0.05— Station mode (mobile base,collision_base_dofsnon-empty): node paramsstation_motion_translation_m/station_motion_rotation_rad(defaults the twokDefault*;on_configurereturns FAILURE outside (0, cap]; the shipped launch files pass neither, so deployments run the defaults).update_station(now_ns)(each/joint_statestick) trips when the planar distance of the prismatic base dofs from the anchor exceeds the translation threshold or a revolute dof's delta, wrapped to [-pi, pi], exceeds the rotation threshold;leave_station(now_ns, reason, dof, delta, limit)then retires every base-frame allowance (grasp, place, #349 workspace, tracked key), closes every K5 release window, drops the tracked-cover passes, and stampsbase_moved_ns_(predates_base_motion(stamp_ns)refuses declarations, region measurements and declared release records stamped at or before it). A clock running backwards does the same with reasonclock_reset.note_station_allowances()re-anchors at the measured base pose when an allowance goes live after none was (station_allowance_live(),anchor_station()). Logssafety.station_left reason=base_moving|clock_reset.- Tracked grasp exemption (#418 K2) — removed from the open kernel (ADR-0121 step 3) — the tracked-object grasp exemption is provided by OpenRAL Pro's exemption provider (the launch passes
tracked_grasp_exemption_enabledonly ascontact_exemptions.tracked_grasp_exemption_enabled, and only with a provider). The open kernel keepstracked_grasp_extra_contact_links(default empty: fixed jaws on a body link, OT-6 amendment 2026-10-17): with anexemption_providerthe resolved links join the provider's hands (CandidateView::hands);on_configurereturns FAILURE when a name is no collision link or when no provider reads it. - Tracked binding check (#418 K3) — a
tracked_objectattachment is off the hand (safety.attachment_binding_off_hand reason=no_accepted_set|no_live_track|provisional_track|no_measured_state|box_off_hand): still a checked payload, never a handover, no support witness, no K5 release. ATrackedObject.provisionaltrack fails closed here (never payload binding geometry) while staying K2-eligible. - Producer-declared release (2026-11-02) — an attachment whose
released_by_linkis set (the HAL's and the tracker'sfreeze_released_attachment):ingest_attached_objectsrefuses an unknown link (kUnknownLink, fail closed) and the node resolves it into its ownattached_released_by_(node-side, so the provider-visibleAttachedObjectlayout is unchanged); the node refuses the whole set (safety.released_payload_rejected reason=attach_link_moves) when its attach link is one FK moves (link_static_: a dof on its chain other than the zeroed mobile-base ones);apply_declared_release(beforeapply_tracked_release) freezes it in the base frame (attach_link = -1, so never world-checked; no support witness; K3off_hand=released) and runs the K5 window keyed on (object id, epoch, stamp): the releasing link asrelease_hand_linkand the touch links exempt untilreleased_payload_clearance > tracked_release_clear_m(fresh measured state) ortracked_release_timeout_s, thentouch_count = 0, a plain obstacle (safety.released_payload/safety.released_payload_closed reason=separation|timeout); a heartbeat never reopens a closed window; a record that leaves the wire frees its slot. No provider needed. Safety-WG review and a hazard-log row owed. - Tracked release window (#418 K5) —
tracked_release_clear_m/tracked_release_timeout_s: the kernel's own freeze window for a provider-decided release (on_configurereturns FAILURE outside (0, 0.1] m / (0, 10] s). The jaw-open release decision (tracked_release_jaw_joints/_jaw_open_sign/_gap/_dwell_s) was removed from the open kernel (ADR-0121 step 3) and is the exemption provider's (contact_exemptions.tracked_release_*). -
Explained cells (#418 K7) — removed from the open kernel (ADR-0121 step 3) —
workspace_explained_cells_enabledis the exemption provider's (contact_exemptions.workspace_explained_cells_enabled). The open kernel keepsstatic_points_file(default ""): the declared static geometry as base-frame points (the launch passes one centre per cell the bridge marks,_static_points_file(kernel_cells=True), and only with a provider), loaded at provider load (load_static_points; an unreadable/malformed/empty file refuses the provider) and re-marked once per grid lattice (refresh_static_cells, padded bykExplainedStaticPadCells), only on the base frame's own lattice; handed to the provider asCandidateView::static_cells. -
Parameter guard —
param_guard_(add_on_set_parameters_callback, registered after every declaration) refuses every runtime change to an already-declared parameter while the lifecycle state is notUNCONFIGUREDor onceparams_locked_(set byon_cleanupand by a configure that does not succeed) is true; launch overrides and new declarations (an exemption provider's own parameters, declared ininitializeduring CONFIGURING) pass — pinned byExemptionProviderKernelTest.AProviderDeclaresItsParametersUnderTheRealStateMachine. Pinned byLifecycleKernelTest.SafetyLimitParametersAreRefusedAfterConfigure(over the real/set_parametersservice). Seedocs/reference/ros-graph-security.md. -
Exemption provider params (ADR-0121) —
exemption_provider(default "": none, today's verdicts) names a pluginlib class derivingExemptionProvider;exemption_provider_links(the launch passesRobotDescription.hand_links()) is the kernel's own relaxable-link mask.load_exemption_providerruns at configure after the collision model and never fails configure: offhal_mode: sim, an empty mask, a link the model does not know, a pluginlib load failure, anapi_versionother thankExemptionProviderApiVersion, orinitializereturning false / throwing all leave the kernel with no provider, ERRORsafety.exemption_provider refused, and/diagnosticsexemption_provider=refused: <why>. Loaded: WARNsafety.exemption_provider loaded,/diagnosticsexemption_provider=loaded: <name>andexemption_provider_pairs; per candidate the node fills a preallocatedCandidateView(tracked set after K1 without K6-retired identities, measured state when fresh) and callsbegin_candidate; tolerated pairs WARNsafety.exemption_provider_contact≤ 1 Hz and set span attributesafety.exemption_provider_pairs. The provider'sDeclarationView::handsare built bybuild_grasp_hands:grasp_contact_linksplus the resolvedtracked_grasp_extra_contact_links. With a provider,deploy_e2ehands it the rules (_hand_rules_to_provider): the #349 switches off and the rules step 3 removed from the open kernel (K2, the K5 release decision, K7, OT-10) never passed in-tree, every rule's parameters mirrored undercontact_exemptions., so the in-tree rules and the provider never both decide; without a provider those params are not emitted at all.on_cleanupunloads it. Inspection:exemption_provider_status(),exemption_provider_loaded(),exemption_provider_extra_jaws().
cpp/openral_safety_kernel/include/openral_safety_kernel/exemption_provider.hpp
C++ (Layer 5). The installed exemption-provider seam (ADR-0121): the interface a private provider (OpenRAL Pro) implements to RELAX a verdict the open kernel is about to reach, inside bounds the kernel enforces (asked last, only about a tripping pair, only on a link in its mask, sim only, fail closed).
kExemptionProviderApiVersion = 5— Bumped on any layout or semantics change; a provider reporting another version is refused at load (refused: api_version 4 != 5). v2 added the self and payload pair hooks,DeclarationView, the measured FK,end_candidateandon_reset; v3 the cover hold, the K5 release and the brake config; v4 the attachment identities (AttachmentView),static_points_declared,voxel_overflow; v5 the kernel's own verdicts a provider must not re-derive: the #349 verdict per pair query (workspace_exempt, onworkspace_contact_config, which replacesbrake_config),TrackedObjectView::confirmed_fresh, and the per-bindingReleaseMemoryinReleaseQuery::memory.enum class ProviderVerdict { kRefuse, kTolerate }— Anything butkToleratekeeps the open verdict.struct TrackedObjectView— Read-only POD snapshot of one tracked object as the kernel accepted it (after K1, never K6-retired): identity hash and epoch, role/status flags, the kernel's owncover_ok,visible_cells,confirmed_ns,confirmed_fresh(API v5: the kernel'sregion_measurement_freshonconfirmed_nsagainstgrasp_region_max_age_s),support_z/floor_z, the validatedbox.struct DeclarationView— The live grasp declaration as the kernel's own ingest validated it:live(ADR-0115 verdict),refused,wrong_claim,tracked_active+key_hash(K2 identity checks),stamp_ns,timeout_s, the kernel-ingestedgrasp_region/workspace(null when not live) and thehandsbuilt fromgrasp_contact_links.struct CandidateView— Everything a provider may read for one candidate: model, grid (null without a fresh grid), the kernel's FK / q / dq at the fresh measured state (null when stale), the tracked views (each with itsdeclaration_key_hash), the kernel's mask,now_ns,position_mode,control_period_s,declaration,region_max_age_ns,tracked_frame_ok. Kernel-owned, valid for the call.struct SelfPairQuery,struct PayloadPairQuery— A link-link pair, and a carried payload's pair with a cell or a link (object index,attached_modeland object pointer,object_xf, attach and other link, cell, distance, row, row FK).enum class ResetReason,struct CandidateOutcome— Why the kernel forgot its command chain; an accepted JOINT_POSITION chunk's last row, commanded joints (null = all),horizon,accepted_ns.struct VoxelPairQuery— One (robot link, occupied cell) pair about to trip:link(always in the mask),cell, base-framecell_center_base, the opendistance, the checkedrowand its FK.- Every pair query also quotes the kernel's own #349 measurement of the row:
hand_speed_mps, rawhand_lead_m(before any allowance; both +inf = unknown),hand_contact(the measured hand already touches, measured without the provider), and (API v5)workspace_exempt: the kernel's own #349 verdict for the pair (workspace_region_exemptsonProviderGate::workspace; for self and payload-self pairs both links slow and both origins inside), false unless the provider enabled the rule with the in-tree one off and a workspace is live.CandidateViewalso hastracked_stream_fresh,grid_seq(bumped per ingested grid),workspace_period_s,static_cells/static_cells_n(the declared static colliders' cells on this grid; null when none or off-lattice). struct AttachmentView(API v4) — Per accepted attachment, index-aligned with the AttachedModel:object_id_hash,epoch,attach_link,evidence(kLegacy/kTracked/kProvisionalSingle/kUntrackedGrasp),on_hand(K3),track_indexintoCandidateView::tracked(the bound track, or the one live provisional track the evidence names; -1 = none),bind_low_z(kUntrackedGrasp: the payload's lowest base-frame z at the first ingest that saw the hold, kept while it lasts; NaN = unknown). The kernel keeps only the identity match and that measurement.CandidateView::attached_modelpoints at the AttachedModel.struct CoverHoldQuery,struct ReleaseQuery(API v3),struct WorkspaceContactConfig,struct ReleaseMemory(API v5) — A box whose kernel cover fell short with the kernel's own last pass (last_pass_ns,max_age_ns, measured FK); a bound payload at a fresh measured state (object, attached model, bindingobject_id_hash/epoch, attach link,on_hand= the K3 verdict, measured q, the tracked views, andmemory: that binding'sReleaseMemory, kernel-owned inBoundPayload, reset whenever a binding starts, never read by the kernel:jaw,hold_set,hold,open_since_ns); the #349 rule and brake a provider enables while the in-tree rule is off (enabled,max_speed_mps,max_lead_m,brake_enabled,hold_max_consecutive; validated at load: unsound bounds, a brake without the rule, or the rule (or its brake) without the hand measurement refuse the provider).PayloadPairQuery::release_hand_link: a frozen payload in its K5 window, offered topayload_self_pairon the hand that let it go.class ExemptionProvider—hold_cover(query)/release_payload(query) noexcept(API v3, defaultkRefuse; the kernel performs any hold or freeze inside its own bounds),workspace_contact_config() const noexcept(API v5, replaces v3'sbrake_config; default disabled; the rule, its verdict and the brake mechanism stay the kernel's),replaces_grasp_region() const noexcept(default false; true = the provider is the grasp exemption source and the open ADR-0115 region exempts nothing, read once at load),api_version(),name()(quoted in every disclosure),initialize(model, params, logger)(configure time; false = decline),begin_candidate(view) noexcept,end_candidate(outcome) noexcept,on_reset(why) noexcept,voxel_pair/self_pair/payload_voxel_pair/payload_self_pair(query) noexcept(defaultkRefuse). Hooks on the per-chunk path must not allocate.compose,inverse_rigid,apply,voxel_center,point_in_obb,footprint_gap,grid_cell_of(collision.hpp) — Exported rigid-transform / grid helpers so a provider's rules use the kernel's own arithmetic.struct ProviderGate(collision.hpp) /VoxelGrid::provider_gate— The provider pointer, the kernel's mask, the checked row and the row's measuredhand_speed_mps/hand_lead_m/hand_contact, and (API v5)workspace: the #349 region the kernel computes its quoted verdict on (the live workspace on the provider's bounds, this row's speed and allowance-applied lead; null = no verdict, never applied by the kernel itself), handed tocheck_self_collision/check_attached_self_collision(gateparameter, null = no provider) and read from the grid by the voxel checks.
cpp/openral_safety_kernel/include/openral_safety_kernel/force_observer.hpp
C++ (Layer 5). Allocation-free external joint-torque observer (#373): a generalized-momentum observer over the kernel's own CollisionModel tree, hand-rolled RNEA (no Eigen/KDL/Pinocchio). Exactly discretised, so stable at any sample period. external-torque-observer.md.
struct LinkInertial,struct JointFrictionModel,struct ForceObserverModel— per-link mass/COM/inertia (link frame), per-joint armature/viscous/Coulomb/offset, gravity, gain K, Coulombtanhscale; built once at configure.struct ForceObserverState— pre-sized RNEA scratch,M, previousM/momentum/drive,residual(the τ_ext estimate, N·m, dof order),dof_link.init_force_observer(model, n_dof, state)— size every buffer (configure time).rnea(model, dyn, q, qd, qdd, with_gravity, run_fk, state, tau) noexcept— inverse dynamics incl. armature, mimic links projected through their multiplier.mass_matrix(model, dyn, q, state) noexcept— M(q) by n unit-acceleration RNEA passes.friction_torque(dyn, joint, qd) noexcept— the modelled friction for one joint.force_observer_update(model, dyn, q, qd, effort, dt_s, state) noexcept -> bool— one sample; resets and returns false on non-finite input ordt_s <= 0.reset_force_observer(state) noexcept— forget history; the next sample re-seeds.
cpp/openral_safety_kernel/include/openral_safety_kernel/collision.hpp
Allocation-free attached-payload contact handling, plus the staged 26-DOP → exact-convex-hull narrow phase for the arm-link-vs-world-voxel check (collision-hull-narrow-phase.md, collision-tight-geometry.md).
struct CollisionHit— One collision check's outcome and, on a hit, its E-stop evidence. Since ADR-0121 alsoprovider_pairs/provider_link/provider_cell/provider_min_distance: disclosure of the pairs the loaded exemption provider tolerated, never a decision. Since #349 alsoworkspace_pairs/workspace_link/workspace_cell/workspace_min_distance: disclosure of the (hand link, cell) pairs within the margin the live workspace tolerated, never a decision.link_a/link_b/min_distancename the single deepest tripped pair;sweep_min_distanceis the separate sweep-wide minimum and never supplies the evidence distance.advisoryis the one field that is itself a decision — refuses the action without latching, for an attached payload only, never for a robot link.hull_hull_distance(a, b, margin, fallback, depth_is_box_bound = nullptr) -> double— Stage 2 for a self-collision pair: GJK on the two links' exact hulls, replacing the OBB SAT when both ship stage-2 geometry. The optional out-parameter reports whether the returned depth is the (looser but sound) box's bound rather than a true hull measurement — GJK proves an overlap but does not size it. Disclosure only; never gates the trip decision.check_contact_force_gate(attached, now_ns, robot_threshold_n = +inf) -> ContactForceGateResult— Declaration-scoped contact-force gate for a place, where geometric clearance is zero by design. Only ever adds a refusal, evaluated after every geometric check has passed. Requires positive, non-future declaration and witness stamps and a witness within the smaller of the declaration's remaining lifetime and the existing attached-collision freshness budget, a matching object/target, and a named calibration. Zero stamps count as missing. Missing or stale feedback leaves geometry unchanged. Uses the smaller of the declaration threshold and robot ceiling; it grants no contact permission.kMaxContactForceThresholdN = 140.0and the 600 s timeout ceiling mirror the schema's caps. Allocation-free.place_approach_allowance_cap(resolution) -> double— The place approach allowance's cap at a live voxelresolution:min(1.5 × voxel, 4 cm),0.0for an unusable resolution.constexpr, header-inline; the single definition the geometry and the log line both quote.place_approach_allowance(grid, object_index, center) -> double— Margin reduction the live place declaration grants this payload against this occupied cell, or0.0. Returns the reduction only when the region is valid, the object is inobject_mask, the box is finite/non-degenerate, and the cell centre is inside it (exact point-in-OBB). Reduces the margin only — deepening past it still stops, and arm-vs-world is untouched.enum class PlaceRegionStatus— Outcome of a place-region ingest:kOk,kNoObject(ordinary pre-grasp state),kBadPose(non-finite pose; the node also returns it for a wire quaternion not unit to 1e-6),kBadExtents,kDegenerate,kOversize,kOversizeVolume,kBadGeometry,kGeometryOverflow. Every non-kOkvalue means no allowance.ingest_place_region(pose, half_extents, object_mask, out) -> PlaceRegionStatus— Validate a producer-supplied region intoout, fail-closed toward no allowance (a bad region can only make the kernel more permissive). Rejects a non-finite pose/extent, an over-large side or volume, and an emptyobject_mask, each under its own status. Not on the hot path.ingest_place_target_geometry(geometry, store, region) -> PlaceRegionStatus— Lowers the declared target's own collision primitives into an already-validatedregion, so a payload can be adjudicated against the modelled receptacle instead of its voxel quantisation. Call only after the box validates; anything butkOkresets the whole region.storemust be sized tokMaxPlaceTargetPrimitives(64) and outlive every check reading the region. Rejects a malformed shape or an over-cap list — a half-modelled receptacle is worse than none. Not on the hot path.place_target_distance(region, prim, prim_xf) -> double— Exact surface distance from one attached payload primitive to the declared target's own geometry;+infinitywhen the declaration ships none, collapsing to the pre-existing voxel-only path. Allocation-free.place_region_status_reason(status) -> const char*— Stable snake_case token for aPlaceRegionStatus, used as thereason=key of the node's place-region log lines. Never null.support_contact_exempts(object, object_xf, center, resolution, slack) -> bool— Whether objecti's attested support contact explains this occupied cell: the cell must be inside the attested patch laterally and no higher above the plane than the voxel's own projected half-width plus attested depth, slack, and one voxel of co-planar headroom. Mirrored in lockstep bysupport_patch_withholds(03-world-state.md). Caller must have already established the witness is live.update_support_contact_witnesses(attached, scratch, grid, live_mask, margin) -> uint8— Refreshes the per-object support-witness latch against the measured configuration; a bit clears on separation and is never re-set here, so re-contact after a lift is a new violation. Returns 0 (fail-closed) when the map is unusable. Reads occupancy, so it is partitioned against the Layer-2 payload clearing that withholds the attested patch's cells precisely so this latch keeps something to measure.update_attached_voxel_contacts(attached, scratch, grid, contact_mask, contact_distance, mask_capacity, distance_capacity, snapshot_objects: uint8) -> bool— Snapshots the occupied voxel contacts present at attachment for the objects whose bit is set insnapshot_objects(others are only refreshed) and refreshes them against the measured payload pose; only that embedded subset (the payload's own uncleared occupancy residue) still exempts anything, no bits added after the snapshot. An inlinebool snapshotoverload snapshots all objects.using SlotOrigin = std::array<int, 8>— Per slot of a re-ordered attached set, the old slot its payload came from (-1: new to the set).carry_slot_bits(old_bits, from) -> uint8— Per-slot bits moved with their payload across a re-ordered set (new bit i = old bitfrom[i], 0 for a new slot): the node carries witness liveness this way, so a record moving slot never re-arms a killed witness.carry_attached_contacts(contact_mask, cells, contact_distance, stride, max_objects, from, n_objects, temp_block) -> void— Re-indexes the attach-time residue (mask bits and per-object distance blocks) for a re-ordered set; carried payloads keep their baseline, new and vacated slots are cleared; allocation-free, onestride-sized temp block breaks permutation cycles.place_advisory_depth(resolution) -> double—min(0.2 × resolution, 5 mm), the depth past the place approach allowance within which an attached payload's world contact is refusable rather than latching.0.0for an unusable resolution, collapsing to today's latched stop.link_joint_value(model, i, q) -> double/link_joint_gain(model, i, q) -> double— Linki's joint value for column valueq: through its calibration curve (CollisionModel::curve_point_first/_count/curve_points, thecollision_curve_*params; clamped at the ends) and thenmimic_multiplier * u + mimic_offsetfor a mimic link; its derivative (segment slope, 0 where it clamps, times the mimic multiplier).forward_kinematicsand the force observer pose / differentiate every link through them (#533). Allocation-free.check_self_collision(model, scratch, margin, workspace = nullptr) -> CollisionHit— #349: with a liveWorkspaceContactRegion, a pair of two hand links (both in its mask, both link origins inside its box) does not trip while the hands are slow (workspace_link_slowon both); counted inworkspace_pairs, at its own depth insweep_min_distance.nullptr= the unchanged check.check_attached_self_collision(model, attached, scratch, margin, workspace = nullptr, gate = nullptr, narrow_under = nullptr)applies the same rule to a carried payload on its attach link against another hand link; under a live workspace a refined box payload is checked as its measured inner box, andnarrow_under(when set) is the workspace that narrowing uses instead, never enabling the rule.payload_narrowing_workspace(in_tree_rule, provider_loaded, ingested_live, ingested) -> const WorkspaceContactRegion*— ADR-0121: with #349 handed to a provider, the kernel's live ingested workspace for that narrowing (nullptrotherwise).check_voxel_collision(model, scratch, grid, margin) -> CollisionHit— Checks every FK'd robot primitive against the occupied cells of a dense voxelgrid. Two narrowly scoped exemptions, both default off: the ADR-0115 grasp region (declared contact links, cells centred in the region) and, after it, the #349 manipulation workspace (hand links, cells centred in the confirmed workspace, while the hand is slow —workspace_contact_exempts); tolerated workspace pairs are counted in the hit. Last of all (ADR-0121), a pair still about to trip on a link ingrid.provider_linksis offered togrid.provider(VoxelPairQuery; capsules before, boxes after the narrow phase) and, onkTolerate, does not trip, is counted inprovider_pairsand reachessweep_min_distanceat its own depth; no provider, an unmasked link, a clear pair or an open-exempt pair is never offered. Never setsadvisory— a robot link against the world is always a latching stop. A boxed link with tight geometry runs a staged narrow phase (26-DOP, then exact hull GJK) that only tightens, never loosens, the reported distance versus the plain OBB. One narrowly scoped exemption: whilegrid.grasp_regionis valid, a mask link vs a cell centred in its box does not trip and reachessweep_min_distanceonly, at its own depth (the lifecycle's velocity band clamps an untripped check's slack to 0, so it reads as the slowest rate, never a negative slack that would hide the other pairs' graded slowdown) and never spends the stage-2 budget; every other link's trips are unchanged or, with the budget freed, fewer. Allocation-free.struct GraspTargetRegion/VoxelGrid::grasp_region— Producer-measured region of a live grasp declaration (ADR-0115 draft):valid,link_mask(std::bitset<kMaxGraspMaskLinks>, 256), base-framepose,half_extents, plus lifecycle bookkeepinghandover/object_indexthe geometry never reads. Invalid by default — no exemption anywhere; armed only by the lifecycle node withgrasp_allowance_enabled.kMaxGraspRegionHalfExtentM = 0.20,kMaxGraspRegionVolumeM3 = 0.03,kMaxGraspDeclarationTimeoutS = 120.0— Safety-WG placeholder caps on a grasp region and its declaration's backstop; past any of them it grants nothing.kGraspRetiredCapacity = 16/class RetiredGraspSet— The kernel's retired grasp-declaration identities (HZ-0115-3, multi-pick per goal): a fixed ring of (std::hashoftarget_id,stamp_ns);contains(hash, stamp),insert(hash, stamp) -> bool(true when full and the oldest was evicted; a held identity is a no-op),clear(),size(). No allocation (the lifecycle retires on the candidate path); a hash collision only refuses a fresh identity. Capacity is a Safety-WG placeholder.enum class GraspRegionStatus— Outcome of a grasp-region ingest:kOk,kNoLinks,kBadPose(non-finite pose; the node also returns it for a wire quaternion not unit to 1e-6),kBadExtents,kDegenerate,kOversize,kOversizeVolume. Every non-kOkvalue means no exemption.ingest_grasp_region(pose, half_extents, link_mask, out) -> GraspRegionStatus— Validate a grasp region intoout, fail-closed toward no exemption. Frame matching is the caller's job. Not on the hot path.grasp_target_exempts(grid, link_index, center) -> bool— Whether the live grasp region exempts this link from the occupied cell centred atcenter(base frame): valid region, link in the mask, finite non-degenerate box, centre inside it (the exact point-in-OBB testplace_approach_allowanceuses). Allocation-free.grasp_region_contains(region, p) -> bool— Whether base-frame pointpis inside a valid grasp region's box (the containment half ofgrasp_target_exempts); the lifecycle asks it of the declared payload's origin during the handover. Allocation-free.grasp_region_status_reason(status) -> const char*— Stable snake_case token for aGraspRegionStatus, for thereason=key of grasp-region log lines. Never null.kMaxTrackedObjects = 32,kMaxTrackedHullVertices = 64— Issue #418 K1 caps on the tracker'sTrackedObjectSetas the kernel ingests it (mirrorTrackedObjectSet.objectsmax_length=32and the 64-vertex hull bound; the ≤ 4 hulls bound is the IDL sequence's). A set past a cap is refused whole.tracked_box_meets_hand(model, scratch, attached, object, box, half_extents, slack) -> bool— Issue #418 K3 binding check: does a tracked object's box lie withinslack(one voxel at the call site) of a capsule or OBB of the carrying attachment's own links (attach link + touch links), at the configuration FK'd intoscratch(the lifecycle passes the measured one)? The kernel's lowering of the tracker's pinch volume; ceiling "within a cell of the hand", not "between the pads". False for a degenerate/non-finite box or slack. Decides only whether a TRACKED_OBJECT binding may carry exemptions, never removes a payload from a check. Allocation-free.released_payload_clearance(model, scratch, attached, object) -> double— Issue #418 K5 release-window separation: lower bound on the gap betweenobject's primitives (plain box/capsule, no stage-2 refinement, so it reads low) and every link exempt against it (attach link, touch links,AttachedObject.release_hand_link) at the configuration FK'd intoscratch;+infwhen no exempt link has geometry. AnAttachedObjectwithattach_link == -1is frozen in the base frame (pose_in_linkis its base pose). Allocation-free.kMaxGraspHands = 4,struct TrackedGraspTable— Issue #418: the robot's hands (n_hands,hand_links[h]finger bitsets,extra_links,link_point[l]each finger's TCP sample) and box slots a tracker-based grasp rule would choose between. The open kernel fills only the hands (build_grasp_hands) and hands them to a loaded ADR-0121 exemption provider (CandidateView::hands); it never exempts by this table (the K2 rule andVoxelGrid::tracked_graspwere removed in step 3; the provider fills the boxes on its own copy).build_grasp_hands(model, allowlist, table, extra = {}) -> bool— Configure-time: groups the allowlisted finger links into hands by mount (thegrasp_links_one_handgrouping) and records each finger's TCP sample (mean of its primitives' origins, link frame).extra(tracked_grasp_extra_contact_links, resolved only with a provider loaded, OT-6 amendment 2026-10-17): fixed jaws on a body link, grouped with the fingers (TrackedGraspTable::extra_links) but never a TCP sample. False and no hands on an empty allowlist, a bit past the model, a cyclic chain, more thankMaxGraspHandsmounts, or a hand of extra links alone.grasp_hand_tcp(table, scratch, hand) -> Vec3— A hand's TCP at the FK'd configuration: the mean of its fingers' sample points. NaN for an out-of-range hand or a short scratch. Allocation-free.tracked_box_cover(grid, box, half_extents) -> size_t— The cover re-check on the kernel's own grid (the measurement a provider receives ascover_ok, ADR-0121): occupied cells whose base-frame centre is inside the box (window clamped to the grid; 0 for a degenerate grid/box). Once per grid, not on the hot path. Allocation-free.tracked_cover_sufficient(occupied, visible) -> bool—occupied >= max(2, ceil(0.5 * visible)),visiblethe tracker'sTrackedObject.visible_cells.enum class PrimitiveSource { kFallback, kMeasured, kGrown },AttachedPrimitive::source/AttachedPrimitiveInput::source— Issue #418 (hazard OT-10 amendment, Safety-WG review pending): the evidence behind a payload primitive (wireAttachedCollisionPrimitive.geometry_source); anything unknown or unset iskFallback.- Payload-own cells (#418 OT-10 amendment) — removed from the open kernel (ADR-0121 step 3) —
payload_own_cells_enabled/pinch_payload_own_cells_enabled(andPayloadOwnCells,payload_own_cell_exempts,fill_payload_own) are gone from the open kernel; the rule is the exemption provider's (contact_exemptions.payload_own_cells_enabled/contact_exemptions.pinch_payload_own_cells_enabled). The kernel still hands the provider each attachment's evidence (AttachmentView,PrimitiveSource) and the declared static cells. mark_static_cells(grid, base_points, mask, mask_n, pad_cells = 0) -> size_t— The exemption provider's static cells (CandidateView::static_cells;pad_cells: the kernel passeskExplainedStaticPadCells= 1, OT-11 amendment 2026-10-17: the declared cells plus every cell within one cell, never wrapping; the count returned is the declared cells): clearsmaskand marks every cell ofgridholding a point — the octomap bridge'smark_base_pointsindexing (seedocs/methods/14-duplication-watch.md). 0 for a degenerate grid or a mask shorter than the grid. Once per grid-lattice change.struct WorkspaceContactRegion/VoxelGrid::workspace_region— Producer-confirmed manipulation workspace of a live grasp declaration (issue #349, draft, Safety-WG review pending):valid, hand-linklink_mask(std::bitset<kMaxGraspMaskLinks>), base-framepose,half_extents, plushand_speed_mps(the checked row's commanded hand speed bound, set by the lifecycle per row;+inf= unknown) andmax_speed_mps,hand_lead_m(the checked row's lead over the measured pose;+inf= unknown) andmax_lead_m. Invalid by default — no exemption; armed only by the lifecycle node withworkspace_contact_enabled.kMaxWorkspaceRegionHalfExtentM = 0.50,kMaxWorkspaceRegionVolumeM3 = 0.25— Safety-WG placeholder caps on a workspace (one tote interior or shelf slot); mirrorGraspDeclaration.MAX_WORKSPACE_HALF_EXTENT_M/MAX_WORKSPACE_VOLUME_M3.kMaxWorkspaceContactLeadM = 0.10— Safety-WG placeholder ceiling onworkspace_contact_max_lead_m; mirrors thele=0.10bound onDeployRuntime.workspace_contact_max_lead_m.kWorkspaceCommandFreshPeriods = 2.0— How many control periods a previously accepted JOINT_POSITION command stays row 0's previous row for the workspace hand speed (#349); past it, row 0 is measured against the measured state.kWorkspaceHoldFreshPeriods = 15.0— How many control periods past due the workspace brake's hold anchor (the last command the kernel published for a joint) stays usable (pro#51); calibration point, bounded by the anchor's own lead and relaxed checks.kWorkspaceHoldMaxRows = 256— How many rows of a published chunk the workspace brake keeps per joint as its hold anchor (#480 review: it holds the row due now, not the last row); pre-sized at configure, a hold due past the kept rows falls back to the measured pose.workspace_contact_exempts(grid, link_index, center) -> bool— Whether the live workspace exempts this link from the occupied cell centred atcenter(base frame): valid workspace, link in the hand mask, a finite hand speed ≤ a finite positivemax_speed_mpsand a finite hand lead ≤ a finite positivemax_lead_m, finite non-degenerate box, centre inside it (exact point-in-OBB).check_voxel_collisionasks it only of pairs the ADR-0115 grasp region did not exempt (precedence), andcheck_attached_voxel_collisionof a carried payload's cells on its attach link after the support-witness and attach-residue exemptions, with the same accounting (no stage-2 budget, sweep minimum at its own depth, never the evidence). Allocation-free.workspace_region_exempts(ws, link_index, center) -> bool— The same predicate on aWorkspaceContactRegiondirectly (workspace_contact_exemptsis it ongrid.workspace_region); API v5'sworkspace_exemptquoted to an exemption provider is this onProviderGate::workspace. Allocation-free.ingest_workspace_region(pose, half_extents, link_mask, max_speed_mps, max_lead_m, out) -> GraspRegionStatus— Validate a confirmed workspace intoout(the grasp-region geometry checks against the workspace caps);hand_speed_mpsandhand_lead_mstart unknown. Frame matching is the caller's job. Not on the hot path.attached_object_reach(attached, object) -> double— Radius about a payload's attach-link origin bounding all its primitives (|primitive origin in the link frame| + box |half_extents| or capsule/sphere half_length + radius);+infon a malformed model. The #349 workspace speed bound uses it for a carried payload's attach link (the lead keeps the hand's own reach) (SafetyKernelLifecycleNode::workspace_reach).link_geometry_reach(model, link) -> double— Radius about a link's frame origin bounding all its collision geometry (capsules |origin| + half_length + radius, boxes |origin| + |half_extents|); configure-time.link_displacement_bound(from, to, reach) -> double— Upper bound on how far any point withinreachof a link origin moves between two poses: |Δt| + θ·reach (θ the relative rotation angle);+infon non-finite input. Allocation-free.kDopAxes/kDopAxis[kDopAxes][3]— The 26-DOP's 13 unit axis directions (3 face, 4 corner, 6 edge; each alo/hislab) in the owning OBB's local frame; the first three are the box's own axes. Mirrored in Python asopenral_core.schemas.DOP_AXES(14-duplication-watch.md item 12).kMaxTightHullVertices = 320— Hard ceiling on a stage-2 hull's vertex count, enforced at configure time; a cost bound (the exhaustive-scan support function is linear in vertex count), not a geometry choice. A hull over the cap runs stage 1 only. Mirrored asMAX_TIGHT_HULL_VERTICES.kTightContainmentEpsilonM = 1e-9— Floating-point slackvalidate_tight_geometryallows checking a stage-2 vertex against its own DOP slabs (tangent by construction). The DOP-inside-OBB check itself takes no slack. Mirrored asTIGHT_CONTAINMENT_EPSILON_M.kGjkMaxIterations = 24/kGjkTolerance = 1e-9— Iteration ceiling and convergence tolerance for the stage-2 GJK loop; hitting the ceiling is not a failure — every iteration's result is a lower bound, so a truncated run is simply more conservative.kMaxStage2PerCheck = 32— Ceiling on stage-2 invocations in onecheck_voxel_collisioncall across every link; past it the check keeps refining with stage 1 and the shippedbox_box_distance, so the cap can only make the answer more conservative. Exempt grasp-target pairs never spend it. Changing it changes a real-time bound — belongs in the hazard log.struct LinkHull— Tight convex geometry refining ONEObbinCollisionModel::boxes, in that box's local frame. Fields:dop_lo/dop_hi(stage 1, always on) andvertex_first/vertex_count(stage 2, CSR offset intohull_vertices;vertex_count == 0means stage 1 only).enum class JointKind/is_mimic(kind)—kFixed,kRevolute,kPrismatic, and since #349kMimicRevolute/kMimicPrismatic: a link posed from ANOTHER joint's column (dof_indexis the mimicked joint's) atmimic_multiplier * q + mimic_offset— the URDF<mimic>relation, the OpenArm's follower finger. No qpos slot, no Jacobian column (jacobian_dls_stepskips it; configure refuses one on the EE chain).docs/reference/finger-mimic-geometry.md.CollisionModel::mimic_multiplier/mimic_offset— Per link when the model has a mimic link (collision_mimic_*), else empty (identity relation for every link).CollisionModel::box_hull/hulls/hull_vertices— The threeCollisionModelmembers carrying tight geometry:box_hull(parallel toboxes) indexes intohullsfor the tight representation refining that box,-1for none. An emptybox_hullmeans no box carries tight geometry — the pre-existing behaviour every capsule-lowered robot keeps.AttachedPrimitive::hull_index/AttachedModel::hulls/AttachedModel::hull_vertices— The payload twin of the robot's tight-geometry fields, for the payload-vs-world-voxel check only. Unlike a robot's fixed geometry, a payload's hull arrives on every world-state message and is refilled byingest_attached_objectswithout allocating. Ingest fails DOWN, not closed: an unprovable refinement is dropped and the primitive checked as the plain box (refusing the whole attachment would drop its geometry — the unsafe direction). An over-budget hull is refused whole, never truncated.enum class TightGeometryStatus— Whyvalidate_tight_geometryrefused a model:kOk,kBadArity,kEscapesBox,kHullEscapesDop,kTooManyVertices,kDegenerate. Anything butkOkis fail-closed: the kernel keeps the shipped OBB narrow phase for every link.validate_tight_hull(hull, half_extents, vertices) -> TightGeometryStatus— The containment proof for one tight representation against one box: slabs finite,hull ⊆ 26-DOP ⊆ box, vertex count in budget, CSR slice in range. Shared by the robot's configure-time check and the payload's per-message ingest, so both are held to the same standard. Allocation-free.validate_tight_geometry(model, offending_box) -> TightGeometryStatus— Proves, at configure time, that every declared tight representation is a subset of the shipped OBB it refines, keepingcheck_voxel_collision's broad-phase reach correct.offending_boxreceives the offending index on refusal. Not on the hot path; allocation-free.tight_geometry_status_reason(status) -> const char*— Stable snake_case token naming aTightGeometryStatus, for the kernel's tight-geometry log line. Never null.struct TightPose/tight_pose_init(hull, hull_vertices, box_xf, half_side, out) -> void— Per-link-pose constants for the staged narrow phase, hoisted once per checked configuration outside the cell loop. Holds pointers into the caller'sCollisionModel; must not outlive it. Allocation-free.dop_cell_lower_bound(pose, center, half_side, best_axis) -> double— Stage 1: a conservative lower bound on the surface distance between the link's 26-DOP and an occupied voxel cube, via separating-axis over 16 directions.best_axis(nullable) receives the winning normal, seeding stage 2's search. Allocation-free.struct GjkWitness— Stage-2 warm-start carried between adjacent cells/steps. Stores hull vertex indices and cube-corner sign codes (hints, re-evaluated per cell), never cached Minkowski-difference points;n == 0is a cold start.hull_cell_distance(pose, center, half_side, seed_dir, margin, fallback, witness) -> double— Stage 2: a lower bound on the surface distance between the link's exact convex hull and an occupied voxel cube, seeded from stage 1's separating axis. Every returnable value is a supporting-hyperplane lower bound, so the iteration cap and early exit can only make the answer more conservative; on overlap,fallback(stage 1's figure) is returned instead. Allocation-free (fixed-size stack simplex).hull_hull_distance(a, b, margin, fallback) -> double— Stage 2 for a self-collision pair: the same GJK with the cube's corners replaced by a second hull's vertices.check_self_collisioncalls it for an OBB pair withinmarginwhen both links ship a stage-2 hull; the OBB stays the broad phase and fallback, so a manifest withouttight_geometryis bit-for-bit unchanged. Exists because the OBB alone cannot answer for two interleaving links whose real geometry only sometimes interpenetrates. Does not stop at the first bound clearingmargin(its result is the reportedsweep_min_distance). Cold-started. Allocation-free.
packages/openral_safety/openral_safety/envelope_loader.py
Pydantic → C++ kernel ROS-param bridge.
- module constant
_ACTUATED_JOINT_TYPES: frozenset[str](L191) —{"revolute", "prismatic", "continuous"}, joint types counted as actuated DOF. merge_deploy_envelope(robot_env, deploy) -> SafetyEnvelope(L369) — Apply explicitDeployScene.safetyfields to the robot ceiling with tighten-only validation; omitted fields keep robot manifest values.max_external_joint_torque_nmmerges per joint (union, tighter value), so a deploy scene can never drop a robot ceiling (#373).class EnvelopeIntersection(L62) — The numerical product ofrobot.safety ∩ skill.envelope.compute_intersection(robot, skill, *, deploy=None, gripper_convention=None) -> EnvelopeIntersection(L433) — Robot ceiling ∩ optional deploy/workcell envelope ∩ optional skill envelope; rejects (never clamps) any deploy or skill safety field that loosens the robot ceiling. Gripper channels come from each actuated end effector's command range, or fromgripper_convention(a simulated scene's encoding) when set.kernel_params_from_envelope(envelope) -> dict[str, object](L588) — Canonical scalar/AABB envelope → kernel ROS-param dict.- module constant
_JOINT_KIND_CODE: dict[JointType, int](L671) —{REVOLUTE: 1, CONTINUOUS: 1, PRISMATIC: 2}, the kernel's per-joint kind code used when flattening the kinematic chain. - module constant
_MIMIC_KIND_CODE: dict[JointType, int](L679) —{REVOLUTE: 3, CONTINUOUS: 3, PRISMATIC: 4}: aMimicJointedge's kernel kind, posed from the mimicked joint's column. collision_params_from_description(robot, *, margin_m=None) -> dict[str, object](L843) — Flatten collision geometry + ACM + the kinematic chain into the kernel's collision params. RaisesROSConfigErrorunless the links form one connected tree, and again if it cannot lower a primitive's shape, rather than silently mis-approximating it. A boxed link withtight_geometryalso lowers the staged-narrow-phase DOP/hull arrays. Amimic_jointsedge lowers tocollision_joint_kind3/4 on the mimicked joint's column plus the per-linkcollision_mimic_multiplier/collision_mimic_offsetarrays (#349), and ends withwith_joint_curves.with_joint_curves(params, robot) -> dict[str, object](L1059) —paramspluscollision_curve_point_first/_count/collision_curve_pointsfor every link whosecollision_dof_indexcolumn is a joint with aJointSpec.urdf_curve(the kernel and the self-filter pose it atcurve(q), a mimic atmultiplier * curve(q) + offset); stale curve arrays dropped, none emitted without a curve. Works on the manifest or the MJCF lowering; the deploy launch re-applies it after picking one (#533)._force_observer_params(robot, spec, ordered, edge_of_child) -> dict[str, object](L1103) — The #373 observer model as the kernel'sforce_observer_*params, parallel to the collision links (joint terms describe the joint into each link; fixed / mimic edges get zeros). Emitted bycollision_params_from_descriptionwhenrobot.force_observeris set.merge_extra_allowed_pairs(params, pairs) -> dict[str, object](L1154) — Additive deploy-scene ACM merge. Resolves link names, rejects unknown/self pairs, dedupes order-insensitively, no-ops when self-collision geometry is disabled.ee_link_index_from_collision_params(params) -> int(L1200) — Picks the predictive-Cartesian EE control link (the kinematically deepest collision link with no mimic or curved joint on its chain — the kernel refuses such an EE) for the kernel's Jacobian look-ahead;-1when no collision model (predictive disabled, reactive floor only).
packages/openral_safety/openral_safety/dynamics_lowering.py
Offline MJCF → ForceObserverSpec lowering for the kernel's external-torque observer (#373); imports mujoco lazily.
lower_force_observer_from_mjcf(robot, *, manifest_dir=None, gain_per_s=50.0, coulomb_velocity_rad_s=0.05, limit_margin_rad=0.02) -> ForceObserverSpec(L48) — Inertials re-expressed in the manifest link frames (refuses unless one rigid root transform maps every manifest link's q = 0 FK onto its MJCF body), welded unmapped bodies folded into their mapped ancestor (refused if a joint moves them), joint terms fromarmature/damping/frictionloss, gravity in the kinematic root frame.
packages/openral_safety/openral_safety/mjcf_lowering.py
Offline MJCF → kernel collision-params lowering; imports mujoco lazily.
- module constant
_MJ_GEOM_PLANE: int = 0(L35) - module constant
_MJ_GEOM_SPHERE: int = 2(L36) - module constant
_MJ_GEOM_CAPSULE: int = 3(L37) - module constant
_MJ_GEOM_CYLINDER: int = 5(L38) - module constant
_MJ_GEOM_BOX: int = 6(L39) — MJCFgeom_typeenum valueslower_collision_paramsreads from the compiled model. - module constant
_LOWERABLE_GEOM_TYPES: frozenset[int](L80) —{sphere, capsule, cylinder, box}, the geom types this lowering path handles (mesh/plane skipped). lower_collision_params(model, joint_names, *, margin_m=0.0) -> dict[str, object](L270) — Lowers a compiledmujoco.MjModelto the kernel's collision params: per-link origins, every collidable primitive as a capsule,dof_indexassigned by movable-joint order (not by MJCF joint name, which can differ from the manifest; the deploy launch refuses a result that disagrees with the manifest by name,_mjcf_dof_mismatches), ACM = parent↔child + MJCF excludes + a neutral-pose overlap sweep.
packages/openral_safety/openral_safety/kernel_predicates.py
The Python mirror of the C++ kernel's narrow phase (cpp/openral_safety_kernel/src/collision.cpp), batched over a leading configuration axis. Anything offline that decides what the kernel will do must ask the same question with the same geometry. Every dispatch is exhaustive over CollisionShape and ends in a typed ROSConfigError, never a silent fallback.
- module constant
_DEGENERATE_AXIS: float = 1e-9(L68) — near-zero-length-axis tolerance used when normalizing a separating axis. - module constant
_TERNARY_ITERS: int = 48(L70) — ternary-search iteration count forbox_capsule_distance's convex point→segment minimization. box_box_distance(a_tf, a_half, b_tf, b_half) -> NDArray(L94) — 15-axis separating-axis surface gap between two oriented boxes (port of the C++ kernel); the max over the 15 candidates is the exact signed separation.<= 0means overlap.box_capsule_distance(box_tf, box_half, cap_tf, cap_radius, cap_half_length) -> NDArray(L145) — Box↔capsule gap: the capsule's segment ternary-searched against the box in its local frame, minus the radius.capsule_distance(a_tf, a_radius, a_half_length, b_tf, b_radius, b_hl) -> NDArray(L186) — Capsule↔capsule gap: segment-segment minimum distance minus both radii. A sphere is a capsule withhalf_length = 0.shape_distance(a_shape, a_tf, b_shape, b_tf) -> NDArray(L247) — Dispatch reproducing the kernel's self-collision routing (box↔box, box↔capsule either order, else capsule/sphere); the single entry point an offline sweep should use.shape_max_extent_m(shape) -> float(L288) — Farthest any point ofshapelies from its own origin; bounds how far a link's geometry sits from a joint axis.bounding_capsule_segment(shape, origin) -> tuple[p0, p1, radius](L303) — A capsule that containsshape, for consumers (today onlycumotion_config) that can only express capsules; a box takes its longest axis as the segment and the half-diagonal of the rest as the radius.eroded_shape(shape, eps_m) -> CollisionShape | None(L363) — Minkowski erosion by aneps_mball;Nonewhen empty, which a caller must read as "cannot certify", never as "no overlap".
packages/openral_safety/openral_safety/urdf_lowering.py
Offline URDF(+SRDF) → manifest collision-model lowering tool; lazy-imports yourdfpy / trimesh (the [lowering] group). Populates robot.yaml's collision geometry + ACM (the hand-reviewable manifest path), distinct from mjcf_lowering (the runtime MJCF path).
An ACM entry removes a self-collision check, so every rule here fails toward fewer entries. The always-colliding proof (_certified_always_colliding) is a branch-and-bound Lipschitz-bounded sweep over the pair's relative-DoF subspace whose cost knobs can only withhold an entry, never certify an unsound one.
parse_srdf_disabled_pairs(srdf_path) -> set[frozenset[str]](L85) — Parse a MoveIt SRDF's<disable_collisions>rows into unordered link pairs (the ACM).fit_capsule_to_vertices(vertices, *, headroom_m=CAPSULE_HEADROOM_M) -> tuple[CapsuleShape, tuple[float×6]](L249) — Minimum-volume bounding capsule containing every vertex: axis searched over the principal axes + a 256-direction hemisphere + local refinement, the line through the minimal enclosing circle of the projection, the segment the shortest that still holds every vertex; the radius then grows by the declaredheadroom_m. Containment holds for every candidate axis by construction. Returns the shape + link-frame origin.LinkFit(L476) — Frozen dataclass: one link's fittedprimitives((shape, origin)list), the winningkind(capsule/box/capsule×k),volume_ratio(union ÷ hull volume),max_protrusion_m/mean_protrusion_m(largest / mean support excess over the hull),candidates({kind: (volume_ratio, max_protrusion_m, mean_protrusion_m)}) andfitted(every candidate's primitives, for re-picking in a review).fit_link_primitives(mesh, *, headroom_m=CAPSULE_HEADROOM_M, max_capsules=3, force_box=False) -> LinkFit(L515) — The one fitting step both lowering paths call on a link'strimesh.Trimesh(collision + visual, link frame): fits one capsule (fit_capsule_to_vertices), one box (fit_obb_to_vertices) and capsule chains of 2..max_capsules(the mesh cut into equal slabs along the capsule axis, each slab fitted), every candidate holding every vertex with the headroom; picks the least mean protrusion (support excess over the convex hull, averaged over directions), ties within_PROTRUSION_TIE_FRACTIONgoing to the cheaper kernel kind (capsule < fewer capsules < box); excess volume and max protrusion are reported per candidate.force_boxfor a link that will carrytight_geometry.fit_link_with_tight_geometry(link_name, mesh, *, headroom_m=CAPSULE_HEADROOM_M) -> LinkCollisionGeometry(L606) — One link as a box (fit_obb_to_vertices, origin rounded and half-extents rounded up to the manifest's 4 dp) plus thetight_geometryderived in that rendered frame (tight_geometry.tight_geometry_for_box), somesh ⊆ hull ⊆ DOP ⊆ boxholds for the box the kernel loads. What--tight-linkand a manifest-refined link lower to.- module constant
_RENDER_DP: int = 4(L603) — the precisionfit_link_with_tight_geometryrounds the box to before deriving its refinement (mirrorsopenral_cli.collision._BLOCK_FLOAT_DP). _rendered(shape, origin) -> tuple[CollisionShape, origin](L652) — A primitive rounded to the manifest's 4 dp;_fit_linkreturns every fitted primitive this way so the ACM certificate and the regression test reason about the numbers the kernel loads, not an unrounded twin.- module constant
_SPLIT_GRID_M: float = 0.01(L676) — step of the cut-plane grid_split_tight_piecessearches along a link's long axis; cuts land on its multiples, so the planes are round numbers and stable under a CAD revision. _slab_hull_points(mesh, axis, grid) -> tuple[list[ndarray], list[ndarray]](L679) — Per grid band the hull vertices of the mesh vertices inside it, per plane the mesh edges' crossings — the point setslice_plane(cap=False)keeps, reduced band by band (hull(A ∪ B) = hull(hull(A) ∪ hull(B))) so the cut search is affordable on a 331 k-vertex CAD mesh._best_cuts(slab_volume, n, k) -> tuple[float, list[int]](L716) — Thek - 1ofngrid planes minimising the summedslab_volume(a, b)(plane-1= the link's start,n= its end), by a dynamic program over the additive objective: O(k·n²) slab evaluations against C(n, k-1) for trying every cut; ties keep the lower plane. Returns(total, ascending plane indices),total = infwhen every cover has a degenerate slab._split_tight_pieces(link_name, mesh, k) -> list[LinkCollisionGeometry](L747) — A link askslabs along its capsule axis, eachfit_link_with_tight_geometry(box + DOP + exact hull): the cut planes are the_SPLIT_GRID_Mgrid positions_best_cutspicks for the least total hull volume, so a re-lower reproduces them from the mesh alone; slabs are cut as_capsule_chaincuts, so each piece's hull holds its solid slab and the union holds the link. For a link one hull would swallow the space around (the OpenArm torso: foot plate, column, shoulder block — one hull is 5.6× the mesh and 0.12 m past the column). RaisesROSConfigErrorwhenkleaves no grid position or a slab is degenerate._as_tight_links(tight) -> dict[str, int](L831) —{link: pieces}from either spelling oftight_links(a mapping, or bare names = one piece each). RaisesROSConfigErrorfor a piece count below 1 (it would otherwise quietly mean "unrefined")._fit_link(link_name, mesh, tight_links) -> list[LinkCollisionGeometry](L844) — One link's entries:fit_link_with_tight_geometryfor a linktight_linksmaps to 1,_split_tight_piecesfork > 1, elsefit_link_primitivesat manifest precision; the step both readers share._tight_links_of(robot, extra) -> dict[str, int](L864) — Links to lower as box + hull with their piece count: every link the manifest already refines (count = its tight entries) plusextra, the larger count winning — sticky, socollision checkreproduces a refined or split manifest and dropping a refinement or a slab is a manifest edit._twin_link_meshes(robot, urdf_model, manifest_dir) -> dict[str, Any](L2841) — The robot's MJCF twin mesh geoms per manifest link, in the link frame, when every mapped twin body frame coincides with its URDF link frame at zero (_TWIN_FRAME_TOL = 1e-6);lower_robotfolds them into the fit so the primitives hold the simulated robot's CAD too (the menagerie H1's forearm is 46 mm longer than h1_description's). Empty (and logged) when the frames differ,mujocois missing or the robot has no twin.- module constant
_PROTRUSION_TIE_FRACTION: float = 0.03(L1),_PROTRUSION_DIRS: int = 1024(L1),_UNION_VOLUME_SAMPLES: int = 60_000(L418) —fit_link_primitives's tie window, support-excess direction count and fixed-seed Monte-Carlo sample count for a chain's union volume. CAPSULE_HEADROOM_M = 0.001(L135) — declared clearance every URDF-lowered capsule keeps around its link's geometry; absorbs the manifest's 4-dp rendering (tests/unit/test_collision_geometry_enclosure_urdf.py).lower_link_geometry(urdf_path, *, tight_links=(), extra_meshes=None, sweeps=None) -> list[LinkCollisionGeometry](L946) — The primitive set of every URDF link with a<collision>(and of a<visual>-only link whenextra_meshescarries twin CAD for it), fitted byfit_link_primitivesto the link's<collision>and<visual>geometry together (box→8 corners, cylinder/sphere→circumscribing polytope, mesh→trimesh); a lone sphere<collision>with no visual stays an exact sphere. A link may yield several entries (a capsule chain); a link intight_links(names, or{link: pieces}) lowers tofit_link_with_tight_geometryinstead, inkslabs when mapped tok > 1.sweeps({link: (x, y, z)}, fromFixedAttachment.sweep_xyz) fits a link as the convex hull of its cloud and a copy moved by that travel (one hull, so a splitting fitter cannot cover only the two ends), which holds the whole straight sweep._link_sweepsrefuses a swept link that carries other links (they ride the travel uncovered). RaisesROSConfigErrorwhen a link's geometry resolves only partially; skips a link none of whose geometry resolves.- module constant
_CERTIFY_MAX_DOF: int = 5(L1167) - module constant
_CERTIFY_MAX_CELLS: int = 400_000(L1171) - module constant
_CERTIFY_MAX_LEVELS: int = 96(L1174) - module constant
_COARSE_NODES: int = 7(L1176) — the four_certified_always_collidingcost knobs (see the module intro); hitting any withholds the ACM entry, never soundness. - module constant
_MJCF_RNG_SEED: int = 20260610(L1184) - module constant
_MJCF_N_SAMPLES: int = 2000(L1185) — defaults forlower_robot_from_mjcf's seeded always-colliding sweep. modelled_links(robot) -> set[str](L2955) — The links lowered geometry may land on: the joint chain,fixed_attachmentslinks andmimic_jointsfollowers (the producers name followers as touch links)._check_mimic_frames(robot, urdf_ref, lowered) -> None[private] —lower_robotrefuses (ROSConfigError) a lowered mimic follower whose manifest origin/axis is not the URDF's: the kernel poses it from the row._manifest_welded_joints(robot, urdf_ref) -> frozenset[str][private] — URDF-movable joints afixed_attachmentsrow spans (a twin's welds, every movable joint on the row's URDF path); the always-colliding proof holds them at zero, as the kernel does. Delegates to_check_attachment_rows._check_attachment_rows(robot, model) -> frozenset[str][private] — Refuses a row that is not the URDF's parent → child transform at zero (composed through any links between; 1e-4 tolerance) or that spans a joint the manifest keeps as a kernel DoF (the kernel would hold the child rigid while that joint moves it); returns the joints the rows weld. Rows between links the URDF does not connect are left alone._urdf_zero_path(model, child, parent) -> list | None[private] — The URDF joints fromparentdown tochild, orNonewhen the URDF does not connect them.acm_for_geometry(urdf_path, geoms, *, srdf_path=None, margin_m=0.0, welded=frozenset()) -> set[frozenset[str]](L1603) — The ACM for the exact primitives the kernel will load (a flat list, or a mapping by link to one primitive or its list), decided with the kernel's own predicates at the robot's own margin, each link pair's gap folded over its primitives.ACM = adjacent ∪ always-colliding ∪ [SRDF-disabled if given]— geometry can prove a pair always collides but never that it never does, so without an SRDF a sometimes-colliding pair stays checked. Deterministic, no RNG.sample_acm_from_urdf(urdf_path, *, margin_m=0.0) -> set[frozenset[str]](L1673) — No-SRDF fallback:adjacent ∪ always-collidingfrom the URDF's own geometry. Conservative against a precise-mesh SRDF (its disabled set is a subset, never false-permissive). The name is now a misnomer (nothing is sampled) but is kept as public API/provenance value._static_mesh_filename_handler(urdf_path) -> handler(L1756) —_rd_mesh_filename_handlerpluspackage://refs throughopenral_core.assets.resolve_package_uri, raisingROSConfigErroron one that does not resolve; for STATIC links only, never installed in_load_urdf(resolving the openarm arm meshes would flipselect_loweringoff the MJCF path)._urdf_link_meshes(robot, link_body, manifest_dir) -> dict[str, Trimesh](L1857) — URDF<collision>+<visual>geometry of every MJCF-mapped manifest link, in the link frame, matched through the joint of the samesim_joint_name(or name);fit_collision_geometry_from_mjcfunions it into the link's fit. RaisesROSConfigErrorwhen that joint's URDF origin differs from the manifest's (_TWIN_FRAME_TOL; the frames would not coincide) or a mesh does not load;{}without a URDF. Added after OpenArm's link6 hull missedopenarm_description's link6 by 10.6-13 mm. Also unions the URDF geometry of everyfixed_attachmentschild the MJCF maps a body for, after_check_attachment_rowsvalidates the rows._static_link_meshes(robot, link_body, manifest_dir) -> dict[str, Trimesh](L1781) — Geometry of every static link — afixed_attachmentschild the MJCF has no body for (the OpenArm torso) — from the URDF's<collision>and<visual>elements, in the link frame. Fails closed: a static link absent from the URDF or with geometry that does not all load raisesROSConfigError; one with no<collision>is skipped with a warning; a robot with no static link returns{}without opening the URDF._fixed_link_world(robot, link_body, body_tf) -> dict[str, ndarray](L1951) — World pose of every linkfixed_attachmentsreach from a mapped MJCF body, upward (T_parent = T_child · origin⁻¹) and downward to a fixpoint, so a static link under the chain's root is placed from the mounts the MJCF carries instead of assuming the root is MuJoCo's world; two routes disagreeing by more than_TWIN_FRAME_TOLraiseROSConfigError.class LoweredCollisionModel(L1702) — Frozen dataclass result:collision_geometry(several entries per link allowed),allowed_collision_pairs(sorted tuples),acm_source("srdf"|"sampling"|"mjcf"),srdf_path,joint_fk.lower_joint_fk(robot, urdf_ref) -> dict[str, tuple[xyz, rpy, axis]](L2021) — Per-manifest-joint forward kinematics read from the URDF, matched bychild_link; needed to place the link capsules. Unmatched (synthetic) joints are omitted.lower_robot_from_mjcf(robot, *, n_samples=2000, seed=20260610, margin_m=0.0, manifest_dir=None, acm_only=False, tight_links=None) -> LoweredCollisionModel(L2612) — MJCF backend for robots with no URDF collision geometry (e.g. bimanualopenarm): fits the geometry withfit_collision_geometry_from_mjcf(kept from the manifest underacm_only, aslower_robotkeeps it), lowers joint FK from mujoco, and derives a conservative ACM from a seeded mujoco-FK overlap sweep over that geometry, folding each link pair's gap over its primitives as the kernel does, and never auto-disabling a pair whose two links both carry a hull (the kernel re-asks those of the hulls) — the one remaining sampled criterion, since the URDF joint-tree proof doesn't apply here. A static link (_static_link_meshes) is re-placed by_fixed_link_worldat every sample (it follows its parent, which may move), is adjacent to itsfixed_attachmentsparent, and is in scope so an SRDF row naming it survives. A manifestassets.srdfis unioned into the sweep's disabled set for hand-reviewed exemptions the sweep can't prove; hand-editing the generated ACM block is forbidden. Refuses a manifest whosefixed_attachmentsdeclaresweep_xyz(only the URDF fit covers a sweep).acm_source="mjcf".- module constant
_MOVABLE_JOINT_TYPES: tuple[str, ...](L1283) —("revolute", "continuous", "prismatic"), joint typeslower_joint_fk/acm_for_geometrytreat as movable. lower_robot(robot, *, srdf_path=None, acm_only=False, geometry_only=False, manifest_dir=None, tight_links=None) -> LoweredCollisionModel(L3002) — Top-level entry; threadsrobot.safety.self_collision_margin_mintoacm_for_geometryso the ACM matches the kernel's live threshold. Geometry is scoped to the joint links plus everyfixed_attachmentsandmimic_jointslink (a mimic follower is a touch link the kernel must know), so a URDF body link the kernel should see is onefixed_attachmentsrow away. ACM source precedence: explicitsrdf_path→ manifestassets.srdf→ URDF-only fallback. RaisesROSConfigErroron zero fitted links, never an empty geometry/ACM the kernel would silently not check.select_lowering(robot, *, manifest_dir=None) -> LoweringSource(L3191) — Provenance-correct routing:"srdf"(SRDF + usable URDF geometry),"sampling"(URDF geometry, no SRDF),"mjcf"(no usable URDF geometry but an MJCF exists, e.g.openarm's unresolved package mesh refs, oropenamrobot_v2's URDF whosebase_linkresolves only partly — a URDFlower_link_geometrywould refuse is not usable for routing). RaisesROSConfigErrorwhen no lowerable asset exists.lower_robot_auto(robot, *, acm_only=False, geometry_only=False, manifest_dir=None, tight_links=None) -> LoweredCollisionModel(L3237) — Single dispatch overselect_lowering→lower_robotorlower_robot_from_mjcf(acm_onlykeeps the manifest geometry on both paths;tight_linksadds box + hull links on top of those the manifest already refines,_tight_links_of); the one entry point the CLI and the regression test both call, so routing can never diverge. RaisesROSConfigErrorwhen atight_linksname matches no lowered link (a typo must not leave a link silently unrefined), and whentight_linksis combined withacm_only(which keeps the manifest geometry, so the request would be dropped silently).fit_obb_to_vertices(vertices, *, headroom_m=CAPSULE_HEADROOM_M) -> tuple[BoxShape, tuple[float×6]](L348) — Minimum-volume oriented bounding box (trimesh.bounds.oriented_boundsover the hull), half-extents re-measured from the cloud in that frame and grown byheadroom_m; every vertex inside by construction.- module constant
_MJCF_STROKE_SAMPLES: int = 9(L1191) — leader positionsfit_collision_geometry_from_mjcfsweeps a coupled follower over. mjcf_coupled_joints(model) -> dict[int, list[tuple[int, float, float]]](L2177) — MuJoCo joint equalities (q[obj1] = c0 + c1·q[obj2]) as a two-way map, joint id →[(other joint, c0, c1)], so a follower is set correctly whichever side the manifest drives (OpenArm drivesobj1). RaisesROSConfigErroron a non-linear or non-invertible coupling.twin_coupled_joints(robot, model) -> dict[int, list[tuple[int, float, float]]](L2370) —mjcf_coupled_jointsplus followers the twin drives by a mirror actuator (sim.grippers[].mirror_actuator_index: gym-aloha's ViperX second finger,q_follower = -q_leader), added both ways when that actuator is a joint actuator on its own joint with the leader's gain/bias and the negated control range. Used by the MJCF fit's follower exclusion, its ACM sweep and_declared_mimic_followers(so a declared mirror mimic validates), and by the twin enclosure test.with_twin_gripper_curves(robot, model) -> RobotDescription(L2316) —robotwith eachsim.grippers[]entry innormalisedwrite mode that declares nourdf_curvegiven the twin's own stroke as its curve,((0, lo), (1, hi))overctrl_range(_manifest_to_mjcf_affine, actuator checked 1:1; the MJCF joint bysim_joint_name, else name, else the one its actuator drives). The deploy launch passes it towith_joint_curveswhen it keeps the MJCF lowering, which otherwise posed the gripper link straight from the [0, 1] column: WidowX'sleft_fingerslide reached 1 m and its world-map coverage ball came out 1.6 m (0.767 m with the curve). A declared curve (MakerMods Metal) is kept.ROSConfigErrorwhen the actuator does not drive the joint 1:1 (the launch then keeps the manifest model)._declared_mimic_followers(robot, model, followers) -> set[int](L2414) — The MJCF follower joints the manifest models asmimic_joints(compared through the leader'surdf_curveat its breakpoints, #533), each checked to be an equality follower of itsmimicsjoint — or that joint itself — with the SAME multiplier/offset in the manifest channel's units (ROSConfigErrorotherwise; a normalised gripper converts through_manifest_to_mjcf_affine);fit_collision_geometry_from_mjcfleaves them out of the leader's sweep and fits them as their own rigid links._gripper_actuator(robot, grip) -> int(L2257) — The MJCF actuator the twin writes asim.grippers[]command to, resolved asMujocoTwinHALdoes: the gripper'sactuator_index, else the joint'ssim.actuator_indexentry, else its position injoints;-1when the map omits it, which_manifest_to_mjcf_affinerefuses naming the missing entry._manifest_to_mjcf_affine(robot, model, joint, leader) -> tuple[float, float](L2273) —(a, b)with the MJCF leader qpos= a + b·vfor manifest valuev: identity, orlo + (hi - lo)·voverctrl_rangefor awrite_mode: normalisedsim.grippers[]entry, whose actuator (_gripper_actuator) must exist and be a gear-1 joint transmission on the leader (ROSConfigErrorotherwise).fit_collision_geometry_from_mjcf(robot, *, manifest_dir=None, stroke_samples=9, tight_links=()) -> list[LinkCollisionGeometry](L2481) —fit_link_primitivesper manifest link over every geom of its MJCF body — collision and visual, meshes and primitives — in the body frame. An equality-coupled follower body (OpenArm's second finger) is folded into its leader's child link, swept overstroke_samplesleader positions, so the primitives hold the gripper at every opening. When the manifest declares a URDF, each mapped link is fitted to the union of its MJCF geometry and its URDF geometry (_urdf_link_meshes), so the primitives hold both the twin's mesh and the one ROS tools and Isaac draw. A static link (afixed_attachmentschild with no MJCF body) is fitted from the URDF via_static_link_mesheswith the same fitter andtight_linksrule. Pinned bytests/unit/test_collision_geometry_enclosure.py(twin meshes) andtests/unit/test_collision_geometry_urdf_enclosure.py(URDF meshes). A follower the manifest declares inmimic_jointsis not folded in: it is its own rigid link, fitted in its own body frame (#349). A body a mimic row owns is fitted only under that row's link (the Metal's logicalfinger_pairgets none). Fits every joint link, mimic follower andfixed_attachmentschild the MJCF maps a body to;_static_link_meshescovers the unmapped fixed children.LoweringSource—Literal["srdf", "sampling", "mjcf"]; the sourceselect_loweringresolves to (matchesLoweredCollisionModel.acm_source).
packages/openral_safety/openral_safety/static_geometry.py
Declared static geometry → base-frame surface points for the octomap bridge (#349, docs/reference/manipulation-workspace-contact.md §3.1).
load_static_geometry(path) -> tuple[StaticGeometry, Path](L34) — Load + validate aStaticGeometryYAML; returns it and its directory;ROSConfigErroron a missing / non-YAML / invalid file.surface_points(geometry, base_dir, spacing_m) -> NDArray(L76) — Every declared surface (box faces, mesh triangles) sampled at mostspacing_mapart,(N, 3)base frame; each surface point lies withinspacing_mof a sample.ROSConfigErroron spacing ≤ 0 or a missing/malformed mesh.write_points_file(points, path) -> None(L129) — The octomap bridge'sstatic_points_fileformat: onex y zper line,#header.
packages/openral_safety/openral_safety/tight_geometry.py
Derive a box's tight_geometry (26-DOP + exact hull) from the geometry it bounds; containment is definitional (mesh ⊆ hull ⊆ DOP ⊆ box). Moved here from tools/generate_tight_geometry.py so the collision lowering can refine links; the tool re-exports the moved names.
derive_tight_geometry(points, half_extents) -> dict[str, Any](L269) — The DOP slabs and the exact hull, refined toward the hull under theMAX_TIGHT_HULL_VERTICESbudget (refine_dop_to_budget) when it is over; a mapping forTightCollisionGeometryplus reviewer diagnostics.refine_dop_to_budget(points, dop_lo, dop_hi, budget) -> Points(L187) — A ≤budget-vertex envelope built only from tangent planes ofconv(points), starting from the DOP; refuses to emit one that cuts the points.hull_overhang_m(hull_points, mesh_points, mesh_faces, *, samples_per_edge=24) -> float(L106) — Sampled distance from the hull's facets to the real mesh surface (exact per sample, brute force, batched).hull_overhang_upper_bound_m(hull_points, mesh, *, samples_per_edge=24) -> float(L156) — The same measurement from above via a KD-tree over a fixed-seed surface sample, for CAD meshes too large for the brute-force query.tight_geometry_for_box(mesh, half_extents) -> TightCollisionGeometry(L309) — DOP + hull + padded overhang for a box-frame mesh, written at 1 nm (slabs rounded outward) so a re-lowering reproduces it byte for byte.round_up_m(value, precision_m=1e-6) -> float(L68) — Round a sampled distance up, never down.- module constant
HULL_OVERHANG_SAFETY_MARGIN: float = 1.2(L65) — pad on a sampled overhang;_OVERHANG_BATCH,_OVERHANG_MAX_SAMPLES,_SURFACE_SAMPLES,_SURFACE_SEED,_WRITE_DP— the query's memory bound, sample caps, seed and write precision.
packages/openral_safety/openral_safety/cumotion_config.py
Derive a cuRobo (cuMotion) robot-config from the lowered collision geometry. Pure module; uses kernel_predicates.bounding_capsule_segment. Deliberately over-covers the kernel's geometry — cuRobo can only express spheres, and a planner that believes the arm is thinner than it is emits trajectories the kernel then has to E-stop. Looser than the kernel is fine; tighter is not.
- module constant
_ACTUATED_JOINT_TYPES: frozenset[JointType](L50) —{REVOLUTE, PRISMATIC, CONTINUOUS}, joint typesactuated_joint_namescounts as single-DOF movable. class CuMotionSphere(L56) — Frozen dataclass:center(link-frame(x, y, z)),radius— one cuRobo collision sphere.capsule_to_spheres(p0, p1, radius, *, count) -> list[CuMotionSphere](L68) — Samplecountspheres evenly along the segmentp0→p1(endpoints inclusive forcount >= 2; midpoint forcount == 1).spheres_for_capsule(shape) -> int(L110) — Sphere count to tile a lowered primitive with centres ≤ one radius apart;1for a sphere / zero-length capsule. Also accepts aBoxShape.link_collision_spheres(geom, *, count=None) -> list[CuMotionSphere](L134) — Lower oneLinkCollisionGeometry(capsule, sphere, or box) to cuRobo spheres in its link frame, via the containing capsule.sphere_model_geometry(geoms) -> dict[str, list[LinkCollisionGeometry]](L156) — Each link's primitives as the capsules cuRobo's spheres actually cover (box → containing capsule; capsules/spheres unchanged) — a strictly larger solid than the kernel's box, so it needs its own ACM proof.actuated_joint_names(robot) -> list[str](L206) — Single-DOF movable joint names, in manifest order — the cuRobocspace.joint_names.- module constant
_SPHERE_DP: int = 6(L215) — decimal places sphere centers/radii are rounded to when rendered into the YAML fragment. render_cumotion_config(robot, model, *, urdf_path=None) -> str(L218) — Render a cuRoborobot_cfgYAML fragment with a generated-provenance header. Spheres come fromrobot.collision_geometry(falling back tomodel.collision_geometryonly when the manifest carries none). The ACM is not copied verbatim: givenurdf_pathit is widened with pairs proven always-colliding for the sphere model, so the planner stays looser than the kernel, never tighter. Withouturdf_paththe manifest ACM is used as-is and the header says so.
packages/openral_reasoner_ros/openral_reasoner_ros/reasoner_node.py
reasoner_node lifecycle wrapper. Thin rclpy shell around openral_reasoner.ReasonerCore.
build_spatial_memory(path, ingest, goals_json, *, now_ns=0) -> SpatialMemoryBuild(L813) — The reasoner node's spatial memory from a persisted scene graph (a load failure is a warning; declared goals are still seeded), live ingest, andnav_goals_json(ADR-0133, repeated names refused): the memory, whether detections are ingested (writable), andplaces_onlywhen the goals are its only source. An empty goal list is no source (no memory without a path or ingest).class SpatialMemoryBuild(L803) —build_spatial_memory's result:memory(orNone),writable,places_only,origin,warnings.- module constants
_FAILURE_SOURCES,_PERCEPTION_KINDS— closed sets:hal/sensor/rskill/safety/wam/criticandmotion/objects/ocr/scene_change. (L339) - module constant
_PERCEPTION_KINDS: tuple[str, ...](L348) —("motion", "objects", "ocr", "scene_change"). - module constant
_QOS_WORLD_STATE(L268) —KEEP_LAST=1, RELIABLE, VOLATILE, the/openral/world_state_slowsubscription QoS. - module constant
_QOS_FAILURE(L274) —KEEP_LAST=50, RELIABLE, VOLATILE, the six/openral/failure/*subscription QoS. - module constant
_QOS_PERCEPTION(L280) —KEEP_LAST=10, BEST_EFFORT, VOLATILE, the four perception-topic subscription QoS. - module constant
_QOS_PROMPT(L286) —KEEP_LAST=10, RELIABLE, VOLATILE, the/openral/promptpublisher/subscription QoS. - module constant
_QOS_MAP(L318) —KEEP_LAST=1, RELIABLE, TRANSIENT_LOCAL, the latched/mapsubscription QoS. - module constant
_QOS_COMPLETION_CAMERA(L329) —KEEP_LAST=1, BEST_EFFORT, VOLATILE, the VLM completion-camera subscription QoS. - module constants
_KIND_TIMEOUT,_KIND_CONTROLLER,_SEVERITY_WARN,_SEVERITY_FAIL— IDL-mirror constants foropenral_msgs/FailureTrigger, kept inline (not thefailure_bushelper) so the reasoner emits without pulling the rate-limiter into the dispatch path. (L374) - module constant
_KIND_CONTROLLER: int = 5(L375) - module constant
_SEVERITY_WARN: int = 1(L377) - module constant
_SEVERITY_FAIL: int = 2(L384) - module constant
_SKILL_FAILURE_KIND_NAMES: dict[int, str](L390) —{_KIND_TIMEOUT: "timeout", _KIND_CONTROLLER: "controller"}, kind-derived failure-state names for_emit_skill_failure_event. - module constants
_EXECUTE_SKILL_SERVER_PROBE_S,_LIFECYCLE_SERVER_PROBE_S— 100 mswait_for_server/wait_for_serviceprobes so an absent server/peer can't block the executor thread. (L401) - module constant
_LIFECYCLE_SERVER_PROBE_S: float = 0.1(L403) - module constant
_MISSION_VERIFY_WINDOW_S: float = 40.0(L357) — fallback verify window when the activeRewardContractsets noframe_window_s. - module constant
_DEFAULT_SUCCESS_THRESHOLD: float = 0.8(L366) — fallback reward-gatesuccess_thresholdwhen noRewardContractis loaded. - module constant
_DEFAULT_CHECK_FLOOR: float = 0.5(L367) — fallback reward-gatecheck_floorwhen noRewardContractis loaded. - module constant
_FAILURE_TIER_FOR_SOURCE: dict[str, str](L418) — trigger taxonomy mapping each/openral/failure/<source>to its tier:safety → "A",hal/sensor/rskill/wam/world_state → "B",critic → "C". Used to stampreasoner.tieron the OTel span; the preemption threshold itself is decided inline in_on_failure. - (the
hal_mode == "sim"gate imports the canonicalopenral_core.SIM_EXECUTABLE_CONTROL_MODES— trimmed to the six packer-implemented modes, see the Layer-0 core entry — rather than a module-local frozenset.) def _required_control_modes(manifest: RSkillManifest) -> set[ControlMode](L471) — Pure helper for the deploy-path palette gate. Readsaction_contractby specificity, fromNone(no constraint) down through representation/slots/legacydim.def _action_executable(manifest: RSkillManifest, description: RobotDescription, hal_mode: str) -> bool(L496) — Pure helper:Truewhen every_required_control_modes(manifest)is in the executable set forhal_mode(sim's fixed set, else the robot's declared modes). Empty required set →True.def _state_contract_verdict(manifest: RSkillManifest, n_joints: int, *, policy_state_published: bool) -> _StateContractVerdict(L534) — Pure helper for the palette's state-contract gate, mirroring the skill runner'sobs["state"]selection. Areads_world_state_policy_stateskill needs a/openral/policy_statepublisher whatever its layout ("no_policy_state"drops it; the runner reads and checks the vector every step even when an assembler then overwrites it) and itsdimis never compared with the joint count. A wrapped layout always needs a registered assembler ("assembler") unless policy state feeds it, else"no_assembler". Otherwise a declareddimmust equaln_joints("admit"/"dim_mismatch"; unsetdim= the joint vector). Issue #474.- type alias
_StateContractVerdict(L529) —Literalof the six verdicts above; the node's branch per verdict is checked by mypy. - module constants
_POLICY_STATE_TOPIC = "/openral/policy_state",_POLICY_STATE_WATCH_S: float = 1.0(L408) — the topic the gate counts publishers on, and the re-check period while a policy-state skill waits for one. ReasonerNode._arm_policy_state_watch()/_watch_for_policy_state()/_cancel_policy_state_watch()(L6180) — Armed by the palette seed while any capability-matched skill setsuse_world_state_policy_state(the HAL advertises/openral/policy_statelazily, destroys it on deactivate, and autostarts independently of the reasoner). Every_POLICY_STATE_WATCH_Sit compares the publisher's presence with what the last seed decided on (_policy_state_published_at_seed) and re-seeds via_maybe_seed_palette_from_search_pathswhen it appeared or disappeared, so a skill is admitted once the topic is live and dropped again when it goes. Cancelled onon_cleanupand whenever a seed matches no such skill.def _resets_search_episode(call) -> bool(L587) — Pure helper for the find→re-prompt cascade bound.Truewhen dispatchingcallends the active-search episode;Falsefor the three read-only search actions, so a search loop's own budget can never be reset by its own query and fail to terminate.def _camera_label(camera: str) -> str(L780) — How a tool-result re-prompt (locate_in_view,query_scene) names the camera:camera '<id>', or "the primary camera" for a blank id, never'default', which a model copies back as a literal camera id no multi-camera deployment serves.def _resolve_execute_prompt(call_prompt: str, active_text: str | None) -> str(L764) — Blank → the active mission task's text; used forExecuteRskillTool.promptand for a blankQueryTaskProgressTool.task(which the reward monitor would otherwise resolve to its launch-timetaskparameter)._on_query_task_progress_responsedrops a reply that lands after the active task instance changed: same mission object, same task id and text, as_on_mission_verify_responseand_on_vlm_completion_verdictnow also require (a re-sent identical goal builds a new mission whoset1matches by id and text).class ReasonerNode(LifecycleNode)(L875) — Lifecycle node wrappingReasonerCore. Optional injectedspatial_memoryenables the recall/resolve tools; otherwisespatial_memory_path/spatial_memory_ingestparams can load or build one.memory_md_pathenables the memory tools.hal_modeselects the action-mode palette gate;tick_hz(default 0.2 Hz) is the heartbeat rate. Withmanifest_runtime_json(the deploy's resolvedDeployRuntime),manifest_bridge_onandmanifest_unit_serialset by the launch, every palette seed (configure and/openral/skill_registry_changed) also builds the robot manifest (openral_core.build_robot_manifest, write-/remote-control flags from the env) and emits it to the dashboard (producer.emit_robot_manifest, ADR-0129). The robot's rSkill list (openral_core.allowed_rskills_from_env, read once at construction) is passed to every palette build (playbooks are not filtered: they are procedures, and the LLM can only call what the palette offers); at seed the node names listed rSkills that aren't installed (with the install command) or can't run, and logs an error when the list leaves no skill to dispatch.- Grasp/place target grounding (real pick-and-place design §2.2-2.3). Params
grasp_target_voxel_m(0.0 = unset: no standalone default — on a manifest with arole: gripperjoint an unset value failson_configurewithROSConfigError, once, instead of a per-callROSReasonerInvalidPlanthe LLM would burn its replanning ladder on, so no cell-specific fallback pads it; a gripperless manifest needs none;deploy_e2epasses_octomap_resolution(hal_mode), the resolution octomap_server gets) andgrasp_target_extrinsic_error_m(MAX_PLANAR_ERR_M, 0.015) — their sum pads a grounded seed box._load_grounding_context()loads the manifest at the start ofon_configure(a load failure warns and a named target is then refused; a gripper manifest without the voxel raisesROSConfigError→ configure FAILURE); no robot unit and no cell geometry are read._ground_targets(call) -> (grasp, place)runs in_dispatch_execute_rskillbefore any latch:openral_reasoner.groundingover the latest/openral/world_state_slowdetected_objects(bbox now on the wire) and the spatial-memory scene graph; aROSReasonerInvalidPlanis logged, recorded as afailedexecution with a disambiguation hint, and NO goal is sent._send_execute_rskill_goalfillsgrasp_declaration_valid/grasp_declarationandplace_declaration_valid/place_declarationfor the matching dispatch generation; the runner stamps, attributes and strips any region as before. Paramobject_tracking("off"; issue #418, the deploy'sDeployRuntime.object_tracking): not"off"→ both groundings run withobject_tracking=True(the grasp query hinted withopenral_core.hand_jointof the grounded contact links), and the goal's grasp declaration is encoded withquery_factory=openral_msgs/ObjectQuery. _submit_client_warmup(client) -> None— Aton_configure, kicks a managed LLM sidecar's boot onto_llm_poolinstead of leaving it to the first tick, off the executor thread so the lifecycle transition returns promptly. No-op for clients withoutwarm(); a failure here only warns, sinceselect_tool's lazy path still owns whether the server is usable.on_configure(self, state) -> TransitionCallbackReturn(L1432) — BuildToolUseClientfrom env if not injected, attach subscribers to world-state/failure/perception/prompt/registry topics, create the prompt/failure publishers +execute_rskillaction client. Readsvram_lifecycle_peers(GPU peers auto-deactivated around eachexecute_rskill) andvram_refused_rskill_ids(policies the deploy CLI's reward VRAM preflight refused at launch), loads the reward manifest, and probes GPU total VRAM for the pre-dispatch fit check.on_activate(self, state) -> TransitionCallbackReturn(L1881) — Arm the gate-only timer beat at thetick_hzROS parameter (declared with the constructor'stick_hzas default; ≤ 0 fails the transition).on_deactivate(self, state) -> TransitionCallbackReturn(L1894) — Cancel the tick timer (subscriptions remain attached).on_cleanup(self, state) -> TransitionCallbackReturn(L1916) — Tear down pending skill-goal deadline timers, destroy the action client and every cached per-topic emit_prompt publisher, drop cached lifecycle/service clients, clear the in-flight goal / cancel-reason / tick-trampoline state, and reap the LLM/VLM worker pools and inbox guard.on_shutdown(self, state) -> TransitionCallbackReturn(L2031) — Final shutdown.destroy_node(self) -> None(L2014) — Reaps thereasoner-llm/reasoner-vlmworker pools (no wait; an in-flight provider call is not interruptible) and detaches + destroys the executor-inbox guard condition beforeLifecycleNode.destroy_node, so a node destroyed without acleanup/shutdowntransition drops a late worker completion instead of triggering a destroyed guard (#381). Idempotent withon_cleanup._on_failure(source, msg)— Drop a trigger this node published itself (header.frame_id= node name); else append aFailureEventRecordto the renderer and preempt the next tick per the tier taxonomy: Tier A (safety) atseverity ≥ WARN, Tier B/C atseverity ≥ FAIL. When acriticFAIL is a reward wake and anexecute_rskillgoal is in flight, cancels that goal (latched reason"reward") instead of ticking — the reward signal stops the VLA now, not at thedeadline_sclock — and the canceled result re-enters mission verification._on_object_query(record)— A matchingworld_stateKIND_OBJECT_QUERYfailure records typed reason/workspace/observation evidence, cancels the active manipulation and waits for its terminal result, then forces recovery only while the task's persisted failed-dispatch count, this goal included, plus any earlier success whose reward verdict is still pending (_pending_success_verdicts, held from the query to its verdict), is belowDEFAULT_MAX_ATTEMPTS(judged successes spend none of it, #562). At the cap, the task remains blocked until a new operator goal, unless a failure the block predicted does not come true: a pending verdict that resolves without one (no score, a raising query, a VLM continuation a lifecycle transition dropped) or a canceled goal that comes back SUCCEEDED re-checks it (_reconcile_object_query_block) and lifts it below the cap. An escalation for a goal whose task a new goal replaced cancels it with no budget reflection (that verdict would reach the new goal's context). Delayed failures without the exact active action UUID are ignored. No prompt handoff or safety reset._on_execute_rskill_resultrecords the canceled attempt, counts it inTaskState.failures(_count_failure; the goal never reaches the reward gate), and only then allows the recovery tick; a goal that comes back SUCCEEDED because it finished before the cancel landed takes the success path instead and releases the recovery wait; the runner's grounding and contact gates remain authoritative._FAILURE_SOURCESincludesworld_state._on_tick(*, force=False, tier="heartbeat", trigger="heartbeat", coalesced=())— No-op while the node is not active (_is_active, set inon_activate, cleared first inon_deactivate/shutdown; prompts and failures arriving meanwhile are kept for the next activation). Every call site names itstrigger(prompt,tool_result:<source>,skill_result,skill_failure,failure:<source>,safety_latched,object_query,mission_advance,verdict,active_search,decompose). Single-flight trampoline over_start_tick: a tick requested mid-dispatch is coalesced (forcewins, every trigger kept ascoalesced) and replayed after, bounded by_MAX_TICK_REPLAYS=4._on_safety_status(msg)— Subscribes the latched/openral/safety_status(RELIABLE + TRANSIENT_LOCAL, read-only); feedsContextRenderer.set_safety_statuswith thedrop_reasonname (failure_bus.drop_reason_label) and receipt time. A new latch forces a Tier-Asafety_latchedtick unless a safety FailureTrigger forced one within_SAFETY_TICK_DEDUP_S(2 s: the same kernel stop)._on_execute_rskill_result(call, generation, goal_id, future, traceparent)— Result done callback: runs_handle_execute_rskill_result, then forces askill_resulttick unless that handling already forced one or issued a reward-verify query. A reward/patience cancel records a[stopped]line with the reason._on_execute_rskill_feedback(rskill_id, feedback_msg)— Feeds the in-flight line (set_inflight_feedback) and logs at ~1 Hz._note_outcome(tool, summary, *, ok, reflection=None, wake=True)— Records a non-skill tool outcome as a(<tool>)line in## EXECUTION(lifecycle transitions,reload_gst_pipeline, unanswerablequery_scene/query_task_progress, refuseddecompose_mission, what was said to the operator withwake=False)._handoff_to_operator(text)— Publishestexton/openral/promptunder the node's own frame_id (self-filtered) and notes it; used whenReasonerCore.llm_gave_upflips (once per failure run). Runs the blocking LLM call on a single-worker pool so the rclpy executor is never starved, then marshals dispatch back onto the executor. A round-trip landing after deactivate/cleanup is dropped by a generation check._tick_after_handler(*, tier, trigger)— Counts a tick request now and forces the tick through the executor inbox once the current callback returns, so its context includes everything that callback records. (L7325)_task_key(self) -> tuple[int, str | None]—(mission generation, active task id): what a plan was made for; captured when a tick's LLM call starts. (L7210)_discard_stale_plan(self, call, task_key) -> None—_finish_llm_tickdrops anexecute_rskill/decompose_missionwhose task ended while the call was in flight (a verdict completed or abandoned it, a new goal replaced it), logs it and records anot sentline in## EXECUTION. (L7216)- Mission lifecycle.
_on_promptseeds aMissionStatefrom the operator goal, gated byshould_rebuild_mission(cascades never rebuild; an in-progress mission needs explicitnew_goalmetadata)._dispatch_execute_rskillrefuses to send a goal once the active task has usedDEFAULT_MAX_TASK_DISPATCHESdispatches (routing it to the abandon path: subdivision offer, then hand-off), else records the attempt and the accepted goal handle a reward wake can cancel, withdeadline_sset to the resolved patience ceiling. On skill return,_maybe_verify_active_mission_task(call, *, traceparent, succeeded=False, dispatch_task_id=None, dispatch_mission_generation=None, dispatch_completes_task=None, judged_success=False, judged=False, budget_ended=False)drops a stale result (the goal's dispatch task/generation is no longer the active task: a new goal or a decompose replaced it while it ran); keeps a judged success only for a goal whose prompt is the task's (judged_prompt_is_task); for an aborted goal that ran out its budget unjudged with no reward monitor (asks_completion_after_budget) asks the model once and completes the task on yes, else settles it through_settle_task_without_verifier(which appliestask_step_without_verifier); then counts a failed result inTaskState.failures(_count_failure, once, reward monitor or not) and appliestask_step_without_verifier(acompletes_task_on_successskill's success completes the task, or only its step when the call'sfinal_stepis false; the dispatch bound, and with no reward monitor the failed-attempt cap, abandon it; the bound also abandons, through_bound_unjudged_dispatch→_apply_mission_verdict(subdivision offer first), when a configured reward monitor is off the graph and no verdict can come; a success nobody can verify marks the task so the next operator prompt rebuilds the mission), each logged asmission: <complete|abandon> task …; otherwise it issues a windowedquery_task_progressand_on_mission_verify_responseapplies the three-tier verdict (auto-pass / vlm_check / ladder), gated on the progress head; a success it scores not done counts one failure (_gate_ladder→_count_failure; a failed dispatch was counted on return), so the gate's ladder caps failed dispatches, neverfinal_step=Falsesteps it did not judge, and a task fed successes the gate scores not done still ends; a success it could not score (ok=False) is no verdict, counts nothing and meets the dispatch bound (_bound_unjudged_dispatch); an inconclusivevlm_checkfalls back into the retry ladder rather than retrying forever._emit_mission_completesummarizes a finished queue. - VLM completion adjudication.
completion_camera_topicparam (default""= disabled;deploy_e2epassescamera_topic(_primary_rgb_camera(...)), ADR-0108) subscribes and caches each frame as JPEG._adjudicate_completion(task_text) -> bool | Noneasks the tool-use client'sdescribe_image;None(no frame/client/provider error) degrades to the replanning ladder rather than a false verdict._complete_active_and_advanceis the shared advance path for both the native-complete and VLM-confirmed branches. - Task subdivision on replan.
_should_offer_subdivision(active, offered, max_depth) -> booldecides whether an abandoned task gets one decomposition offer, bounded by a one-offer-per-task set and the max depth, so a task that declines still terminates in human-handoff._dispatch_decompose_missionflat-splices finer children into a target task, or replaces the whole queue only when it hasn't started yet. No actuation. - Per-task locate budget.
_charge_task_locate_budget(call, *, traceparent) -> bool(top of_dispatch_locate_in_view) charges one locate cycle against the active task; onceDEFAULT_MAX_TASK_LOCATE_ATTEMPTSis exhausted without anexecute_rskilldispatch it abandons the subtask with a specific reason and forces a Tier-C tick, without dispatching the locate. Fixes a live locate-loop theSearchProgressmiss budget can't bound (that budget resets on a hit). A failed service call or nonemptyLocateInView.failure_reasonconsumes the same budget and re-prompts with visibility unknown and the cause; onlyfound=falsewith an empty reason is a completed no-match. Cleared on a new operator goal and on a realexecute_rskilldispatch. _on_skill_registry_changed(msg)— Palette refresh: walks installed rSkills, loads each manifest, rebuilds the palette against the active capabilities + commercial flag (preserving every availability flag, includingmemory_available), installs it viaset_palette._dispatch(call, *, traceparent=None)— Routing-only switch over theReasonerToolCallvariants; delegates to the per-tool_dispatch_*methods.WaitToolis a deliberate no-op;ReloadGstPipelineToolis a log-and-acknowledge stub pending its service IDL._dispatch_emit_prompt(call, *, traceparent)— Publish aPromptStampedoncall.target_topic(per-topic publisher cache;/openral/promptreuses the standing cascade publisher); stamps the threaded-throughtraceparentintometadata_json. A topic outsideEMIT_PROMPT_TOPICSis refused by_emit_prompt_publisher(ValueError) and the prompt is dropped with a warning, even for an unvalidated call._dispatch_spatial_query(call, *, traceparent)— Read-only: runs aRecallObjectTool/ResolvePlaceToolagainst the injectedSpatialMemoryand republishes the result as a cascade prompt. Bounded by aSearchProgress/SearchBudget; exhausting it abandons the active mission task so later heartbeats cannot restart a terminal search. Arecall_objectmiss escalates policy-driven to a livelocate_in_viewfor the same term when a detector is available and the term hasn't already been escalated this streak. With a latched/map, every approach viewpoint is refined through the occupancy grid before rendering (BLOCKED when none exists)._maybe_load_spatial_memory()— Deployment wiring: onon_configure, when no backend was injected andspatial_memory_pathis set, loads the persisted scene graph and flipsspatial_memory_available. Load failure degrades to a WARNING + no backend, never a fabricated map._maybe_load_memory()— Deployment wiring: onon_configure, whenmemory_md_pathis set, parsesMEMORY.md, renders the## MEMORYblock, loads the archive log, and flipsmemory_available. Read failure degrades to a WARNING + empty store._dispatch_memory_write(call, *, traceparent)— The reasoner's write-capable dispatch: applies theMemoryWriteToolop to the liveMemoryStore, archives any displaced entry, persistsMEMORY.md, re-renders## MEMORY, and re-prompts a short confirmation. Advisory — a persist failure logs, never raises._dispatch_memory_search(call, *, traceparent)— Read-only:MemoryStore.searchover the archive (superseded/deleted entries; current memory is already in## MEMORY), re-prompted with the hits. No actuation, no file write._emit_scene_objects_span()— Dashboard telemetry: when a spatial-memory backend is wired, publishes theworld.scene_objectsspan for the scene-objects card + SLAM-map overlay. Advisory only; failures swallowed at DEBUG.is_collective_target(text) -> bool— Imported fromopenral_core(single source of truth, shared with theGroundedSubtaskschema validator); true when a task text targets a set. Drives the execute grounding gate._emit_enumeration_invite(task, *, traceparent)— Grounding gate's self-prompt: tells the LLM the active task targets a collective set and todecompose_missioninto one concrete subtask per object before any actuation._dispatch_execute_rskill(call, *, traceparent)— Probes the action server; when it is not on the graph yet,_defer_until_execute_serverholds the busy latch and re-probes for up toexecute_server_wait_sbefore emitting aKIND_CONTROLLERFailureTrigger. Refuses a collective-target task without recording an attempt (grounding gate), and a second goal while one is in flight (busy gate, watchdog-bounded so a dead runner can't wedge the latch forever). A three-tier VRAM/reward-fit check (_refuse_unfittable_vla: the launch preflight'svram_refused_rskill_ids, the live free-VRAM probe, the static pair fit against total VRAM) refuses before dispatch rather than risking a slow CUDA OOM abort. The first tier holds when the probe is skipped (lifecycle peers configured) and the pair fits the total (#475). Routes GPU-peer eviction through_free_vram_peers_then_sendwhen configured._send_execute_rskill_goal(call, generation, traceparent)— BuildExecuteRskill.Goal, generate and send its UUID explicitly, and attach the generation-bound goal-response handler; that UUID is copied by the runner into declarations and returned in query-failure evidence._free_vram_peers_then_send(call, peers, generation, traceparent)— Deactivate each GPU lifecycle peer and send the goal only once every deactivation response returns, so a peer's VRAM is released before the runner loads the policy. Peers whose service is absent are skipped; a late deactivation from an invalidated generation is immediately reactivated instead of sending a stale goal._reactivate_vram_peers()— Reactivate the peers deactivated for the last dispatch (idempotent). Called on terminal result and on goal reject/error, not on a deadline (the policy may still be resident)._on_reactivate_result(peer, future)— Best-effort log of a reactivationchange_stateoutcome._change_state_async(node, transition) -> future | None— Shared helper: lazily cache aChangeStateclient per peer node and call it asynchronously;Noneif the service isn't on the graph or SROS2 refuses this enclave the client (ADR-0130: the reasoner may not cycle the kernel, HAL or E-stop producers; logged as a refusal, never raised). Used by both lifecycle dispatch and VRAM eviction._dispatch_lifecycle_transition(call)— Refuses (error log, no call) acall.nodeoutsideself._palette.node_ids; else drives<call.node>/change_statevia_change_state_async; on success attach_on_lifecycle_response, on an absent service log + skip.- module constant
_FEEDBACK_LOG_PERIOD_S: float = 1.0(L584) — WARNING-log throttle period for per-chunk action feedback. _on_execute_skill_feedback(rskill_id, feedback_msg)— Forward action feedback to the operator log, throttled to one WARNING per_FEEDBACK_LOG_PERIOD_S(a VLA goal streams one feedback per chunk); suppressed lines go to DEBUG._on_execute_skill_goal_response(call, generation, sent_at, future, traceparent)— Ignore/cancel stale generations; on rejection emit aFailureTrigger; on acceptance arm the deadline timer and attach the result handler._on_execute_skill_result(call, generation, goal_id, future, traceparent)— Ignore stale generations, cancel the deadline timer; log success or emit aFailureTriggerwithControllerEvidenceon abort/cancel/failure. The replanning ladder classifies on the typedfailure_kind, not the prose: a config/capability-mismatch result drops that rSkill from the palette until rebuilt; a deadline-miss drives a "timed out" reflection; controller/runtime failures remain retryable.- module constant
_LEGACY_FAILURE_REASON_PREFIXES: tuple[tuple[str, str], ...](L631) — deprecated-in-place prose→FAILURE_*prefix table, consulted only when a failed result carriesFAILURE_NONE(a pre-failure_kindproducer). _rskill_failure_kind(result) -> int— Typed failure kind for a terminal result; the runner-stamped uint8 is authoritative, falling back to the deprecated prose-prefix table only for a producer that predates the field._failure_kind_name(value) -> str | None— TheExecuteRskill.ResultFAILURE_*constant name for a uint8 (reverse of_failure_kind_value), passed toreflect_on_failurewith the result'sevidence_json._failure_kind_value(name) -> int— Resolve anExecuteRskill.ResultFAILURE_*constant by name off the generated IDL rather than re-declaring the values, so the reasoner cannot drift frompackages/msgs.- module constant
_PERMANENT_FAILURE_KIND_NAMES: frozenset[str](L651) —{"FAILURE_CONFIG_ERROR", "FAILURE_CAPABILITY_MISMATCH"}. - module constant
_TIMED_OUT_FAILURE_KIND_NAMES: frozenset[str](L663) —{"FAILURE_DEADLINE_MISSED"}. _palette_after_rskill_failure(palette, rskill_id, failure_kind) -> ToolPalette— Drop a skill after a typed, session-persistent availability failure, classified onfailure_kind(never on prose);FAILURE_NONEis "unclassified", never "permanently broken"._on_execute_skill_deadline(*, call, generation, sent_at, goal_handle, traceparent)— Ignore stale generations; latch a"patience"cancel reason (a patience-expired attempt still runs the reward verify gate), cancel the goal, and emit aKIND_TIMEOUTFailureTrigger.- Ladder persistence.
_persist_ladder_state()snapshotsReasonerLadderStateto theladder_state_pathparam after every ledger mutation;_maybe_restore_ladder_state()reloads it aton_configure, so a restart resumes the ladder and preserves an object-query-blocked task until a new operator goal. _on_lifecycle_response(call, future)— Log theChangeStateresult and note it in## EXECUTION; lifecycle failures surface in the target node's own logs (noFailureTriggerre-emission)._publish_skill_failure(*, kind, rskill_id, evidence, traceparent, trace_id=None, tick=True)— Build + publish aFailureTriggeron/openral/failure/rskill(frame_id = node name, so_on_failuredrops the echo), mirror it onto the OTLP span path via_emit_skill_failure_eventso the OTLP-only dashboard can tally it, and force a Tier-Bskill_failuretick after the calling handler returns (_tick_after_handler).tick=False(the patience deadline) leaves the tick to the cancel result, which carries the news._emit_skill_failure_event(*, kind, rskill_id, evidence)— Stamp anopenral.event.skill_failurespan event carrying the failure state, on the active tick span when recording or a transient span otherwise. Drives the dashboard "skill failures" counter.renderer(self) -> ContextRenderer(L7371) — Direct read access for tests asserting buffer state.dispatched_calls(self) -> tuple[Any, ...](L7376) — Snapshot of tool calls the reasoner has dispatched (in order).set_palette(self, palette) -> None(L7380) — Replace the active palette (rebuilt on/openral/skill_registry_changed)._QOS_REGISTRY_CHANGED(L295) — RELIABLE + TRANSIENT_LOCAL + KEEP_LAST=1 so a late-subscribing reasoner sees the most recent invalidation.main(args=None) -> int(L7385) — Entry point forros2 run openral_reasoner_ros reasoner_node.
packages/openral_prompt_router/openral_prompt_router/prompt_router_node.py
Single lifecycle node that fans in operator prompts from any external source into /openral/prompt. CLI is the only v1 adapter; WebSocket / voice / Slack are out of scope.
- module constant
DEFAULT_SOURCES: dict[str, int] = {"cli": 100, "dashboard": 100, "auto": 10}— Default source → priority registry; human sources get 100, machine cascades get 10. (L80) - module constant
_QOS_PROMPT(L60) —KEEP_LAST=10, RELIABLE, VOLATILE, the fan-out publisher / per-source subscriber QoS. - module constant
_STARTUP_PROMPT_SUBSCRIBER_TIMEOUT_S: float = 30.0(L71) — how longon_activatewaits for a subscriber before publishing the configured startup prompt anyway. class PromptRouterNode(LifecycleNode)(L87) — Lifecycle node.__init__(*, node_name="openral_prompt_router", sources=None)— Initialise with a source → priority registry. Defaults toDEFAULT_SOURCES.on_configure(self, state) -> TransitionCallbackReturn(L128) — Build the/openral/promptfan-out publisher and one/openral/prompt_in/<source>subscriber per allowed source.on_activate(self, state) -> TransitionCallbackReturn(L150) — Publish the startup prompt if configured; then idle (purely reactive)._reasoner_subscribed(self) -> bool(L244) — The startup prompt's release condition: theopenral_reasonernode's/openral/promptsubscription is in the graph AND this publisher has matched every discovered subscription (graph discovery precedes the endpoint match; a sample published in between is dropped under VOLATILE; #421 review). A subscriber with incompatible QoS never matches, so the wait then ends on its timeout.on_deactivate(self, state) -> TransitionCallbackReturn(L159) — Stop forwarding (subscriptions remain attached).on_cleanup(self, state) -> TransitionCallbackReturn(L165) — Drop the publisher; subscriptions auto-cleaned by rclpy._on_inbound(source, priority, msg)— Forward the inbound PromptStamped onto/openral/promptafter merging{"source": ..., "priority": ...}intometadata_json(preserving any per-source fields).forwarded_count(self) -> int(L263) — Number of prompts forwarded sinceon_configure(for tests).main(args=None) -> int(L268) — Entry point forros2 run openral_prompt_router prompt_router_node.
python/cli/src/openral_cli/prompt.py
openral prompt "do X" CLI adapter. Publishes a one-shot PromptStamped onto /openral/prompt_in/cli for the prompt-router to fan out. rclpy lazy-imported so openral --help stays sub-second.
prompt_command(text, topic="/openral/prompt_in/cli", wait_s=1.0, discovery_wait_s=5.0, new_goal=False, correlation_id=None, robot=None)(L40) —robotjoins that real deploy's ROS scope first (openral_cli._dds_scope.join_robot_scope_or_exit, #557). Initialise rclpy, publish one PromptStamped withmetadata_json={"source_cli": true}plus"new_goal": trueunder--new-goaland"correlation_id"under--correlation-id, wait briefly for the subscriber to be discovered, then shut down. Exits 2 if rclpy / openral_msgs are not importable (with a hint atjust ros2-build). The prompt-router preserves the mission-replacement flag when stampingsource/priority.
Observability (Layer 6 — fully shipped)
python/observability/src/openral_observability/_sdk.py
Idempotent OTel SDK setup + flush helper.
configure_observability(*, service_name="openral", endpoint=None, sample_ratio=None) -> bool— Install OTLP/gRPC tracer + meter + logger providers; readsOTEL_EXPORTER_OTLP_ENDPOINTwhenendpointis None;Trueif exporters were installed,Falsefor the no-op path. On success also starts the system-metrics collector and registersshutdown_observabilityviaatexit.sample_ratio(orOPENRAL_OTEL_SAMPLE_RATIO) selects the trace sampler:None/1.0→ always-on, else a parent-based ratio sampler. (L115)configure_worker_observability(service_name, *, endpoint=None, sample_ratio=None) -> bool— Cross-process bootstrap for a spawned worker: callsconfigure_observabilitythen attaches the parent trace context from env, so a child spawned withenv={**os.environ, **traceparent_env()}joins the parent trace. (L240)_resolve_sampler(sample_ratio) -> Sampler— Resolve the trace sampler from arg + env, defaulting to always-on; a garbage env value also falls back to always-on rather than silently dropping every span. (L353)shutdown_observability() -> None— Flush + shut down all three providers; idempotent and safe with no exporter installed. Stops the system-metrics collector before draining the meter so the final sample lands in the export batch. (L410)
python/observability/src/openral_observability/tracing.py
Span-context-manager helpers; safe to call before configure_observability.
rskill_span(name, *, rskill_id=None, role=None, **attrs)— Span for a Skill lifecycle phase; emitsrskill.id/rskill.rolefromsemconv. (L62)inference_span(name="skill.chunk_inference", *, chunk_index=None, kind: InferenceKind="foreground", **attrs)— Span for one VLA inference plus theopenral.inference.durationhistogram (emitted together so they cannot diverge).InferenceKind = Literal["foreground", "prefetch", "single"]is the closed timing-axis label set. (L92)safety_span(name="safety.check", *, check_name=None, severity="info", **attrs)— Span for a safety check; the C++ kernel parents its ownsafety.checkto the Python tick via the propagator. (L146)world_state_span(name, *, traceparent="", **attrs)(L180) — Span for one World State event, attributes prefixedworld_state.; a non-empty W3Ctraceparent(e.g. a declaration'strace_id, the runner'srskill.execute) parents it, so the event replays from the skill's trace. Used forworld_state.object_query.reasoner_span(name="reasoner.tick", *, tick_idx=None, model=None, force=None, **attrs)— Span for oneReasonerCore.tick. Setsreasoner.{tick.idx, model, force}and accepts any extrareasoner.*attribute via**attrs. (L214)start_reasoner_span(name="reasoner.tick", *, tick_idx=None, model=None, force=None, **attrs) -> Span— Non-attaching variant for the phased tick: returns a started span without attaching it, soprepare_tick→ off-threadrun_prepared_llm→finish_tickcan carry it between phases (each re-attaching viause_span) without an intermediate executor callback seeing it as current. Caller ownsspan.end(). (L285)- module constant
P(L53) —ParamSpec("P"), generic parameter type var fortraced's decorator signature. - module constant
R(L54) —TypeVar("R"), generic return type var fortraced's decorator signature. traced(name=None)— Decorator that wraps a sync function in a span named after it. (L313)
python/observability/src/openral_observability/cli.py
Root-span helper for the openral CLI.
cli_command_span(subcommand, *, mode=None, run_id=None, **attrs)— Open thecli.commandroot span for one CLI invocation; recordscli.subcommand,openral.run.id, optionalopenral.run.mode/openral.run.git_sha. (L51)
python/observability/src/openral_observability/diagnostics.py
diagnostic_msgs/DiagnosticArray heartbeat helper, shared by every OpenRAL lifecycle node.
Level— Mirror ofdiagnostic_msgs/DiagnosticStatuslevel constants (OK=0,WARN=1,ERROR=2,STALE=3); re-exported sostatus_fncallbacks can avoid importingdiagnostic_msgson pure-Python hosts. (L31)class DiagnosticsHeartbeat(L48) — 1 Hz/diagnosticspublisher attached to arclpy.lifecycle.LifecycleNode.__init__(node, *, hardware_id, component_name, status_fn, rate_hz=1.0). An exception insidestatus_fnis converted to a synthetic ERROR-level diagnostic so the timer never crashes the node.hardware_id(self) -> str(L112) — Return the configuredhardware_idfield.component_name(self) -> str(L117) — Return the configuredDiagnosticStatus.namevalue.create_publisher(self) -> None(L121) — Open the/diagnosticspublisher. Call fromon_configure.start(self) -> None(L138) — Start the 1 Hz publish timer. Call fromon_activate.stop(self) -> None(L155) — Cancel the publish timer. Call fromon_deactivate.destroy(self) -> None(L167) — Destroy the publisher. Call fromon_cleanup/on_shutdown.publish_once(self) -> None(L179) — Publish oneDiagnosticArrayimmediately.
python/observability/src/openral_observability/lifecycle.py
Make LifecycleNode transition-callback failures observable, and keep a node alive on an unavailable change_state transition — rclpy silently converts an uncaught callback exception to TransitionCallbackReturn.ERROR without logging, so a composing host sees only exit code 4.
log_lifecycle_errors(callback) -> callback— Decorator foron_configure/on_activate/… transition callbacks. Transparent on success; on an uncaught exception logs the callback name + traceback and returnsTransitionCallbackReturn.FAILUREinstead of letting rclpy swallow it silently. Applied toRskillRunnerNode,_WorldStateLifecycleNode,HALLifecycleNodeBase, andReasonerNode. Lazy-importsrclpyso the module stays import-safe on pure-Python hosts. (L52)refuse_unavailable_transitions(node) -> None— Guard aLifecycleNode'schange_stateservice: an id-only request (launch_rosChangeStateevents,ros2 service call) naming a transition the current state lacks (a repeateddeactivate) is logged and answeredsuccess: falsewith the state unchanged, instead of rclpy (Jazzy) raisingRCLErrorout of the executor and killing the node. Checked against the state machine's available transitions before rclpy runs, so labelled requests (rclpy refuses an unknown label itself), valid transitions and any other failure inside a transition are untouched. Called in__init__byReasonerNode,RskillRunnerNode,HALLifecycleNodeBase,_WorldStateLifecycleNode,ObjectTrackerNode,Propagator,SegmenterNode,RosImageObjectDetectorNode(detector + on-demand locators),PromptRouterNode,ComplianceRecorderNodeandSafetyPassthroughNode. The E-stop sources (deadman, hardware E-stop, human E-stop forwarder) use the dependency-free copyopenral_safety_watchdog.transition_guard.refuse_unavailable_transitions. (L117)
python/observability/src/openral_observability/semconv.py
Single source of truth for OpenRAL OTel attribute / span / metric names. Final[str] constants grouped by wire namespace exactly as the module's own # ── section banners divide them; each constant's value is its own description.
rskill.* — short-prefix span/metric attributes
- const RSKILL_ID: str = "rskill.id" (L33)
- const RSKILL_ROLE: str = "rskill.role" (L34)
- const RSKILL_TICK_MS: str = "rskill.tick_ms" (L36)
- const RSKILL_INFERENCE_MS: str = "rskill.inference_ms" (L37)
- const RSKILL_SENSORS_MS: str = "rskill.sensors_ms" (L38)
- const RSKILL_WORLD_STATE_MS: str = "rskill.world_state_ms" (L39)
- const RSKILL_SAFETY_MS: str = "rskill.safety_ms" (L40)
- const RSKILL_HAL_MS: str = "rskill.hal_ms" (L41)
- const RSKILL_ACTION_APPLIED: str = "rskill.action_applied" (L42)
- const RSKILL_SAFETY_VIOLATIONS: str = "rskill.safety_violations" (L43)
- const RSKILL_EPISODE_IDX: str = "rskill.episode_idx" (L44)
- const RSKILL_STEP_IDX: str = "rskill.step_idx" (L45)
- const RSKILL_REWARD: str = "rskill.reward" (L46)
- const RSKILL_TERMINATED: str = "rskill.terminated" (L47)
- const RSKILL_TRUNCATED: str = "rskill.truncated" (L48)
- const INFERENCE_KIND: str = "inference.kind" (L50)
- const INFERENCE_CHUNK_INDEX: str = "inference.chunk_index" (L51)
- const INFERENCE_CHUNK_SIZE: str = "inference.chunk_size" (L52)
- const INFERENCE_ENGINE: str = "inference.engine" (L53)
- const INFERENCE_DEVICE: str = "inference.device" (L54)
- const INFERENCE_DURATION_MS: str = "inference.duration_ms" (L55)
- const SAFETY_SEVERITY: str = "safety.severity" (L57)
- const SAFETY_CHECK_NAME: str = "safety.check_name" (L58)
- const SAFETY_KERNEL: str = "safety.kernel" (L59)
reward.* — task-progress reward monitor scores
- const REWARD_PROGRESS: str = "reward.progress" (L62)
- const REWARD_SUCCESS: str = "reward.success" (L63)
- const REWARD_STALLED: str = "reward.stalled" (L64)
- const REWARD_SUCCEEDED: str = "reward.succeeded" (L65)
- const REWARD_FRAMES: str = "reward.frames" (L66)
- const REWARD_TASK: str = "reward.task" (L67)
- const REWARD_CAMERA: str = "reward.camera" (L68)
openral.run.* — CLI invocation
- const RUN_ID: str = "openral.run.id" (L72)
- const RUN_MODE: str = "openral.run.mode" (L73)
- const RUN_GIT_SHA: str = "openral.run.git_sha" (L74)
openral.unit.* / org / site — which machine (resource attributes, issue #467)
- const UNIT_SERIAL: str = "openral.unit.serial" (L80)
- const ORG_ID: str = "openral.org.id" (L81)
- const SITE_ID: str = "openral.site.id" (L82)
openral.record.* — compliance records (OTLP log-record attributes)
- const RECORD_KIND: str = "openral.record.kind" (L87)
- const RECORD_ID: str = "openral.record.id" (L88)
- const RECORD_SCHEMA_VERSION: str = "openral.schema.version" (L89)
- const RECORD_RETENTION_CLASS: str = "openral.retention.class" (L90)
- const METRIC_FAILURE_COUNT: str = "openral.failure.count" (L368)
openral.tick.* — runner cadence
- const TICK_IDX: str = "openral.tick.idx" (L94)
- const TICK_RATE_HZ: str = "openral.tick.rate_hz" (L95)
- const TICK_DEADLINE_MS: str = "openral.tick.deadline_ms" (L96)
openral.rskill.* — rSkill identity (namespaced)
- const RSKILL_ID_NS: str = "openral.rskill.id" (L100)
- const RSKILL_REVISION_NS: str = "openral.rskill.revision" (L101)
- const RSKILL_ROLE_NS: str = "openral.rskill.role" (L102)
- const RSKILL_ACTION_HORIZON: str = "openral.rskill.action_horizon" (L103)
openral.hal.*
- const HAL_ADAPTER: str = "openral.hal.adapter" (L107)
- const HAL_ROBOT_MODEL: str = "openral.hal.robot.model" (L108)
- const HAL_CONTROL_MODE: str = "openral.hal.control_mode" (L109)
- const HAL_JOINT_NAMES: str = "openral.hal.joint.names" (L114)
- const HAL_JOINT_POSITIONS: str = "openral.hal.joint.positions" (L115)
- const HAL_JOINT_VELOCITIES: str = "openral.hal.joint.velocities" (L116)
- const HAL_JOINT_EFFORTS: str = "openral.hal.joint.efforts" (L117)
- const HAL_JOINT_POSITION_LIMITS_LO: str = "openral.hal.joint.position_limits_lo" (L118)
- const HAL_JOINT_POSITION_LIMITS_HI: str = "openral.hal.joint.position_limits_hi" (L119)
- const HAL_JOINT_VELOCITY_LIMITS: str = "openral.hal.joint.velocity_limits" (L120)
- const HAL_JOINT_EFFORT_LIMITS: str = "openral.hal.joint.effort_limits" (L121)
- const HAL_JOINT_STAMP_NS: str = "openral.hal.joint.stamp_ns" (L122)
- const HAL_ACTION_NEXT: str = "openral.hal.action.next" (L129)
- const HAL_ACTION_DIM: str = "openral.hal.action.dim" (L130)
- const HAL_ACTION_HORIZON: str = "openral.hal.action.horizon" (L131)
- const HAL_ACTION_APPLIED: str = "openral.hal.action.applied" (L132)
- const HAL_EE_NAMES: str = "openral.hal.ee.names" (L136)
- const HAL_EE_POSE_PREFIX: str = "openral.hal.ee.pose" (L137)
- const HAL_GRIPPER_POSITION: str = "openral.hal.gripper.position" (L138)
- const HAL_GRIPPER_FORCE_N: str = "openral.hal.gripper.force_n" (L139)
openral.sensors.*
- const SENSORS_MODALITY: str = "openral.sensors.modality" (L143)
- const SENSORS_SOURCE: str = "openral.sensors.source" (L144)
- const SENSORS_AGE_MS: str = "openral.sensors.age_ms" (L145)
- const SENSORS_WIDTH: str = "openral.sensors.width" (L146)
- const SENSORS_HEIGHT: str = "openral.sensors.height" (L147)
- const SENSORS_CHANNELS: str = "openral.sensors.channels" (L148)
- const SENSORS_ENCODING: str = "openral.sensors.encoding" (L149)
- const SENSORS_THUMBNAIL_JPEG_B64: str = "openral.sensors.thumbnail_jpeg_b64" (L154)
openral.system.* — host / GPU / CPU health
- const SYSTEM_GPU_INDEX: str = "openral.system.gpu.index" (L158)
- const SYSTEM_GPU_NAME: str = "openral.system.gpu.name" (L159)
openral.world_state.*
- const WORLD_STATE_STALENESS_MS: str = "openral.world_state.staleness_ms" (L163)
- const WORLD_STATE_COMPONENTS_STALE: str = "openral.world_state.components_stale" (L164)
- const WORLD_STATE_HAS_LATCHED_ERROR: str = "openral.world_state.has_latched_error" (L165)
- const WORLD_STATE_COMPONENT: str = "openral.world_state.component" (L166)
openral.world_state.scene_objects.* (durable spatial-memory scene-object graph)
- const WORLD_SCENE_OBJECTS_LIST: str = "openral.world_state.scene_objects.list" (L172)
- const WORLD_SCENE_OBJECTS_COUNT: str = "openral.world_state.scene_objects.count" (L173)
- const WORLD_SCENE_OBJECTS_FRAME: str = "openral.world_state.scene_objects.frame_id" (L174)
- const WORLD_SCENE_OBJECTS_SOURCE_NODE: str = "openral.world_state.scene_objects.source_node" (L175)
openral.dataset.*
- const DATASET_REPO_ID: str = "openral.dataset.repo_id" (L179)
- const DATASET_EPISODE_IDX: str = "openral.dataset.episode_idx" (L180)
- const DATASET_FRAME_IDX: str = "openral.dataset.frame_idx" (L181)
- const DATASET_EPISODE_SUCCESS: str = "openral.dataset.episode.success" (L185)
Span names
- const SPAN_CLI_COMMAND: str = "cli.command" (L189)
- const SPAN_RSKILL_TICK: str = "rskill.tick" (L190)
- const SPAN_RSKILL_CONFIGURE: str = "rskill.configure" (L191)
- const SPAN_RSKILL_ACTIVATE: str = "rskill.activate" (L192)
- const SPAN_RSKILL_EXECUTE: str = "rskill.execute" (L193)
- const SPAN_RSKILL_CHUNK_INFERENCE: str = "rskill.chunk_inference" (L194)
- const SPAN_HAL_READ_STATE: str = "hal.read_state" (L195)
- const SPAN_HAL_SEND_ACTION: str = "hal.send_action" (L196)
- const SPAN_SENSORS_READ_LATEST: str = "sensors.read_latest" (L197)
- const SPAN_WORLD_STATE_SNAPSHOT: str = "world_state.snapshot" (L198)
- const SPAN_WORLD_STATE_OBJECT_QUERY: str = "world_state.object_query" (L200) — Issue #418: one object-query escalation, parented on the goal's skill-execution trace.
- const SPAN_WORLD_SCENE_OBJECTS: str = "world.scene_objects" (L201)
- const SPAN_SAFETY_CHECK: str = "safety.check" (L202)
- const SPAN_REWARD_SCORE: str = "reward.score" (L203)
- const SPAN_REASONER_TICK: str = "reasoner.tick" (L205)
- const SPAN_DEPLOY_BRINGUP: str = "deploy.bringup" (L207)
- const BRINGUP_NODE: str = "openral.bringup.node" (L219)
- const BRINGUP_TRANSITION: str = "openral.bringup.transition" (L220)
- const BRINGUP_RESULT: str = "openral.bringup.result" (L221)
- const REASONER_MODEL: str = "reasoner.model" (L224)
- const REASONER_TICK_IDX: str = "reasoner.tick.idx" (L225)
- const REASONER_TOOL: str = "reasoner.tool" (L226)
- const REASONER_RSKILL_ID: str = "reasoner.rskill_id" (L227)
- const REASONER_SUPPRESSED_REASON: str = "reasoner.suppressed_reason" (L228)
- const REASONER_ERROR_KIND: str = "reasoner.error_kind" (L229)
- const REASONER_FORCE: str = "reasoner.force" (L230)
- const REASONER_LLM_S: str = "reasoner.llm_s" (L235)
- const REASONER_PROMPT_TOKENS: str = "reasoner.prompt_tokens" (L237)
- const REASONER_SERVED_MODEL: str = "reasoner.served_model" (L240) — the model the endpoint reported serving the tick's call (an OpenRouter ~…-latest alias resolves server-side); set from OpenAICompatibleToolUseClient.served_model.
- const REASONER_MISSION_JSON: str = "reasoner.mission_json" (L247)
- const REASONER_OFFERED_SKILLS: str = "reasoner.offered_skills" (L248) — skill ids offered on the tick when a skill-tool cap narrows the palette (#494); absent without a cap.
- const SKILL_FAILURE_STATE: str = "openral.event.skill_failure.state" (L255)
- const REASONER_TIER: str = "reasoner.tier" (L260)
- const REASONER_RATIONALE: str = "reasoner.rationale" (L261) — the selected call's rationale, capped at REASONER_RATIONALE_MAX; the dashboard folds it into topics.reasoner.detail.
- const REASONER_RATIONALE_MAX: int = 500 (L264)
- const REASONER_MESSAGE: str = "reasoner.message" (L265) — an emit_prompt call's prompt text, capped at REASONER_MESSAGE_MAX; the dashboard passes it as topics.reasoner.message so the console folds only identical prompts.
- const REASONER_MESSAGE_MAX: int = 300 (L268)
- const REASONER_AWAITING_OPERATOR: str = "reasoner.awaiting_operator" (L269) — True while the reasoner has said something to its operator (an emit_prompt on /openral/prompt, or a hand-off) that no operator prompt has answered yet (#660).
- const REASONER_OPERATOR_QUESTION: str = "reasoner.operator_question" (L272) — what it said, capped at REASONER_MESSAGE_MAX chars; same host gate as the rationale.
- const REASONER_INFLIGHT_SKILL: str = "reasoner.inflight_skill" (L274) — rskill_id in flight when the tick ran.
- const REASONER_INFLIGHT_STATE: str = "reasoner.inflight_state" (L276) — phase of that goal: "dispatching" (accepted / loading weights) or "running"; stamped by ReasonerCore on every tick, read by the dashboard's _reasoner_detail.
- const REASONER_TRIGGER: str = "reasoner.tick.trigger" — what started the tick (issue #620). (L283)
- const REASONER_COALESCED_TRIGGERS: str = "reasoner.tick.coalesced_triggers" — triggers merged into the tick while the previous one was in flight. (L285)
- const REASONER_SKIPPED_SINCE_LAST: str = "reasoner.tick.skipped_since_last" — timer beats suppressed since the previous LLM call. (L287)
- const REASONER_WAIT_UNTIL: str = "reasoner.wait.until" — the chosen wait's condition. (L289)
- const REASONER_WAIT_TIMEOUT_S: str = "reasoner.wait.timeout_s" — the chosen wait's bound. (L290)
- const SPAN_SIM_RUN: str = "sim.run" (L292)
- const SPAN_SIM_STEP: str = "sim.step" (L293)
- const SPAN_PHYSICS_STEP: str = "physics.step" (L294)
Span-event names
- const EVENT_ESTOP_REQUESTED: str = "openral.event.estop_requested" (L312)
- const EVENT_ROBOT_MANIFEST: str = "openral.robot.manifest" (L315) — event_name of the OTLP log record carrying the robot manifest (ADR-0129), emitted by producer.emit_robot_manifest.
- const EVENT_SENSOR_STALE: str = "openral.event.sensor_stale" (L316)
- const EVENT_STALENESS_LATCHED: str = "openral.event.staleness_latched" (L317)
- const EVENT_ERROR_LATCHED: str = "openral.event.error_latched" (L318)
- const EVENT_SAFETY_VIOLATION: str = "openral.event.safety_violation" (L319)
- const EVENT_ACTION_DROPPED: str = "openral.event.action_dropped" (L322)
- const EVENT_DEADLINE_MISSED: str = "openral.event.deadline_missed" (L323)
- const EVENT_SKILL_FAILURE: str = "openral.event.skill_failure" (L330)
- const EVENT_CHUNK_PREFETCH_HIT: str = "openral.event.chunk_prefetch_hit" (L334)
- const EVENT_CHUNK_PREFETCH_MISS: str = "openral.event.chunk_prefetch_miss" (L335)
- const EVENT_EPISODE_CLOSED: str = "openral.event.episode_closed" (L340)
Metric instrument names
- const METRIC_TICK_DURATION: str = "openral.tick.duration" (L344)
- const METRIC_INFERENCE_DURATION: str = "openral.inference.duration" (L345)
- const METRIC_TICK_BUDGET_VIOLATIONS: str = "openral.tick.budget_violations" (L346)
- const METRIC_TICK_DEADLINE_MISSES: str = "openral.tick.deadline_misses" (L347)
- const METRIC_SAFETY_VIOLATIONS: str = "openral.safety.violations" (L348)
- const METRIC_HAL_READ_STATE_DURATION: str = "openral.hal.read_state.duration" (L349)
- const METRIC_HAL_SEND_ACTION_DURATION: str = "openral.hal.send_action.duration" (L350)
- const METRIC_HAL_ESTOP_COUNT: str = "openral.hal.estop.count" (L351)
- const METRIC_SENSORS_AGE_MS: str = "openral.sensors.age_ms" (L352)
- const METRIC_SENSORS_STALE_READS: str = "openral.sensors.stale_reads" (L353)
- const METRIC_WORLD_STATE_STALENESS_MS: str = "openral.world_state.staleness_ms" (L354)
- const METRIC_WORLD_STATE_COMPONENTS_STALE: str = "openral.world_state.components_stale" (L355)
- const METRIC_OBSERVABILITY_EXPORT_FAILURES: str = "openral.observability.export_failures" (L356)
- const METRIC_SIM_EPISODE_COUNT: str = "openral.sim.episode.count" (L357)
- const METRIC_SYSTEM_GPU_MEMORY_USED_MB: str = "openral.system.gpu.memory_used_mb" (L361)
- const METRIC_SYSTEM_GPU_MEMORY_TOTAL_MB: str = "openral.system.gpu.memory_total_mb" (L362)
- const METRIC_SYSTEM_GPU_UTIL_PCT: str = "openral.system.gpu.utilization_pct" (L363)
- const METRIC_SYSTEM_CPU_UTIL_PCT: str = "openral.system.cpu.utilization_pct" (L364)
- const METRIC_SYSTEM_RAM_USED_MB: str = "openral.system.ram.used_mb" (L365)
- const METRIC_SYSTEM_RAM_TOTAL_MB: str = "openral.system.ram.total_mb" (L366)
- const METRIC_SIM_EPISODE_SUCCESS: str = "openral.sim.episode.success" (L367)
Closed-set label vocabularies (for metric labels)
- const LABEL_RSKILL_ID: str = "rskill.id" (L375)
- const LABEL_RSKILL_REVISION: str = "rskill.revision" (L376)
- const LABEL_HAL_ADAPTER: str = "hal.adapter" (L377)
- const LABEL_ROBOT_MODEL: str = "robot.model" (L378)
- const LABEL_CONTROL_MODE: str = "control_mode" (L379)
- const LABEL_ENGINE: str = "engine" (L380)
- const LABEL_DEVICE: str = "device" (L381)
- const LABEL_KIND: str = "kind" (L382)
- const LABEL_MODALITY: str = "modality" (L383)
- const LABEL_CHECK_NAME: str = "check_name" (L384)
- const LABEL_SEVERITY: str = "severity" (L385)
- const LABEL_SIGNAL_KIND: str = "signal_kind" (L386)
- const LABEL_COMPONENT: str = "component" (L387)
- const LABEL_REASON: str = "reason" (L388)
- const METRIC_THRESHOLD_MS: str = "openral.metric.threshold_ms" (L394)
- const METRIC_THRESHOLD_DIR: str = "openral.metric.threshold_dir" (L400)
- const THRESHOLD_DIR_UPPER: str = "upper" (L401)
- const THRESHOLD_DIR_LOWER: str = "lower" (L402)
Run-mode enum (closed set for openral.run.mode)
- const RUN_MODE_SIM: str = "sim" (L406)
- const RUN_MODE_HARDWARE: str = "hardware" (L407)
- const RUN_MODE_BENCHMARK: str = "benchmark" (L408)
Safety kernel enum (closed set for safety.kernel — see SAFETY_KERNEL)
- const SAFETY_KERNEL_NULL: str = "null" (L412)
- const SAFETY_KERNEL_CPP: str = "cpp" (L413)
python/observability/src/openral_observability/metrics.py
Cached OTel meter instruments — safe to call before configure_observability.
get_meter() -> Meter— Resolve the OpenRAL meter against the currentMeterProvider. (L65)get_tick_duration() -> Histogram—openral.tick.duration, unitms. (L100)get_inference_duration() -> Histogram—openral.inference.duration, unitms. (L115)get_hal_read_state_duration() -> Histogram—openral.hal.read_state.duration, unitms. (L127)get_hal_send_action_duration() -> Histogram—openral.hal.send_action.duration, unitms. (L139)get_sensors_age_ms() -> Histogram—openral.sensors.age_ms, unitms. (L151)get_world_state_staleness_ms() -> Histogram—openral.world_state.staleness_ms, unitms. (L163)get_tick_budget_violations() -> Counter—openral.tick.budget_violations. (L178)get_tick_deadline_misses() -> Counter—openral.tick.deadline_misses. (L189)get_safety_violations() -> Counter—openral.safety.violations, labelscheck_name/severity. (L200)get_failure_count() -> Counter—openral.failure.count{component, kind, severity}, one perFailureTriggerthe compliance recorder sees. (L214)get_hal_estop_count() -> Counter—openral.hal.estop.count. (L229)get_sensors_stale_reads() -> Counter—openral.sensors.stale_reads. (L250)get_sim_episode_count() -> Counter—openral.sim.episode.count; sim episodes that ran to completion (terminated or truncated). (L261)get_sim_episode_success() -> Counter—openral.sim.episode.success; sim episodes that hittask.success_keyat least once. (L272)get_observability_export_failures() -> Counter—openral.observability.export_failures, labelsignal_kind. (L283)get_world_state_components_stale() -> UpDownCounter—openral.world_state.components_stale. (L308)get_system_gpu_memory_used_mb() -> UpDownCounter—openral.system.gpu.memory_used_mb, unitMBy. (L322)get_system_gpu_memory_total_mb() -> UpDownCounter—openral.system.gpu.memory_total_mb, unitMBy. (L334)get_system_gpu_util_pct() -> UpDownCounter—openral.system.gpu.utilization_pct, unit%. (L346)get_system_cpu_util_pct() -> UpDownCounter—openral.system.cpu.utilization_pct, unit%. (L358)get_system_ram_used_mb() -> UpDownCounter—openral.system.ram.used_mb, unitMBy. (L370)get_system_ram_total_mb() -> UpDownCounter—openral.system.ram.total_mb, unitMBy. (L382)record_histogram_ms(instrument, value_ms, attributes=None) -> None— Record a millisecond value, skipping negatives andNaN. (L397)
python/observability/src/openral_observability/producer.py
Producer-side helpers for recording rich span attributes on OpenRAL hot-path spans. Safe to call on no-op spans; lists are truncated to _MAX_JOINTS / _MAX_EE_FRAMES and floats rounded to 3 decimals.
emit_robot_manifest(manifest: RobotManifest, *, logger_provider: LoggerProvider | None = None) -> None(L424) — Send the robot manifest as one OTLP log record (event_name = EVENT_ROBOT_MANIFEST, body its JSON with theschemaalias), which the dashboard caches forGET /api/manifest. A no-op without an OTLP endpoint.record_joint_state(span, *, names, positions, velocities=None, efforts=None, position_limits=None, velocity_limits=None, effort_limits=None, stamp_ns=None) -> None— Attach per-joint attributes to ahal.read_statespan. (L100)record_action(span, *, next_row, dim=None, horizon=None, applied=None, gripper_position=None, gripper_force_n=None) -> None— Attach commanded-action attributes to ahal.send_actionspan. (L148)record_ee_poses(span, ee_poses) -> None— Flatten aname → Pose6Dmapping onto aworld_state.snapshotspan. (L179)record_sensor_frame_attrs(span, *, modality=None, encoding=None, width=None, height=None, channels=None, age_ms=None, thumbnail_bytes=None, thumbnail_already_encoded_b64=False) -> None— Attach sensor-frame attributes to asensors.read_latestspan. (L205)emit_sensor_frame_span(frame, *, sensor_name, age_ms, flip_180=False, tracer_name=…) -> None— The shared producer of a dashboardsensors.read_latestspan for one camera frame: optional flip of a display-only copy (the policy's actual frame is never mutated), then span + attrs + thumbnail. Both frame emitters route through this one function so they can't drift apart. (L251)encode_frame_thumbnail— but the span is opened first and the function returns as soon asspan.is_recording()is false (no OTLP endpoint / dashboard off): the flip copy and the JPEG only feed the span, and at 30 Hz per camera they held ~25 % of the deploy runtime's GIL on an AGX Orin for nothing. The flip is passed toencode_frame_thumbnail; the span never copies a full-resolution flipped frame.encode_rgb_thumbnail(rgb) -> bytes | None— Encode an HWC uint8 RGB ndarray to a small JPEG for OTLP; returnsNoneif Pillow is unavailable. (L311)encode_frame_thumbnail(frame, *, flip_180=False) -> bytes | None— Encode anopenral_core.SensorFrame(RGB8/BGR8/MONO8/JPEG/PNG) as a small JPEG thumbnail; returnsNonefor non-renderable encodings. (L344) Raw frames are subsampled to the 320x240 box before any copy, and the optional 180° flip and BGR swap run on that small view: 0.6 ms per 1920x1200 frame on a Jetson AGX Thor instead of 8.2 ms, which at three cameras x 30 Hz had left a competing Python thread 34 % of its speed. JPEG input decodes in reduced-scale draft mode. Display-only (the dashboard tile); Foxglove reads the full-resolution ROS image topics.modality_for_encoding(encoding) -> str— Map aFrameEncodingto the dashboard's modality label (rgb/mono/depth/raw/unknown); shared byDeployRunnerand the world-state node so both produce identical labels. (L61)_MODALITY_BY_ENCODING: dict[str, str](L49) — Canonical encoding → modality lookup table.
python/observability/src/openral_observability/rclpy_spin.py
Quiet teardown for rclpy executor spin threads.
spin_executor_until_shutdown(executor) -> None(L20) —executor.spin()until a signal-driven shutdown, which ends it quietly:ExternalShutdownException,KeyboardInterruptand aRuntimeError(coversRCLError/InvalidHandle, and a subscription take racing the shutdown) raised after the context went down (the SIGINT handler invalidates it mid-spin) return normally instead of printing a thread traceback; aRuntimeErrorwith the context still up propagates. Thethreading.Threadtarget of the dashboard's e-stop / safety-status / perception-overlay executors and ofRos2ImageSensorReader's private node (the Isaacdeploy simteardown traceback inruntime_node). Third twin ofopenral_hal.lifecycle.spin_until_shutdownandopenral_rskill_ros.compose.spin_until_shutdown; kept in the lowest layer so the runner and dashboard share one copy.spin_node_until_shutdown(node) -> None(L45) —rclpy.spin(node)with the same quiet-teardown contract: spins the node on a privateSingleThreadedExecutorthroughspin_executor_until_shutdown; the caller still destroys the node and callsrclpy.try_shutdown(). Themain()spin ofsegmenter_node(the Isaacdeploy simteardown crash, a take racing the shutdown),reward_monitor_node,scene_vlm_node,depth_provider_nodeandcritic_producer_node.
python/observability/src/openral_observability/system_metrics.py
Background sampler for the openral.system.* gauges; feeds the dashboard's System Health card via psutil (CPU + RAM) and optional pynvml (GPU memory + util).
start_system_metrics_collector(*, interval_s=1.0) -> bool— Start a daemon thread that samples host metrics everyinterval_sseconds. ReturnsFalseand a quiet no-op when neitherpsutilnorpynvmlis importable. Idempotent; re-starts retune the interval. (L46)stop_system_metrics_collector(*, timeout_s=2.0) -> None— Signal the collector thread to stop and join. Safe to call when not running. (L76)_nvml_query(read, what, gpu_index) -> Any | None— Run one NVML read, returningNonewhen the device does not implement it. Each GPU metric is queried independently, so an unsupported call (e.g. no discrete VRAM pool on a unified-memory SoC) cannot also drop the other metrics. Logged once per (device, query). (L146)
python/observability/src/openral_observability/propagation.py
W3C TraceContext inject / extract for cross-process trace correlation.
current_traceparent() -> str | None— W3Ctraceparentvalue for the active span, orNoneoutside a span. (L54)current_trace_id() -> str | None— The 32-hex trace id of the active span, orNoneoutside a span (including no-op observability mode). The id half ofcurrent_traceparent, for the fields that store a bare pointer into the trace tree —RunResult.trace_id,RSkillEvalResult.trace_id. (L69)inject_traceparent(carrier=None) -> dict[str, str]— Write the active span'straceparent(and optionaltracestate) into a carrier dict; used by producers ofActionChunk.msg/ExecuteRskill.action/FailureTrigger.msg. (L87)extract_traceparent(traceparent, tracestate=None) -> Context— Parse a wire-sidetraceparentinto an OTelContextforcontext.attach/trace.use_span; consumed by the C++ safety kernel and any Python ROS consumer. (L117)traceparent_env(carrier=None) -> dict[str, str]— Env-var carrier (OTEL_TRACEPARENT+ optionalOTEL_TRACESTATE) for the active span, built frominject_traceparent; pass asenv=tosubprocess/multiprocessingso a worker joins the parent trace.{}when no valid span is in scope. (L153)attach_traceparent_from_env(env=None) -> object | None— Worker-side counterpart: readOTEL_TRACEPARENT/OTEL_TRACESTATEfromenv(defaultos.environ) andcontext.attachthe parent context; returns the detach token, orNonewhen absent/empty. (L195)remote_parent_from_env(env=None)[@contextmanager] — Scopeattach_traceparent_from_envfor a workermain(): attaches on enter, detaches on exit; yields the detach token (orNonewhen no carrier present). (L238)
python/observability/src/openral_observability/compliance.py
Compliance records out as OTLP log records (issue #467).
const CLOCK_SOURCE_ENV: str = "OPENRAL_CLOCK_SOURCE"(L54) — how the host clock is disciplined; defaultmonotonic_unsynced.class ComplianceEmitter(L85) — Stamps theComplianceRecordenvelope (uuid4record_id, a freshstream_idper emitter with a gap-freeseq,ts_ns,clock_source, the active span's ids) and sends one OTLP log record per record: JSON body,openral.record.*attributes, record trace context.logger_provider=overrides the global provider;log=(aComplianceLog) also writes each record to the on-robot log before it goes out (#469);on_log_error=(record, error)is called when that write fails (elseemitraises). Thread-safe.emit(kind, **fields) -> record(L120) — Build, log, send and return one record; a wiretrace_idis parsed (trace_ids_from_wire) and a malformed one dropped with a warning; aFailureRecordalso countsopenral.failure.count. A failed on-robot log write raisesROSRuntimeErrorafter the record was still sent (itsseqis spent, soverifyshows the gap).send_record(logger, record) -> None(L190) — One record as one OTLP log record (JSON body,openral.record.*attributes, trace context);emitandcompliance_log.shipuse it.software_inventory() -> list[SoftwareComponent](L242) — MR Annex III §1.1.9 identification: everyopenral*distribution, plus, with a ROS overlay sourced,openral_safety_kernel(binary SHA-256) andopenral_safety(sources digest) markedsafety_relevant; missing software is left out. The recorder records it on every activate.images_may_leave_host(endpoint=None) -> bool(L309) — Camera thumbnails go only to the deployer's own network (loopback / private / link-local address, or a dotless host such asotelcol) unlessOPENRAL_TELEMETRY_IMAGE_CONSENT=1; default endpoint is the oneconfigure_observabilityinstalled; withholding logstelemetry.images_withheldonce per endpoint. Checked before the JPEG encode inemit_sensor_frame_spanandDeployRunner, and again inrecord_sensor_frame_attrs.free_text_may_leave_host(endpoint=None) -> bool(L337) — The same rule for model free text (a reasoner tick's rationale, which can paraphrase the operator's prompt and name a person), with its own consentOPENRAL_TELEMETRY_TEXT_CONSENT=1; withholding is logged once per endpoint.ReasonerCorestampsreasoner.rationaleonly when it returns True.
python/observability/src/openral_observability/compliance_log.py
The on-robot compliance log: append-only, hash-chained JSONL per writer and retention class (issue #469). <root>/<writer>/<class>/<YYYY-MM-DD>.jsonl, each line {"prev_hash", "record"}.
const COMPLIANCE_DIR_ENV: str = "OPENRAL_COMPLIANCE_DIR"(L66) — set → the log is on; the deploy launch always sets it on real hardware.const GENESIS: str(L69) —"0" * 64, theprev_hashof a writer-class's first line.const RAW_TELEMETRY_DAYS: int = 90(L72) — default keep fortelemetry_raw, which has no floor.default_compliance_dir() -> Path(L88) —$OPENRAL_COMPLIANCE_DIR, else$XDG_STATE_HOME/openral/compliance.class ComplianceLog(L117) — One process's writer (writer=recorder/runtime/cli), so two processes never fork a chain; opening quarantines a torn tail to<segment>.quarantine.append(record) -> None(L173) — OneO_APPENDwrite, fsync'd for the safety / trace / incident classes;OSErrorpropagates.from_env(*, writer) -> ComplianceLog | None[@classmethod] (L149) — The log at$OPENRAL_COMPLIANCE_DIR,Nonewhen unset.records(root, cls) -> Iterator[ComplianceRecord](L213) — Every record of a class, all writers.verify(root, *, partial=False) -> list[str](L222) —partial(anexportof some classes or days) skips first links andseqgaps. Brokenprev_hashlinks, non-record lines, quarantined tails, and (unless retention pruned something)seqgaps perstream_id.hold(root, *, on) -> None(L273) — Legal hold on the whole log (AI Act Art. 73(6));prunablereturns nothing while held.prunable(root, today, keep_days=None) -> list[Path](L283) — Segments pastmax(RETENTION_FLOOR_DAYS, keep_days); a floor never shrinks.delete(segments) -> None(L303) — Deletes and marks the classprunedforverify; the CLI records each as aretention_deleteintervention.export(root, out, *, classes, since) -> int(L315) — Whole segments to a.tar.gzthe recipient canverify.ship(root, exporter, *, resource_attributes) -> int(L337) — Sends unshipped records, one acknowledged export each, resuming fromship.state; stops at the first refusal.
python/observability/src/openral_observability/failure_bus.py
Publisher helper + IDL-mirror constants for the namespaced /openral/failure/{...} bus.
class FailureSource(str, Enum)(L119) —HAL | SENSOR | SKILL | SAFETY | WAM | CRITIC | WORLD_STATE; the string value is the topic suffix (WORLD_STATE: issue #418, the object tracker's query escalations on/openral/failure/world_state).topic_for(source: FailureSource) -> str(L185) — Pure helper:FailureSource → /openral/failure/<suffix>.drop_reason_label(code: int, status_cls: Any, prefixes: tuple[str, ...] = ("KIND_", "DROP_")) -> str— Name aSafetyStatus.drop_reasonby reverse-mapping it against the generated message class's ownKIND_*/DROP_*constants (lower-cased; when unknown,drop_reason_<code>for the default prefixes, else the first prefix plus the code, e.g.severity_<code>);prefixesalso names aFailureTriggerkind/severity. The one implementation the dashboard, the skill runner and the reasoner share. (L138)KIND_*/SEVERITY_*intmodule constants (L105–L121) — Mirroropenral_msgs/msg/FailureTrigger(incl.KIND_COLLISION = 10, stamped by the safety kernel on every collision stop); bump both when the IDL changes. A test pins the two sides name-for-name and value-for-value against the generated constants.KIND_TIMEOUT: int = 0(L96)KIND_FORCE: int = 1(L97)KIND_WORKSPACE: int = 2(L98)KIND_PERCEPTION: int = 3(L99)KIND_CRITIC: int = 4(L100)KIND_CONTROLLER: int = 5(L101)KIND_SELFVERIFY: int = 6(L102)KIND_HUMAN: int = 7(L103)KIND_WAM: int = 8(L104)KIND_REASONER_TIMEOUT: int = 9(L105)KIND_COLLISION: int = 10(L106)KIND_OBJECT_QUERY: int = 11(L107) — Issue #418:ObjectQueryEvidence; bus-only (not inSafetyStatus).KIND_GRASP_OUTCOME: int = 12(L108) — Issue #353:GraspOutcomeEvidencefrom the HAL vision attachment bridge on/openral/failure/hal; bus-only (not inSafetyStatus).KIND_SUPPRESSED_SUMMARY: int = 254(L109)SEVERITY_INFO: int = 0(L111)SEVERITY_WARN: int = 1(L112)SEVERITY_FAIL: int = 2(L113)SEVERITY_ABORT: int = 3(L114)TOPIC_PREFIX: str = "/openral/failure"(L116)DEFAULT_RATE_LIMIT_HZ: dict[int, float | None](L203) — Per-severity defaults (INFO/WARN → 10/s, FAIL/ABORT → unlimited).DEFAULT_SUMMARY_PERIOD_S: float = 1.0(L210)class _TokenBucket(L213) — Private, lock-protected.__init__(rate_hz, *, capacity=1.0, clock=time.monotonic);try_consume() -> bool.class FailureBusPublisher(L262) —__init__(node, source, *, rate_limit_hz=None, summary_period_s=1.0, clock=None). Configure the publisher; does not open the ROS publisher.topic(self) -> str(L325) — The full topic this publisher writes to.source(self) -> FailureSource(L330) — The source layer this publisher represents.create_publisher(self) -> None(L334) — Open the ROS 2 publisher with the bus QoS profile.start(self) -> None(L356) — Start the 1 HzKIND_SUPPRESSED_SUMMARYroll-up timer.stop(self) -> None(L369) — Cancel the suppressed-summary timer (on_deactivate).destroy(self) -> None(L375) — Tear down the publisher + timer (on_cleanup).publish(self, *, kind, severity, evidence, rskill_id='', trace_id=None) -> bool(L386) — Emit oneFailureTrigger, subject to rate-limiting (Falsewhen rate-limited).
python/observability/src/openral_observability/logging.py
trace_context_processor(_logger, _method_name, event_dict)— structlog processor that stampstrace_id/span_idon every log event. (L60)resolve_log_level() -> int(L76) — Resolve the OpenRAL log floor fromOPENRAL_LOG_LEVEL(name or int); defaults toINFO, notDEBUG; an unparseable value falls back to the default rather than raising. Below the floor the stdlib check short-circuits before rendering/shipping, which matters since several DEBUG call sites fire per control tick. Governs log records only — dashboard span rows are banded separately bydashboard.store._is_headline_span.apply_structlog_level_floor()— Configure structlog's stock renderer to drop events belowresolve_log_level(); called byconfigure_observabilityon its no-endpoint path, where the stock config otherwise printed every DEBUG event (a deploy runtime emits one per 750 Hz joint state and per camera frame — ~10 % of the process's GIL on an AGX Orin). (L104)install_structlog_bridge(logger_provider)— Wire the structlog processor chain to forward records to the OTelLoggerProvider, with both the bridge logger and theopenralroot logger set toresolve_log_level(). (L138) Every structlog logger is a child of the bridge logger (_bridge_child), so a package module logger outside theopenralnamespace (e.g.openral_world_state.object_tracker.tracker) honoursOPENRAL_LOG_LEVELand is exported and printed (a stdoutConsoleRendererhandler on the bridge logger); before #418 r4 such loggers fell to the root logger and lost every INFO/DEBUG event whenever an OTLP endpoint was set.
python/observability/src/openral_observability/dashboard/store.py
In-memory aggregator for openral dashboard — feeds the SSE stream and the /api/state JSON endpoint. Thread-safe, bounded (200 events, 600 metric samples per series). Registered headline span families each populate one card slot in self._topics.
Event-log severity band (distinct from the headline-card routing above). _is_headline_span(name) bands a span's Event Log row: ERROR status → error; a small allow-list of names/prefixes (cli.command, rskill.execute/configure/activate, reasoner.tick, world.scene_objects, sim.run, detect.probe.*) → info; everything else → debug. Deliberately an allow-list rather than a deny-list, so a new high-rate span stays quiet in the event log until promoted here instead of flooding it by default; every span is still indexed in full for openral replay.
class TelemetryEvent— Frozen dataclass holding one event log row (ts_unix,kind,title,attrs,severity). (L243)to_json(self) -> dict[str, Any](L269) — Return a plain-dict view suitable for JSON serialization.class TelemetryStore— Read-side aggregator over OTLP signals. (L395)ingest_spans(payload: list[ResourceSpans]) -> int— Decode + record spans; populates headline cards, increments span-event counters, publishes a delta to every subscriber queue. Returns the number of spans recorded. (L504)ingest_metrics(payload: list[ResourceMetrics]) -> int— Decode + record metric data points; appends per-series samples and tracks cumulative sums. Keeps at most_METRIC_SERIES_MAX(512)(name, labels)series, evicting the least recently updated (labels are sender-chosen). (L538)ingest_logs(self, payload) -> int(L559) — Decode + record OTLPResourceLogs(the structlog→OTel bridge) as event-log rows: body → title, logger name → kind, severity number → level. Shares the bounded event ring with spans; the UI defaults the Debug chip off. Returns the number of log records recorded.snapshot() -> dict[str, Any]— One-shot view: service identity, headline cards, event ring, counters, metric series with p50/p95. (L612)subscribe() -> asyncio.Queue— Register an SSE subscriber. The queue is bounded; on overflow the oldest payload is dropped so the producer never blocks. (L986)unsubscribe(queue) -> None— Drop a subscriber's queue. (L1002)set_estopped(self, value) -> None(L643) — Force the e-stop latch flag from an authoritative operator action.set_skill_result(self, result) -> None(L630) — Record the latest dashboard skill action ({goal_id, skill_id, state, success, failure_reason, trace_id, ts_unix},staterunningthenfinished) undertopics.skill_result, also served in/api/mission, and push it to subscribers at once (#662).set_manifest(self, manifest: RobotManifest) -> None(L622) — Serve a manifest from a file (run_dashboard(manifest_path=...), the deploy launch's--manifest) until a fresheropenral.robot.manifestrecord arrives; bumpsmanifest_revand pushes to SSE subscribers.manifest(self) -> RobotManifest | None(L617) — The latest robot manifest (ADR-0129), cached from itsopenral.robot.manifestlog record byingest_logs(a malformed one keeps the last good one; the record is not an event-log row).snapshot()carriesmanifest_rev, bumped on every new manifest so the UI knows to refetchGET /api/manifest.set_hal_estop(name, estopped) -> None— Record one HAL's own e-stop latch (its/diagnosticsheartbeat) undertopics.hal_estop[name]with its receive time; the UI treats the robot as stopped while the kernel or any fresh HAL latch is set. (L661)set_safety_status(*, latched, drop_reason, drop_reason_label, detail, rskill_id, trace_id, stamp_unix) -> None— Record oneSafetyStatusfrom the latched/openral/safety_statustopic and push it to SSE subscribers. A latch setstopics.safety.estopped; only a latched → released transition clears it, so a publisher that never latches cannot undo an operator E-STOP. The only authoritative safety state the dashboard has, distinct from the span-inferred latch which stops updating the moment a kernel actually latches.stamp_unixis load-bearing: it lets the card tell a live latch from a dead publisher's leftover durable value. (L676)set_world_pose(self, x, y, yaw) -> None(L761) — Record where this robot's map sits in its scene's sharedworld(topics.world_pose,{x, y, yaw, frame: "world"}), served as/api/mission'sworld_pose; set byrun_dashboard(world_pose=...)for a robot of a scene with several robots (openral-pro#99).record_safety_failure(*, kind_label, severity_label, evidence_json, rskill_id, trace_id, stamp_unix) -> bool— Record one safety-kernelFailureTriggerfrom/openral/failure/safetyastopics.safety_failure(kind, severity, rskill_id, trace_id, stamps,repeats, and a one-linetextbuilt from the decodedFailureEvidence: link vs object, penetration in mm — "distance not evaluated" for the kernel's NaN sentinel, "≤ … (box bound)" for a box-bound depth — the voxel cell relative to the robot base, the active allowances (workspace fromworkspace_declaration_live), the stopped skill) plus a protectedsafety.failureevent-log row. It does not claim a latch (thesafety_statusslot does). A stop repeating the last one's kind, severity and skill within 5 s of its last repeat only bumpsrepeats(no row, no fan-out) and returnsFalse. The console trace renders it as an error row. Each row also keepsdetail(_stop_detail:{kind, link, other, depth_m}); a latch takes the detail of a stop within 2 s of its start, either side (safety_status.latch_detail, frozen for the latch, cleared on release). (L784)list_traces(self) -> list[dict[str, Any]](L1194) — Return one record per indexed trace_id, most-recent first.lookup_trace(self, trace_id) -> list[dict[str, Any]] | None(L1212) — Return every indexed span fortrace_idin chronological order, orNone.-
_reasoner_detail(attrs) -> str | None(L1905) — The console trace row's one-line why for areasoner.tickspan (alsotopics.reasoner.detail):<skill> <running|dispatching> · <tier> · <llm latency> · suppressed: <reason> · error: <kind> — <rationale>, each part only when present,Nonewhen empty. A suppressed (palette_empty,retry_cap) or errored tick says so, so a retry-capped call's rationale never reads as the call that ran. The rationale is present only when the reasoner was allowed to export it (free_text_may_leave_host). -
TelemetryStore.set_perception_detections(self, *, camera, detections, model_id, frame_width, frame_height, stamp_unix, flip_180=False) -> None(L882) — Record one detector result as a camera overlay and push it to SSE subscribers; each box dict carrieslabel,confidence,bbox_xyxy,det_idandcontour([[x, y], …]in the bbox's pixel frame, orNone).camerais the wiresensor_id, the join key between a frame and its boxes;frame_width/frame_heightlet the tile scale boxes onto its aspect-preserving thumbnail. An emptydetectionslist is recorded, not dropped, so "found nothing" is expressible rather than leaving a stale overlay painted. TelemetryStore.set_perception_masks(self, *, camera, masks, rskill_id, stamp_unix, flip_180=False) -> None(L941) — Record one segmenter result as a camera overlay: plural full-frame masks in the producer's area-ascending order, with advisory scores carried for display only (never used to rank or filter). Fed from the segmenter node's diagnostic re-publication of its one-shot service reply, off by default. Display only — nothing in the safety or attachment path reads this topic.
python/observability/src/openral_observability/dashboard/perception_overlay_subscriber.py
Detector boxes + segmenter masks drawn over the camera tiles. Same shape as safety_status_subscriber.py — one node created at launch, spun on a daemon thread, inert-but-harmless without rclpy / the openral_msgs overlay. Read-only and advisory: it decides what an operator sees, never what the robot does.
- module constant
PERCEPTION_OBJECTS_TOPIC: str = "/openral/perception/objects"— the detector node'soutput_topicdefault. (L50) - module constant
PERCEPTION_MASKS_TOPIC: str = "/openral/perception/masks"(L51) - module constant
PERCEPTION_MASKS_TOPIC: str = "/openral/perception/masks"— the segmenter node'sdebug_masks_topicdefault; a diagnostic re-publication of its latest reply, off by default there, so subscribing costs nothing when nobody enabled it. dashboard_flip_180() -> bool— Whether this host rotates the dashboard's display copy of camera frames, parsingOPENRAL_DASHBOARD_FLIP_180with the same truthy set as the sensor leg and the world-state node. Stamped onto each overlay so the renderer applies exactly the flip the image got. (L66)mono8_mask_to_png_b64(data: bytes, width: int, height: int) -> str— Encode one mono8 mask as a base64 LA PNG whose alpha channel is the mask, so the frontend tints it with one composite instead of decoding pixels in JS. RaisesValueErrorwhendatais not exactlywidth * heightbytes. (L95)class PerceptionOverlaySubscriber(L143) — Opens the node + subscription immediately, at the detector's sensor-class QoS (BEST_EFFORT + VOLATILE + KEEP_LAST=5) — a RELIABLE subscriber would never match and the overlay would sit silently blank.available(self) -> bool(L221) — True when the subscription is live (rclpy +openral_msgspresent).masks_available(self) -> bool(L226) — True when the mask subscription is live (needsSegmentMasksbuilt).close(self) -> None(L315) — Tear down the node/executor and shut rclpy down only if it started it._on_objectsand_on_maskseach drop a malformed payload with a logged decode-failure rather than letting an exception kill the spin thread and end overlays for the session. The mask leg is optional (its ownImportErrorguard) so an olderopenral_msgsbuild withoutSegmentMaskskeeps drawing boxes;masks_availablereports it separately fromavailable. Wired inrun_dashboardontoapp.state.perception_overlay.
python/observability/src/openral_observability/dashboard/estop_publisher.py
Persistent ROS 2 e-stop publisher for the dashboard (safety-critical) — the dashboard's first rclpy publisher. One publisher created at dashboard startup so DDS discovery happens once; a later press publishes instantly instead of racing a fresh subprocess's discovery.
routers_subscribed(infos, router_node) -> int(L30) — How many of a topic's subscriptions belong torouter_node(by node name), so a bag recorder orros2 topic echoon the prompt topic does not count as a router.class EstopPublisher— Creates the node +/openral/estop+/openral/estop_clearedpublishers immediately at RELIABLE/VOLATILE/depth-10 QoS, matching the HAL/kernel/runner subscriptions; degrades to inert (callers fall back to the shell-out path) when rclpy/ROS is unavailable. (L46) It also holds the operator-prompt publisher on/openral/prompt_in/dashboard(prompt(text, metadata_json)returns the subscribers reached, 0 with no prompt router,Nonewithoutopenral_msgs); thepromptaction uses it before theopenral promptshell-out (#679).available(self) -> bool(L116) — True when the persistent publisher is live (rclpy + ROS present).trigger(self) -> bool(L120) — Publish/openral/estopinstantly. ReturnsFalseif unavailable.clear(self) -> bool(L124) — Publish/openral/estop_clearedinstantly. ReturnsFalseif unavailable.- (property)
prompts -> bool(L129) — True when operator prompts go through this node (a prompt publisher on/openral/prompt_in/dashboardexists), not theopenral promptCLI. prompt(self, text, metadata_json) -> int | None(L133) — Publish one operator prompt on the dashboard's prompt-router input, once. Returns how many prompt routers (ROUTER_NODEsubscriptions, viarouters_subscribed) it reached —0publishes nothing — orNonewhen this node carries no prompts (use the shell-out).close(self) -> None(L165) — Tear down the node + executor; shut down rclpy only if we started it.
python/observability/src/openral_observability/dashboard/safety_status_subscriber.py
The dashboard's first rclpy subscriber: one node created at launch, spun on a daemon thread, inert-but-harmless without rclpy / the openral_msgs overlay. Read-only: no publisher, no service client, no authority over the robot.
- module constant
SAFETY_STATUS_TOPIC: str = "/openral/safety_status"(L46) - module constant
SAFETY_FAILURE_TOPIC: str = topic_for(FailureSource.SAFETY)(L48) —/openral/failure/safety(the static topic graph resolves the call); the kernel's typed stops, fed toTelemetryStore.record_safety_failure. DIAGNOSTICS_TOPIC: str(L51) —/diagnostics: the subscriber also reads each HAL heartbeat's ownestoppedlatch (TelemetryStore.set_hal_estop), since a kernel release does not release a restart-only HAL or one whose re-arm failed.drop_reason_label— re-exported fromopenral_observability.failure_bus(moved there so the skill runner and the reasoner share it).class SafetyStatusSubscriber— Opens the node + subscription immediately at the publishers' QoS (RELIABLE + TRANSIENT_LOCAL + KEEP_LAST=1) — a VOLATILE subscriber would never match and the card would sit silently empty. Also subscribes to/diagnostics(each HAL heartbeat'sestopped, intoTelemetryStore.set_hal_estop) and/openral/failure/safety(logging each new stop). Every callback logs, never raises, an exception (ROSSafetyViolationexcepted), since they share one spin thread; a missing ROS install is left torun_dashboardto report. Wired inrun_dashboardontoapp.state.safety_status. (L81)available(self) -> bool(L157) — True when the subscription is live (rclpy +openral_msgspresent).close(self) -> None(L209) — Tear down the node/executor and shuts rclpy down only if it started it.
python/observability/src/openral_observability/dashboard/discovery.py
mDNS advertise + browse for the live dashboard. Optional, requires the mdns extra; when zeroconf is not importable, Discovery stays disabled and the dashboard runs exactly as before.
- module constant
SERVICE_TYPE: str = "_openral-otlp._tcp.local."— mDNS service type for all OpenRAL dashboard OTLP receivers. Single source of truth for the advertiser and browser. (L30) class DiscoveredRobot(BaseModel)— One mDNS-discovered OpenRAL service; the/api/robotswire shape used by external operator tooling. Fields:name: str,addresses: list[str],port: int,properties: dict[str, str] = {},last_seen: float. (L37)class RobotRegistry— Thread-safe map of discovered robots (zeroconf callbacks run off-thread). (L47)upsert(self, robot) -> None(L55) — Insert or replace the entry keyed byrobot.name.remove(self, name) -> None(L64) — Remove the entry for name if it exists (idempotent).list_robots(self) -> list[DiscoveredRobot](L73) — Return all known robots sorted by name.class Discovery— Owns theZeroconfinstance, advertiser, and browser for the dashboard. Attributeenabled: bool. Wired intorun_dashboardinserver.py;app.state.discoveryholds the instance (orNonewhen themdnsextra is absent or zeroconf failed). (L83)robots(self) -> list[DiscoveredRobot](L99) — Delegate to the underlying registry.start(self, *, host, port) -> None(L107) — Start browsing always; advertise only on a non-loopback, non-wildcard bind.stop(self) -> None(L151) — Unregister the advertised service, cancel the browser, and close Zeroconf.
python/observability/src/openral_observability/dashboard/app.py
The robot dashboard's routes (ADR-0129). One app behind two listeners; _gate (an HTTP middleware) sets request.state.principal and enforces the listener rules before any route runs.
LAN_INGEST_ENV: str(L126) —"OPENRAL_DASHBOARD_LAN_INGEST": set to1to accept OTLP ingest on/v1/*from LAN hosts (default off; loopback always may).create_app(store: TelemetryStore | None = None, *, verifier: TokenVerifier | None = None, bridge_url: str = "ws://127.0.0.1:8765") -> FastAPI(L1568) — Build the app: OTLP/HTTP receivers (/v1/*, local listener only — loopback, or LAN withLAN_INGEST_ENV=1), reads (/api/config→mode/role/robot_id/org(the enrolment's org slug,""without one)/write_controls/remote_control/jaeger_ui_url,/api/manifest(404 until one arrives; skills dropped with write controls off,remoteper the remote-control flag, onlyestopfor a LAN client),/api/state,/api/stream[?images=0](SSE; ends at the token'sexpremotely),/api/camera/{source}/snapshot.jpg,/api/traces,/api/spans/{id},/api/robots),POST /api/actions/{id:path}(E-STOP resolvable without a manifest and fired before the body is read, then announced in the background; others validated againstargs_schemawithjsonschema, announced, then run:estop_reset→ kernel service (409 on cooldown),prompt→openral prompt,skill:<id>→ExecuteRskillgoal (202 +goal_id); refusals 403 per role (every kind butestopneeds at least operator whatever the manifest'smin_role) / LAN /OPENRAL_DASHBOARD_REMOTE_CONTROL/OPENRAL_DASHBOARD_WRITE_CONTROLS;promptpasses the text after--),GET/PUT/PATCH /api/robot-settings(also at/api/settings, the path the pinned console calls; relays the JSON body unchanged to<site>/api/robot/consolewithopenral_core.robot_secret_path()as Bearer andUser-Agent: openral-robotthrough one client per app that never follows a redirect, and returns openral.com's status and JSON as they are, butcanWritefalse for anyone but the local operator, an empty answer as an empty response, and openral.com's 401 (credential refused) as 409; 409 when the robot isn't linked or was linked again since the dashboard started (the enrolment on disk no longer matches its verifier's), 502 when openral.com can't be reached; relayed writes audited without the value; the local operator may use all three, a LAN viewerGETonly, the tunnelGETonly and only with remote control on),POST /api/transcribe, the 3D view (POST /api/viz/ticket,WS /wsproxy tobridge_url— ticket required remotely and off loopback,Originchecked on upgrade, closed at ticket expiry, bridge→browser frames through aBridgeRelay(latest-wins for heavy snapshot topics; reading the bridge pauses while its ordered backlog is full)),/viz/{path}(Lichtblick, fetched on first use, under_VIZ_CSP; its index.html carries this robot's layout fromopenral_foxglove_bringup.layoutin Lichtblick's default-layout slot) and/{path}(the robot UI fromapp.state.ui_dir, elsestatic/fallback.html, under_UI_CSP; an HTML file's inline scripts are allowed by sha256). The local listener refuses a cross-origin write (CSRF), any request or/wsupgrade carrying Cloudflare forwarding headers (cf-ray,cf-connecting-ip,cf-warp-tag-id,cdn-loop: cloudflare), and any LAN write butestop, a viz ticket and (opted in) OTLP ingest on/v1/*; the remote listener spends each token'sjtion its first write (TokenVerifier.spend; E-STOP exempt) and answers a replay 401; both CSPs allowconnect-src 'self'only;proxy_headersis off inrun_dashboard. Request bodies are capped at_MAX_BODY_BYTES(64 MiB) raw and gzip-decoded (413); STT decodes at most_STT_MAX_SECONDS(120 s) of audio (413).mission_view(snapshot) -> dict(L1183) — What a program following the robot needs, in a few hundred bytes: the mission (goal, the prompt'scorrelation_id, each task's id / text / status / attempts / failures / verdict,finished), the reasoner's last tick (tick_idx,tool,rskill_id,error_kind,message), andstopped/estopped/latched/latch_reason/latch_detail({kind, link, other, depth_m}of the kernel stop that caused the latch,Nonewhile not latched or with no stop near it). A robot of a scene with several robots also getsworld_pose({x, y, yaw, frame: "world"}, its map's origin in the sharedworld; absent otherwise; openral-pro#99).skill_resultis the last dashboard skill run (TelemetryStore.set_skill_result:runningwhen the action server accepts the goal, thenfinishedwithsuccess,failure_reasonandtrace_idfrom_drain_skill_goal_stdout; #662). Served byGET /api/mission(plusts_unix) and, one event per change, byGET /api/mission/stream(_sse_stream(view=mission_view)) (#659).
python/observability/src/openral_observability/dashboard/bridge_relay.py
Latest-wins relay for the /ws proxy: reads the foxglove.websocket.v1 frames it carries and, for snapshot-type topics only, keeps just the newest unsent message per subscription, so a slow tunnel never builds a backlog. Every other frame is relayed unchanged, in order.
LATEST_WINS_SCHEMAS: frozenset[str](L54) — Heavy snapshot message types (images, camera info, point clouds, laser scans, occupancy grids),/msg/stripped. Sampled streams (JointState,Imu,Odometry) are deliberately absent.MAX_ORDERED_BYTES(L67) — 8 MiB: unsent ordered frames held beforefull().class BridgeRelay(L77) —BridgeRelay(max_ordered_bytes=MAX_ORDERED_BYTES). Ordered bridge→browser queue with per-subscription coalescing; single event loop.droppedcounts coalesced messages (logged by the proxy asdashboard.bridge_relay_coalesced).from_browser(frame) -> None(L98) — Learnssubscribe/unsubscribe(the frame itself is forwarded by the caller); malformed ids are ignored.from_bridge(frame) -> None(L119) — Queues a frame; learnsadvertise/unadvertise; replaces an unsent older message of a latest-wins subscription.full() -> bool(L138) — The unsent ordered frames reached the bound: the caller stops reading the bridge until it has sent them.pending() -> bool(L142) — Anything to send.drain() -> list[str | bytes](L146) — Frames to send now, in order; still counted towardfull()untilsent().sent() -> None(L160) — The lastdrain()reached the browser: releases its ordered bytes from the bound.
python/observability/src/openral_observability/dashboard/remote_auth.py
Who is asking (ADR-0129 §6, Interface B): the local / LAN / remote principal and the robot-token check of the remote (tunnel) listener. Never logs Authorization headers or tickets.
- module constant
ROLE_RANK: dict[str, int](L51) —viewer<operator<admin; admin acts as operator on the robot. class Principal(L73) — Frozen dataclass:mode(local|lan|remote),role,sub,jti,exp(the last three remote only;expends streams).remote_listener(app) -> ASGIApp(L91) — Wrap the app for the remote listener: tags each scope so_gatedemands a token. Nothing a client sends sets the tag.is_remote(scope) -> bool(L104) — Whether a request came in throughremote_listener.load_enrolment(path: Path | None = None) -> RobotEnrolment | None(L109) — The enrolmentopenral robot linkwrote (openral_core.enrolment_path()),Nonewhen unlinked;ValueErrorfor an invalid file.class JwksCache(L124) — The issuer's ES256 keys, loaded from a disk cache, refetched (httpx) only for an unknownkidand at most once percooldown_s(60 s), written back to disk.key(self, kid: str) -> PyJWK | None(L160) — The keykid, refetching once if unknown.class TokenVerifier(L190) — Checks an openral.com robot token against this robot's enrolment and the issuer'sJwksCache.spend(self, principal: Principal) -> bool(L199) — Record a write made withprincipal's token;Falseif itsjtialready made one (replay). Held untilexp+ 60 s leeway, at most 4096; full of live tokens it refuses (fail closed).verify(self, token: str) -> Principal | str(L218) — Interface B in order — headeralgES256 (nevernone/HMAC),typabsent orat+jwt, knownkid; signature;iss; a singleaud(strict_aud) equal to the enrolled origin;exp/iatwith 60 s leeway andexp − iat ≤ 300;sub/jti/org/role/robotpresent;robot/orgequal to the enrolment; a known role. A refusal is a reason string, never the token.class VizTickets(L272) — Random 256-bit tickets for/ws(a JWT never goes in a URL), bound to the caller'ssub/role, reusable untilTTL_S(900 s) but never past the minting token'sexp; one pool ofMAXper mode (local/lan/remote), so a ticket works only on its listener and a LAN flood evicts only LAN tickets.issue(self, principal: Principal) -> str(L291) — A new ticket forprincipal; prunes expired ones in its mode's pool, then the oldest.expires_at(self, ticket: str | None, *, remote: bool) -> float | None(L308) — Whenticketexpires on the remote (remote=True) or local listener, orNoneif unknown there or expired.jwks_cache_file() -> Path(L318) —$OPENRAL_CACHE_DIR/dashboard/jwks.json.bearer(authorization: str | None) -> str | None(L324) — The token of anAuthorization: Bearerheader.allowed_origins() -> frozenset[str](L330) —$OPENRAL_DASHBOARD_ALLOWED_ORIGINS(comma-separated), default openral.com's www, dev and viz origins.
python/observability/src/openral_observability/dashboard/ui_assets.py
The robot UI served at /: the pinned prebuilt robot console (source not in this repo, ADR-0131), fetched once; $OPENRAL_DASHBOARD_UI_DIR serves a local build instead (a directory without index.html → the fallback, no fetch); neither → static/fallback.html (status + E-STOP).
class PinnedAsset(NamedTuple)(L48) —url,sha256,sizeof one pinned download.- module constant
ROBOT_UI: PinnedAsset | None(L56) — The pinned robot-console build (rewritten bytools/pin_robot_ui.py);Noneserves the fallback page. - module constant
UI_DIR_ENV = "OPENRAL_DASHBOARD_UI_DIR"(L44) sha256_of(path: Path) -> str(L72) — Hex sha256 of a file, read in chunks.ensure_bundle(name: str, asset: PinnedAsset) -> Path | None(L107) — Download (size + sha256 verified), extract with thedatatar filter minus*.map, and move into$OPENRAL_CACHE_DIR/dashboard_assets/<name>/<sha256>/only when complete; the directory holdingindex.html, orNone(logged). Shared withviz_assets.ui_dir() -> Path | None(L143) — The local build, else the fetched pin, elseNone; no download.ensure_ui_assets() -> Path | None(L154) — Fetch the pin if not cached; called best-effort byrun_dashboard. Logsdashboard.ui_sourceonce at INFO:source=pinned(+url),local(+path) orfallback.
python/observability/src/openral_observability/dashboard/tunnel.py
The robot's Cloudflare Tunnel (ADR-0129 §3): a user systemd service that survives reboots, or the dashboard's own child without user systemd; no install, no root. The token reaches cloudflared through TUNNEL_TOKEN / EnvironmentFile, never argv.
TUNNEL_PORT: int(L48) — 4319, where openral.com's tunnel ingress sends/apiand/ws.REMOTE_PORT_ENV: str(L51) —OPENRAL_DASHBOARD_REMOTE_PORT: a scene robot's own remote listener port, behind the scene's router on 4319 (run_dashboard's default when--remote-portis not given).CLOUDFLARED: dict[str, PinnedAsset](L56) — cloudflared 2026.10.7 perplatform.machine()(x86_64, aarch64).TUNNEL_TOKEN_RE: re.Pattern[str](L71) — A Cloudflare tunnel token (base64 of its JSON credentials);write_tunnel_tokenrefuses anything else.tunnel_env_path() -> Path(L93) —tunnel.envnext to the enrolment file.write_tunnel_token(token: str) -> Path(L98) — StoreTUNNEL_TOKEN=<token>, mode 0600,O_NOFOLLOW.read_tunnel_token() -> str | None(L116) — The stored token, orNonewhen not linked.SERVICE: str(L74) —openral-tunnel.service, the user unitopenral robot linkinstalls.install_service(exe: Path) -> str | None(L159) — Write the user unit (EnvironmentFile=tunnel.env,Restart=always),systemctl --user enable --nowit andloginctl enable-linger(boot without login);None, or why not. Refuses to replace a unit that runs another robot's tunnel while that robot'stunnel.envexists and the service is active (one service per host, kept by the robot it was linked for; the reason namessystemctl --user disable --nowto free it); a unit whose robot is gone or stopped is taken over.service_active() -> bool(L201) — Whether the user service is running.ensure_cloudflared() -> Path | None(L128) — The pinned binary, fetched once into the cache; else one onPATH; elseNone.start_tunnel(remote_port: int) -> subprocess.Popen[bytes] | None(L206) — Runcloudflared tunnel --no-autoupdate runas a child unless the user service already runs this robot's tunnel (itsEnvironmentFileis thistunnel.env);Nonewhen not linked, the service holds it, or no binary. Warns on aremote_portother than 4319 unlessREMOTE_PORT_ENVsays a router fronts it.
python/observability/src/openral_observability/dashboard/remote_router.py
Several linked robots on one host (a deploy sim scene) share the tunnel port: every robot's tunnel ingress is localhost:4319. One router there splices each connection, unchanged, to its robot's own remote listener by the Host of its first request (each robot's cloudflared carries only its own host); each robot still checks its own tokens.
route_host(aud: str) -> str(L45) — A robot's tunnel host: its enrolmentaud's hostname, lower case.request_host(head: bytes) -> str(L55) — The host a request head names (lower case, no port), read as strictly as the robot's parser:ValueErroron a bad request line, a field line that is notname: value(whitespace before the colon, a folded line) or not exactly oneHost.HEAD_TIMEOUT_S: float(L38) — 10 s: how long a new connection gets to send its first request head before it is closed.serve_router(routes: Mapping[str, int], port: int = TUNNEL_PORT) -> asyncio.Server(L138) — Listen on127.0.0.1:port;421for a host no robot answers to,400for a malformed head,502when that robot's dashboard is down; a half-close is passed on both ways;OSErrorwhen the port is taken.main(argv=None) -> int(L152) —python -m openral_observability.dashboard.remote_router --route HOST=PORT ..., asdeploy simstarts it; exits 1 (logged) when the port is taken; on SIGINT stops at once, closing open connections instead of waiting for them.
python/observability/src/openral_observability/dashboard/viz_assets.py
- module constant
LICHTBLICK: PinnedAsset(L20) — Lichtblick v1.30.0lichtblick-web.tar.gz(MPL-2.0), pinned by sha256 + size. ensure_viz_assets() -> Path | None(L35) — The Lichtblick build (viaensure_bundle), with aNOTICE.txtnaming its MPL-2.0 source; fetched on the first/viz/request.
python/observability/src/openral_observability/dashboard/server.py
run_dashboard(*, host="127.0.0.1", port=4318, remote_port=None, bridge_port=8765, manifest_path=None, inprocess_cmd=None, store=None, log_level="warning", world_pose=None) -> None(L94) — Start the local listener onhost:portand, when the robot is linked (load_enrolment), the remote listener on127.0.0.1:remote_port(default$OPENRAL_DASHBOARD_REMOTE_PORT, else 4319; aremote_portwithout an enrolment is aValueError; a variable that is not a port, or a port another process holds, turns the remote listener and tunnel off with an error log and leaves the local listener and its E-STOP running) with aTokenVerifier; both withproxy_headersoff and a 30 s WebSocket ping, run together until SIGINT/SIGTERM (one stopping stops both). Fetches the robot UI best-effort (ensure_ui_assets), starts the persistentEstopPublisher, the safety-status and perception-overlay subscribers and mDNS discovery, prints the URL banner and warnings for a non-loopback bind, write controls and remote control; when linked, also runs the robot's tunnel (tunnel.start_tunnel) and stops it on exit.manifest_path(aRobotManifestJSON file) is served until the runtime sends a fresher one; an unreadable file is logged and ignored. Wheninprocess_cmdis set, spawns it pointed at this dashboard's OTLP endpoint.world_pose((x, y, yaw)) seeds/api/mission'sworld_pose(openral dashboard --world-pose, passed by the deploy launch).spawn_dashboard/attached_dashboard— Inverse of--inprocess; seedashboard/attach.pybelow (a separate module despite the name symmetry with this file).
python/observability/src/openral_observability/dashboard/attach.py
The --inprocess inverse: spawn openral dashboard as a child process and attach the current process's telemetry to it. Used by openral sim run --dashboard / openral deploy run --dashboard / openral benchmark run --dashboard.
- module constant
_LOG(L30) —logging.getLogger(__name__). - module constant
_ENV_ENDPOINT: str = "OTEL_EXPORTER_OTLP_ENDPOINT"(L32) - module constant
_ENV_PROTOCOL: str = "OTEL_EXPORTER_OTLP_PROTOCOL"(L33) - module constant
_HTTP_OK: int = 200(L34) — healthz poll success code. spawn_dashboard(*, host="127.0.0.1", port=4318, ready_timeout_s=10.0) -> Iterator[str | None][@contextmanager] (L38) — Spawnopenral dashboardas a child, set the OTLP env, poll/healthzuntil ready, yield the URL, and SIGINT the child on exit. YieldsNoneifopenralisn't on PATH, the child dies early, or the health check never passes within the timeout._wait_healthy(healthz_url, child, *, timeout_s) -> bool(L202) — Pollhealthz_urluntil it returns_HTTP_OKorchildexits ortimeout_selapses._shutdown_child(child) -> None(L217) — SIGINT the child and wait, escalating if needed.attached_dashboard(*, enabled, port=4318, subcommand=None, mode=None) -> Iterator[bool][@contextmanager] (L129) — Convenience wrapper for CLI commands that gate dashboard attach on a flag.enabled=FalseyieldsFalseas a true no-op (no FastAPI/uvicorn imports).enabled=Truedelegates tospawn_dashboard, re-runsconfigure_observabilityon the new endpoint, and re-opens thecli.commandroot span so workload spans have a real recording ancestor instead of being orphaned under the pre-dashboard root. Drains viashutdown_observabilityinfinally. YieldsTrueiff the child reported healthy.
python/observability/src/openral_observability/dashboard/store.py — F7 trace index additions
Bounded per-trace_id span index for query-time bag↔OTel join.
class _IndexedSpan(L281) — Frozen-ish record retained bytrace_id:name,trace_id,span_id,parent_span_id,start_ns,end_ns,attrs,status_code,status_message,events..to_json()returns a plain dict carryingduration_ms.TelemetryStore.list_traces() -> list[dict]— One row per indexed trace_id (trace_id,span_count,last_seen_unix), most-recent first. BacksGET /api/traces.TelemetryStore.lookup_trace(trace_id: str) -> list[dict] | None— Every indexed span fortrace_id, sorted ascending bystart_unix_ns.Nonewhen the trace is not (or no longer) in the bounded index. BacksGET /api/spans/{trace_id}._TRACE_INDEX_MAX_TRACES = 64/_TRACE_INDEX_MAX_SPANS = 2048— Memory caps. Older trace_ids evict FIFO on insertion.
python/observability/src/openral_observability/dashboard/app.py — F7 routes
GET /api/traces— JSON{"traces": [...]}fromTelemetryStore.list_traces.GET /api/spans/{trace_id}— JSON{"trace_id", "spans": [...]}fromTelemetryStore.lookup_trace; 404 when the trace is not indexed.
python/observability/src/openral_observability/tracing_lttng.py
Opt-in LTTng tracepoints around the realtime hot path. No-op when OPENRAL_ROS2_TRACING is unset; falls back to JSONL when lttngust is missing.
ENV_TRACING_GATE = "OPENRAL_ROS2_TRACING"(L62) — Truthy values (1/true/yes/on) enable the backend; anything else leaves every tracepoint a no-op.ENV_TRACING_FALLBACK_DIR = "OPENRAL_ROS2_TRACING_FALLBACK_DIR"(L68) — Override for the JSONL fallback directory (default: a fresh owner-onlytempfile.mkdtemp(prefix="openral-lttng-fallback-")dir, logged at INFO; never a fixed shared/tmppath). The JSONL file opens withO_NOFOLLOW; a planted symlink (ELOOP) disables tracing with an error log.TP_RUNNER_TICK = "openral:runner_tick"(L76)TP_HAL_READ_STATE = "openral:hal_read_state"(L77)TP_HAL_SEND_ACTION = "openral:hal_send_action"(L78)TP_SENSORS_READ_LATEST = "openral:sensors_read_latest"(L79)TP_WORLD_STATE_SNAPSHOT = "openral:world_state_snapshot"(L80)TP_SKILL_STEP = "openral:skill_step"(L81)TP_ACTION_PUBLISH = "openral:action_publish"(L82)TP_SAFETY_VALIDATE = "openral:safety_validate"(L83) — Tracepoint base names;lttng_tracepointappends_begin/_endsuffixes.is_enabled() -> bool(L114) — Single source of truth for the gate.lttng_tracepoint(name, **attrs) -> Iterator[None](L181) — Context manager that fires<name>_begin/<name>_endaround the block. Attaches the active OTeltrace_idasotel_trace_idso CTF traces can join back to OTel.class LttngSession(name, output_dir)(L95) — Identity of an active session.class LttngSessionError(RuntimeError)(L90) — Raised by the subprocess wrappers.- module constant
_BACKEND_RESOLVED: bool = False(L109) — whether_resolve_backendhas run yet (cached-resolution guard). - module constant
_BACKEND: Any = None(L110) — the cached resolved tracer backend (_LttngUstBackend/_JsonFallbackBackend/None). - module constant
_WARNED_ONCE: bool = False(L111) — one-time fallback-warning latch consumed by_warn_fallback. - module constant
_TRACEPARENT_PART_COUNT: int = 4(L87) — expectedtraceparentdash-separated part count. - module constant
_LOG(L57) —logging.getLogger(__name__). start_session(*, name, output_dir) -> LttngSession(L343) —lttng create / enable-event openral:* / add-context / start.stop_session(*, name) -> None(L368) —lttng stop+destroy(flush + teardown).view_session(*, output_dir) -> None(L380) —babeltrace2 OUTPUT_DIR; falls back to listing files whenbabeltrace2is absent.
python/dataset/src/openral_dataset/recorder.py
In-memory per-rollout accumulator with multi-sink fan-out.
@dataclass class EpisodeHeader(episode_idx, task_string, fps, robot_name, stamp_ns)— Per-episode metadata pushed to sinks atepisode_start. (L55)@dataclass class DatasetFrame(episode_idx, frame_idx, observation_state, images, action, reward, terminated, truncated, stamp_ns, trace_id="", span_id="")— Per-tick frame pushed to sinks atrecord_frame.trace_id(32 hex) /span_id(16 hex) carry the producingrskill.tickspan's ids (ISSUE-109 forward link);""when no valid span was in scope. (L78)@dataclass class EpisodeSummary(episode_idx, success, n_frames, stamp_ns)— Per-episode close-out pushed to sinks atepisode_end. (L119)class DatasetSink(Protocol)— Fan-out target withopen_episode/write_frame/close_episode/finalize. (L137)open_episode(self, header) -> None(L151) — Begin a new episode. Idempotent only within one episode.write_frame(self, frame) -> None(L154) — Append one frame to the current episode.close_episode(self, summary) -> None(L157) — Finalise the current episode (success flag, frame count).finalize(self) -> None(L160) — Flush pending I/O and release resources. Idempotent.class RolloutRecorder(*, robot, task_string, fps, sinks, repo_id=None)— In-memory accumulator that fans every step out to one or moreDatasetSinkimplementations and writes the OTelopenral.dataset.repo_id/episode_idx/frame_idxattributes on the activerskill.tickspan. (L164)episode_start(*, task_string=None) -> int— Open a new episode; returns its idx. (L293)record_frame(*, observation_state, images, action, reward, terminated, truncated, stamp_ns, trace_id=None, span_id=None) -> int— Append one frame. Captures the activerskill.tickspan's(trace_id, span_id)onto the frame (ISSUE-109); explicittrace_id/span_idoverride the live capture (the offline converter replays the bag's original ids). (L338)episode_end(*, success: bool) -> EpisodeSummary— Close the current episode. (L451)finalize() -> None— Flush all sinks idempotently. (L484)prop fps, robot_name, repo_id, n_sinks, expected_state_shape(L219–239) — Read-only views consumed by callers building the per-frame payload (robot_nameL224,repo_idL229,n_sinksL234,expected_state_shapeL0).expected_image_keys() -> tuple[str, ...]— Camera keys (withoutobservation.images.prefix) the sinks expect; derived fromRobotDescription.sensors[*].vla_feature_key. (L253)
python/dataset/src/openral_dataset/schema_map.py
Pure RobotDescription → LeRobot v3 features dict mapping; no I/O, no lerobot import.
- module constant
_LEROBOT_IMAGE_DTYPE: str = "video"(L31) - module constant
_LEROBOT_STATE_DTYPE: str = "float32"(L32) - module constant
_LEROBOT_ACTION_DTYPE: str = "float32"(L33) — LeRobot v3 feature dtypesfeatures_from_robotassigns. - module constant
_IMAGE_MODALITIES: frozenset[str](L38) —{"rgb", "depth", "rgbd", "thermal", "ir"}, sensor modalities mapped to image features. @dataclass class FeatureSpec(key, dtype, shape)— Decoupled feature descriptor; sinks translate to lerobot's{'dtype', 'shape', 'names'}format. (L42)features_from_robot(robot: RobotDescription, *, fps: float) -> dict[str, FeatureSpec]— Build the LeRobot v3 features dict for the recorder. ReadsObservationSpec.state_shape,ActionSpec.dim, andSensorSpec.vla_feature_key(image modalities only) from the robot manifest. (L59)
python/dataset/src/openral_dataset/bag.py
Mcap-backed DatasetSink for online hardware recording.
- module constant
TOPIC_TICK: str = "/openral/tick"(L53) - module constant
TOPIC_EPISODE: str = "/openral/episode"(L54) - module constant
TOPIC_IMAGE: str = "/openral/dataset/image"(L59) — the three mcap topic names the converter imports by symbol. - module constant
_TICK_SCHEMA: dict[str, Any](L66) — JSON Schema for the/openral/tickmessage. - module constant
_IMAGE_SCHEMA: dict[str, Any](L99) — JSON Schema for the/openral/dataset/imagemessage. - module constant
_EPISODE_SCHEMA: dict[str, Any](L125) — JSON Schema for the/openral/episodemessage. - module constant
PHASE_START: int = 0(L139) - module constant
PHASE_END: int = 1(L140) — the twoEpisode.phaseenum values. - module constant
_NDIM_H: int = 1(L144) - module constant
_NDIM_HW: int = 2(L145) - module constant
_NDIM_HWC: int = 3(L146) — expectedndarray.ndimfor a mono/2D/HWC image frame. - module constant
_QUEUE_MAXSIZE: int = 1024(L152) — bound on the writer thread'squeue.Queue;write_framedrops (counted inn_dropped) rather than block the hot path when full. - module constant
_WRITER_JOIN_TIMEOUT_S: float = 5.0(L157) —finalize's join timeout on the writer thread. - module constant
_MCAP_INSTALL_HINT: str(L161) — install hint raised whenmcapis not importable. - module constant
_STOP(L173) — sentinel_Stop()instance enqueued to tell the writer thread to exit. class Rosbag2Sink(DatasetSink)— Writes everyRolloutRecorderevent into an mcap file readable byros2 bag info/ Foxglove / mcap-cli. Daemon writer thread + bounded queue sowrite_framenever blocks on disk I/O. Topics:/openral/tick(metadata plus inlineobservation_state/actionarrays),/openral/episode(phase markers),/openral/dataset/image(one frame per camera per tick) — self-sufficient for conversion, no separate topic join needed. (L176)bag_path(self) -> Path(L251) — Output bag path (read-only).n_ticks_written(self) -> int(L256) — Number of/openral/tickmessages successfully written.n_episode_markers_written(self) -> int(L261) — Number of/openral/episodemessages (start + end) written.n_images_written(self) -> int(L266) — Number of/openral/dataset/imagemessages successfully written.n_dropped(self) -> int(L271) — Number of messages dropped because the writer queue was full.open_episode(self, header) -> None(L277) — Open the bag on first call; emit Episode(PHASE_START).write_frame(self, frame) -> None(L291) — Enqueue a Tick message (incl. inlineobservation_state/action+ the frame'strace_id/span_id, ISSUE-109) and one DatasetImage message per camera; never blocks. The off-thread mcap write reads the ids off the frame because the OTel context is gone by then.close_episode(self, summary) -> None(L334) — Emit Episode(PHASE_END) with success flag.finalize(self) -> None(L344) — Drain queue, stop writer thread, close mcap. Idempotent.
python/dataset/src/openral_dataset/converter.py
Offline mcap rosbag2 → LeRobotDataset v3 converter.
- module constant
_MCAP_INSTALL_HINT: str(L49) — install hint raised whenmcapis not importable. @dataclass class DatasetSummary(output_root, n_episodes, n_frames, n_success, repo_id)— Returned byfrom_bagdescribing what landed on disk. (L56)class Rosbag2ToLeRobotConverter(L84) — Offline replay of aRosbag2Sink-produced mcap into a LeRobotDataset v3.Rosbag2ToLeRobotConverter.from_bag(*, bag_path, robot, output_root, repo_id=None, license="CC-BY-4.0", fps=None) -> DatasetSummary— Walk aRosbag2Sink-produced mcap, group ticks under episode markers, join each tick's inline arrays + camera frames, and replay each episode through a realLeRobotDatasetSinkto produce a reloadable v3 dataset with real proprio/action/video. Each replayed tick re-injects the bag's original(trace_id, span_id)so the on-disk frame points at the source rollout, not the convert run. RaisesROSConfigErroron a missing bag, missing episode markers, or a mismatched robot. (L104)
python/dataset/src/openral_dataset/frame_trace.py
ISSUE-109 — pivot a written LeRobotDataset frame back to its OTel ids.
read_frame_trace(*, root, episode_idx, frame_idx) -> tuple[str, str]— Return the(trace_id, span_id)stamped on a v3 frame. Reads theroot/data/**/*.parquetcorrelation columns directly viapyarrow(no video decode), so it works without a torchcodec/ffmpeg backend. RaisesROSConfigErrorwhen the root has no parquet, the dataset predates the columns, or no(episode_idx, frame_idx)row matches. Backsopenral replay --frame. (L28)
python/dataset/src/openral_dataset/sinks.py
LeRobotDataset v3.0 (codebase_version="3.0") writer; deferred LeRobotDataset.create so per-camera shapes come from the first frame.
- module constant
DEFAULT_LICENSE: str = "CC-BY-4.0"(L43) - module constant
DEFAULT_VCODEC: str = "libsvtav1"(L48) — default license / video codec for a newLeRobotDatasetSink. - module constant
_FPS_INTEGER_TOLERANCE: float = 1e-6(L51) — tolerance for treating a recorded fps as an integer. - module constant
_TRACE_FEATURES: dict[str, dict[str, Any]](L59) — thetrace_id/span_idstring-feature specs added to every LeRobot v3 dataset (ISSUE-109). - module constant
_LEROBOT_INSTALL_HINT: str(L67) — install hint raised whenlerobot>=0.5.1is not importable. class LeRobotDatasetSink(DatasetSink)— Implementation ofDatasetSinkwriting LeRobot v3 datasets via reallerobot.datasets.LeRobotDataset.create / add_frame / save_episode / finalize. Lazy-imports lerobot at construction. (L85)__init__(*, root, robot, fps, repo_id=None, license="CC-BY-4.0", vcodec="libsvtav1")— RaisesROSConfigErrorif lerobot ≥ 0.5.1 is not importable. (L120)open_episode(header) -> None— Stash the task string for per-frame tagging. (L255)write_frame(frame) -> None— Validates per-frame shapes against the declared features, then forwards toLeRobotDataset.add_frame. Adds the frame'strace_id/span_idasstringparquet columns (ISSUE-109). (L274)close_episode(summary) -> None— CallsLeRobotDataset.save_episode(parallel_encoding=True)and accumulates the per-dataset success counter. (L351)finalize() -> None— CallsLeRobotDataset.finalize()then appendsdataset_success_rate/license/repo_idand the dataset-leveltrace_ids/n_traces(distinct OTel traces, ISSUE-109) tometa/info.json["metadata"], and writes the per-episodeepisode_index → trace_idmap to themeta/openral_traces.jsonsidecar. (L392)
python/observability/src/openral_observability/replay/bag_reader.py
Read a rosbag2 (mcap) recording as a stream of BagMessage for the F7 bag↔OTel replay correlator.
- module constant
_TRACEPARENT_RE_BYTES(L40) —re.compile(rb"00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})"), matches atraceparentembedded in a raw CDR payload. - module constant
_TRACEPARENT_RE_STR(L43) — same pattern,strform, for JSON-schema-encoded payloads. - module constant
_RAW_TRACE_ID_RE(L48) —re.compile(r"^[0-9a-f]{32}$"). - module constant
_RAW_SPAN_ID_RE(L49) —re.compile(r"^[0-9a-f]{16}$"). class BagMessage(L84) — One rosbag2 record surfaced to the bag↔OTel replay correlator; fieldstopic,log_time_ns,publish_time_ns,trace_id,traceparent,schema_name,payload_summary._trace_id_from_json_payload(payload) -> tuple[str, str](L52) — Return(trace_id_hex, traceparent)from ajsonschemapayload._resolve_mcap_path(path) -> Path(L117) — Find the actual.mcapfile inside a rosbag2 directory._extract_traceparent_from_ros2msg(payload) -> tuple[str, str](L135) — Return(trace_id_hex, traceparent)from a CDR payload, or empties.read_bag(bag_path) -> Iterator[BagMessage](L144) — Yield every message inbag_pathas aBagMessage.
python/observability/src/openral_observability/replay/correlator.py
Merge a rosbag2 message stream with dashboard-indexed OTel spans into one sorted timeline for openral replay.
class TimelineEntry(L27) — One row in the correlated timeline; fieldskind: Literal["bag", "span"],ts_ns,trace_id,topic,span_name,attrs,duration_ms.to_json(self) -> dict[str, Any](L55) — Return a plain-dict view suitable forjson.dumps.list_bag_trace_ids(bag_messages) -> list[dict[str, Any]](L68) — Return distinct trace_ids inbag_messageswith their per-trace counts.build_timeline(bag_messages, spans, *, trace_id=None) -> list[TimelineEntry](L95) — Mergebag_messages+spansinto one sorted timeline.
python/observability/src/openral_observability/replay/trace_query.py
Minimal read-only HTTP client for the dashboard's F7 trace-query endpoints (GET /api/traces, GET /api/spans/{trace_id}).
- module constant
_HTTP_NOT_FOUND: int = 404(L23) class TraceQueryError(RuntimeError)(L26) — Raised when the dashboard does not return a usable JSON body.class DashboardTraceClient(L31) — Minimal read-only HTTP client for the dashboard trace endpoints.base_url: str = "http://127.0.0.1:8000",timeout_s: float = 5.0.list_traces(self) -> list[dict[str, Any]](L45) — ReturnGET /api/tracesdecoded, sorted server-side most-recent first.get_spans(self, trace_id) -> list[dict[str, Any]](L54) — Return every span fortrace_id; empty list when not indexed.
python/observability/src/openral_observability/replay/cli.py
openral replay implementation: record a bag with the right topics, then join it against dashboard-indexed OTel spans by trace_id.
- module constant
ProfileName(L38) —Literal["slim", "full"], the tworos2 bag recordtopic/regex profiles. - module constant
RECORD_PROFILES: dict[str, dict[str, list[str]]](L52) — theslim(safety/estop/world-state-slow + compressed camera images) andfull(adds world-state-fast, joint_states, tf, all perception, every camera stream, and — bytopic_types— everyLaserScan/PointCloud2/Imutopic whatever a manifest names it) topic + regex + topic-type lists; camera regexes are built fromre.escape(CAMERA_TOPIC_PREFIX). build_record_command(*, profile, output_dir, storage="mcap", extra_topics=(), extra_regex=()) -> list[str](L102) — Compose theros2 bag recordargv forprofile. Verbatim topics are folded into the--regexas anchored patterns, never passed as explicit topics: rosbag2 (Jazzy) stops discovery once as many topics are subscribed as were listed explicitly, so mixing the two silently dropped later topics.topic_typesgo to--topic-types.run_record(*, profile, output_dir, storage="mcap", extra_topics=(), extra_regex=(), dry_run=False) -> tuple[list[str], subprocess.CompletedProcess[bytes] | None](L233) — Invokeros2 bag recordwith the chosen profile.class ReplayResult(L156) — Output ofrun_replay— both summary + the joined timeline; fieldstrace_id,bag_trace_ids,timeline,bag_path.to_json(self) -> dict[str, Any](L175) — Return a plain-dict view suitable forjson.dumps.run_replay(*, bag_path, trace_id, dashboard_url) -> ReplayResult(L185) — Readbag_path, fetch matching spans, return the joined timeline.write_timeline(result, out_path) -> None(L306) — Persist aReplayResultas pretty-printed JSON toout_path.