Skip to content

feat(materials)!: unified PLR materials, review fixes, single-sequence SSE, site binding - #395

Merged
Xuwznln merged 59 commits into
devfrom
feat/unified-plr-materials-integrated
Nov 25, 2026
Merged

Xuwznln merged 59 commits into
devfrom
feat/unified-plr-materials-integrated

Conversation

@Xuwznln

@Xuwznln Xuwznln commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

Summary

Draft: CI run for the unified PLR materials work, integrated on dev 2e772b61b. 54 commits; the full description follows before merging.

  • Device subtrees accept only PLR materials. A material whose subtree cannot be built puts that device into maintenance mode; the Host and the other devices keep running.
  • The authority validates config.type format and checks that PLR keys are unique within a tree, on every write path.
  • Creating a material places it in the same transaction. materials.assign goes through the materials service move. V1 POST /materials instantiates a PLR material.
  • The runtime and materials database baselines are reset; old databases are rebuilt.
  • Every SSE frame has an id, and /api/v1/events uses one sequence. The materials stream sends a reset when it cannot resume.
  • ActionContext is injected by type. A material can be bound by its Site, and a Site can be chosen by its owner at admission.
  • Workflow export → import round-trips. A rejected manual confirmation cancels the task.

Known before merge: the README demo e2e still pins the old LabDeviceMaterialsDemo commit; Xuwznln/LabDeviceMaterialsDemo#13 migrates that demo.

…ees PLR-only

Drivers create materials through one path: the client materials service
serializes the PLR tree (ResourceTreeSet) and the authority creates and
places it in a single transaction.

- MaterialTreeCreate.placement: the authority mounts the new root on its
  parent / Site inside the create transaction, using the same rules as a
  move; any failure rolls back the whole tree.
- materials.create(..., node=, parent=, site=, display_name=): resolves the
  Site (ResourceSite instance, uuid, label or index), creates and places
  atomically, then projects the material onto the device through the
  transfer load path and returns the tracker's instance.
- materials.assign onto device-own Sites (site=ResourceSite / uuid, or
  slot=label); the Host append_resource device branch moves onto the Site,
  resolving the selector before the commit point. One material per Site.
- The authority rejects non-PLR materials (no config.type) entering a
  device subtree, on every move/transfer/settlement/mount and when a device
  is created with held materials. Such materials made the device fail to
  restart, because device children are rebuilt as PLR resources.
- Legacy non-PLR children already under a device are skipped (named in an
  error log) instead of taking the whole device down.
…ites

The heater used to write its samples straight into the materials authority
(class Resource, no PLR serialization) and move them onto the device's
Sites. After a restart the device rebuilds its children as PLR resources,
so those samples made the whole device fail to start.

- VirtualHeatingSample is a registered PLR resource (virtual_heating_sample);
  temperature and heating progress are its own state and round-trip through
  serialize_state / load_state.
- Samples are created with materials.create(..., node=, site=) on the
  device's own Sites (atomic create-and-place, display name 加热样品 N).
- On restart the driver adopts the instances the framework re-attached,
  mapping each Site's occupant uuid to the tracker instance; no duplicates.
- Each heating step reports the sample through materials.update; no direct
  gateway writes and no private platform material remain.
The fixture mounts an identity-only deck under the bench device, which the
authority now rejects (device subtrees only hold PLR materials).
Every driver creator takes the device's children through one split
(split_plr_material_tree in DeviceClassCreator.__init__): each material
subtree keeps the part that deserializes as PLR, and a node without
config.type is cut off together with what hangs under it; parent Site
occupancy pointing at it is cleared in the local copy (authority untouched).

This covers materials attached after construction and the ones a device is
built with (a liquid handler's deck, a workstation deck): a deck with one
legacy material on it still initializes with the device. Each cut material
is named in an error log. Previously a single legacy node failed the whole
subtree (or the whole device).
…ed from

Contract (unilabos.resources.material_class), field name kept as class /
class_name and documented where it is defined:
- class records what the material was initialized from: the registry
  resource name (e.g. container, virtual_heating_sample), equal to its
  template name. The implementation module (class.module) can be looked up
  in the registry by that name; it is not stored again.
- children without a registry entry (wells, tip spots, ad-hoc PLR
  resources) fall back to the PLR class name; devices keep their registry
  device name.
- config.type is the PLR class name. Rebuilding PLR instances (device
  restart) deserializes by config.type directly; class is a record only.

Changes:
- from_plr_resources / resource_tree_to_create derive class by the
  contract; instantiate_registry_resource stamps the registry name on the
  draft; registry sync writes class_name = registry name for entries that
  declare an implementation (module_name keeps class.module); the legacy
  graph upgrade and example graphs use the registry name.
- The authority resolves the stored class against the template: a registry
  template not yet re-synced (class still the PLR name) accepts the registry
  name, and a client that could not reach the registry (class fell back to
  config.type) is normalized to the template's registry name.
- materials.db stays on the v1 baseline (no migration).
- Visualization and the mesh manager look the registry up by template_name.
…efore deserializing

PLR deserializes by config.type and only finds classes already imported in
the process. The PLR registration hook (plr_additional_res_reg) now has two
defined ways to make them importable:

1. explicit: register_plr_module / register_plr_class (unchanged), for
   classes that are not reachable through a registry entry;
2. by registry: register_registry_resources(*names) takes a material's class
   (the registry name it was initialized from; legacy rows fall back to the
   template name), looks up the entry's class.module - usually a factory
   function - and registers the module part, i.e. the file the factory lives
   in, which defines or imports the class it returns.

to_plr_resources registers the names found in the tree, then register()
imports everything pending once per process; the class itself is still
resolved only by config.type. The registry-wide scan in
find_plr_resource_class stays as the last resort for rows without a
registry name.
On Windows with a Chinese locale, text=True / open() default to GBK. The
dependency installer read pip/uv output strictly as GBK, so a non-GBK byte
failed the driver package install. Subprocess output (pip, uv, dora) is now
decoded as UTF-8 with errors="replace"; the session file and the dora
benchmark log are written and read as UTF-8.
goal_response_callback checks _take_settled (jobs already settled when the
device went offline); the hand-written _RosExecutionAdapter stub predates it.
The test only runs where unilabos_msgs is installed, so it went unnoticed.
… UTF-8 mode

Tests read UTF-8 files with a bare read_text() and decoded subprocess output
with text=True, both defaulting to the locale (GBK on Chinese Windows), so 7
tests failed there while CI (PYTHONUTF8=1) passed. read_text / write_text /
text-mode open() now pass encoding="utf-8", subprocess calls decode UTF-8
with errors="replace", and tests/conftest.py puts child processes in UTF-8
mode (PYTHONUTF8 / PYTHONIOENCODING, same as CI).
…abos

subprocess_env now puts the repository root first on PYTHONPATH (as
test_process_lifetime already does). Where an older unilabos is installed in
the environment, `python -m unilabos` otherwise ran that copy: unknown
--root_devices_as_slaves, and the old CLI was refused by the new server (401).
…st 9

pytest 9 attaches its capture handlers directly to loggers that do not
propagate (unilabos.comm). Turning propagation on as well made every record
reach caplog twice, so the WARNING/DEBUG sequence the test checks was off by
one. Propagation is only switched on when pytest did not attach the handler.
The frontend keeps a single event stream per station, because a second
long-lived connection per tab starves REST under HTTP/1.1. It
refreshes material views on material.changed from that stream. The
backend only published material changes on /api/v1/materials/events,
so material views fell back to a 30 s poll.

While this process holds the materials authority, /api/v1/events now
compares the ledger tail about once a second, together with the
workflow poll. When the tail changes it pushes an id-less
material.changed with data {"sequence": <tail>}, like the
runtime.logs.changed notices. The workflow cursor and Last-Event-ID are
untouched, the baseline is fixed before the response headers, and a
failed ledger read skips that round instead of breaking the stream.
/api/v1/materials/events stays for clients that replay by sequence.
Node meta_data.inventory_requirements is what scheduling, preflight
and task binding use. The V1 graph root list was always [] (dev keeps
no separate requirement table), so requirements that will be reserved
never showed up in clients. The frontend's node 资源需求 tab and run
preparation said 「该工作流没有声明库存需求」 for the demo's flow.

Reading a graph now projects each node requirement into the V1 shape:
- uuid is uuid5 of workflow, node and key, so it is stable per read.
- content maps to current_substance, lot to lot (splittable), material
  to material (1 件).
- A key repeated across nodes becomes <node_uuid>/<key>, as task
  bindings write it.
- A quantity given by a runtime reference reads 0 and is flagged
  quantity_dynamic.
- The original entry, the inventory mode and whether reservation is
  deferred ride along in meta_data.unilab.

Nodes stay the only source: nothing new is stored, and the existing
visibility filter still hides private sub-graph requirements.
The materials page refreshes incrementally. It rereads only the ids a
material.changed names, and a notice that names nothing reads nothing,
so a bare {"sequence": N} never refreshed the page.

The notice now carries material_uuids: every material row in the
ledger window, plus the owner of every Site that was occupied,
vacated, created or deleted (its Site list changed). When the list
cannot be exact (more than 500 rows, a resource template change, a
reset ledger) material_uuids is left out, which tells the client to
reload everything. A test against a real MaterialsService places a
sample on a device Site and gets back both the sample and the device.
…the V1 filters

The frontend decides what a material is and whether it can be picked
from inventory_status / inventory_presence / disposition. The V1
records only had lifecycle_status, so every material read 状态未知 and
the material picker refused them all. It also sends V1 filters that the
list and graph endpoints ignored.

Inventory facts, derived from the lifecycle (V1 InstanceState words):
- active -> warehouse, reserved -> reserved, in_use -> in_use,
  quarantined -> quarantined, consumed -> consumed, retired -> used.
- Presence is always current: this backend has no station departure.
- Disposition is active, or discarded once soft-deleted.
- Devices are not inventory and get null facts.
- Only warehouse (active) can be reserved by a new task, which is the
  same rule _select_inventory_material applies to an explicit material.

Filters:
- GET /materials: category=material|device by resource type;
  inventory_scope=current|history, where history is empty because
  nothing departs; empty_containers_only=true keeps materials with no
  content registration (a zero-quantity one still counts). Unknown
  values are a 1000.
- GET /materials/graph: inventory_scope, and repeated material_uuid for
  an incremental reread. It returns those materials plus the owners of
  their current Sites, so current_site_uuid resolves in the same
  response, and only links between returned nodes. Deleted or unknown
  ids are absent, which the client reads as removed.
Typed inventory command handlers parse their payload in place: dict(),
int(), float() and pydantic model construction. A payload of the wrong
shape (spec as a string, node_requirements as a list, a non-numeric
count, a payload that is not an object) raised ValueError or TypeError.
That escaped as a bare HTTP 500 with no envelope and left no
processed-command record, so a retry ran the handler again.

Such errors are now rejected like any other invalid parameter: a
failure envelope with code 1000, recorded and replayed under the same
command_id.
A tree create can place its root on a site of its parent in the same
transaction. Clients that build payloads by hand must still send
`placement: null`, because the command entry compares the payload with
the full typed dump. OpenLabSite's createTree is synced to this.
… detaches locally

materials.assign(node, material, slot=/site=) onto one of the device's own
Sites had three defects:

- A material nested under a local PLR parent stayed under it locally,
  while the authority moved it onto the device Site. From then on every
  strict snapshot of the old parent's tree was refused with "runtime tree
  contains material UUIDs outside downloaded tree", and that tree stopped
  syncing.
- The local mount happened before the authority move. When the authority
  refused (occupied Site, category, ingress reservation, PLR-only device
  subtree), the material stayed mounted as a device root that the
  authority never placed.
- A Site uuid passed as `site` was trusted without checking it is one of
  this device's Sites. A Site of another device put the material under
  that device in the authority while it was mounted here.

The selector, uuid or label, now goes through the same match against the
device's own Sites. The authority move runs right after the commit point,
before anything local changes. Only then is the material detached from its
local PLR parent and registered as a device root. The old parent's tree,
now one child short, is reported in the same snapshot step.

ResourceTracker.add_resource drops a stale parent index entry when a former
child is registered as a root.
…e authority

Device init prunes materials without config.type from the local tree, but
left the authority untouched. That tree's node set then never matched the
authority, so every strict snapshot of it was refused ("runtime tree does
not match downloaded material UUID set"). The observer dropped them as
drift, and all PLR state changes on that deck (volumes, tips) were lost
until the legacy row was removed by hand.

The pruned branch roots are now recorded on the device's tracker
(legacy_material_uuids). When the node gets its resource service, it moves
each one out of the device subtree in the authority, making it an
independent root and freeing the Site it held. This runs for both
backends: HostLink and ROS 2 create the driver first and set the service
afterwards. A failed move is logged and stays pending. The init error
log now says the material is moved out, and asks to recreate it from the
registry and delete the old row.
…evice-specific barcode

A new sample always used resource_id <device>-sample-<n> and barcode
OPENLAB-HEAT-<n>. Both must be unique among undeleted materials. So:

- When the sample on a site was moved away (or, on upgrade, a legacy
  sample was moved out of the device subtree), the site could never be
  provisioned again. heat_site failed with "site N has no heating sample".
- A second heater in the same lab got no samples at all, because its
  barcodes collided with the first heater's.

Barcodes now carry the device id (OPENLAB-HEAT-<device>-<n>). When
<device>-sample-<n> is still taken by the sample that left, the new sample
gets -2, -3, ... on both its resource_id and its barcode. The sample that
left is not touched.
/api/v1/events polled the materials ledger once a second directly on the
event loop: latest(), changes() and one get_site per Site row. These reads
take the materials store lock, which a writer holds for its whole
transaction. While another thread held a write for 2 s, the loop stalled
for 1.3 s. Every open /api/v1/events connection did this every second,
and that stream is now the one each browser tab keeps.

The poll, and the baseline read before the response headers, now run in
asyncio.to_thread. A Site that appears several times in the ledger window
is looked up once.
…ventory_requirements

GET /workflows/{uuid}/graph now derives the V1 root inventory_requirements
from the nodes. POST /workflows/import refused any non-empty list, so a
graph with node requirements could no longer be exported and imported
back. The request failed with 1000 "暂不支持在导入图中携带
inventory_requirements".

Import now accepts the list when it is exactly what the read derives from
the imported nodes. That list is a read echo: it is dropped, and the
imported workflow derives its own list from its new nodes. The comparison
ignores uuid and workflow_uuid, which follow the workflow identity. Any
other list (an edited quantity, an extra or hand-written entry) is still
refused, because requirements live in the nodes'
meta_data.inventory_requirements.
…n empty reread

GET /api/v1/materials/graph?material_uuid= (an empty value) counted as an
incremental reread of no materials and returned an empty graph. Empty
values are now dropped. Only empty values means the full graph; mixed
with real uuids, only the real ones are reread.
…ory_requirements

api_v1_migration.md described material.changed with only the sequence.
api_v1_route_map.md still said the graph's inventory_requirements list was
always empty, and that import refused it unconditionally.
…ransaction

V1 POST /api/v1/materials did three separate transactions: create the
tree, move it onto the requested Site or parent, then create the
reagent. When a later step failed, a compensating delete removed the
material, but it swallowed its own errors. A crash or a failed delete
could leave a material that was created but not placed, and the
intermediate state was visible in between.

The placement now uses the tree's own MaterialPlacement: the Site's owner
as parent, with the Site as the selector, or the parent alone. The tree
create and the optional reagent run under one outer materials write, which
is re-entrant, so inner mutations do not commit. Any failure rolls
everything back, and the compensating delete is gone.
…resume

After a restart on a new data directory, a browser reconnects to
/api/v1/materials/events with its old Last-Event-ID. When that id was
ahead of the new ledger, the stream sent nothing until the new ledger
grew past it, so pages that rely on this stream went stale. When the new
ledger had already grown past it, the stream resumed in the middle of
another database's history.

The stream now follows /api/v1/events:
- a fresh connection gets an id-only watermark frame;
- a cursor it cannot resume gets stream.reset with the new watermark as
  its id and data.reason, and the connection stays open. The reason is
  cursor_ahead when the cursor is past the ledger tail, and
  epoch_changed when the cursor came from another ledger.

To tell ledgers apart, the SSE id is now <sequence>:<epoch>. The epoch
is a 16-hex digest of the ledger's first event_uuid: fixed for one
database (the ledger is append-only) and different for any other. An
empty ledger has no epoch, and its id stays <sequence>.

Old clients keep working. Browsers echo the id without parsing it, and
a page that ignores stream.reset still gets the new watermark from that
frame, so later materials.changed events arrive. A plain numeric
Last-Event-ID is still accepted, with only the cursor_ahead check. A
client that parsed the id as an integer should read data.sequence.

The realtime, materials and API catalog docs describe the epoch and the
reset. An invalid cursor answers with the 1000 envelope, not HTTP 422,
as it already did.
A carrier's direct children are its slot holders, and each holder sits at the
position of its Site; the material is placed on the holder. The graph
reconciliation that fills Site occupancy by matching child positions took the
holders for occupants, so every empty Site of a carrier loaded from a graph file
(the shape ResourceTreeSet itself exports) was recorded as occupied by its own
holder, and the Host refused to restore the carrier ("占用关系冲突").

Holders (type resource_holder) are skipped when matching occupants.
…epairing old data

main is not released yet, so old development databases are rebuilt rather
than migrated or repaired. runtime and materials move to contract_version 2
(schema v1 stays the baseline): a database written before the reset is
refused with the existing "incompatible, needs rebuild" error, or backed up
and rebuilt when database_rebuild_on_mismatch is set.

With the reset, the code that existed only for old data goes away:
MaterialsService.repair_site_occupant_parents and its call in
ServerServices.open (it moved legacy occupants under carrier holders and
could keep the authority from starting), and the in-place re-parent branch
of a move onto the Site a material already occupies, which only that repair
used. Such a move is now "already at destination".

The database guide notes that schema upgrades move to versioned,
Flyway-like migrations after main is released.
…ery write path

The authority only checked that config.type was a non-empty string, and only
on create and move. A V1 PUT /materials/{id} config without type, a patch, or
a device snapshot could drop or blank the type of a material a device holds,
and a PLR key that clashed with another one in the same tree was committed,
then failed the Host's local load.

One check (_assert_plr_tree_rules) now runs on the final state of every
write that changes a material's parent or config: create_tree (after its
placement, plus every device the new tree contains), move and transfer (and
so instantiate, material.io and placements), patch_material (and so V1 PUT)
and apply_snapshot. apply_delta changes neither parent nor config. A PLR
tree is what one device holds (sub-devices hold their own) or the whole tree
of a root material that is not under a device:

- every material a device holds carries a well-formed config.type: a Python
  identifier, the PLR class name. Missing, blank or malformed is rejected
  with 1000. Whether the class exists is left to the Host, which can see
  driver packages the authority cannot;
- PLR keys (config.name) are unique within the tree; a clash is an identity
  conflict naming the key and the materials.
…e mode

An unknown config.type made require_plr_config_type raise inside the driver
creator and took the device (on HostLink: the whole startup) down, while a
material without config.type was silently cut off and later moved out of the
device subtree in the authority.

Every driver creator now builds the device's material subtrees first
(build_device_materials). If one cannot be built (missing or malformed type,
unknown class, deserialization error) it raises DeviceMaterialError naming
the material uuid and its config.type, and the device enters maintenance
mode, reusing the unavailable-device mechanism HostLink already has for
backend-unsupported devices: the device and its sub-devices do not start,
the Host and the other devices start normally, and the record (with
maintenance, material_uuid, material_type and a reason naming the device)
reaches the capability snapshot, GET /api/v1/devices (unavailable) and
/api/v1/health. ROS 2's HostNode records the same entry.

The built instances are reused when the driver is attached, so nothing is
deserialized twice. The silent split (split_plr_material_tree) and the
legacy detach that moved such materials out of the device in the authority
(tracker.legacy_material_uuids, DeviceNode._detach_legacy_materials) only
served old databases, which are now rebuilt, and are removed.
materials.assign(node_B, uuid, slot=...) on a material device A still held
re-parented it in the authority while A kept its local instance: both
trackers mapped the uuid and A's strict snapshots failed. Assign with a
material parent also mounted locally before the authority move, so a
rejected move left the local mount behind.

assign now runs the same flow as materials.transfer
(MaterialsService.transfer_material): the authority validates and commits
the move, the device that held the material (its owner in the authority, or
none) unloads it, and the target device loads and rebuilds the subtree. Same
device and cross device take this one path, and a rejected move changes
nothing locally. A material already at the destination and held by the node
is a no-op. The result lists the rebuilt instances ("resources"); the parent
can still be a PLR key the node holds, and site / slot are resolved by the
authority (uuid, label or the Site's own index). Assign goes through the
node's own materials gateway and refuses to run on the node's executor.

HostLinkLocalRuntime.dispatch_material_sync runs a load / unload on a local
device; HostLinkBackend uses it for its local devices. Host-sent
RESOURCE_APPEND (deduct-and-mount) still uses append_resource.
…s through the instantiate path

V1 POST /materials wrote an identity-only node from the template, without a
PLR instance, so placing it on a device Site was always rejected ("only PLR
materials") and nothing it created could be deserialized on a device.

The request now initializes a PLR instance first and converts it with the
same plr_resources_to_create path as instantiate_material:

- config.type given: the template definition's config plus the request's
  config / data, deserialized through ResourceTreeSet;
- otherwise a registry PLR resource template is instantiated from the
  registry (with its default children);
- otherwise the template's implementation (module_name's class, or
  class_name) when it is a known PLR class, deserialized as above.

The root then gets the uuid, the resource_id as its PLR key, the display
name, barcode, description, meta_data and V1 position, and the tree is
created, placed and filled in the existing single transaction. A template
that cannot be instantiated is rejected with 1000 naming the template and
asking for config.type; nothing is created.

Tests that create materials from class-less V1 templates now declare a PLR
class on the template.
…he paths they name

- V1 create-place-fill atomicity: the failing request used to be rejected by
  the FastAPI request model and never reached the service. It now passes the
  model and fails inside create_reagent, after the tree and its placement
  were written in the same transaction (a spy checks that), and the test
  asserts material and ledger counts are unchanged.
- inventory.reserve malformed payload: node_requirements was a list, so the
  command failed at dict(list) instead of the bad quantity. It is now a
  node -> requirements mapping and the rejection names the bad value.
- A real PLR LiquidHandler built through PyLabRobotCreator goes through
  LiquidHandler.deserialize (to_dict=True) with its deck referenced from
  children[0]: the deck and its labware are deserialized and tracked once;
  a deck holding an unknown class puts the device into maintenance mode.
…ection

Every /api/v1/events connection read the materials ledger once a second in
the default thread pool, the same pool the runtime.v1 control socket's
outbound pump and the edge proxy use; /api/v1/materials/events read it on
the event loop itself, also once per connection. With many tabs and a long
write, messages to the Host were delayed.

LedgerWatch (server/services/materials/ledger_watch.py) is one per materials
authority: a dedicated daemon thread reads the ledger tail once a second
while anyone subscribes, reads the new rows (500 per batch, the rest on the
next round), works out the changed materials once, and hands the batch to
every subscriber. A subscriber gives its own starting point: the watch
catches it up from there, or sends a reset batch when the cursor is ahead
(database reset). Connection baselines and the ledger epoch are read on the
same thread, not in the default pool. Read errors are logged and retried on
the next round without dropping subscribers; a subscriber whose delivery
fails is dropped; with no subscribers and no pending reads the thread exits
and forgets its position.

/api/v1/events turns batches into material.changed frames as before.
/api/v1/materials/events (including the epoch / reset handling of
e125c66) now streams the watch's rows instead of polling per connection,
and sends stream.reset (cursor_ahead) when the ledger shrinks under a live
connection instead of going silent.
…s has defined semantics

Topology link writes (upsert_link, delete_link_record, ensure_links) wrote
no ledger rows, so with the 30 s polling gone a link change never notified
anyone. They now append a ledger row (aggregate_type "link", operation
create / update / delete, delta naming both endpoint materials) in the same
write transaction. A link deleted and created again keeps counting versions
from the ledger, so the (type, uuid, version) uniqueness holds. The ledger
CHECK and the protocol's AggregateType gain "link"; the materials baseline
fingerprint is updated (still the pre-release v1 baseline).

material.changed on /api/v1/events now has a defined meaning: with the key,
material_uuids is exactly the materials that changed (Sites map to their
owner, links to both endpoints) and an empty list means no material changed
(only lots or reservations moved the ledger), so nothing needs rereading;
without the key the window could not be listed (template change, ledger
reset) and clients reread everything. /api/v1/materials/events sends link
rows as materials.changed like any other row. The realtime and V1 migration
guides document this.
material.changed and runtime log notices carry no SSE id. The watch loop
used to fall back to data.sequence, so a materials ledger tail became the
workflow cursor and every later task notice was dropped until watch_timeout.
Only a frame's own integer id now moves the cursor.
…ules

The graph's root inventory_requirements is a projection of the nodes. It now
uses the execution plan's rules in one place:

- Disabled nodes and their descendants are not listed and do not turn a key
  into <node>/<key>. The disabled rule is the plan's own, now a shared
  node_or_ancestor_disabled, so preflight and task bindings, which resolve
  keys against the plan, accept every listed key.
- Composite private sub-graphs are not listed on this layer, but still count
  for key uniqueness because bindings resolve against the whole plan.
- Quantities are normalized like the scheduler reads them, so "1200" is
  1200 and not a dynamic 0.

The projection test about hiding private sub-graph requirements now uses a
graph with private nodes.
duplicate_graph gave nodes and edges new ids but only rewrote parent_uuid and
edge ends. Everything else kept the old ids: a node_output material source on
an inventory requirement, depends_on, condition_guards, condition and loop
expressions, carry_next, result references in params and composite mappings.
An exported graph with a node_output source was therefore refused on import.

Node ids are UUIDs, so remap_node_references rewrites every string or key that
equals an old node id, without listing shapes. Copying a workflow also runs
the workflow's own reserved metadata (output bindings, resource scopes)
through the same table, so they point at the copy's nodes. The unused
requirement duplication is gone.
Two things stopped export -> import of a composite parent:

- The import re-derived the root inventory_requirements from the visible
  nodes and compared the whole projection. The export's requirement_key
  counts the private sub-graph (water becomes <node>/water), so the echo was
  refused. An entry is now an echo when it is a requirement declared on its
  consume_node_uuid, compared on that node and meta_data.unilab.inventory.
  The projected fields are read-only and cannot disagree across projection
  rules; a hand-written or edited entry is still refused.
- The export holds only the visible layer and import dropped the reserved
  metadata, so the invocation came back as a hollow node without its private
  sub-graph. Import now expands each composite invocation again from its
  pinned publication under the new invocation uuid and saves once. The
  expansion is shared with insert_composite_invocation.

Export -> import -> export is now stable for composite parents with loops and
carry in the child, groups, loops, conditions, disabled nodes and node_output
sources.
…dings

Import dropped all reserved metadata, so a workflow whose nodes use a declared
input could not be imported again ("references an undeclared input"), and
output bindings, resource scopes, node input bindings and authoring order
silently disappeared. The request model also discarded the exported
workflow object.

Import now takes the author's declarations from the exported
workflow.meta_data.unilab (input/output contract, output_bindings,
resource_scopes) and each node's input_bindings and authoring_source_order.
Node references are rewritten to the new ids, then the save path's
validators run: the input contract against the nodes that use it, output
bindings and scopes against existing nodes, and the normalized contract is
stored. A failure is refused with 1000 naming the item. Composite
invocations compile against the imported input contract. Other reserved
metadata, such as source registration, is still not taken.
…he plan

State the rule plainly in the route map: the graph's inventory_requirements
lists only this layer, while requirement_key is unique across the whole
execution plan because bindings and preflight resolve keys against it.
The V1 file index still said the graph list was always empty and that
inventory_bindings took no part in reservation.
Rejecting a confirmation used to fail the step, so the task ended failed
with node_execution_failed. A rejection is the operator stopping the run.

The step is now canceled and keeps manual_confirmation_rejected as its
reason, for both manual_confirm and material_io (they share the
workflow_manual_confirmation gate). The DAG stops as on any canceled step:
downstream nodes are not dispatched and end canceled, the task ends
canceled with error code manual_confirmation_rejected, and task-level
inventory reservations are released as on a normal cancel. A rejected
material_io still leaves the inventory unchanged. A timeout still ends the
step as timeout and the task as failed.
material.changed and runtime.logs.changed are now frontend_event rows,
written by the authority process that owns the Workflow Authority. The
writer is a permanent subscriber of the shared materials ledger poller
and of the in-process log notice hub (Host notices arrive there through
runtime_logs_changed). Each kind is coalesced and written at most once
per second; the first notice after a quiet period is written at once.
material_uuids keeps its meaning and is dropped above 500 entries.

Every frame on /api/v1/events now has an integer id from one sequence,
so Last-Event-ID resume, stream.reset and retention cleanup cover
material and log notices too. A written row wakes the local SSE
connections instead of waiting for the next poll. On restart the writer
resumes after the ledger sequence recorded in the last material row.
…ping

A reconnect with Last-Event-ID continues after that sequence instead of
replaying the last 40 events. A cursor ahead of the latest sequence or
behind the retention window gets stream.reset with the new watermark.

Each poll reads the retention bounds and one page of frontend_event rows
in one SQL snapshot and advances the cursor only to the highest row it
scanned, so rows committed during a scan and rows past a page are no
longer skipped; a full page is followed by the next page at once. Rows
outside the selected channels advance an id-only watermark frame, and a
fresh connection gets one after the backlog. The stream ends when the
server starts shutting down.
The stateless Streamable HTTP endpoint never pushes server-initiated
messages, and its standalone SSE stream had no event ids and no event
store, so a dropped connection lost whatever it would have carried. GET
now returns 405 with Allow: POST, as the MCP transport allows; POST JSON
responses are unchanged.
Every frame on /api/v1/events now carries an id from one sequence, so
the watch loop no longer distinguishes durable workflow frames from
id-less notices: any frame with an id advances the cursor, a frame at or
below the cursor is a replay and is skipped, and stream.reset adopts the
new watermark. Non-integer ids are still ignored, and --after keeps
resuming through Last-Event-ID.

Tests drive the real event stream with material and log rows interleaved
around the task notice and check that the watch ends on the task.
The realtime guide describes the single frontend_event sequence: who
writes material.changed and runtime.logs.changed (the Workflow
Authority process), how they are coalesced and rate-limited (one row per
second per kind), what that means for retention, and what uni-lab-fe
must do (material.changed has ids; a notice without material_uuids
means reload all materials). It also documents /monitor/events resume
and reset, and GET /mcp answering 405. The V1 route map, migration
notes, API catalog, log UI notes and MCP pages follow.
Any parameter annotated ActionContext, Optional[ActionContext] or
ActionContext | None is injected by the framework whatever its name; the
optional forms get None when there is no context (ROS 2), a required one
always gets a context. One helper (bind_action_context) decides for the
HostLink local runtime, host_node and cross-device calls, workstation
sub-steps and the ROS 2 device node.

The AST scan, the decorator, the contract parser and runtime signature
inference exclude such parameters by type from the goal schema, required
list, placeholder_keys, handles, material locks and goal_default. A
parameter named action_context without the annotation is now a
registration error pointing to Optional[ActionContext].
…pies

A ResourceSlot (or list[ResourceSlot] item) may be given as
{"site_uuid": ...} in workflow inputs, node params and ad-hoc action params.
Task creation and run preflight share one resolution path: one read of
Site facts from the materials authority (POST /inventory/site-admission),
then the reference becomes the occupant's {"uuid"}, checked against the
parameter's AllowedResourceTemplates, and is frozen into the plan, the
attempt params and the task input (material_site_bindings records it).

An unknown Site, an empty Site or a wrong template is a preflight error:
material_site_invalid on task creation and invalid_material_site in the
preflight report, with reason, parameter and Site in the details.
A SiteSlot parameter with a Material.site relation (and a SiteSlot
workflow input) may be given as {"owner_uuid": ...}. At task admission the
scheduler reserves, through the existing ingress reservation, the first
free Site under that owner (by ordinal) whose acceptor (template whitelist
and allowed categories) takes the occupant material, then freezes the Site
uuid into the plan, the attempt params and the task input
(site_selections). An input used by several nodes is selected once.

No acceptable Site fails the task before start (plan_not_executable,
reason no_acceptable_site); all acceptable Sites taken keeps it pending
with wait_reason site_group_unavailable until one frees. Forms that can
never work are rejected at task creation (site_selection_invalid). The run
preflight reads the candidates without reserving.

The reservation turns in_transit when the action using the Site is
dispatched; an in_transit carrier placed straight into its reserved Site
completes it, and the task end closes what is left
(ingress-reservations/finish-task). Exact Site uuids are unchanged.
…run post_init

A device that calls materials.assign from its post_init makes the authority
commit the move and then ask the device to unload / load through the Host
relay and HostLink material.sync. The ROS 2 Slave registered its downlink
handlers (material.sync, resource tree sync, resource append, device manage)
only after every device had been initialized, so that callback came back as
"unknown action: material.sync" and the assign failed with 503 while the move
stayed committed.

setup_slave_network_client now registers the downlink handlers when it
creates the Slave's HostLink client, before the link connects and before any
device exists; main_slave_run no longer registers them after device init.
The handlers look the device node up per request: a ROS device node is in
registered_devices before its driver's post_init runs, so a device still in
post_init is found, and a device that does not exist yet gets a clear error.
Incoming requests run on the client's RPC worker pool and the projection runs
on the node's executor, so an assign blocking in post_init does not wait on
itself, also when source and target are the calling device.

The HostLink Slave already registered its handlers in _start_slave before
assembling devices, and its nodes are in the local runtime before post_init;
a test now covers an assign from post_init there as well.
…the destination

When the device-side unload or load of an assign fails after the authority
committed the move, the caller sees an error while the move stands. Calling
assign again then got "material is already at destination" from the
authority; unless the node already held the material, assign re-raised it,
so the retry could never succeed.

A no-change answer now means the authority already has the material where it
was asked to be. If the node holds it, assign stays a no-op; if not, assign
loads that subtree from the authority through the same material_sync load
the transfer uses, on the destination Site, and returns success. Only real
errors raise. A multi-material command that the authority rejects as
no-change because one material is already in place is retried one material
at a time, so the others still move.

The authority keeps committing before it projects to devices: it does not
probe reachability first (a device can still drop between a probe and the
dispatch) and does not roll back. A failed projection converges on retry:
replaying the same command replays unload / load, and a new assign loads from
the authority as above. The transfer_material docstring and the materials
guide say so.
@Xuwznln
Xuwznln marked this pull request as ready for review November 25, 2026 08:54
@Xuwznln
Xuwznln merged commit 6270abb into dev Nov 25, 2026
5 checks passed
@Xuwznln
Xuwznln deleted the feat/unified-plr-materials-integrated branch November 27, 2026 13:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant