Skip to content

Layer 4–6 — Reasoning, Safety, Observability

Part of the OpenRAL public-symbol inventory. Hand-curated; (LNN) markers are refreshed by tools/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 (today openral_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 the lifecycle_transition tool description by _tool_palette_to_anthropic_tools for each peer in palette.node_ids (leading / ignored); the schema's node enum 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, wait while 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 in openral_core.schemas, re-exported here unchanged.
  • module constant _ENDPOINT_PRESETS: dict[str, ReasonerEndpointPreset] — Back-compat alias of openral_core.REASONER_ENDPOINT_PRESETS: per-endpoint url/dialect/auth_required/timeout_s/tool_choice for each OPENRAL_REASONER_ENDPOINT name. 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 by resolve_reasoner_system_prompt.
  • render_robot_context_prompt(capabilities: RobotCapabilities | None, *, base_prompt=DEFAULT_SYSTEM_PROMPT) -> str (L391) — Appends a deterministic ## THIS ROBOT body-awareness block (embodiment, locomotion, manipulation/sensing, payload, control modes) to the prompt; None returns base_prompt unchanged. 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 ROBOT block). env is injectable for tests; called from ReasonerNode.on_configure.
  • class ToolUseClient(Protocol) (L552) — LLM tool-use client contract: model_id, optional last_prompt_tokens. Raises ROSReasonerInvalidPlan on a bad/mismatched tool call, ROSPlanningError on transport failure.
  • select_tool(self, *, context_text, palette, system_prompt=DEFAULT_SYSTEM_PROMPT) -> ReasonerToolCall (L574) — Pick exactly one ReasonerToolCall for context_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 raises ROSReasonerInvalidPlan); max_tokens optionally caps completion tokens, else the endpoint default applies; max_tokens_param names the cap field, switched to max_completion_tokens at 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 of OPENRAL_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, else ROSConfigError), defaulting to DEFAULT_FIRST_CALL_TIMEOUT_S unless 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 as OpenAICompatibleToolUseClient(first_call_timeout_s=…); _send applies it as the read timeout of each request until the first reply, and again after an APITimeoutError (a model the server unloaded reloads on the next request); logged as reasoner.llm.first_call_timeout. At or below timeout_s it does nothing; the class default is 0.0 (off).
  • module constant REASONER_TOOL_CHOICE_ENV: str = "OPENRAL_REASONER_TOOL_CHOICE" (L664) — auto/required override for an uncurated model on a bare-URL openai endpoint or on the anthropic dialect (required → Anthropic any); validated on every path via openral_core.parse_reasoner_tool_choice, and ignored with a reasoner.tool_choice_ignored warning for curated models and named openai endpoints.
  • module constant _ANTHROPIC_UNCURATED_MAX_TOKENS: int = 16000 — completion cap for an uncurated anthropic model with no OPENRAL_REASONER_MAX_TOKENS (thinking counts against it).
  • module constant _NO_TOOL_CALL_NUDGE: str — the one-shot follow-up sent when a tool_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 mentions tool_choice or its disable_parallel_tool_use sub-field; triggers the runtime required → auto retry.
  • _rejects_max_tokens(exc) -> bool — True for an OpenAI 400 asking for max_completion_tokens.
  • _prose_reply_error(text, *, model_id) -> ROSReasonerInvalidPlan — The error for an auto reply with no tool call after the nudge (#522): quotes the text (whitespace-collapsed, ≤300 chars) so the node feeds it back into ## EXECUTION; logged reasoner.no_tool_call. Not a wait, which is retry-cap exempt and sends no hint back.
  • _log_tool_choice_downgrade(model_id, exc) -> None — The one reasoner.tool_choice_downgraded log both clients emit after a successful auto retry.
  • _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_choice matches.
  • _openai_tool_calls(choices) -> list / _openai_may_nudge(choices) -> bool — First choice's tool calls; whether a tool-less reply is nudge-worthy (not length / content_filter).
  • _anthropic_tool_use_block(response) / _anthropic_may_nudge(response) -> bool — First tool_use block or None; whether a tool-less reply is nudge-worthy (not refusal / max_tokens).
  • module constant REASONER_MAX_SKILL_TOOLS_ENV: str = "OPENRAL_REASONER_MAX_SKILL_TOOLS" (L655) — per-tick skill-tool cap override read by resolve_max_skill_tools; 0 = no cap.
  • resolve_max_skill_tools(client) -> int | None (L1088) — The per-tick skill-tool cap for the model client talks to (#494): OPENRAL_REASONER_MAX_SKILL_TOOLS when set (0 → None, negative / non-integer → ROSConfigError), else the max_skill_tools of the curated ReasonerModel whose served_model_id is client.model_id, else None. Keyed on the built (or injected) client so the two cannot disagree; ReasonerNode.on_configure resolves it right after building the client, before any resource opens.
  • build_tool_use_client_from_env() -> ToolUseClient — Model-first client factory: OPENRAL_REASONER_MODEL resolves openral_core.REASONER_MODELS for dialect/endpoint/auth/hosting/tool-choice/token-cap; OPENRAL_REASONER_ENDPOINT overrides location (a named preset, a bare URL, or managed); API_KEY/MAX_TOKENS/TIMEOUT_S override 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 and auto). DIALECT is needed only for a bare URL and always wins when set. No hidden model default. On an Ollama reply (system_fingerprint fp_ollama) OpenAICompatibleToolUseClient.select_tool raises ROSPlanningError when 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_choice required (sent as any) or auto; a forced-tool-use refusal downgrades to auto for the client's life once an auto retry succeeds (reasoner.tool_choice_downgraded).
  • _create(self, client, **kwargs) — messages.create with the current tool_choice, retried once as auto on 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; under auto a prose reply is nudged once, then raises ROSReasonerInvalidPlan; a refusal or max_tokens cut-off raises ROSPlanningError. last_prompt_tokens sums 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; under auto a prose reply is nudged once, then raises ROSReasonerInvalidPlan; a length / content_filter finish raises ROSPlanningError. last_prompt_tokens sums both calls.
  • _complete(self, client, messages, tools) -> tuple[list, Any] — One chat.completions.create, adapting at runtime to a forced-tool-use refusal (→ auto) and a max_completion_tokens 400; 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) — ToolUseClient over OpenAI's Responses API (/v1/responses), built for the openai endpoint: OpenAI's reasoning models take function tools only there. Same tick contract as the Chat Completions client (forced call, runtime auto downgrade, one nudge then ROSReasonerInvalidPlan, refusal / max_output_tokens cut-off → ROSPlanningError); store=False, parallel_tool_calls=False, reasoning left at the model default, max_tokens sent as max_output_tokens.
  • _respond(self, client, instructions, inputs, tools) — One responses.create, retried once as auto on a forced-tool-use refusal.
  • select_tool(self, *, context_text, palette, system_prompt=DEFAULT_SYSTEM_PROMPT) -> ReasonerToolCall (L2804) — Call the Responses API and decode the function_call output item.
  • describe_image(self, *, image_jpeg, question) -> str (L2847) — Frame question as input_text + input_image over 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 with strict: False.
  • _responses_function_call(response) / _responses_text(response) -> str / _responses_refusal(response) -> str | None / _responses_may_nudge(response) -> bool — Responses output readers: first function_call item; concatenated output_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, including WaitTool; per-skill names use collision-resistant execute_rskill__<slug>_<sha1-8>. lifecycle_transition's node carries enum: 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-only input_schema key.
  • _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. A lifecycle_transition whose node is not in palette.node_ids raises ROSReasonerInvalidPlan.
  • 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-max execute_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 when entry.object_target is 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 no titles 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-generated title of every field/model/enum and model/enum docstring descriptions (an explicit Field(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_schema parses 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 with name stripped from both properties and required. Used to drop rskill_id from per-skill ExecuteRskillTool schemas. (L1998)
  • module constant _TOOL_ADAPTER: TypeAdapter[ReasonerToolCall] (L375) — cached TypeAdapter(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-run vllm serve on :8000. (L68)
  • module constant DEFAULT_COSMOS3_MODEL: str — nvidia/Cosmos3-Edge, served id of the curated cosmos3-edge registry entry. (L74)
  • module constants AUTOSTART_ENV / BOOT_TIMEOUT_ENV / SIDECAR_SCRIPT_ENV / DEFAULT_BOOT_TIMEOUT_S — env knobs: OPENRAL_COSMOS3_AUTOSTART (0 disables 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_port treats as loopback (a client URL may name 0.0.0.0; the server never binds it).
  • _bind_host(hostname: str) -> str (L90) — The address the autostarted sidecar binds for a _LOOPBACK_HOSTS name: ::1 stays ::1, everything else (0.0.0.0, localhost) is 127.0.0.1, so the unauthenticated vLLM is never exposed on every interface. Used by _spawn_argv.
  • find_cosmos3_sidecar_script() -> Path — Locate tools/cosmos3_reasoner_sidecar.py (env override or repo-parent walk); raises ROSConfigError when 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, or None (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() lets ReasonerNode.on_configure start 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 matching RSkillManifest at palette-build time, plus quantization_dtype (the manifest's quantization.dtype; not shown to the LLM, read by the skill-subset precision tie-break), result_only (a wrapped ROS action/service with no result_trajectory_field: ReasonerCore keeps no backstop live while it is in flight on an unchanged context), completes_task_on_success (mirrors RosIntegration.completes_task_on_success: the node completes the active mission task when the goal succeeds) and max_execution_s (the manifest's latency_budget.max_execution_s, sizing inflight_backstop_s); none is shown to the LLM. object_target ("grasp_required" / "grasp_and_hand_required" / "not_applicable" / None, set by build_tool_palette(object_tracking=True, grasp_hand_required=...) from RSkillManifest.actuates_manipulator) is: _format_skill_tool_description appends 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 a mode: continuous detector, surfaced to the LLM as coverage (not a tool) so it can read tracked objects from world state and reserve locate_in_view for the long tail.
  • class OnDemandDetectorEntry(BaseModel) (L221) — Frozen record for a mode: on_demand open-vocab locator, surfaced as a selectable locate_in_view option — a read-only prompt-able tool, never an ExecuteRskill policy.
  • detector_alias(rskill_name) -> str (L142) — Short LLM-/operator-facing detector id: strips the OpenRAL/ 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 the locate_in_view service 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-supplied detector value 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: primary skills, back-compat execute_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, with on_demand_detectors as its options), scene_query_available (query_scene, independent of detection), memory_available (memory_write/memory_search). A cross-validator rejects skills/execute_rskill_ids passed with disagreeing ids.
  • skill(self, rskill_id: str | None) -> RSkillToolEntry | None — the entry for rskill_id, or None (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 when openral_core.rskill_matches_robot admits it (not the scaffold, kind in EXECUTE_RSKILL_KINDS, embodiment/capability/license checks) — the predicate the robot manifest's skill:* actions share (ADR-0129). A continuous detector becomes coverage only; on_demand becomes a locate_in_view option; segmenter is dropped and surfaced nowhere. Output is id-sorted for a deterministic tool schema. object_tracking (the deploy's object_tracking is not off; the reasoner node passes it) sets each entry's object_target; grasp_hand_required (several hands, no grasp_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 canonical task_space_compatible verdict against the caller's legacy_ok, returning a warning string only on disagreement (None otherwise, 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 of text in any script (_ / - split), short stopword list removed.
  • query_keywords(text) -> frozenset[str] (L190) — mission_keywords plus the RSkillAction value an everyday verb names (put → place, point → look, move → reach, …); query side only.
  • score_skill(entry, keywords) -> float (L234) — Relevance of one RSkillToolEntry: 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 narrowed palette, scores for every skill (best first, in tie-break order), query, the ids kept as sticky / focused (top operator prompt's best match) / support, the tried ids demoted among ties, and k.
  • offered(self) -> tuple[str, ...] (L290) — Offered ids in palette order (sorted for an id-only palette).
  • max_score(self) -> float (L297) — Best score; 0.0 means 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 most k slots in order: in-palette sticky ids (in flight), the best match for focus (with one skill in flight, any k ≥ 2 leaves it a slot), recent ids (last dispatch), the best SUPPORT_ACTIONS skill 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, then PRECISION_RANK of RSkillToolEntry.quantization_dtype, then rskill_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 ≤ k skills is returned as the same object; k < 1 raises ValueError.

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's timeout_s exceeds the goal's patience ceiling (then capped at the declaration's MAX_TIMEOUT_S).
  • gripper_hands — re-exported from openral_core.gripper_hands (moved there so the HAL's approach-armed grasp target groups hands without importing the reasoner; see docs/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_id set → that spatial-memory node's bbox_3d; else the single live lifted detection whose label equals ref.label (case-insensitive). The box, padded by pad_m on 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 in base_frame), becomes search_box; target_id="obj:<label or node_id>", region=None. Raises ROSReasonerInvalidPlan on no match, more than one match without object_id, an unknown node id, a missing box, a box in a frame other than base_frame (no tf2 here: a fixed-base cell's lift must run in its base frame), no gripper joint, no contact_links named 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_links is gripper_hands(...) (a bare str element is a one-link hand); an empty ref.contact_links defaults to the hand of a single-hand robot. With object_tracking (issue #418) it also carries target_queries=(ObjectQuery(ref.label, count, TARGET, hand),), count="all" when several live detections carry the label — which then grounds with search_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 its search_box unchanged (side by side). hand is a hint (openral_core.hand_joint). declared_hand (the deployment's declared grasping hand, the reasoner's grasp_contact_links from the scene's grasp declaration) is used when ref names no contact_links, under the same one-whole-hand rule; empty on a multi-hand robot, an unnamed hand is refused as before. With object_tracking a matching detection / memory node outside base_frame (the lift's map), or with no bbox_3d, grounds with no search_box (logged reasoner.grounding_seed_dropped; no tf2 in the reasoner) instead of refusing; ground_place_target the same; without tracking it still refuses. With object_tracking and ref.object_id the TARGET query's seed is that node's box padded by pad_m in the node's own frame (around its pose with no bbox_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_target never builds the scope.
  • ground_place_target(ref, *, live_objects, scene_graph, base_frame, patience_s, pad_m, object_tracking=False) -> PlaceDeclaration (L387) — The mirror of ground_grasp_target for an OPTIONAL named surface: ref.object_id / ref.place_node_id set → that spatial-memory node's bbox_3d; else the single live lifted detection whose label equals ref.label. The padded, gravity-aligned box becomes search_box (a hint the producer refuses a patch outside of); target_id="surface:<label or node_id>", region=None. Raises ROSReasonerInvalidPlan on 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 outside base_frame — the hint is optional, but a supplied one that does not ground refuses the goal (message: "the place hint could not be grounded…" + omit place_target to place on the measured surface), never a fall-back to placing anywhere. With object_tracking (issue #418) it also carries destination_query=ObjectQuery(ref.label, "one", DESTINATION), and several matches — or none (Addendum G: the standing query keeps looking) — ground with no search_box instead of refusing.
  • hand_joint — re-exported from openral_core.hand_joint (see docs/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 Isaac placement_success task via IsaacPlacementSuccess.placements_for) → one TARGET query per class (instance suffix _<n> dropped, _ read as a space — a non-class prim name such as stock_object / carton_b needs IsaacPlacement.label; placed more than once → count="all"), then at most one DESTINATION query (a fixed region such as a shelf slot gives none). Raises ROSConfigError on no placement or several destination objects. Used by openral deploy sim (_object_queries_json).
  • ground_workspace(source, destination, *, anchor_xyz, base_frame, pad_m, headroom_m, evidence_ref) -> PlaceRegion (L542) — A GraspDeclaration.workspace_box from boxes: the gravity-aligned hull of the source fixture and the destination, padded, plus headroom_m on top; an axis wider than twice MAX_WORKSPACE_HALF_EXTENT_M is cut to that window around anchor_xyz (the target). Raises ROSReasonerInvalidPlan past 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 by openral_world_state.SpatialMemory.
  • recall_object(self, query, *, now_ns) -> RecallObjectResult (L58) — Recall objects matching query (empty result = not found).
  • resolve_place(self, query, *, from_node_id=None) -> ResolvePlaceResult (L62) — Resolve a place/room/agent reference (raises ROSObjectNotInMemory on 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_ids renders a match whose approach failed grid refinement as BLOCKED instead of a pose.
  • format_resolve_place_result(reference, result) -> str (L135) — render a ResolvePlaceResult as an LLM-readable text block.
  • nav_goal_places(goals, stamp_ns=0) -> list[SpatialNode] (L279) — One declared spatial-memory PLACE node per NavGoal (node_id nav_goal:<name>, label = name, typed aliases and description), so resolve_place matches a name or alias exactly; format_resolve_place_result then gives the heading (yaw and quaternion). ContextRenderer._render_nav_goals lists the declared places one per line with their quaternion and a how-to header; ToolPalette.places_only hides recall_object when 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). found is True when recall_object had ≥1 match (even if grid-BLOCKED) or resolve_place resolved; drives the reasoner's recall→locate_in_view escalation. ambiguous: resolve_place matched several nodes (ROSObjectNotInMemory.candidates, named in text) — 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 each recall_object match's approach viewpoint; None marks 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 wires refine_approach_pose over its latched /map subscription.

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 to budget.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 refusal reason, and a reflection carrying workspace and recent observation evidence. (L172)
  • object_query_step(evidence, *, failures, max_attempts=DEFAULT_MAX_ATTEMPTS) -> ObjectQueryStep — Return recover only while the active mission task's persisted failed dispatch count (TaskState.failures, counting the goal this query fails) is below max_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), blocked until 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 as t1; a delayed result can only recover or block the mission generation that dispatched it. (L280)
  • class SearchProgress (L124) — attempt counter against a SearchBudget. 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; True while budget remains, else False.
  • 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_PATTERN compiled; prompt_correlation_id full-matches it.
  • prompt_correlation_id(metadata_json) -> str | None (L73) — The caller's correlation_id in a prompt's metadata when it is well formed (openral_core.robot_ui.CORRELATION_ID_PATTERN), else None. _on_prompt puts it on the mission the prompt starts (MissionState.correlation_id, kept by decompose_mission and across a resume, shown in reasoner.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 from source is a person's or their program's: not one of CASCADE_PROMPT_SOURCES and not the machine cascade auto. _on_prompt clears ContextRenderer.awaiting_operator on one. That field holds what the reasoner last said to its operator (an emit_prompt on OPERATOR_PROMPT_TOPIC, or _handoff_to_operator) until an operator prompt answers; each tick span carries it as reasoner.awaiting_operator and, where free text may leave the host, reasoner.operator_question (_stamp_awaiting_operator), and mission_view serves both as awaiting_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, declared SuccessCondition) 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) — Once should_rebuild_mission said 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 not new_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": true metadata (an operator reply must not silently discard the in-flight queue), or when active_succeeded_unverified and 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). With answers_question (the reasoner had asked its operator something and this is an operator prompt), a prompt without new_goal is 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_QUESTION on the completion-camera frame) whether the task is done; yes completes it, anything else settles it as task_step_without_verifier says.
  • 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: complete when the run's outcome is a judged success (judged_success: the scene's grade or a declared SuccessCondition) on the task's final_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's final_step; abandon at max_dispatches dispatches of any outcome when no reward gate will judge this result (no reward monitor, or a step), or with no reward monitor once failures reach max_attempts (a success nobody can judge is not a failure, #562); step when 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); else None. The per-skill tool schema offers final_step only on skills with completes_task_on_success, and the system prompt's approach rule tells the LLM to send the approach drive with final_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_state refuses 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) — None on 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 parsing from_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 a MemoryStore.
  • render_line(self) -> str (L62) — Render the entry as one round-trip-stable MEMORY.md line.
  • class MemoryStore (L68) — Ordered set of MemoryEntry rendered to / parsed from MEMORY.md.
  • from_markdown(cls, text) -> MemoryStore (L78) — Parse a MEMORY.md body. Unrecognized lines are ignored (lenient).
  • to_markdown(self) -> str (L113) — The full on-disk MEMORY.md (title + schema marker + sections).
  • to_context_block(self, *, cap=None) -> str (L132) — The ## MEMORY block the reasoner injects into its context; cap renders only the top-cap entries 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 explicit add/update/supersede/delete edit. Returns an entry to archive (or None).
  • 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, matching openral_prompt_router.DEFAULT_SOURCES; human sources stamp 100 so they drain first.
  • module constant _FAILURE_ADAPTER: TypeAdapter[FailureEvidence] (L122) — cached TypeAdapter(FailureEvidence) used to decode a failure buffer entry's evidence_json.
  • module constant _PERCEPTION_ADAPTER: TypeAdapter[PerceptionEventMetadata] (L123) — cached TypeAdapter(PerceptionEventMetadata) used to decode a perception buffer entry's metadata_json.
  • class FailureEventRecord (frozen dataclass) (L127) — Failure-buffer entry; fields source, kind, severity, evidence_json, rskill_id, trace_id, stamp_ns. Rendered with kind/severity names (kind=COLLISION severity=ABORT) and its age.
  • const SAFETY_STATUS_LIVENESS_S: float = 3.0 — a /openral/safety_status stamp older than this renders ## SAFETY as UNKNOWN, never "clear" (HZ-0096-1). (L90)
  • failure_kind_name(kind: int) -> str — FailureTrigger/SafetyStatus KIND_* number → name without the prefix ("KIND_<n>" if unknown), built from the openral_observability.failure_bus IDL mirror. (L112)
  • class SafetyStateRecord(BaseModel) (frozen Pydantic, extra="forbid") — Latest /openral/safety_status as the LLM sees it: latched, reason (drop_reason name, "" when clear), stamp_ns. Set via ContextRenderer.set_safety_status; rendered as ## SAFETY (clear / dropping / LATCHED / UNKNOWN). (L202)
  • class PerceptionEventRecord (frozen dataclass) (L144) — Perception-buffer entry; fields kind, text, metadata_json, stamp_ns.
  • class PromptRecord (frozen dataclass) (L154) — Operator-prompt-buffer entry; fields text, metadata_json, stamp_ns, priority=DEFAULT_PROMPT_PRIORITY. priority is filled by append_prompt from metadata_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 via ContextRenderer.set_robot_model; rendered as ## ROBOT.
  • render_playbooks_block(entries: list[tuple[str, str]]) -> str (L714) — Renders the ## PLAYBOOKS system-prompt block from (name—trigger, PLAYBOOK.md body) entries; "" when none match. Playbooks guide decisions only — every motion still goes through execute_rskill + the safety kernel.
  • class MemoryEntry / class MemoryStore (openral_reasoner.memory, own section below) — The self-maintained MEMORY.md semantic-memory model (complementary to the geometric scene graph), advisory only. Round-trips the file; renders a capped ## MEMORY context block; applies explicit add/update/supersede/delete edits; consolidates duplicates; searches the archive. Loaded at configure by reasoner_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); fields rskill_id, outcome ("ok"|"failed"|"stopped"), summary, reflection (failures only), stamp_ns, evidence_json="" (the result's FailureEvidence, rendered as an evidence=… 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 ## REWARD via set_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_out comes from the typed ExecuteRskill.Result.failure_kind when the caller has it; None falls back to a deprecated substring probe over the prose. failure_kind (an ExecuteRskill.Result FAILURE_* name) selects a kind-specific hint from _FAILURE_KIND_REFLECTIONS (stale perception → retry the same skill; config/capability → another skill; …); FAILURE_SAFETY_ESTOP picks collision-vs-other-kernel-stop-vs-operator-e-stop from evidence_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 declared SuccessCondition (success_condition) judged the run, whatever the verdict; a skill's or checker's word, none and an unreadable payload are not. Feeds asks_completion_after_budget(judged=...).
  • task_outcome_judged_success(task_outcome_json) -> bool (L514) — True when the run's TaskOutcome is a succeeded verdict judged by the scene (scene) or a declared SuccessCondition (success_condition); a skill's or checker's own "done", and an unreadable payload, are not. Feeds task_step_without_verifier(judged_success=...).
  • task_outcome_text(task_outcome_json) -> str (L564) — Issue #635: the ## EXECUTION phrase for ExecuteRskill.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 reads task_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 a KIND_GRASP_OUTCOME miss — names the hand (jaw link), the declared target and the jaw's shortfall, and points at the levers execute_rskill already has (a re-grounded grasp_target.object_id, the other hand via grasp_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 when ReasonerCore's per-kind retry ladder is exhausted for tool.
  • class ContextRenderer (L827) — Stateful renderer. ContextRenderer(*, buffer_size=8, robot_model=None, now_ns=None): with a now_ns clock every event line, the in-flight line, ## REWARD and the world-state stamp carry their age.
  • set_robot_model(self, robot_model) -> None (L953) — Sets/clears the static ## ROBOT self-model; does NOT bump seq.
  • set_memory_block(self, memory_block) -> None (L968) — Sets/clears the ## MEMORY block from the MEMORY.md store; does NOT bump seq.
  • set_mission(self, mission) -> None (L1009) — Sets/clears the active task queue rendered as ## MISSION; a new goal is an event so it DOES bump seq.
  • set_spatial_memory(self, graph) -> None (L976) — Sets/clears the spatial-memory snapshot whose OBJECT nodes render as memory_objects[<frame>]: <label> id=<node_id>@(x,y,z) size=(…) — the ids grasp_target.object_id takes; does NOT bump seq (ingest jitter).
  • set_in_view(self, objects) -> None (L1025) — Sets/clears the latest continuous-detector enumeration rendered as in_view[<camera>] in ## WORLD_STATE; bumps seq only when the rendered enumeration actually changes.
  • set_inflight_skill(self, rskill_id, *, stamp_ns=0, state='running') -> None (L1045) — Records (or clears) the in-flight execute_rskill goal with its phase ("dispatching" until accept, then "running"), rendered as the leading in_flight: line in ## EXECUTION; state changes bump seq.
  • set_inflight_feedback(self, text) -> None — Latest ExecuteRskill feedback of the in-flight goal, shown on the in_flight: line; never bumps seq; cleared when the in-flight skill changes. (L1065)
  • set_safety_status(self, status) -> None — Sets the SafetyStateRecord rendered as ## SAFETY; bumps seq when latched or reason changes or a status arrives after the last one went stale (the 1 Hz refresh of a live, unchanged state is not an event). Without a now_ns clock the section always reads UNKNOWN, never clear. (L1074)
  • safety_latched(self) -> bool — True while the last safety status was latched; read by ReasonerCore's safety_latched gate (which holds a beat only while the context is unchanged). (L1131)
  • inflight_skill(self) -> str | None (L1136) — rskill_id of the goal currently in flight, or None; also read by ReasonerCore's in-flight backstop gate.
  • inflight_state(self) -> str | None (L1141) — Phase of the in-flight goal ("dispatching" / "running"), or None.
  • note_located(self, objects) -> None (L1148) — Folds open-vocab locate_in_view hits into a sticky located[<camera>] line (latest-wins, capped) that survives the continuous detector's per-frame clobber, keeping a mislabelled goal noun grounded for decompose/dispatch; bumps seq.
  • clear_located(self) -> None (L1192) — Drops the sticky open-vocab grounding on a new operator goal; bumps seq when non-empty.
  • set_reward_state(self, reward) -> None (L1206) — Sets/clears the two-head reward assessment rendered as ## REWARD; bumps seq.
  • mission(self) -> MissionState | None (L1235) — the active MissionState, or None; 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_active the active task + activate the next, bumps seq; None when the mission is finished or unset.
  • append_failure(self, record) -> None (L1269) — pushes a failure event onto the rolling buffer; bumps seq. A GraspOutcomeEvidence payload (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 on clear_failures, advance_mission and a set_mission with a different mission object (re-setting the same one, as the subdivide path does, keeps them); capped at buffer_size.
  • append_execution(self, record, *, wake=True) -> None (L1288) — Pushes a skill execution outcome onto the rolling buffer; bumps seq so feedback wakes an idle heartbeat. wake=False records something the model already knows (what it said to the operator) without bumping seq.
  • clear_failures(self) -> None (L1347) — drops stale failure/execution context (and the open grasp misses) after /openral/estop_cleared so 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; bumps seq. A record repeating the newest one of its kind (same text) is dropped with no seq bump (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; bumps seq.
  • forget_conversation(self, *, keep=None) -> None (L1318) — Drop the previous goal's operator exchange when a new goal replaces it (#661): every queued prompt but keep, the (emit_prompt) lines in ## EXECUTION, and awaiting_operator. Skill outcomes and failures stay.
  • render(self, *, world_state) -> str (L1407) — Returns the deterministic text snapshot for one LLM tick. ## WORLD_STATE covers joint_state/ee_poses/battery/diagnostics plus a 3D scene_objects[<frame>] line (one entry per instance — label, centre, size, track — never deduped by label; a repeated_labels: line flags labels a bare name cannot ground), the memory_objects[<frame>] node-id line, and a depth-free, pixel-space in_view[<camera>] line (so grounding still works with RGB-only / no octomap); note_located hits render as a sticky located[<camera>] line distinct from in_view. ## REWARD (when set) carries both reward heads distinctly labelled so the LLM never blurs progress (persist-vs-replan) with success (done-ness). ## WORLD_STATE also renders base_pose and a holding: line from attached_objects (released ones, released_by_link set, excluded); ## SAFETY sits before ## REWARD once 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 counter ReasonerCore uses to short-circuit a heartbeat tick when nothing has changed since the last successful tick.
  • refresh_clock_state(self) -> None — Folds time-dependent context into seq: a safety status crossing SAFETY_STATUS_LIVENESS_S either way bumps it. ReasonerCore.prepare_tick calls it once per tick before its gates and the render; ## SAFETY renders the freshness evaluated here, so reading seq or rendering never changes the renderer. (L1094)
  • drain_prompts(self, *, seen=None) -> tuple[PromptRecord, ...] (L1819) — Pull-once, priority-desc + arrival-asc order; does NOT bump seq. seen drains 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_json drops 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_json drops 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's base_frame (the kernel's grid frame, never the map), or robot base frame (_UNKNOWN_BASE_FRAME) when no manifest is loaded. Wire/schema names are unchanged.
  • _decode_evidence(payload) -> FailureEvidence | None (L1964) — Decode a FailureTrigger.evidence_json through the union; None for an empty or rejected payload (the failure line still shows it raw). Used by append_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_FIELDS or past the _PROMPT_FIELD_BUDGET backstop 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_KEYS so the reasoner reads them as base-frame, not map, positions. (L1978)
  • _extract_priority(metadata_json) -> int — Parse a top-level priority field out of a PromptStamped's metadata; returns DEFAULT_PROMPT_PRIORITY on 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; fields tool_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's PreparedTick.trigger, "" when suppressed before the LLM), traceparent (None when no real TracerProvider is 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_S without a budget. (L145)
  • _call_identity(call) -> str — Canonical retry-cap identity of a tool call: the full argument payload minus rationale (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 between prepare_tick and finish_tick: LLM inputs (context_text, palette, system_prompt) plus prepare-time snapshots (started, seq, prompts, an unattached OTel span, renderer, force, tier, trigger, coalesced). The seq/prompts snapshots bound finish_tick to only what the model actually saw. llm_s/prompt_tokens are 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 (see ReasonerCore below).
  • class ReasonerCore (L253) — Orchestrator.
  • max_skill_tools(self) -> int | None (L386) — the configured per-tick skill-tool cap, or None (read-only).
  • llm_gave_up(self) -> bool — True once every LLM_ERROR_BACKOFF_S retry 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 active wait, or None. (L381)
  • offered_palette(self, palette, renderer) -> ToolPalette (L390) — The palette the LLM sees this tick: palette narrowed by select_skill_subset to max_skill_tools skills, 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 is sticky; the newest prompt of the top-priority band is the focus (offered on the tick it arrives, before finish_tick drains it); the task's last dispatched skill is recent (outside a mission, the last ExecuteRskillTool this core returned); the task's tried_rskill_ids are 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 logs reasoner.skill_subset (query, every score, kept and tried ids, max_score); with a cap set, prepare_tick stamps reasoner.offered_skills on every tick span (absent without a cap). Without a cap, returns palette unchanged.
  • 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 + wait are exempt); short-circuits on a finished mission or idle heartbeat. force=True bypasses every gate but the retry cap. Wraps the tick in a reasoner.tick OTel 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 any wait. A timer beat reaches the LLM only as llm_error_retry, wait_timeout, backstop (skill in flight, inflight_backstop_s since the last call) or context_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 blocking select_tool round-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. A WaitTool arms the wait hold (reasoner.wait.* on the span); a transport ROSPlanningError leaves the context unseen and arms the LLM_ERROR_BACKOFF_S retry (marked seen once they run out); ROSReasonerInvalidPlan marks 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; raises ValueError on stall_patience < 1 or min_delta < 0. Fires one CriticEvidence in two mutually exclusive, one-shot-per-streak cases: success (score crosses threshold) or stall (stall_patience consecutive 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 one CriticWatchdog per critic_id so several reward models share the /openral/failure/critic source 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 per critic_id (threshold bound on first sight) and delegates.
  • known_critics(self) -> frozenset[str] (L328) — Return the critic_id set 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_action plus the estop latch/reset pair and the SafetyStatus topic. Refuses (nonfinite) a candidate whose flat holds 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/estop on an envelope violation; drops silently while already latched; otherwise forwards unchanged on /openral/safe_action. Emits a safety.check OTel span per candidate.
  • _envelope_violation(msg) -> tuple[str | None, str] (L465) — Dispatches on control_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, publishes std_msgs/Empty on /openral/estop, and updates the latched SafetyStatus.
  • _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 once estop_reset_cooldown_s (default 0.5 s) has elapsed since the last estop.
  • SafetySupervisorNode (L873) — Back-compat alias of SafetyPassthroughNode, 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.stamp is 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 for ros2 run openral_safety supervisor_node.
  • module constant _KERNEL_LABEL_PASSTHROUGH: str = "passthrough" (L57) — safety.kernel span/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_violation can 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_reset enforces 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 — With world_voxel_enabled, on_configure returns FAILURE for a world_voxel_deadline_ms outside (0, 2000] or a world_voxel_data_age_budget_ms outside (0, 3000]; the budget defaults to 1500 and 0 does not disable it. Deliberate mirror of DeployRuntime's caps, pinned by tests/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-dof joint_external_torque_max (0 = unmonitored). on_configure returns 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_states message 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); diagnostics force_observer / force_peak_ratio. /openral/estop_reset restarts the estimate.
  • Workspace contact params (#349) — workspace_contact_enabled (default false; requires grasp_allowance_enabled), workspace_contact_links (each a collision link, non-empty), workspace_contact_max_speed_mps and workspace_contact_control_period_s (finite > 0), workspace_contact_max_lead_m (finite, > 0, ≤ kMaxWorkspaceContactLeadM), workspace_contact_jaw_joints (each a collision_joint_names entry; 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_hold keeps up to kWorkspaceHoldMaxRows rows on every accept and hold, whoever owns the rules; workspace_hold_q returns the last row due at or before now, never a later one), usable until kWorkspaceHoldFreshPeriods periods 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, WARN safety.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_configure returns FAILURE otherwise and WARNs the rule (both bounds, the freshness window) when on. The node ingests GraspDeclaration.workspace_region next 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_summary on 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_states velocity at most collision_state_deadline_ms old — on_joint_state stores it per dof in dq_meas_, a message naming a joint without one forgets it; then workspace_hand_speed of 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 of link_displacement_bound(prev row, row) / period; row 0's previous row is, per commanded joint, its previously accepted command while workspace_command_fresh — held, due ≤ kWorkspaceCommandFreshPeriods periods 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 of link_displacement_bound(measured, row) with the jaw joints held at measured, not divided by the period); unknown → +inf for 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. WARNs safety.workspace_contact (speed + speed_source=measured|commanded, and lead) ≤ 1 Hz per link, and adds workspace_gate_active= (the stop line's key; the FailureTrigger's workspace_contact_active stays 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, which workspace_gate_active= and workspace_denied= then report too) to safety.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_m span attributes and max speed (+ max_speed_source) + max lead to safety.workspace_contact_summary.
  • kMaxRegionMeasurementAgeS = 4.0 (2 × kMaxWorldVoxelDeadlineMs) — Cap on grasp_region_max_age_s / place_region_max_age_s, how old a producer-measured region's stamp_ns may be and still exempt anything. 0 (default) resolves to 2 × world_voxel_deadline_ms; on_configure returns 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_dofs non-empty): node params station_motion_translation_m / station_motion_rotation_rad (defaults the two kDefault*; on_configure returns FAILURE outside (0, cap]; the shipped launch files pass neither, so deployments run the defaults). update_station(now_ns) (each /joint_states tick) 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 stamps base_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 reason clock_reset. note_station_allowances() re-anchors at the measured base pose when an allowance goes live after none was (station_allowance_live(), anchor_station()). Logs safety.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_enabled only as contact_exemptions.tracked_grasp_exemption_enabled, and only with a provider). The open kernel keeps tracked_grasp_extra_contact_links (default empty: fixed jaws on a body link, OT-6 amendment 2026-10-17): with an exemption_provider the resolved links join the provider's hands (CandidateView::hands); on_configure returns FAILURE when a name is no collision link or when no provider reads it.
  • Tracked binding check (#418 K3) — a tracked_object attachment 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. A TrackedObject.provisional track fails closed here (never payload binding geometry) while staying K2-eligible.
  • Producer-declared release (2026-11-02) — an attachment whose released_by_link is set (the HAL's and the tracker's freeze_released_attachment): ingest_attached_objects refuses an unknown link (kUnknownLink, fail closed) and the node resolves it into its own attached_released_by_ (node-side, so the provider-visible AttachedObject layout 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 (before apply_tracked_release) freezes it in the base frame (attach_link = -1, so never world-checked; no support witness; K3 off_hand=released) and runs the K5 window keyed on (object id, epoch, stamp): the releasing link as release_hand_link and the touch links exempt until released_payload_clearance > tracked_release_clear_m (fresh measured state) or tracked_release_timeout_s, then touch_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_configure returns 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_enabled is the exemption provider's (contact_exemptions.workspace_explained_cells_enabled). The open kernel keeps static_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 by kExplainedStaticPadCells), only on the base frame's own lattice; handed to the provider as CandidateView::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 not UNCONFIGURED or once params_locked_ (set by on_cleanup and by a configure that does not succeed) is true; launch overrides and new declarations (an exemption provider's own parameters, declared in initialize during CONFIGURING) pass — pinned by ExemptionProviderKernelTest.AProviderDeclaresItsParametersUnderTheRealStateMachine. Pinned by LifecycleKernelTest.SafetyLimitParametersAreRefusedAfterConfigure (over the real /set_parameters service). See docs/reference/ros-graph-security.md.

  • Exemption provider params (ADR-0121) — exemption_provider (default "": none, today's verdicts) names a pluginlib class deriving ExemptionProvider; exemption_provider_links (the launch passes RobotDescription.hand_links()) is the kernel's own relaxable-link mask. load_exemption_provider runs at configure after the collision model and never fails configure: off hal_mode: sim, an empty mask, a link the model does not know, a pluginlib load failure, an api_version other than kExemptionProviderApiVersion, or initialize returning false / throwing all leave the kernel with no provider, ERROR safety.exemption_provider refused, and /diagnostics exemption_provider=refused: <why>. Loaded: WARN safety.exemption_provider loaded, /diagnostics exemption_provider=loaded: <name> and exemption_provider_pairs; per candidate the node fills a preallocated CandidateView (tracked set after K1 without K6-retired identities, measured state when fresh) and calls begin_candidate; tolerated pairs WARN safety.exemption_provider_contact ≤ 1 Hz and set span attribute safety.exemption_provider_pairs. The provider's DeclarationView::hands are built by build_grasp_hands: grasp_contact_links plus the resolved tracked_grasp_extra_contact_links. With a provider, deploy_e2e hands 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 under contact_exemptions., so the in-tree rules and the provider never both decide; without a provider those params are not emitted at all. on_cleanup unloads 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_candidate and on_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, on workspace_contact_config, which replaces brake_config), TrackedObjectView::confirmed_fresh, and the per-binding ReleaseMemory in ReleaseQuery::memory.
  • enum class ProviderVerdict { kRefuse, kTolerate } — Anything but kTolerate keeps 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 own cover_ok, visible_cells, confirmed_ns, confirmed_fresh (API v5: the kernel's region_measurement_fresh on confirmed_ns against grasp_region_max_age_s), support_z / floor_z, the validated box.
  • 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-ingested grasp_region / workspace (null when not live) and the hands built from grasp_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 its declaration_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_model and 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-frame cell_center_base, the open distance, the checked row and its FK.
  • Every pair query also quotes the kernel's own #349 measurement of the row: hand_speed_mps, raw hand_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_exempts on ProviderGate::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. CandidateView also has tracked_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_index into CandidateView::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_model points 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, binding object_id_hash / epoch, attach link, on_hand = the K3 verdict, measured q, the tracked views, and memory: that binding's ReleaseMemory, kernel-owned in BoundPayload, 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 to payload_self_pair on the hand that let it go.
  • class ExemptionProvider — hold_cover(query) / release_payload(query) noexcept (API v3, default kRefuse; the kernel performs any hold or freeze inside its own bounds), workspace_contact_config() const noexcept (API v5, replaces v3's brake_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 (default kRefuse). 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 measured hand_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 to check_self_collision / check_attached_self_collision (gate parameter, 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, Coulomb tanh scale; built once at configure.
  • struct ForceObserverState — pre-sized RNEA scratch, M, previous M/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 or dt_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 also provider_pairs / provider_link / provider_cell / provider_min_distance: disclosure of the pairs the loaded exemption provider tolerated, never a decision. Since #349 also workspace_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_distance name the single deepest tripped pair; sweep_min_distance is the separate sweep-wide minimum and never supplies the evidence distance. advisory is 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.0 and 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 voxel resolution: min(1.5 × voxel, 4 cm), 0.0 for 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, or 0.0. Returns the reduction only when the region is valid, the object is in object_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-kOk value means no allowance.
  • ingest_place_region(pose, half_extents, object_mask, out) -> PlaceRegionStatus — Validate a producer-supplied region into out, 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 empty object_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-validated region, so a payload can be adjudicated against the modelled receptacle instead of its voxel quantisation. Call only after the box validates; anything but kOk resets the whole region. store must be sized to kMaxPlaceTargetPrimitives (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; +infinity when 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 a PlaceRegionStatus, used as the reason= key of the node's place-region log lines. Never null.
  • support_contact_exempts(object, object_xf, center, resolution, slack) -> bool — Whether object i'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 by support_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 in snapshot_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 inline bool snapshot overload 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 bit from[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, one stride-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.0 for an unusable resolution, collapsing to today's latched stop.
  • link_joint_value(model, i, q) -> double / link_joint_gain(model, i, q) -> double — Link i's joint value for column value q: through its calibration curve (CollisionModel::curve_point_first / _count / curve_points, the collision_curve_* params; clamped at the ends) and then mimic_multiplier * u + mimic_offset for a mimic link; its derivative (segment slope, 0 where it clamps, times the mimic multiplier). forward_kinematics and the force observer pose / differentiate every link through them (#533). Allocation-free.
  • check_self_collision(model, scratch, margin, workspace = nullptr) -> CollisionHit — #349: with a live WorkspaceContactRegion, 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_slow on both); counted in workspace_pairs, at its own depth in sweep_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, and narrow_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 (nullptr otherwise).
  • check_voxel_collision(model, scratch, grid, margin) -> CollisionHit — Checks every FK'd robot primitive against the occupied cells of a dense voxel grid. 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 in grid.provider_links is offered to grid.provider (VoxelPairQuery; capsules before, boxes after the narrow phase) and, on kTolerate, does not trip, is counted in provider_pairs and reaches sweep_min_distance at its own depth; no provider, an unmasked link, a clear pair or an open-exempt pair is never offered. Never sets advisory — 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: while grid.grasp_region is valid, a mask link vs a cell centred in its box does not trip and reaches sweep_min_distance only, 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-frame pose, half_extents, plus lifecycle bookkeeping handover/object_index the geometry never reads. Invalid by default — no exemption anywhere; armed only by the lifecycle node with grasp_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::hash of target_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-kOk value means no exemption.
  • ingest_grasp_region(pose, half_extents, link_mask, out) -> GraspRegionStatus — Validate a grasp region into out, 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 at center (base frame): valid region, link in the mask, finite non-degenerate box, centre inside it (the exact point-in-OBB test place_approach_allowance uses). Allocation-free.
  • grasp_region_contains(region, p) -> bool — Whether base-frame point p is inside a valid grasp region's box (the containment half of grasp_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 a GraspRegionStatus, for the reason= key of grasp-region log lines. Never null.
  • kMaxTrackedObjects = 32, kMaxTrackedHullVertices = 64 — Issue #418 K1 caps on the tracker's TrackedObjectSet as the kernel ingests it (mirror TrackedObjectSet.objects max_length=32 and 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 within slack (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 into scratch (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 between object'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 into scratch; +inf when no exempt link has geometry. An AttachedObject with attach_link == -1 is frozen in the base frame (pose_in_link is 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 and VoxelGrid::tracked_grasp were 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 (the grasp_links_one_hand grouping) 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 than kMaxGraspHands mounts, 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 as cover_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)), visible the tracker's TrackedObject.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 (wire AttachedCollisionPrimitive.geometry_source); anything unknown or unset is kFallback.
  • 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 (and PayloadOwnCells, 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 passes kExplainedStaticPadCells = 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): clears mask and marks every cell of grid holding a point — the octomap bridge's mark_base_points indexing (see docs/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-link link_mask (std::bitset<kMaxGraspMaskLinks>), base-frame pose, half_extents, plus hand_speed_mps (the checked row's commanded hand speed bound, set by the lifecycle per row; +inf = unknown) and max_speed_mps, hand_lead_m (the checked row's lead over the measured pose; +inf = unknown) and max_lead_m. Invalid by default — no exemption; armed only by the lifecycle node with workspace_contact_enabled.
  • kMaxWorkspaceRegionHalfExtentM = 0.50, kMaxWorkspaceRegionVolumeM3 = 0.25 — Safety-WG placeholder caps on a workspace (one tote interior or shelf slot); mirror GraspDeclaration.MAX_WORKSPACE_HALF_EXTENT_M / MAX_WORKSPACE_VOLUME_M3.
  • kMaxWorkspaceContactLeadM = 0.10 — Safety-WG placeholder ceiling on workspace_contact_max_lead_m; mirrors the le=0.10 bound on DeployRuntime.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 at center (base frame): valid workspace, link in the hand mask, a finite hand speed ≤ a finite positive max_speed_mps and a finite hand lead ≤ a finite positive max_lead_m, finite non-degenerate box, centre inside it (exact point-in-OBB). check_voxel_collision asks it only of pairs the ADR-0115 grasp region did not exempt (precedence), and check_attached_voxel_collision of 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 a WorkspaceContactRegion directly (workspace_contact_exempts is it on grid.workspace_region); API v5's workspace_exempt quoted to an exemption provider is this on ProviderGate::workspace. Allocation-free.
  • ingest_workspace_region(pose, half_extents, link_mask, max_speed_mps, max_lead_m, out) -> GraspRegionStatus — Validate a confirmed workspace into out (the grasp-region geometry checks against the workspace caps); hand_speed_mps and hand_lead_m start 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); +inf on 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 within reach of a link origin moves between two poses: |Δt| + θ·reach (θ the relative rotation angle); +inf on non-finite input. Allocation-free.
  • kDopAxes / kDopAxis[kDopAxes][3] — The 26-DOP's 13 unit axis directions (3 face, 4 corner, 6 edge; each a lo/hi slab) in the owning OBB's local frame; the first three are the box's own axes. Mirrored in Python as openral_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 as MAX_TIGHT_HULL_VERTICES.
  • kTightContainmentEpsilonM = 1e-9 — Floating-point slack validate_tight_geometry allows checking a stage-2 vertex against its own DOP slabs (tangent by construction). The DOP-inside-OBB check itself takes no slack. Mirrored as TIGHT_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 one check_voxel_collision call across every link; past it the check keeps refining with stage 1 and the shipped box_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 ONE Obb in CollisionModel::boxes, in that box's local frame. Fields: dop_lo/dop_hi (stage 1, always on) and vertex_first/vertex_count (stage 2, CSR offset into hull_vertices; vertex_count == 0 means stage 1 only).
  • enum class JointKind / is_mimic(kind) — kFixed, kRevolute, kPrismatic, and since #349 kMimicRevolute / kMimicPrismatic: a link posed from ANOTHER joint's column (dof_index is the mimicked joint's) at mimic_multiplier * q + mimic_offset — the URDF <mimic> relation, the OpenArm's follower finger. No qpos slot, no Jacobian column (jacobian_dls_step skips 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 three CollisionModel members carrying tight geometry: box_hull (parallel to boxes) indexes into hulls for the tight representation refining that box, -1 for none. An empty box_hull means 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 by ingest_attached_objects without 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 — Why validate_tight_geometry refused a model: kOk, kBadArity, kEscapesBox, kHullEscapesDop, kTooManyVertices, kDegenerate. Anything but kOk is 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, keeping check_voxel_collision's broad-phase reach correct. offending_box receives the offending index on refusal. Not on the hot path; allocation-free.
  • tight_geometry_status_reason(status) -> const char* — Stable snake_case token naming a TightGeometryStatus, 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's CollisionModel; 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 == 0 is 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_collision calls it for an OBB pair within margin when both links ship a stage-2 hull; the OBB stays the broad phase and fallback, so a manifest without tight_geometry is 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 clearing margin (its result is the reported sweep_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 explicit DeployScene.safety fields to the robot ceiling with tighten-only validation; omitted fields keep robot manifest values. max_external_joint_torque_nm merges per joint (union, tighter value), so a deploy scene can never drop a robot ceiling (#373).
  • class EnvelopeIntersection (L62) — The numerical product of robot.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 from gripper_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}: a MimicJoint edge'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. Raises ROSConfigError unless 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 with tight_geometry also lowers the staged-narrow-phase DOP/hull arrays. A mimic_joints edge lowers to collision_joint_kind 3/4 on the mimicked joint's column plus the per-link collision_mimic_multiplier / collision_mimic_offset arrays (#349), and ends with with_joint_curves.
  • with_joint_curves(params, robot) -> dict[str, object] (L1059) — params plus collision_curve_point_first / _count / collision_curve_points for every link whose collision_dof_index column is a joint with a JointSpec.urdf_curve (the kernel and the self-filter pose it at curve(q), a mimic at multiplier * 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's force_observer_* params, parallel to the collision links (joint terms describe the joint into each link; fixed / mimic edges get zeros). Emitted by collision_params_from_description when robot.force_observer is 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; -1 when 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 from armature / 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) — MJCF geom_type enum values lower_collision_params reads 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 compiled mujoco.MjModel to the kernel's collision params: per-link origins, every collidable primitive as a capsule, dof_index assigned 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 for box_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. <= 0 means 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 with half_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 of shape lies 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 contains shape, for consumers (today only cumotion_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 an eps_m ball; None when 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 declared headroom_m. Containment holds for every candidate axis by construction. Returns the shape + link-frame origin.
  • LinkFit (L476) — Frozen dataclass: one link's fitted primitives ((shape, origin) list), the winning kind (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)}) and fitted (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's trimesh.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_FRACTION going to the cheaper kernel kind (capsule < fewer capsules < box); excess volume and max protrusion are reported per candidate. force_box for a link that will carry tight_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 the tight_geometry derived in that rendered frame (tight_geometry.tight_geometry_for_box), so mesh ⊆ hull ⊆ DOP ⊆ box holds for the box the kernel loads. What --tight-link and a manifest-refined link lower to.
  • module constant _RENDER_DP: int = 4 (L603) — the precision fit_link_with_tight_geometry rounds the box to before deriving its refinement (mirrors openral_cli.collision._BLOCK_FLOAT_DP).
  • _rendered(shape, origin) -> tuple[CollisionShape, origin] (L652) — A primitive rounded to the manifest's 4 dp; _fit_link returns 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_pieces searches 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 set slice_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) — The k - 1 of n grid planes minimising the summed slab_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 = inf when every cover has a degenerate slab.
  • _split_tight_pieces(link_name, mesh, k) -> list[LinkCollisionGeometry] (L747) — A link as k slabs along its capsule axis, each fit_link_with_tight_geometry (box + DOP + exact hull): the cut planes are the _SPLIT_GRID_M grid positions _best_cuts picks for the least total hull volume, so a re-lower reproduces them from the mesh alone; slabs are cut as _capsule_chain cuts, 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). Raises ROSConfigError when k leaves no grid position or a slab is degenerate.
  • _as_tight_links(tight) -> dict[str, int] (L831) — {link: pieces} from either spelling of tight_links (a mapping, or bare names = one piece each). Raises ROSConfigError for 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_geometry for a link tight_links maps to 1, _split_tight_pieces for k > 1, else fit_link_primitives at 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) plus extra, the larger count winning — sticky, so collision check reproduces 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_robot folds 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, mujoco is 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 when extra_meshes carries twin CAD for it), fitted by fit_link_primitives to 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 in tight_links (names, or {link: pieces}) lowers to fit_link_with_tight_geometry instead, in k slabs when mapped to k > 1. sweeps ({link: (x, y, z)}, from FixedAttachment.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_sweeps refuses a swept link that carries other links (they ride the travel uncovered). Raises ROSConfigError when 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_colliding cost 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 for lower_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_attachments links and mimic_joints followers (the producers name followers as touch links).
  • _check_mimic_frames(robot, urdf_ref, lowered) -> None [private] — lower_robot refuses (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 a fixed_attachments row 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 from parent down to child, or None when 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-colliding from 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_handler plus package:// refs through openral_core.assets.resolve_package_uri, raising ROSConfigError on one that does not resolve; for STATIC links only, never installed in _load_urdf (resolving the openarm arm meshes would flip select_lowering off 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 same sim_joint_name (or name); fit_collision_geometry_from_mjcf unions it into the link's fit. Raises ROSConfigError when 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 missed openarm_description's link6 by 10.6-13 mm. Also unions the URDF geometry of every fixed_attachments child the MJCF maps a body for, after _check_attachment_rows validates the rows.
  • _static_link_meshes(robot, link_body, manifest_dir) -> dict[str, Trimesh] (L1781) — Geometry of every static link — a fixed_attachments child 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 raises ROSConfigError; 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 link fixed_attachments reach 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_TOL raise ROSConfigError.
  • 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 by child_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. bimanual openarm): fits the geometry with fit_collision_geometry_from_mjcf (kept from the manifest under acm_only, as lower_robot keeps 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_world at every sample (it follows its parent, which may move), is adjacent to its fixed_attachments parent, and is in scope so an SRDF row naming it survives. A manifest assets.srdf is 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 whose fixed_attachments declare sweep_xyz (only the URDF fit covers a sweep). acm_source="mjcf".
  • module constant _MOVABLE_JOINT_TYPES: tuple[str, ...] (L1283) — ("revolute", "continuous", "prismatic"), joint types lower_joint_fk/acm_for_geometry treat 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; threads robot.safety.self_collision_margin_m into acm_for_geometry so the ACM matches the kernel's live threshold. Geometry is scoped to the joint links plus every fixed_attachments and mimic_joints link (a mimic follower is a touch link the kernel must know), so a URDF body link the kernel should see is one fixed_attachments row away. ACM source precedence: explicit srdf_path → manifest assets.srdf → URDF-only fallback. Raises ROSConfigError on 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, or openamrobot_v2's URDF whose base_link resolves only partly — a URDF lower_link_geometry would refuse is not usable for routing). Raises ROSConfigError when no lowerable asset exists.
  • lower_robot_auto(robot, *, acm_only=False, geometry_only=False, manifest_dir=None, tight_links=None) -> LoweredCollisionModel (L3237) — Single dispatch over select_lowering → lower_robot or lower_robot_from_mjcf (acm_only keeps the manifest geometry on both paths; tight_links adds 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. Raises ROSConfigError when a tight_links name matches no lowered link (a typo must not leave a link silently unrefined), and when tight_links is combined with acm_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_bounds over the hull), half-extents re-measured from the cloud in that frame and grown by headroom_m; every vertex inside by construction.
  • module constant _MJCF_STROKE_SAMPLES: int = 9 (L1191) — leader positions fit_collision_geometry_from_mjcf sweeps 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 drives obj1). Raises ROSConfigError on a non-linear or non-invertible coupling.
  • twin_coupled_joints(robot, model) -> dict[int, list[tuple[int, float, float]]] (L2370) — mjcf_coupled_joints plus 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) — robot with each sim.grippers[] entry in normalised write mode that declares no urdf_curve given the twin's own stroke as its curve, ((0, lo), (1, hi)) over ctrl_range (_manifest_to_mjcf_affine, actuator checked 1:1; the MJCF joint by sim_joint_name, else name, else the one its actuator drives). The deploy launch passes it to with_joint_curves when it keeps the MJCF lowering, which otherwise posed the gripper link straight from the [0, 1] column: WidowX's left_finger slide 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. ROSConfigError when 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 as mimic_joints (compared through the leader's urdf_curve at its breakpoints, #533), each checked to be an equality follower of its mimics joint — or that joint itself — with the SAME multiplier/offset in the manifest channel's units (ROSConfigError otherwise; a normalised gripper converts through _manifest_to_mjcf_affine); fit_collision_geometry_from_mjcf leaves 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 a sim.grippers[] command to, resolved as MujocoTwinHAL does: the gripper's actuator_index, else the joint's sim.actuator_index entry, else its position in joints; -1 when the map omits it, which _manifest_to_mjcf_affine refuses 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·v for manifest value v: identity, or lo + (hi - lo)·v over ctrl_range for a write_mode: normalised sim.grippers[] entry, whose actuator (_gripper_actuator) must exist and be a gear-1 joint transmission on the leader (ROSConfigError otherwise).
  • fit_collision_geometry_from_mjcf(robot, *, manifest_dir=None, stroke_samples=9, tight_links=()) -> list[LinkCollisionGeometry] (L2481) — fit_link_primitives per 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 over stroke_samples leader 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 (a fixed_attachments child with no MJCF body) is fitted from the URDF via _static_link_meshes with the same fitter and tight_links rule. Pinned by tests/unit/test_collision_geometry_enclosure.py (twin meshes) and tests/unit/test_collision_geometry_urdf_enclosure.py (URDF meshes). A follower the manifest declares in mimic_joints is 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 logical finger_pair gets none). Fits every joint link, mimic follower and fixed_attachments child the MJCF maps a body to; _static_link_meshes covers the unmapped fixed children.
  • LoweringSource — Literal["srdf", "sampling", "mjcf"]; the source select_lowering resolves to (matches LoweredCollisionModel.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 a StaticGeometry YAML; returns it and its directory; ROSConfigError on a missing / non-YAML / invalid file.
  • surface_points(geometry, base_dir, spacing_m) -> NDArray (L76) — Every declared surface (box faces, mesh triangles) sampled at most spacing_m apart, (N, 3) base frame; each surface point lies within spacing_m of a sample. ROSConfigError on spacing ≤ 0 or a missing/malformed mesh.
  • write_points_file(points, path) -> None (L129) — The octomap bridge's static_points_file format: one x y z per 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 the MAX_TIGHT_HULL_VERTICES budget (refine_dop_to_budget) when it is over; a mapping for TightCollisionGeometry plus reviewer diagnostics.
  • refine_dop_to_budget(points, dop_lo, dop_hi, budget) -> Points (L187) — A ≤budget-vertex envelope built only from tangent planes of conv(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 types actuated_joint_names counts 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) — Sample count spheres evenly along the segment p0→p1 (endpoints inclusive for count >= 2; midpoint for count == 1).
  • spheres_for_capsule(shape) -> int (L110) — Sphere count to tile a lowered primitive with centres ≤ one radius apart; 1 for a sphere / zero-length capsule. Also accepts a BoxShape.
  • link_collision_spheres(geom, *, count=None) -> list[CuMotionSphere] (L134) — Lower one LinkCollisionGeometry (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 cuRobo cspace.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 cuRobo robot_cfg YAML fragment with a generated-provenance header. Spheres come from robot.collision_geometry (falling back to model.collision_geometry only when the manifest carries none). The ACM is not copied verbatim: given urdf_path it is widened with pairs proven always-colliding for the sphere model, so the planner stays looser than the kernel, never tighter. Without urdf_path the 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, and nav_goals_json (ADR-0133, repeated names refused): the memory, whether detections are ingested (writable), and places_only when 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 (or None), writable, places_only, origin, warnings.
  • module constants _FAILURE_SOURCES, _PERCEPTION_KINDS — closed sets: hal/sensor/rskill/safety/wam/critic and motion/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_slow subscription 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/prompt publisher/subscription QoS.
  • module constant _QOS_MAP (L318) — KEEP_LAST=1, RELIABLE, TRANSIENT_LOCAL, the latched /map subscription 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 for openral_msgs/FailureTrigger, kept inline (not the failure_bus helper) 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 ms wait_for_server / wait_for_service probes 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 active RewardContract sets no frame_window_s.
  • module constant _DEFAULT_SUCCESS_THRESHOLD: float = 0.8 (L366) — fallback reward-gate success_threshold when no RewardContract is loaded.
  • module constant _DEFAULT_CHECK_FLOOR: float = 0.5 (L367) — fallback reward-gate check_floor when no RewardContract is 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 stamp reasoner.tier on the OTel span; the preemption threshold itself is decided inline in _on_failure.
  • (the hal_mode == "sim" gate imports the canonical openral_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. Reads action_contract by specificity, from None (no constraint) down through representation/slots/legacy dim.
  • def _action_executable(manifest: RSkillManifest, description: RobotDescription, hal_mode: str) -> bool (L496) — Pure helper: True when every _required_control_modes(manifest) is in the executable set for hal_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's obs["state"] selection. A reads_world_state_policy_state skill needs a /openral/policy_state publisher 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 its dim is 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 declared dim must equal n_joints ("admit" / "dim_mismatch"; unset dim = the joint vector). Issue #474.
  • type alias _StateContractVerdict (L529) — Literal of 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 sets use_world_state_policy_state (the HAL advertises /openral/policy_state lazily, destroys it on deactivate, and autostarts independently of the reasoner). Every _POLICY_STATE_WATCH_S it 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_paths when it appeared or disappeared, so a skill is admitted once the topic is live and dropped again when it goes. Cancelled on on_cleanup and whenever a seed matches no such skill.
  • def _resets_search_episode(call) -> bool (L587) — Pure helper for the find→re-prompt cascade bound. True when dispatching call ends the active-search episode; False for 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 for ExecuteRskillTool.prompt and for a blank QueryTaskProgressTool.task (which the reward monitor would otherwise resolve to its launch-time task parameter). _on_query_task_progress_response drops a reply that lands after the active task instance changed: same mission object, same task id and text, as _on_mission_verify_response and _on_vlm_completion_verdict now also require (a re-sent identical goal builds a new mission whose t1 matches by id and text).
  • class ReasonerNode(LifecycleNode) (L875) — Lifecycle node wrapping ReasonerCore. Optional injected spatial_memory enables the recall/resolve tools; otherwise spatial_memory_path/spatial_memory_ingest params can load or build one. memory_md_path enables the memory tools. hal_mode selects the action-mode palette gate; tick_hz (default 0.2 Hz) is the heartbeat rate. With manifest_runtime_json (the deploy's resolved DeployRuntime), manifest_bridge_on and manifest_unit_serial set 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 a role: gripper joint an unset value fails on_configure with ROSConfigError, once, instead of a per-call ROSReasonerInvalidPlan the LLM would burn its replanning ladder on, so no cell-specific fallback pads it; a gripperless manifest needs none; deploy_e2e passes _octomap_resolution(hal_mode), the resolution octomap_server gets) and grasp_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 of on_configure (a load failure warns and a named target is then refused; a gripper manifest without the voxel raises ROSConfigError → configure FAILURE); no robot unit and no cell geometry are read. _ground_targets(call) -> (grasp, place) runs in _dispatch_execute_rskill before any latch: openral_reasoner.grounding over the latest /openral/world_state_slow detected_objects (bbox now on the wire) and the spatial-memory scene graph; a ROSReasonerInvalidPlan is logged, recorded as a failed execution with a disambiguation hint, and NO goal is sent. _send_execute_rskill_goal fills grasp_declaration_valid/grasp_declaration and place_declaration_valid/place_declaration for the matching dispatch generation; the runner stamps, attributes and strips any region as before. Param object_tracking ("off"; issue #418, the deploy's DeployRuntime.object_tracking): not "off" → both groundings run with object_tracking=True (the grasp query hinted with openral_core.hand_joint of the grounded contact links), and the goal's grasp declaration is encoded with query_factory=openral_msgs/ObjectQuery.
  • _submit_client_warmup(client) -> None — At on_configure, kicks a managed LLM sidecar's boot onto _llm_pool instead of leaving it to the first tick, off the executor thread so the lifecycle transition returns promptly. No-op for clients without warm(); a failure here only warns, since select_tool's lazy path still owns whether the server is usable.
  • on_configure(self, state) -> TransitionCallbackReturn (L1432) — Build ToolUseClient from env if not injected, attach subscribers to world-state/failure/perception/prompt/registry topics, create the prompt/failure publishers + execute_rskill action client. Reads vram_lifecycle_peers (GPU peers auto-deactivated around each execute_rskill) and vram_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 the tick_hz ROS parameter (declared with the constructor's tick_hz as 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 the reasoner-llm / reasoner-vlm worker pools (no wait; an in-flight provider call is not interruptible) and detaches + destroys the executor-inbox guard condition before LifecycleNode.destroy_node, so a node destroyed without a cleanup/shutdown transition drops a late worker completion instead of triggering a destroyed guard (#381). Idempotent with on_cleanup.
  • _on_failure(source, msg) — Drop a trigger this node published itself (header.frame_id = node name); else append a FailureEventRecord to the renderer and preempt the next tick per the tier taxonomy: Tier A (safety) at severity ≥ WARN, Tier B/C at severity ≥ FAIL. When a critic FAIL is a reward wake and an execute_rskill goal is in flight, cancels that goal (latched reason "reward") instead of ticking — the reward signal stops the VLA now, not at the deadline_s clock — and the canceled result re-enters mission verification.
  • _on_object_query(record) — A matching world_state KIND_OBJECT_QUERY failure 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 below DEFAULT_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_result records the canceled attempt, counts it in TaskState.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_SOURCES includes world_state.
  • _on_tick(*, force=False, tier="heartbeat", trigger="heartbeat", coalesced=()) — No-op while the node is not active (_is_active, set in on_activate, cleared first in on_deactivate/shutdown; prompts and failures arriving meanwhile are kept for the next activation). Every call site names its trigger (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 (force wins, every trigger kept as coalesced) and replayed after, bounded by _MAX_TICK_REPLAYS=4.
  • _on_safety_status(msg) — Subscribes the latched /openral/safety_status (RELIABLE + TRANSIENT_LOCAL, read-only); feeds ContextRenderer.set_safety_status with the drop_reason name (failure_bus.drop_reason_label) and receipt time. A new latch forces a Tier-A safety_latched tick 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 a skill_result tick 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, unanswerable query_scene / query_task_progress, refused decompose_mission, what was said to the operator with wake=False).
  • _handoff_to_operator(text) — Publishes text on /openral/prompt under the node's own frame_id (self-filtered) and notes it; used when ReasonerCore.llm_gave_up flips (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_tick drops an execute_rskill / decompose_mission whose task ended while the call was in flight (a verdict completed or abandoned it, a new goal replaced it), logs it and records a not sent line in ## EXECUTION. (L7216)
  • Mission lifecycle. _on_prompt seeds a MissionState from the operator goal, gated by should_rebuild_mission (cascades never rebuild; an in-progress mission needs explicit new_goal metadata). _dispatch_execute_rskill refuses to send a goal once the active task has used DEFAULT_MAX_TASK_DISPATCHES dispatches (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, with deadline_s set 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 applies task_step_without_verifier); then counts a failed result in TaskState.failures (_count_failure, once, reward monitor or not) and applies task_step_without_verifier (a completes_task_on_success skill's success completes the task, or only its step when the call's final_step is 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 as mission: <complete|abandon> task …; otherwise it issues a windowed query_task_progress and _on_mission_verify_response applies 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, never final_step=False steps 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 inconclusive vlm_check falls back into the retry ladder rather than retrying forever. _emit_mission_complete summarizes a finished queue.
  • VLM completion adjudication. completion_camera_topic param (default "" = disabled; deploy_e2e passes camera_topic(_primary_rgb_camera(...)), ADR-0108) subscribes and caches each frame as JPEG. _adjudicate_completion(task_text) -> bool | None asks the tool-use client's describe_image; None (no frame/client/provider error) degrades to the replanning ladder rather than a false verdict. _complete_active_and_advance is the shared advance path for both the native-complete and VLM-confirmed branches.
  • Task subdivision on replan. _should_offer_subdivision(active, offered, max_depth) -> bool decides 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_mission flat-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; once DEFAULT_MAX_TASK_LOCATE_ATTEMPTS is exhausted without an execute_rskill dispatch it abandons the subtask with a specific reason and forces a Tier-C tick, without dispatching the locate. Fixes a live locate-loop the SearchProgress miss budget can't bound (that budget resets on a hit). A failed service call or nonempty LocateInView.failure_reason consumes the same budget and re-prompts with visibility unknown and the cause; only found=false with an empty reason is a completed no-match. Cleared on a new operator goal and on a real execute_rskill dispatch.
  • _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, including memory_available), installs it via set_palette.
  • _dispatch(call, *, traceparent=None) — Routing-only switch over the ReasonerToolCall variants; delegates to the per-tool _dispatch_* methods. WaitTool is a deliberate no-op; ReloadGstPipelineTool is a log-and-acknowledge stub pending its service IDL.
  • _dispatch_emit_prompt(call, *, traceparent) — Publish a PromptStamped on call.target_topic (per-topic publisher cache; /openral/prompt reuses the standing cascade publisher); stamps the threaded-through traceparent into metadata_json. A topic outside EMIT_PROMPT_TOPICS is 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 a RecallObjectTool/ResolvePlaceTool against the injected SpatialMemory and republishes the result as a cascade prompt. Bounded by a SearchProgress/SearchBudget; exhausting it abandons the active mission task so later heartbeats cannot restart a terminal search. A recall_object miss escalates policy-driven to a live locate_in_view for 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: on on_configure, when no backend was injected and spatial_memory_path is set, loads the persisted scene graph and flips spatial_memory_available. Load failure degrades to a WARNING + no backend, never a fabricated map.
  • _maybe_load_memory() — Deployment wiring: on on_configure, when memory_md_path is set, parses MEMORY.md, renders the ## MEMORY block, loads the archive log, and flips memory_available. Read failure degrades to a WARNING + empty store.
  • _dispatch_memory_write(call, *, traceparent) — The reasoner's write-capable dispatch: applies the MemoryWriteTool op to the live MemoryStore, archives any displaced entry, persists MEMORY.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.search over 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 the world.scene_objects span for the scene-objects card + SLAM-map overlay. Advisory only; failures swallowed at DEBUG.
  • is_collective_target(text) -> bool — Imported from openral_core (single source of truth, shared with the GroundedSubtask schema 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 to decompose_mission into 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_server holds the busy latch and re-probes for up to execute_server_wait_s before emitting a KIND_CONTROLLER FailureTrigger. 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's vram_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_send when configured.
  • _send_execute_rskill_goal(call, generation, traceparent) — Build ExecuteRskill.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 reactivation change_state outcome.
  • _change_state_async(node, transition) -> future | None — Shared helper: lazily cache a ChangeState client per peer node and call it asynchronously; None if 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) a call.node outside self._palette.node_ids; else drives <call.node>/change_state via _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 a FailureTrigger; 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 a FailureTrigger with ControllerEvidence on abort/cancel/failure. The replanning ladder classifies on the typed failure_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 carries FAILURE_NONE (a pre-failure_kind producer).
  • _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 — The ExecuteRskill.Result FAILURE_* constant name for a uint8 (reverse of _failure_kind_value), passed to reflect_on_failure with the result's evidence_json.
  • _failure_kind_value(name) -> int — Resolve an ExecuteRskill.Result FAILURE_* constant by name off the generated IDL rather than re-declaring the values, so the reasoner cannot drift from packages/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 on failure_kind (never on prose); FAILURE_NONE is "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 a KIND_TIMEOUT FailureTrigger.
  • Ladder persistence. _persist_ladder_state() snapshots ReasonerLadderState to the ladder_state_path param after every ledger mutation; _maybe_restore_ladder_state() reloads it at on_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 the ChangeState result and note it in ## EXECUTION; lifecycle failures surface in the target node's own logs (no FailureTrigger re-emission).
  • _publish_skill_failure(*, kind, rskill_id, evidence, traceparent, trace_id=None, tick=True) — Build + publish a FailureTrigger on /openral/failure/rskill (frame_id = node name, so _on_failure drops the echo), mirror it onto the OTLP span path via _emit_skill_failure_event so the OTLP-only dashboard can tally it, and force a Tier-B skill_failure tick 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 an openral.event.skill_failure span 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 for ros2 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 long on_activate waits 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 to DEFAULT_SOURCES.
  • on_configure(self, state) -> TransitionCallbackReturn (L128) — Build the /openral/prompt fan-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: the openral_reasoner node's /openral/prompt subscription 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/prompt after merging {"source": ..., "priority": ...} into metadata_json (preserving any per-source fields).
  • forwarded_count(self) -> int (L263) — Number of prompts forwarded since on_configure (for tests).
  • main(args=None) -> int (L268) — Entry point for ros2 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) — robot joins that real deploy's ROS scope first (openral_cli._dds_scope.join_robot_scope_or_exit, #557). Initialise rclpy, publish one PromptStamped with metadata_json={"source_cli": true} plus "new_goal": true under --new-goal and "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 at just ros2-build). The prompt-router preserves the mission-replacement flag when stamping source/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; reads OTEL_EXPORTER_OTLP_ENDPOINT when endpoint is None; True if exporters were installed, False for the no-op path. On success also starts the system-metrics collector and registers shutdown_observability via atexit. sample_ratio (or OPENRAL_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: calls configure_observability then attaches the parent trace context from env, so a child spawned with env={**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; emits rskill.id / rskill.role from semconv. (L62)
  • inference_span(name="skill.chunk_inference", *, chunk_index=None, kind: InferenceKind="foreground", **attrs) — Span for one VLA inference plus the openral.inference.duration histogram (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 own safety.check to the Python tick via the propagator. (L146)
  • world_state_span(name, *, traceparent="", **attrs) (L180) — Span for one World State event, attributes prefixed world_state.; a non-empty W3C traceparent (e.g. a declaration's trace_id, the runner's rskill.execute) parents it, so the event replays from the skill's trace. Used for world_state.object_query.
  • reasoner_span(name="reasoner.tick", *, tick_idx=None, model=None, force=None, **attrs) — Span for one ReasonerCore.tick. Sets reasoner.{tick.idx, model, force} and accepts any extra reasoner.* 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, so prepare_tick → off-thread run_prepared_llm → finish_tick can carry it between phases (each re-attaching via use_span) without an intermediate executor callback seeing it as current. Caller owns span.end(). (L285)
  • module constant P (L53) — ParamSpec("P"), generic parameter type var for traced's decorator signature.
  • module constant R (L54) — TypeVar("R"), generic return type var for traced'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 the cli.command root span for one CLI invocation; records cli.subcommand, openral.run.id, optional openral.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 of diagnostic_msgs/DiagnosticStatus level constants (OK=0, WARN=1, ERROR=2, STALE=3); re-exported so status_fn callbacks can avoid importing diagnostic_msgs on pure-Python hosts. (L31)
  • class DiagnosticsHeartbeat (L48) — 1 Hz /diagnostics publisher attached to a rclpy.lifecycle.LifecycleNode. __init__(node, *, hardware_id, component_name, status_fn, rate_hz=1.0). An exception inside status_fn is converted to a synthetic ERROR-level diagnostic so the timer never crashes the node.
  • hardware_id(self) -> str (L112) — Return the configured hardware_id field.
  • component_name(self) -> str (L117) — Return the configured DiagnosticStatus.name value.
  • create_publisher(self) -> None (L121) — Open the /diagnostics publisher. Call from on_configure.
  • start(self) -> None (L138) — Start the 1 Hz publish timer. Call from on_activate.
  • stop(self) -> None (L155) — Cancel the publish timer. Call from on_deactivate.
  • destroy(self) -> None (L167) — Destroy the publisher. Call from on_cleanup / on_shutdown.
  • publish_once(self) -> None (L179) — Publish one DiagnosticArray immediately.

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 for on_configure/on_activate/… transition callbacks. Transparent on success; on an uncaught exception logs the callback name + traceback and returns TransitionCallbackReturn.FAILURE instead of letting rclpy swallow it silently. Applied to RskillRunnerNode, _WorldStateLifecycleNode, HALLifecycleNodeBase, and ReasonerNode. Lazy-imports rclpy so the module stays import-safe on pure-Python hosts. (L52)
  • refuse_unavailable_transitions(node) -> None — Guard a LifecycleNode's change_state service: an id-only request (launch_ros ChangeState events, ros2 service call) naming a transition the current state lacks (a repeated deactivate) is logged and answered success: false with the state unchanged, instead of rclpy (Jazzy) raising RCLError out 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__ by ReasonerNode, RskillRunnerNode, HALLifecycleNodeBase, _WorldStateLifecycleNode, ObjectTrackerNode, Propagator, SegmenterNode, RosImageObjectDetectorNode (detector + on-demand locators), PromptRouterNode, ComplianceRecorderNode and SafetyPassthroughNode. The E-stop sources (deadman, hardware E-stop, human E-stop forwarder) use the dependency-free copy openral_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 current MeterProvider. (L65)
  • get_tick_duration() -> Histogram — openral.tick.duration, unit ms. (L100)
  • get_inference_duration() -> Histogram — openral.inference.duration, unit ms. (L115)
  • get_hal_read_state_duration() -> Histogram — openral.hal.read_state.duration, unit ms. (L127)
  • get_hal_send_action_duration() -> Histogram — openral.hal.send_action.duration, unit ms. (L139)
  • get_sensors_age_ms() -> Histogram — openral.sensors.age_ms, unit ms. (L151)
  • get_world_state_staleness_ms() -> Histogram — openral.world_state.staleness_ms, unit ms. (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, labels check_name / severity. (L200)
  • get_failure_count() -> Counter — openral.failure.count{component, kind, severity}, one per FailureTrigger the 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 hit task.success_key at least once. (L272)
  • get_observability_export_failures() -> Counter — openral.observability.export_failures, label signal_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, unit MBy. (L322)
  • get_system_gpu_memory_total_mb() -> UpDownCounter — openral.system.gpu.memory_total_mb, unit MBy. (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, unit MBy. (L370)
  • get_system_ram_total_mb() -> UpDownCounter — openral.system.ram.total_mb, unit MBy. (L382)
  • record_histogram_ms(instrument, value_ms, attributes=None) -> None — Record a millisecond value, skipping negatives and NaN. (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 the schema alias), which the dashboard caches for GET /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 a hal.read_state span. (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 a hal.send_action span. (L148)
  • record_ee_poses(span, ee_poses) -> None — Flatten a name → Pose6D mapping onto a world_state.snapshot span. (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 a sensors.read_latest span. (L205)
  • emit_sensor_frame_span(frame, *, sensor_name, age_ms, flip_180=False, tracer_name=…) -> None — The shared producer of a dashboard sensors.read_latest span 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 as span.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 to encode_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; returns None if Pillow is unavailable. (L311)
  • encode_frame_thumbnail(frame, *, flip_180=False) -> bytes | None — Encode an openral_core.SensorFrame (RGB8/BGR8/MONO8/JPEG/PNG) as a small JPEG thumbnail; returns None for 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 a FrameEncoding to the dashboard's modality label (rgb/mono/depth/raw/unknown); shared by DeployRunner and 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, KeyboardInterrupt and a RuntimeError (covers RCLError / 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; a RuntimeError with the context still up propagates. The threading.Thread target of the dashboard's e-stop / safety-status / perception-overlay executors and of Ros2ImageSensorReader's private node (the Isaac deploy sim teardown traceback in runtime_node). Third twin of openral_hal.lifecycle.spin_until_shutdown and openral_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 private SingleThreadedExecutor through spin_executor_until_shutdown; the caller still destroys the node and calls rclpy.try_shutdown(). The main() spin of segmenter_node (the Isaac deploy sim teardown crash, a take racing the shutdown), reward_monitor_node, scene_vlm_node, depth_provider_node and critic_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 every interval_s seconds. Returns False and a quiet no-op when neither psutil nor pynvml is 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, returning None when 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 — W3C traceparent value for the active span, or None outside a span. (L54)
  • current_trace_id() -> str | None — The 32-hex trace id of the active span, or None outside a span (including no-op observability mode). The id half of current_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's traceparent (and optional tracestate) into a carrier dict; used by producers of ActionChunk.msg / ExecuteRskill.action / FailureTrigger.msg. (L87)
  • extract_traceparent(traceparent, tracestate=None) -> Context — Parse a wire-side traceparent into an OTel Context for context.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 + optional OTEL_TRACESTATE) for the active span, built from inject_traceparent; pass as env= to subprocess / multiprocessing so 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: read OTEL_TRACEPARENT / OTEL_TRACESTATE from env (default os.environ) and context.attach the parent context; returns the detach token, or None when absent/empty. (L195)
  • remote_parent_from_env(env=None) [@contextmanager] — Scope attach_traceparent_from_env for a worker main(): attaches on enter, detaches on exit; yields the detach token (or None when 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; default monotonic_unsynced.
  • class ComplianceEmitter (L85) — Stamps the ComplianceRecord envelope (uuid4 record_id, a fresh stream_id per emitter with a gap-free seq, 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= (a ComplianceLog) 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 (else emit raises). Thread-safe.
  • emit(kind, **fields) -> record (L120) — Build, log, send and return one record; a wire trace_id is parsed (trace_ids_from_wire) and a malformed one dropped with a warning; a FailureRecord also counts openral.failure.count. A failed on-robot log write raises ROSRuntimeError after the record was still sent (its seq is spent, so verify shows the gap).
  • send_record(logger, record) -> None (L190) — One record as one OTLP log record (JSON body, openral.record.* attributes, trace context); emit and compliance_log.ship use it.
  • software_inventory() -> list[SoftwareComponent] (L242) — MR Annex III §1.1.9 identification: every openral* distribution, plus, with a ROS overlay sourced, openral_safety_kernel (binary SHA-256) and openral_safety (sources digest) marked safety_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 as otelcol) unless OPENRAL_TELEMETRY_IMAGE_CONSENT=1; default endpoint is the one configure_observability installed; withholding logs telemetry.images_withheld once per endpoint. Checked before the JPEG encode in emit_sensor_frame_span and DeployRunner, and again in record_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 consent OPENRAL_TELEMETRY_TEXT_CONSENT=1; withholding is logged once per endpoint. ReasonerCore stamps reasoner.rationale only 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, the prev_hash of a writer-class's first line.
  • const RAW_TELEMETRY_DAYS: int = 90 (L72) — default keep for telemetry_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) — One O_APPEND write, fsync'd for the safety / trace / incident classes; OSError propagates.
  • from_env(*, writer) -> ComplianceLog | None [@classmethod] (L149) — The log at $OPENRAL_COMPLIANCE_DIR, None when unset.
  • records(root, cls) -> Iterator[ComplianceRecord] (L213) — Every record of a class, all writers.
  • verify(root, *, partial=False) -> list[str] (L222) — partial (an export of some classes or days) skips first links and seq gaps. Broken prev_hash links, non-record lines, quarantined tails, and (unless retention pruned something) seq gaps per stream_id.
  • hold(root, *, on) -> None (L273) — Legal hold on the whole log (AI Act Art. 73(6)); prunable returns nothing while held.
  • prunable(root, today, keep_days=None) -> list[Path] (L283) — Segments past max(RETENTION_FLOOR_DAYS, keep_days); a floor never shrinks.
  • delete(segments) -> None (L303) — Deletes and marks the class pruned for verify; the CLI records each as a retention_delete intervention.
  • export(root, out, *, classes, since) -> int (L315) — Whole segments to a .tar.gz the recipient can verify.
  • ship(root, exporter, *, resource_attributes) -> int (L337) — Sends unshipped records, one acknowledged export each, resuming from ship.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 a SafetyStatus.drop_reason by reverse-mapping it against the generated message class's own KIND_* / DROP_* constants (lower-cased; when unknown, drop_reason_<code> for the default prefixes, else the first prefix plus the code, e.g. severity_<code>); prefixes also names a FailureTrigger kind / severity. The one implementation the dashboard, the skill runner and the reasoner share. (L138)
  • KIND_* / SEVERITY_* int module constants (L105–L121) — Mirror openral_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 in SafetyStatus).
  • KIND_GRASP_OUTCOME: int = 12 (L108) — Issue #353: GraspOutcomeEvidence from the HAL vision attachment bridge on /openral/failure/hal; bus-only (not in SafetyStatus).
  • 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 Hz KIND_SUPPRESSED_SUMMARY roll-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 one FailureTrigger, subject to rate-limiting (False when rate-limited).

python/observability/src/openral_observability/logging.py

  • trace_context_processor(_logger, _method_name, event_dict) — structlog processor that stamps trace_id / span_id on every log event. (L60)
  • resolve_log_level() -> int (L76) — Resolve the OpenRAL log floor from OPENRAL_LOG_LEVEL (name or int); defaults to INFO, not DEBUG; 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 by dashboard.store._is_headline_span.
  • apply_structlog_level_floor() — Configure structlog's stock renderer to drop events below resolve_log_level(); called by configure_observability on 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 OTel LoggerProvider, with both the bridge logger and the openral root logger set to resolve_log_level(). (L138) Every structlog logger is a child of the bridge logger (_bridge_child), so a package module logger outside the openral namespace (e.g. openral_world_state.object_tracker.tracker) honours OPENRAL_LOG_LEVEL and is exported and printed (a stdout ConsoleRenderer handler 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 OTLP ResourceLogs (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}, state running then finished) under topics.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 fresher openral.robot.manifest record arrives; bumps manifest_rev and pushes to SSE subscribers.
  • manifest(self) -> RobotManifest | None (L617) — The latest robot manifest (ADR-0129), cached from its openral.robot.manifest log record by ingest_logs (a malformed one keeps the last good one; the record is not an event-log row). snapshot() carries manifest_rev, bumped on every new manifest so the UI knows to refetch GET /api/manifest.
  • set_hal_estop(name, estopped) -> None — Record one HAL's own e-stop latch (its /diagnostics heartbeat) under topics.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 one SafetyStatus from the latched /openral/safety_status topic and push it to SSE subscribers. A latch sets topics.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_unix is 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 shared world (topics.world_pose, {x, y, yaw, frame: "world"}), served as /api/mission's world_pose; set by run_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-kernel FailureTrigger from /openral/failure/safety as topics.safety_failure (kind, severity, rskill_id, trace_id, stamps, repeats, and a one-line text built from the decoded FailureEvidence: 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 from workspace_declaration_live), the stopped skill) plus a protected safety.failure event-log row. It does not claim a latch (the safety_status slot does). A stop repeating the last one's kind, severity and skill within 5 s of its last repeat only bumps repeats (no row, no fan-out) and returns False. The console trace renders it as an error row. Each row also keeps detail (_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 for trace_id in chronological order, or None.
  • _reasoner_detail(attrs) -> str | None (L1905) — The console trace row's one-line why for a reasoner.tick span (also topics.reasoner.detail): <skill> <running|dispatching> · <tier> · <llm latency> · suppressed: <reason> · error: <kind> — <rationale>, each part only when present, None when 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 carries label, confidence, bbox_xyxy, det_id and contour ([[x, y], …] in the bbox's pixel frame, or None). camera is the wire sensor_id, the join key between a frame and its boxes; frame_width/frame_height let the tile scale boxes onto its aspect-preserving thumbnail. An empty detections list 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's output_topic default. (L50)
  • module constant PERCEPTION_MASKS_TOPIC: str = "/openral/perception/masks" (L51)
  • module constant PERCEPTION_MASKS_TOPIC: str = "/openral/perception/masks" — the segmenter node's debug_masks_topic default; 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, parsing OPENRAL_DASHBOARD_FLIP_180 with 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. Raises ValueError when data is not exactly width * height bytes. (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_msgs present).
  • masks_available(self) -> bool (L226) — True when the mask subscription is live (needs SegmentMasks built).
  • close(self) -> None (L315) — Tear down the node/executor and shut rclpy down only if it started it. _on_objects and _on_masks each 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 own ImportError guard) so an older openral_msgs build without SegmentMasks keeps drawing boxes; masks_available reports it separately from available. Wired in run_dashboard onto app.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 to router_node (by node name), so a bag recorder or ros2 topic echo on the prompt topic does not count as a router.
  • class EstopPublisher — Creates the node + /openral/estop + /openral/estop_cleared publishers 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, None without openral_msgs); the prompt action uses it before the openral prompt shell-out (#679).
  • available(self) -> bool (L116) — True when the persistent publisher is live (rclpy + ROS present).
  • trigger(self) -> bool (L120) — Publish /openral/estop instantly. Returns False if unavailable.
  • clear(self) -> bool (L124) — Publish /openral/estop_cleared instantly. Returns False if unavailable.
  • (property) prompts -> bool (L129) — True when operator prompts go through this node (a prompt publisher on /openral/prompt_in/dashboard exists), not the openral prompt CLI.
  • 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_NODE subscriptions, via routers_subscribed) it reached — 0 publishes nothing — or None when 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 to TelemetryStore.record_safety_failure.
  • DIAGNOSTICS_TOPIC: str (L51) — /diagnostics: the subscriber also reads each HAL heartbeat's own estopped latch (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 from openral_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's estopped, into TelemetryStore.set_hal_estop) and /openral/failure/safety (logging each new stop). Every callback logs, never raises, an exception (ROSSafetyViolation excepted), since they share one spin thread; a missing ROS install is left to run_dashboard to report. Wired in run_dashboard onto app.state.safety_status. (L81)
  • available(self) -> bool (L157) — True when the subscription is live (rclpy + openral_msgs present).
  • 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/robots wire 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 by robot.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 the Zeroconf instance, advertiser, and browser for the dashboard. Attribute enabled: bool. Wired into run_dashboard in server.py; app.state.discovery holds the instance (or None when the mdns extra 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 to 1 to 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 with LAN_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, remote per the remote-control flag, only estop for a LAN client), /api/state, /api/stream[?images=0] (SSE; ends at the token's exp remotely), /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 against args_schema with jsonschema, announced, then run: estop_reset → kernel service (409 on cooldown), prompt → openral prompt, skill:<id> → ExecuteRskill goal (202 + goal_id); refusals 403 per role (every kind but estop needs at least operator whatever the manifest's min_role) / LAN / OPENRAL_DASHBOARD_REMOTE_CONTROL / OPENRAL_DASHBOARD_WRITE_CONTROLS; prompt passes 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/console with openral_core.robot_secret_path() as Bearer and User-Agent: openral-robot through one client per app that never follows a redirect, and returns openral.com's status and JSON as they are, but canWrite false 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 viewer GET only, the tunnel GET only and only with remote control on), POST /api/transcribe, the 3D view (POST /api/viz/ticket, WS /ws proxy to bridge_url — ticket required remotely and off loopback, Origin checked on upgrade, closed at ticket expiry, bridge→browser frames through a BridgeRelay (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 from openral_foxglove_bringup.layout in Lichtblick's default-layout slot) and /{path} (the robot UI from app.state.ui_dir, else static/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 /ws upgrade carrying Cloudflare forwarding headers (cf-ray, cf-connecting-ip, cf-warp-tag-id, cdn-loop: cloudflare), and any LAN write but estop, a viz ticket and (opted in) OTLP ingest on /v1/*; the remote listener spends each token's jti on its first write (TokenVerifier.spend; E-STOP exempt) and answers a replay 401; both CSPs allow connect-src 'self' only; proxy_headers is off in run_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's correlation_id, each task's id / text / status / attempts / failures / verdict, finished), the reasoner's last tick (tick_idx, tool, rskill_id, error_kind, message), and stopped / estopped / latched / latch_reason / latch_detail ({kind, link, other, depth_m} of the kernel stop that caused the latch, None while not latched or with no stop near it). A robot of a scene with several robots also gets world_pose ({x, y, yaw, frame: "world"}, its map's origin in the shared world; absent otherwise; openral-pro#99). skill_result is the last dashboard skill run (TelemetryStore.set_skill_result: running when the action server accepts the goal, then finished with success, failure_reason and trace_id from _drain_skill_goal_stdout; #662). Served by GET /api/mission (plus ts_unix) and, one event per change, by GET /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 before full().
  • class BridgeRelay (L77) — BridgeRelay(max_ordered_bytes=MAX_ORDERED_BYTES). Ordered bridge→browser queue with per-subscription coalescing; single event loop. dropped counts coalesced messages (logged by the proxy as dashboard.bridge_relay_coalesced).
  • from_browser(frame) -> None (L98) — Learns subscribe / unsubscribe (the frame itself is forwarded by the caller); malformed ids are ignored.
  • from_bridge(frame) -> None (L119) — Queues a frame; learns advertise / 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 toward full() until sent().
  • sent() -> None (L160) — The last drain() 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; exp ends streams).
  • remote_listener(app) -> ASGIApp (L91) — Wrap the app for the remote listener: tags each scope so _gate demands a token. Nothing a client sends sets the tag.
  • is_remote(scope) -> bool (L104) — Whether a request came in through remote_listener.
  • load_enrolment(path: Path | None = None) -> RobotEnrolment | None (L109) — The enrolment openral robot link wrote (openral_core.enrolment_path()), None when unlinked; ValueError for an invalid file.
  • class JwksCache (L124) — The issuer's ES256 keys, loaded from a disk cache, refetched (httpx) only for an unknown kid and at most once per cooldown_s (60 s), written back to disk.
  • key(self, kid: str) -> PyJWK | None (L160) — The key kid, refetching once if unknown.
  • class TokenVerifier (L190) — Checks an openral.com robot token against this robot's enrolment and the issuer's JwksCache.
  • spend(self, principal: Principal) -> bool (L199) — Record a write made with principal's token; False if its jti already made one (replay). Held until exp + 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 — header alg ES256 (never none/HMAC), typ absent or at+jwt, known kid; signature; iss; a single aud (strict_aud) equal to the enrolled origin; exp/iat with 60 s leeway and exp − iat ≤ 300; sub/jti/org/role/robot present; robot/org equal 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's sub/role, reusable until TTL_S (900 s) but never past the minting token's exp; one pool of MAX per 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 for principal; prunes expired ones in its mode's pool, then the oldest.
  • expires_at(self, ticket: str | None, *, remote: bool) -> float | None (L308) — When ticket expires on the remote (remote=True) or local listener, or None if 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 an Authorization: Bearer header.
  • 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, size of one pinned download.
  • module constant ROBOT_UI: PinnedAsset | None (L56) — The pinned robot-console build (rewritten by tools/pin_robot_ui.py); None serves 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 the data tar filter minus *.map, and move into $OPENRAL_CACHE_DIR/dashboard_assets/<name>/<sha256>/ only when complete; the directory holding index.html, or None (logged). Shared with viz_assets.
  • ui_dir() -> Path | None (L143) — The local build, else the fetched pin, else None; no download.
  • ensure_ui_assets() -> Path | None (L154) — Fetch the pin if not cached; called best-effort by run_dashboard. Logs dashboard.ui_source once at INFO: source=pinned (+ url), local (+ path) or fallback.

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 /api and /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-port is not given).
  • CLOUDFLARED: dict[str, PinnedAsset] (L56) — cloudflared 2026.10.7 per platform.machine() (x86_64, aarch64).
  • TUNNEL_TOKEN_RE: re.Pattern[str] (L71) — A Cloudflare tunnel token (base64 of its JSON credentials); write_tunnel_token refuses anything else.
  • tunnel_env_path() -> Path (L93) — tunnel.env next to the enrolment file.
  • write_tunnel_token(token: str) -> Path (L98) — Store TUNNEL_TOKEN=<token>, mode 0600, O_NOFOLLOW.
  • read_tunnel_token() -> str | None (L116) — The stored token, or None when not linked.
  • SERVICE: str (L74) — openral-tunnel.service, the user unit openral robot link installs.
  • install_service(exe: Path) -> str | None (L159) — Write the user unit (EnvironmentFile=tunnel.env, Restart=always), systemctl --user enable --now it and loginctl enable-linger (boot without login); None, or why not. Refuses to replace a unit that runs another robot's tunnel while that robot's tunnel.env exists and the service is active (one service per host, kept by the robot it was linked for; the reason names systemctl --user disable --now to 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 on PATH; else None.
  • start_tunnel(remote_port: int) -> subprocess.Popen[bytes] | None (L206) — Run cloudflared tunnel --no-autoupdate run as a child unless the user service already runs this robot's tunnel (its EnvironmentFile is this tunnel.env); None when not linked, the service holds it, or no binary. Warns on a remote_port other than 4319 unless REMOTE_PORT_ENV says 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 enrolment aud'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: ValueError on a bad request line, a field line that is not name: value (whitespace before the colon, a folded line) or not exactly one Host.
  • 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 on 127.0.0.1:port; 421 for a host no robot answers to, 400 for a malformed head, 502 when that robot's dashboard is down; a half-close is passed on both ways; OSError when the port is taken.
  • main(argv=None) -> int (L152) — python -m openral_observability.dashboard.remote_router --route HOST=PORT ..., as deploy sim starts 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.0 lichtblick-web.tar.gz (MPL-2.0), pinned by sha256 + size.
  • ensure_viz_assets() -> Path | None (L35) — The Lichtblick build (via ensure_bundle), with a NOTICE.txt naming 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 on host:port and, when the robot is linked (load_enrolment), the remote listener on 127.0.0.1:remote_port (default $OPENRAL_DASHBOARD_REMOTE_PORT, else 4319; a remote_port without an enrolment is a ValueError; 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 a TokenVerifier; both with proxy_headers off 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 persistent EstopPublisher, 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 (a RobotManifest JSON file) is served until the runtime sends a fresher one; an unreadable file is logged and ignored. When inprocess_cmd is set, spawns it pointed at this dashboard's OTLP endpoint. world_pose ((x, y, yaw)) seeds /api/mission's world_pose (openral dashboard --world-pose, passed by the deploy launch).
  • spawn_dashboard / attached_dashboard — Inverse of --inprocess; see dashboard/attach.py below (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) — Spawn openral dashboard as a child, set the OTLP env, poll /healthz until ready, yield the URL, and SIGINT the child on exit. Yields None if openral isn'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) — Poll healthz_url until it returns _HTTP_OK or child exits or timeout_s elapses.
  • _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=False yields False as a true no-op (no FastAPI/uvicorn imports). enabled=True delegates to spawn_dashboard, re-runs configure_observability on the new endpoint, and re-opens the cli.command root span so workload spans have a real recording ancestor instead of being orphaned under the pre-dashboard root. Drains via shutdown_observability in finally. Yields True iff 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 by trace_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 carrying duration_ms.
  • TelemetryStore.list_traces() -> list[dict] — One row per indexed trace_id (trace_id, span_count, last_seen_unix), most-recent first. Backs GET /api/traces.
  • TelemetryStore.lookup_trace(trace_id: str) -> list[dict] | None — Every indexed span for trace_id, sorted ascending by start_unix_ns. None when the trace is not (or no longer) in the bounded index. Backs GET /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": [...]} from TelemetryStore.list_traces.
  • GET /api/spans/{trace_id} — JSON {"trace_id", "spans": [...]} from TelemetryStore.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-only tempfile.mkdtemp(prefix="openral-lttng-fallback-") dir, logged at INFO; never a fixed shared /tmp path). The JSONL file opens with O_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_tracepoint appends _begin / _end suffixes.
  • 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>_end around the block. Attaches the active OTel trace_id as otel_trace_id so 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_backend has 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) — expected traceparent dash-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 when babeltrace2 is 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 at episode_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 at record_frame. trace_id (32 hex) / span_id (16 hex) carry the producing rskill.tick span'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 at episode_end. (L119)
  • class DatasetSink(Protocol) — Fan-out target with open_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 more DatasetSink implementations and writes the OTel openral.dataset.repo_id / episode_idx / frame_idx attributes on the active rskill.tick span. (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 active rskill.tick span's (trace_id, span_id) onto the frame (ISSUE-109); explicit trace_id/span_id override 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_name L224, repo_id L229, n_sinks L234, expected_state_shape L0).
  • expected_image_keys() -> tuple[str, ...] — Camera keys (without observation.images. prefix) the sinks expect; derived from RobotDescription.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 dtypes features_from_robot assigns.
  • 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. Reads ObservationSpec.state_shape, ActionSpec.dim, and SensorSpec.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/tick message.
  • module constant _IMAGE_SCHEMA: dict[str, Any] (L99) — JSON Schema for the /openral/dataset/image message.
  • module constant _EPISODE_SCHEMA: dict[str, Any] (L125) — JSON Schema for the /openral/episode message.
  • module constant PHASE_START: int = 0 (L139)
  • module constant PHASE_END: int = 1 (L140) — the two Episode.phase enum values.
  • module constant _NDIM_H: int = 1 (L144)
  • module constant _NDIM_HW: int = 2 (L145)
  • module constant _NDIM_HWC: int = 3 (L146) — expected ndarray.ndim for a mono/2D/HWC image frame.
  • module constant _QUEUE_MAXSIZE: int = 1024 (L152) — bound on the writer thread's queue.Queue; write_frame drops (counted in n_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 when mcap is not importable.
  • module constant _STOP (L173) — sentinel _Stop() instance enqueued to tell the writer thread to exit.
  • class Rosbag2Sink(DatasetSink) — Writes every RolloutRecorder event into an mcap file readable by ros2 bag info / Foxglove / mcap-cli. Daemon writer thread + bounded queue so write_frame never blocks on disk I/O. Topics: /openral/tick (metadata plus inline observation_state/action arrays), /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/tick messages successfully written.
  • n_episode_markers_written(self) -> int (L261) — Number of /openral/episode messages (start + end) written.
  • n_images_written(self) -> int (L266) — Number of /openral/dataset/image messages 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. inline observation_state/action + the frame's trace_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 when mcap is not importable.
  • @dataclass class DatasetSummary(output_root, n_episodes, n_frames, n_success, repo_id) — Returned by from_bag describing what landed on disk. (L56)
  • class Rosbag2ToLeRobotConverter (L84) — Offline replay of a Rosbag2Sink-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 a Rosbag2Sink-produced mcap, group ticks under episode markers, join each tick's inline arrays + camera frames, and replay each episode through a real LeRobotDatasetSink to 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. Raises ROSConfigError on 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 the root/data/**/*.parquet correlation columns directly via pyarrow (no video decode), so it works without a torchcodec/ffmpeg backend. Raises ROSConfigError when the root has no parquet, the dataset predates the columns, or no (episode_idx, frame_idx) row matches. Backs openral 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 new LeRobotDatasetSink.
  • 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) — the trace_id/span_id string-feature specs added to every LeRobot v3 dataset (ISSUE-109).
  • module constant _LEROBOT_INSTALL_HINT: str (L67) — install hint raised when lerobot>=0.5.1 is not importable.
  • class LeRobotDatasetSink(DatasetSink) — Implementation of DatasetSink writing LeRobot v3 datasets via real lerobot.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") — Raises ROSConfigError if 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 to LeRobotDataset.add_frame. Adds the frame's trace_id/span_id as string parquet columns (ISSUE-109). (L274)
  • close_episode(summary) -> None — Calls LeRobotDataset.save_episode(parallel_encoding=True) and accumulates the per-dataset success counter. (L351)
  • finalize() -> None — Calls LeRobotDataset.finalize() then appends dataset_success_rate / license / repo_id and the dataset-level trace_ids / n_traces (distinct OTel traces, ISSUE-109) to meta/info.json["metadata"], and writes the per-episode episode_index → trace_id map to the meta/openral_traces.json sidecar. (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 a traceparent embedded in a raw CDR payload.
  • module constant _TRACEPARENT_RE_STR (L43) — same pattern, str form, 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; fields topic, 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 a jsonschema payload.
  • _resolve_mcap_path(path) -> Path (L117) — Find the actual .mcap file 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 in bag_path as a BagMessage.

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; fields kind: 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 for json.dumps.
  • list_bag_trace_ids(bag_messages) -> list[dict[str, Any]] (L68) — Return distinct trace_ids in bag_messages with their per-trace counts.
  • build_timeline(bag_messages, spans, *, trace_id=None) -> list[TimelineEntry] (L95) — Merge bag_messages + spans into 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) — Return GET /api/traces decoded, sorted server-side most-recent first.
  • get_spans(self, trace_id) -> list[dict[str, Any]] (L54) — Return every span for trace_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 two ros2 bag record topic/regex profiles.
  • module constant RECORD_PROFILES: dict[str, dict[str, list[str]]] (L52) — the slim (safety/estop/world-state-slow + compressed camera images) and full (adds world-state-fast, joint_states, tf, all perception, every camera stream, and — by topic_types — every LaserScan / PointCloud2 / Imu topic whatever a manifest names it) topic + regex + topic-type lists; camera regexes are built from re.escape(CAMERA_TOPIC_PREFIX).
  • build_record_command(*, profile, output_dir, storage="mcap", extra_topics=(), extra_regex=()) -> list[str] (L102) — Compose the ros2 bag record argv for profile. Verbatim topics are folded into the --regex as 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_types go 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) — Invoke ros2 bag record with the chosen profile.
  • class ReplayResult (L156) — Output of run_replay — both summary + the joined timeline; fields trace_id, bag_trace_ids, timeline, bag_path.
  • to_json(self) -> dict[str, Any] (L175) — Return a plain-dict view suitable for json.dumps.
  • run_replay(*, bag_path, trace_id, dashboard_url) -> ReplayResult (L185) — Read bag_path, fetch matching spans, return the joined timeline.
  • write_timeline(result, out_path) -> None (L306) — Persist a ReplayResult as pretty-printed JSON to out_path.