Skip to content
Back to skills

Python Bindings

ASecurity

The Python SDK - foreign/python/, PyO3 bindings over the Rust laser-sdk crate. Use when changing the Python surface (PyLaser, the publish/query/kv/fork builders, the agent runtime and the async-callback handler consumer, errors, stubs), the maturin packaging, the .pyi stubs, the pytest suite, or the Python BDD runner under bdd/python/.

  • 14 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added October 7, 2026
developmenttypescriptpythonrustgosqlnodeapibackenddocumentation

Works with

  • cursor
  • terminal
  • cli
  • api
  • mcp

Security analysis

A100/100

Scanned November 30, 2026

npx -y skills add laserdata/laser-sdk --skill python-bindings --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Python Bindings?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Python Bindings
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/laserdata-python-bindings/badge)](https://www.skillsdirectory.com/skills/laserdata-python-bindings)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: python-bindings
description: The Python SDK - foreign/python/, PyO3 bindings over the Rust laser-sdk crate. Use when changing the Python surface (PyLaser, the publish/query/kv/fork builders, the agent runtime and the async-callback handler consumer, errors, stubs), the maturin packaging, the .pyi stubs, the pytest suite, or the Python BDD runner under bdd/python/.
---

# Python bindings (foreign/python)

Python uses PyO3 bindings over the Rust `laser-sdk` crate. Keep data encoding and runtime behavior in Rust. The native TypeScript implementation is maintained separately under `foreign/typescript/`.

## Layout

- `foreign/python/Cargo.toml` - the binding crate (`laser_sdk_py` lib, `cdylib`), depends on `laser-sdk` with the managed and agent surfaces, and uses Iggy's native VSR transport. The crate is excluded from the root workspace and has its own lock.
- `pyproject.toml` - maturin build, PyPI name `laser-sdk`, import name `laser_sdk` (set via `tool.maturin.module-name`, since the cdylib lib name is `laser_sdk_py` to avoid clashing with the Rust crate's `laser_sdk` lib).
- `src/client.rs` and `src/stream.rs` bind `Laser`, capabilities, the stream/topic accessor grammar, typed topics, publish/batch/replay/ensure, and `producer`/`consumer`/`consumer_group`. `src/admin.rs` binds the frozen `StreamInfo`, `TopicInfo` (`message_expiry_ms`), `PartitionInfo`, and `ConsumerGroupSummary` classes that `Laser.streams`, `Stream.get`/`exists`/`topics`, and `Topic.get`/`exists`/`delete`/`partitions`/`add_partitions`/`delete_partitions`/`consumer_groups` return. `ConsumerGroup.delete` removes a group. `Stream.rename`, `Topic.update` (keywords), and `Topic.delete_segments` live in `src/stream.rs`. `src/server.rs` binds `Laser.users`/`user`/`personal_access_tokens`/`personal_access_token`/`ping`/`stats`/`me`/`clients`/`client_info`/`cluster`/`snapshot`/`describe_options`/`metadata_changes`, the `OptionInfo`, `MetadataChangeStart` (static `earliest`/`latest`/`after`/`current`), `MetadataChanges`, `MetadataChangeRecord`, `MetadataItem`, and `MetadataSubject` classes, and the `User`, `UserInfo`, `PersonalAccessToken`, `PersonalAccessTokenInfo`, `ClientInfo`, `ClientConsumerGroup`, `ServerStats`, `CacheMetrics`, `ClusterInfo`, and `ClusterNode` classes. Permissions cross as serde dicts, and user status, node role, and node status are plain words. `get()` and `exists()` read a missing stream or topic as `None` or `False`, and `topics()`, `partitions()`, and `consumer_groups()` raise an error with `stream_or_topic_not_found` set.
- `src/transport.rs` binds `Producer`, `Consumer`, and `ConsumerMessage`. Preserve routing, batching, retry, polling, group, header, and commit behavior. It also provides offset inspection and continuous asynchronous reads.
- Direct and fluent sends return immutable `SendMessagesResponse` and `SendMessagesConfirmationResponse` classes. Keep their stream, topic, partition, and base-offset fields in parity with Rust, regenerate the stub after changes, and never turn an empty confirmation list into a client error.
- `src/publish.rs`, `reader.rs`, `typed.rs`, `schema.rs`, `query.rs`, `watch.rs`, `kv.rs`, `fork.rs`, `graph.rs`, and `filters.rs` bind the data-platform write and read surfaces. `filters.rs` binds `ConsumerFilter`, `FilterExpr`, the filtered reader, and the catalog client, and must stay in parity with `sdk/src/filters/`. Complex managed shapes cross through serde instead of hand-maintained mirror classes.
- `src/batching.rs` binds `Topic.batching()` and `BatchingProducer` (`send`, `flush`, `close`). `Topic.send(payload, *, headers, partition_key)` and `Topic.batch(messages, *, partition_key)` mirror the Rust raw sends.
- `src/registry.rs` binds `Laser.agent_registry()` (`AgentRegistry` with `refresh`, `refresh_presence`, `agents`, `lookup`, `resolve`, `is_quarantined`, `inbox_for`, `inbox_for_principal`, `principal_for`), `publish_card`, `quarantine_signed`, `unquarantine_signed`, `advertise_presence`, `clear_presence`, `client_metadata` (a `ClientMetadataPage` with `clients` and `next_cursor`), and `Laser.agent(id)` returning `AgentScope` (`send`, `ask`, `contract`, `publish_card`, `advertise`, `id`). `agents`, `lookup`, and `resolve` return `RegisteredCard` objects (`agent`, `card`, `observed_at_micros`, `is_fresh`, `serves`, `available_for`), and `resolve_targets` mirrors Rust. The card itself and presence cross as dicts. Route scorers receive `RouteCandidate` objects.
- `src/agent.rs`, `agdx.rs`, `agent_runtime.rs`, `workflow.rs`, `session.rs`, `session_ops.rs`, `rbac.rs`, `context.rs`, `memory.rs`, `state_store.rs`, and `sign.rs` expose agent behavior. Keep these bindings consistent with Rust. `laser.agdx(..., signing_key=)` signs producer envelopes, and `spawn_agent(signing_key=)` signs replies through `PyAgentCtx`. `verifier=` selects receive-side keys. The `agent_ctx` test helper also accepts `signing_key=`.

`laser.sessions(*, stream=, layout=, idle_timeout_ms=, heartbeat_ms=, register_source=, fail_on_dead_letter=, memory_namespace=, context_turns=, context_tokens=, sdk=(language, version))` returns `Sessions` (`src/session.rs`). `SessionLayout` is a complex enum: `Shared()`, `PerAgentTopic()`, `PerAgentPartition({agent: partition})`, `SinglePartition()`. `TopicRetention(expiry_ms=, max_size=)` and `TopicRetention.expire_after(age_ms)` refuse never-expire with no size bound. `create(label)` and `start()` return a `SessionBuilder` (`agent`, `namespace`, `parent(parent, root)`, `with_id`, `idle_timeout(timeout_ms)`, `budget(Budget(tokens=, cost_micros=))`, `tag`, `id()`). `await begin()` returns `(Session, SessionLease)`. `async with builder as session:` begins in `__aenter__`, fails with the exception type and traceback in `__aexit__` when the block raises, ends otherwise, and lets the original exception win when the terminal write fails. `open(conversation_id)` is a lens. `bootstrap(partitions=1, retention=None)` returns `SessionBootstrap` with `registered`. `submit(agent, input).from_(submitter).operation().label().namespace().budget().tag().send()` returns `Submitted` (`session`, `correlation`). `control(stream, id).as_operator(op)` provides `pause`, `resume`, `cancel`, and `force_cancel`.

`Session` exposes `conversation`, `stream`, `agent`, `parent`, `root`, `config`, `as_agent`, `append(envelope_dict)`, `end`, `fail(error_dict)`, `cancel`, `run(lease, work)`, `cancel_requested`, and the `src/session_ops.rs` helpers: `ModelRequest(model, body, *, provider, operation)`, `ModelResponse(body, *, model, finish_reason, usage, duration_ms)`, `assemble(policy) -> AssembledContext` (`fragments`, `manifest` dict, `text()`), `model(request, assembled=None) -> ModelCall`, `tool(name, args) -> ToolCall` (both with `correlation`, `complete`, `fail`), `record_model_call`, `record_retrieval(query, items)`, `record_compaction(dict)`, `state() -> SessionState` (`set`, `patch`, `snapshot`, `get -> dict`), `kv(namespace)`, `linked_graph(name)`, `linked_memory()`, `reference() -> dict`, `redact(fn)`, `acting_on(source_dict)`, and the module function `default_redact`. `context(*, last_n, token_budget)` returns `list[SessionTurn]`, with `display`, `text()`, and `message`, a `ContextMessage` (`id`, `provenance`, `payload`, `body`, `envelope`, `topic`, `timestamp_micros`, `stream_id`, `topic_id`). `SessionBuilder.resume()` reopens a completed or failed session, `begin()` raises `SessionEndedError` (`session`, `status`) for an ended one, `SubmitBuilder.id()` names the submitted session, and `async with` and `run` end a session canceled when the task is cancelled. `AgentCtx.session()` returns the handled record's session. `src/session_reads.rs` binds the managed reads: `Sessions.get(id)`, `list(*, status, root, label_prefix, agent, text, page=0, results=0, as_of=None, series=None)`, `events(id, *, page=0, results=0, as_of=None, series=None)` (a half bound raises `InvalidError`), `state(id, history_limit=0)`, `links(id, surface=None)`, `sources(id)`, `changes(page=0, results=0)`, and `watch(poll_every_ms) -> SessionWatch` (one-call start, a zero interval raises `InvalidError`, `next()` and `async for` yield `SessionChange.Changed` or `Resync`), all returning serde dicts, `Session.status()`, `Session.over_budget()`, `Session.pending_control() -> PendingControl`, `SessionControl.signed_by(key)`, `Laser.read_at(source_dict)`, and `SessionError` for a failed read. `spawn_agent(sessions=Sessions)` applies that factory's configuration, including `fail_on_dead_letter`. P6: `SessionControl.participants(agents)`, `Session.parked() -> ParkedRecords`, `Session.signed_by(key)`, and the `session.parked` and `session.unparked` display types. S0: `Laser.connect(..., resource_naming="stream" | "bare")`, `with_resource_naming`, `resource_naming`, `resource_name(name)`, `Kv.resource_namespace`, `ForkHandle.resource_id`, `ConsumerFilter.schema_stream` and `with_schema_stream(stream)`, `Capabilities.stream_tenancy` and `with_capabilities(stream_tenancy=)`, and `ChangeRecord.stream`. AG-UI: `publish_state_snapshot(source, conversation_id, state)`, `publish_state_delta(source, conversation_id, patch)`, and `reconstruct_state(conversation_id)` take no topic. `SessionRef`, `SessionStateView`, `StateChange`, `SourceFrontier`, `ContextManifest`, and `Fragment` cross as serde dicts. A `SessionPage` dict holds `rebuilding` only when it is true, like the `SessionFlags` keys.

`memory()` returns `ScopedMemory` in the configured namespace, and `memory_in(namespace)` opens another namespace. `ScopedMemory` provides `recall(folded=, agent=, user=, application=)`, `search(query, limit=, folded=)`, `remember(kind=, durable=, dedup=, ...)`, `block(token_budget=None)`, `consolidate(max_items)` returning `ConsolidationReport`, `forget(id)`, `improve(target, weight, *, note)`, and a `handle` property. `checkpoint()` returns a `Checkpoint` with `to_json` and `from_json` methods. `turns_at` and `turns_since` read around its saved offsets. `state_at(checkpoint, init, fold)` and `replay(checkpoint, init, fold)` rebuild state. `ScopedMemory.with_lineage(origin, producer)` stamps remembered items, and `origin` and `producer` read them back. `Kv.in_session(ref_dict)` and `GraphHandle.in_session`, `produced_by`, and `sourced_from` link writes to a session.

`laser.topic(name).replay()` returns `Cursor`. `Laser.assemble_context` reads a conversation with topic, role, last-count, and token-budget controls. `laser.context(conv)` returns `ContextScope`. Its `fetch` and `block` default to `agent.sessions` and map `n` and `token_budget` to Rust `Chain(LastN, TokenBudget)`. Context reads, folds, policies, and estimators receive `ContextMessage`, not `AgentMessage`. `fetch_with(topics, policy)` takes the `LastN`, `TokenBudget(max_tokens, estimator=None)`, `RoleFilter(agents)`, and `Chain` classes, each with `name`, `version`, and `selection(history)`. A custom policy reports `name` and `version` attributes. `state(topics, init, fold, ...)`, `state_with(store, topics, init, fold)`, and `checkpoint` fold the conversation log like Rust, as do the free `context_checkpoint(laser, topics)` and `ConversationState.load`/`load_with`. `memory()` accepts a namespace or a handle, `memory_with(namespace, backend, *, embedder)` picks a backend, and the module constant `CONTEXT_READ_WINDOW` is the 10,000-record read window. RBAC includes `bind_roles(principal, roles, expect_revision=, mutation_id=)` (`define_role` and `delete_role` take `mutation_id=` too, the caller's receipt identity for an exact repeat after a lost reply), `get_bindings(principal)`, `Grant(feature, action, *, effect, resource=ResourcePattern.prefix(..))`, and `authz_history("all" | {"role": n} | {"binding": {"user_id": id}}, after_revision=, limit=)`.

`A2aBridge(laser, source, request_topic, reply_topic, *, capabilities=, signing_key=, target=, public_url=, description=, version=, allowed_origins=)` provides `submit(params_json, *, target=, previous_hops=)`, `submit_in(parent, params_json, *, root=, target=)` as a child session, task, cancel, card, and `signed_card(key)` operations. `McpBridge(laser, source, tool_topic, reply_topic, server_name, *, memory_tools=False, timeout_ms=None, signing_key=, target=, allowed_origins=)` provides initialization, `call_tool(name, params_json, *, target=, previous_hops=)`, `call_tool_in(parent, name, params_json, *, root=, target=)` as a child session, tools, resources, and prompts through configured `McpPrompt` values. Without `target` a bridge call reaches every agent on a shared session topic. `Agdx.request_input(reply_topic, prompt, *, timeout_ms, target=)` addresses its prompt the same way. AG-UI methods include `publish_state_snapshot`, `publish_state_delta`, `reconstruct_state`, and `agui_events`. `AgentCtx.respond_input` answers an interrupt. `serve(host=, port=)` (A2A also `caller=`) runs the Rust axum `router()` on the binding's runtime and returns a `BridgeServer` (`src/bridge_http.rs`), so the routes and the origin guard are the Rust ones. It adds no pip dependency, but the binding crate depends on axum and tokio `net`, which link into the native module. The `caller` hook is an axum middleware that calls the Python hook (plain or async) for `POST /` only and inserts `A2aCallerPrincipal`. A raising hook or a non-string result answers 401. Applications can still host `handle_rpc` through their own framework.

`Laser.memory`, `Laser.memory_on_topic(name, stream=)`, `Laser.memory_topic(name, partitions=, ttl_ms=)`, and `Laser.memory_with(namespace, backend="auto"|"log"|"vector", embedder=None)` return a `MemoryHandle`. `MemoryHandle.remember` takes `agent`, `conversation`, `stream`, `user`, `application`, `kind="fact"`, `durable=False`, and `dedup=False`, and `context`, `consolidate`, `forget(id)`, `append(id, ...)`, and `improve(target, weight)` mirror the Rust handle. `recall(...)` returns `list[MemoryItem]` and `recall_block(...)` the rendered block. `supersede(old_id, payload, ...)` corrects a fact. `Laser.scratch_stream(prefix)` is an `async with` `ScratchStream` (`name`, `laser`, `delete()`). Topic expiry defaults to 30 days. The subclasses `LogMemory(laser)` (`in_namespace`, `on_topic`, `on_stream_topic`, `*_named` state ops), `VectorMemory(embedder)`, and `RerankedMemory(inner, reranker)` build each backend. `VectorMemory(embedder)` is standalone, while `VectorMemory.governed(laser, embedder)` inherits the Laser governor. `to_context_block`, `memory_id_content`, `memory_kind_class`, and `memory_kind_code` are module functions. `MemoryItem.text()` is a method and `MemoryItem.signals` returns `RecallSignal` objects. Embedders can return vectors directly or return awaitables.

Default `recall` reads the managed KV view when the deployment serves it, waiting for the connection's own writes, and folds the log otherwise. `recall(folded=True)` and `fetch_folded` always read the log locally. `MemoryItem.source` identifies the original record. The durable handle also provides `set`, `fetch`, `update`, and `remove` by name. Vector memory returns `UnsupportedError` for those named-state operations. `InMemoryStore` and `FileStore` implement `StateStore`.

`Laser.graph(name)` returns `GraphHandle` with `upsert`, `link`, `unlink`, `relink`, `neighbors(node, dir, edge_type, depth)`, and a fluent traversal: `start_ids`, `start_match(Filter)`, or `start_nearest(embedding, k)`, then `out`, `incoming`, `both`, `hop(dir, edge_type, max)`, `node_filter`, `edge_filter`, `return_edges`/`return_triplets`/`return_paths`, `limit`, `as_of`, `conversation`, `into_query()`, and `fetch()`. Nodes, edges, results, and `SourceRef` cross as serde dicts, with attributes as `[name, value]` pairs. `node_id_content`, `edge_id_content`, `graph_node_entity`, and `graph_edge_relate` construct content IDs and records. `register_graph` defines a graph projection, as demonstrated in `examples/python/memory.py`.

Graph traversals, queries, and KV scans scope with `.conversation(id)`. Build the Rust handles for each Python call and retain owned state between calls. The local vector backend shares its items through `Arc`.

- `src/bin/stub_gen.rs` - generates `laser_sdk.pyi` and appends the exception hierarchy (which `create_exception!` does not expose to the stub gatherer).
- `tests/` - pytest. `test_smoke.py`, `test_parity.py`, `test_parity_helpers.py`, and `test_coordination_client.py` need no server. `test_readme_snippets.py` compiles every README Python block with the standard library compiler (what `just python-docs` runs) and, as an `integration` test, runs every block that contains `asyncio.run(` as a standalone program against the test server. It also checks that every README shows the standalone workflow and memory-correction examples of its languages verbatim, `test_standalone_examples.py` runs the two Python examples and compares their JSON with the TypeScript example test's, and `test_context7.py` checks `context7.json` against the Context7 schema limits (`just python-docs` runs it too). `test_defaults.py` covers the bootstrap defaults and the next-step error texts. `test_cluster.py` and `test_cluster_filters.py` run three-node clusters through `IggyTestCluster` in `iggy_test_server.py` (`set_node_environment`, `kill_node`, `partition_primaries`, `settled_primaries`, `topic_details`), and `test_cluster_filters.py` binds group policies through `StandInCatalog`, which builds and launches the `laser-test-catalog` and `laser-test-routes` binaries of the `test-support/` crate with cargo on first use. `test_integration.py`, `test_filters.py`, `test_publish_failures.py`, `test_resume_parity.py`, and the callback suites (`test_trait_hooks.py`, `test_snapshot_callbacks.py`, `test_workflow_callbacks.py`) use the shared native Iggy fixture. `test_connect_timeout.py`, `test_rbac.py`, and `test_reconnect.py` cover connection behavior.
- `bdd/python/` - the Python BDD runner over the shared Gherkin in `bdd/scenarios/`. Streaming, capabilities, provenance, and agent run against Iggy. Query and key-value CAS use the transport-free reference engine.

## Data stack parity

`src/query.rs` binds Query, `QueryBuilder`, and the `Filter` predicate class (the Rust struct is `PyQueryFilter`, apart from the consumer-filter `FilterExpr`), with `filter`, `having`, `agg_as`, `max_rows`, `rows`, `rows_typed`, `deadline(deadline_ms)`, `deadline_at_micros`, `window(field, every_ms)`, and `execution_id`, an explicit operational target, typed raw SQL parameters, offset paging, and rich result context. Query results expose `fields`, positional tagged `Row.values`, and `page` (a `Page` with `offset`, `total`, `has_more`, `at_least`, `total_pages`). Never restore `row.headers`. Use `QueryResult.value`, `value_text`, `value_u64`, and `value_i64` for field-name access. Walks wrap the Rust `QueryRow`: `rows()` yields `QueryRow` (`row["name"]`, `row[0]`, `keys()`, the same `value*` accessors, `QueryRow.from_page(fields, rows)`), `fetch_all()` returns `QueryRowSet` (`rows`, `frontier_moved`, `len`, indexing, iteration), and `QueryRows` and `TypedQueryRows` expose `frontier_moved`. The walk itself is `RowWalk` in `src/query.rs`, which compares each page's frontier with the first page's.

`src/publish.rs` exposes `arrow_ipc` and `add_arrow_ipc`. Metadata crosses through serde and exact payload length is checked before I/O. Keep the self-contained Arrow stream policy in stubs and README examples.

After a data-contract change, regenerate `laser_sdk.pyi` and update stub tests, Python tests, the shared BDD scenarios, and README examples. Use serde-derived dictionaries for large managed types rather than separate Python data definitions.

## How the binding works

- Every relative duration is milliseconds with an `_ms` name (int or float accepted, `convert::duration_ms`, a pyo3 default written as a float literal such as `max_wait_ms=5000.0`), an absolute deadline is `deadline_at_micros` (`Provenance`, `Intent`, the `Agdx` verbs, `AgdxStream.with_deadline_at_micros`, `QueryRequest.deadline_at_micros`), and other absolute times stay `_micros`. The wire envelope constructors, `QueryBuilder`, and `FilterAnnounce.max_wait_ms` keep their wire names. Every async Rust method becomes a Python awaitable via `async_bridge::awaitable` (or `awaitable_returning` for a read a cancelled caller hands back), whose `Awaitable<'py, T>` return type renders `typing.Awaitable[T]` in the stub from the type the future resolves to. A binding never returns the untyped `future_into_py` result. The factories whose value a program uses as a handle (`Laser.connect`, `connect_env`, `local`, `connect_with_stream`, `memory_topic`) return `async_bridge::handle_awaitable` with a `HandleCall`: the object awaits like any other, and an attribute read, `async with` or `repr` before `await` raises an error naming the missing `await` (`memory = await laser.memory_topic(...)`). Its class is not exported and the stub keeps `typing.Awaitable[...]`. `tests/test_agent_start.py` pins it with the package docstring (`PACKAGE_DOC` in `src/lib.rs`, set as `__doc__` and written to the stub by `pyo3_stub_gen::module_doc!`). Binding doc comments are rustdoc too, so a code sample in one uses a ```` ```python ```` fence, never an indented block, which rustdoc would compile as a Rust doctest. A value whose Rust type renders wrongly (`Vec<u8>` resolves to `bytes` at runtime but renders as a list) carries `#[gen_stub(override_return_type(..))]`, a fixed word vocabulary parameter carries `#[gen_stub(override_type(type_repr = "typing.Literal[..]", ..))]`, and a parameter converted through `convert::payload_bytes` is typed `str | bytes | bytearray`. `tests/test_stub_types.py` pins these shapes. `Laser` is `Clone` (Arc inside), so each method clones it into the async block.
- Rust builders are not exposed directly. Most own a `Laser` clone (the projection, binding and schema handles and the projection and schema list builders among them), and the others that keep a lifetime borrow a caller-held value (the memory handle, a claim-check store, a signing key, an approval grant), so the Python builder classes hold owned, accumulated state and reconstruct + run the Rust builder inside the async block at the terminal (`send`/`fetch`). Fluent setters take `PyRefMut<'_, Self>` and mutate in place.
- Complex managed inputs/outputs ride serde. A Python dict deserializes straight into a wire type (`projection`, `binding`, `schema source`, dead-letter capsule) via `pythonize::depythonize`, and structured replies serialize back to dicts. This binds the whole registry/control surface without a class per type.
- `spawn_agent` calls Python `async def handle(ctx, message)` through the Rust consumer. Capture the event-loop locals and run within `scope(locals, ...)`. `into_future` then schedules the coroutine on the correct loop.
- `lib.rs` installs a wrapper over `pyo3_log::Logger`, so Rust `log` records reach Python `logging`. The Iggy producer's `Client has been shutdown` warning, written whenever a `Laser` closes, is logged at debug. Every other record keeps its level.
- `Laser.query`, `Laser.query_target` (operational index), and `QueryRequest.fork` scope their names through `Laser::resource_name`, because `PyQuery` builds the `Query` itself rather than wrapping the Rust builder. Any other binding that builds a managed request itself must scope its names the same way.
- Map `LaserError` to the hierarchy in `errors.rs` and retain classification attributes such as `code`, `retryable`, and `unsupported`. `TimeoutError` also inherits `builtins.TimeoutError`. `CancelledError` also inherits `asyncio.CancelledError`. Cache these generated exception types in `OnceLock` so both SDK and standard exception handlers recognize them.
- `Cursor`, `WatchReader`, and `TypedRecords` provide `__aiter__` and `__anext__`. They yield buffered records and raise `StopAsyncIteration` when caught up. A later iteration resumes from saved offsets. Keep `poll()` and typed `next()` available.

`Consumer` instead waits for new records until `shutdown()`. It supports automatic and explicit commits, and `next_within(wait_ms)` raises `TimeoutError` like Rust. `commit_interval_ms` defaults to 0 and `auto_commit` to `"all"`, so the default policy is `All` like Rust. `seek(partition, polling=, offset=, timestamp_micros=)` mirrors Rust `Consumer::seek`. `await laser.watch()` reads the capabilities again and raises `UnsupportedError` when the change feed is unavailable, `from_end=True` starts at the feed's end, and `WatchReader.from_offsets` resumes a reader. `WatchReader` holds one Rust reader behind an async lock, so its `missed` and `skipped` counts carry across polls. `header_kinds` reports exact Iggy types. Use `(kind, value)`, such as `("uint16", 7)`, for an explicit numeric width.
- The live consumer avoids an intermediate payload copy. `PyConsumerMessage` retains Apache Iggy's reference-counted `Bytes` until its `payload` getter creates the one Python-owned `bytes` object required by the language boundary.
- `Laser` provides `__aenter__` and `__aexit__` for `async with`. The connection closes when the last shared handle is dropped. `with_default_stream`, `with_ops_stream`, `with_control_topic`, `with_dlq_topic`, and `with_changes_topic` share that connection. `Laser.capabilities()` and `refresh_capabilities()` use Rust discovery. `Capabilities.query`, `kv`, and `filters` are `QueryCaps`, `KvCaps`, and `FilterCaps` objects, never flat booleans. Preserve unavailable-backend handling and explicit handle overrides.
- `Laser.connection_events()` (`src/connection.rs`) is synchronous and returns `ConnectionEvents`, an async iterator of event words. It subscribes on a spawned Tokio task at once, so events after the call are not lost before the first `__anext__`, and it stops after `"shutdown"`.
- `spawn_agent` exposes `max_partitions`, `shutdown_grace_ms`, `retry_max_attempts`, `retry_base_delay_ms`, `dead_letter`, and `middleware`. The dead-letter callback receives message, the full wire capsule dict, and a typed publication error or None through `PyDeadLetterSink`. Middleware `after_handle` receives the message, an {ok, error} result dict, and attempt. Both observers accept direct values or awaitables. `Laser.contract` returns a `Contract` (`Completed`, `Failed`, `NotConsumed`, `TimedOut`) and `Laser.scatter_report(...)` returns a `ScatterReport`. `Provenance` keeps `correlation_id` separately from `idempotency_key`. `AgentMessage` exposes `id` (a `MessageId`), `provenance`, `payload`, `envelope`, and `body()`, with no per-field shortcuts.
- `AgentCtx.fan_out(skill, payload, *, deadline_ms, gather, quorum, principal, policy)` (`deadline_ms` required, as on `scatter` and `scatter_report`, which take `gather=` and `quorum=` too, `policy=` always the route policy) (branches follow the agent inbox route) returns a `Gather` (`ok`, `failures`, `replies()`). `approval_gate(approver, reply_topic, prompt, *, timeout_ms)` returns an `ApprovalGrant` (`approver`, `conversation`, `correlation`, `decision`) that an AGDX verb carries with `grant=`. `respond`, `reply_on`, `respond_input`, and `approval_gate` rebuild the Rust `AgentCtx` per call (`OwnedContext`), so Python replies follow the Rust reply contract. `spawn_agent` consumes the declared per-agent topic under a `PerAgentTopic` layout, refuses `ack_on_pickup` without `respond_on`, and advertises through the hidden `laser_sdk::agent::Advertisement` (`start` before the consumer runs, `withdraw` after). Module functions `agent_message` and `agent_ctx` let tests call handlers without a live consumer.
- Governance delegates to Rust. Preserve mandatory-voter rules and rejection of invalid configurations. `SwappableGovernor.swap` returns the previous policy, and `current` returns the active one. `Intent`, `Vote`, and `Decision` use typed topic encoding. Invalid construction, voting, or folding raises `IntentError`, an `InvalidError` subclass with a `kind`. `ActionDecision.verdict` is a `Verdict`, `with_policy` takes a `PolicyRef`, and `GovernedAction.counters` holds the `ActionCounters`.

Call `Decision.authorizes(intent)` before the effect. Names remain claims unless signatures or topic permissions establish authorship. `SwarmActivity` preserves unknown verdict names and ignores repeated evidence. `CrashContext` exposes `journal`, `dead_letter`, and `last_decision` and escapes control characters in summaries. Keep parity tests and stubs current.
- Contracts default to a 30-second `deadline_ms` like Rust and TypeScript, and take `agent=` (named-agent routing), `expire_if_not_consumed_ms`, `reply_on`, `conversation`, `fence`, and `parent=`/`root=` to run as a child session. `spawn_agent(operations=)` limits the command operations a handler serves. There is no `Laser.runs`, `AgentError`, or `agent_run_state_is_terminal`. `Laser.connect_env`, `local`, `connect_with_stream`, and `with_governor_retention` mirror Rust, and `Laser.connect_env(stream=)` is Rust `connect_env_with_stream`. `NoStreamError` and `NoRespondTopicError` subclass `ConfigError`. Key-value `send()` raises `InvalidError` when a precondition was set, `KvSetRequest.bytes(payload)` sets a raw body, `Kv.exists` returns `KvMetadata`, `copy_to`/`move_to` return an awaitable `KvCopyRequest`, and `cas_fenced` returns an awaitable `KvCasFencedRequest` builder. `execute_query`, `reassemble_channel`, and `consumed` are on `Laser`.
- `Laser.execute_batch` accepts Rust `BatchItem` dictionaries and returns exact reply bytes. `Agdx.status`, `Agdx.fail`, and `AgdxStream.fail` retain their typed data. Convert floating-point millisecond durations through `convert::duration_ms`. Negative, non-finite, and out-of-range values must raise `InvalidError` rather than panic.
- `Kv.lease` and `Kv.renew_lease` return `Lease` with token, granted lifetime, position, and `valid_until` on the `time.monotonic()` clock. Python inherits the dedicated Rust coordination connection, validation, and timeout reset. An uncertain acquisition repeats its prepared identity until its requested lifetime since the first send has passed before raising.

Pass `MutationPosition { topic_generation, partition, offset }` to `Kv.get_entry_at_least` for takeover reads. An unmet position returns stale rather than absent data. `LaserError.ambiguous_mutation` requires operation-specific recovery and must not trigger generic handler retries.

## Versioning and naming

- The Python package is `laser-sdk` on PyPI, imported as `laser_sdk`. The internal Rust crate is `laser-sdk-python` (`publish = false`) with cdylib lib `laser_sdk_py`, named to avoid clashing with the `laser_sdk` dependency crate. Maturin renames the built module to `laser_sdk` via `module-name`.
- Python follows the shared workspace version, currently `0.11.0`. Its dependency must select the matching Rust `laser-sdk` crate.

## Working on it

- Build into a venv: `maturin develop` (the venv lives at `foreign/python/.venv` in local dev).
- Regenerate stubs after any surface change: `cargo run --bin stub_gen`, then check `laser_sdk.pyi` is current.
- `cargo check` for fast type-checking. The crate is outside the workspace, so the workspace clippy/test gates do not cover it: run them here too.
- Lint and format with ruff (configuration in the repo-root `ruff.toml`): `ruff check` and `ruff format --check` over `foreign/python`, `bdd/python`, and `examples/python`. The generated `.pyi` is excluded.
- Tests: `pytest -q` against the versioned Iggy server, plus the BDD suite in `bdd/python`. `LASER_TEST_IGGY_SERVER` selects a local Iggy binary for development.
- After a Rust API or wire change, update Python bindings and regenerate stubs. Update the corresponding tests and documentation in the same authorized change.
- After any public surface change, regenerate `docs/parity.md` with `python3 scripts/check-parity.py --write`, then run `just parity-check`.

`Topic.ensure(partitions, replication_factor=None)` and `Topic.producer(..., replication_factor=None)` set a topic's replication factor on create, `None` the server default. The module constant `MAX_REPLICATION_FACTOR` is 32. Rust validates the range and raises `InvalidError`, and the server's refusal of a factor above the node count is a `TransportError` carrying `iggy_error_code`.

## Publish recovery

`Laser.connect` takes `connect_timeout_ms`, `publish_timeout_ms`, `publish_max_retries`, and `publish_retry_backoff_ms`, which override the `LASER_CONNECT_TIMEOUT_MS` and `LASER_PUBLISH_*` variables. `Topic.producer(retries=None, retry_interval_ms=None)` inherits the connection's retry count and delay, and `retries=0` disables resends. A publish that gives up raises `PublishFailedError` with `stream`, `topic`, `committed`, `unconfirmed`, and the cause as `__cause__`. Each Rust error variant maps to its own exception class, and a handler rejection raises `RejectedError`. Defaults and outage handling are in [publish recovery](../../../docs/publish-recovery.md) and [connect timeout and cleanup](../../../docs/connect-timeout.md).

## Consumer-group filters

Group handles, filter setup, scan budgets, progress, and cross-language test parity follow the [consumer-filters](../consumer-filters/SKILL.md) skill.

## Custom memory and parity surface

`Laser.memory_custom(backend)` wraps a Python object with `remember`, `recall`, `improve`, `forget` (sync or async, dict scopes and queries). `MemoryHandle.reranker(callable)` returns a reranked handle, and the callable runs only when a recall carries `semantic` text. `Topic.cbor(cls)` and `await Topic.schema(schema_id, cls)` are typed topics. Avro and JSON Schema publication encodes values. Protobuf publication requires encoded bytes through the plain raw builder with a schema ID. `PublishRequest.claim_check(store, threshold_bytes)` uses the blob store hooks. `Topic.producer(background=True)` or `background=BackgroundConfig(...)` switches to Iggy's buffered mode and `Producer.shutdown()` waits for sends in flight, flushes, and closes. `Topic.producer(sharding=fn)` calls `fn(ShardRequest) -> int` inline in each background send (`sharding.rs` holds the GIL bridge), and an exception fails that send. `Encryption.aes256_gcm(key)` (`encryption.rs`) passes as `encryption=` to `Topic.producer`, `Topic.consumer` and `ConsumerGroup.consumer`. `Topic.producer(idempotent=True)` sets `ProducerBuilder::idempotent` on the Rust producer. Hooks take a plain callable or an object with the hook method, sync or async. Async hooks run on the calling event loop with its context variables. Sync hooks run on an SDK worker thread and must not block. `ForkHandle.create(continuous=True)` refuses `severed` at the same time. `Workflow.run_id(id)` resumes a run. `step`, `budget` and `run_id` return the workflow so calls chain, `step(label, run=callable)` is a local step, and `WorkflowOutcome` has `completed_steps`, `status` and `text(label)`. `Laser.bootstrap(partitions=1, retention=None)` and `__version__` exist. `Capabilities.is_open_only()`, `serves_consistency(level)`, and `with_capabilities(managed=, query=, query_consistency=, kv=, filters=, materializations=, versions=OpVersions(..), backends=[..])`. `AgdxStream` gains `channel`, `with_deadline_at_micros`, `with_target`, `content_type`, `buffered`, `flush`. `Intent.validate()`. `SigningKey.sign` and `sign_with_context` return a signature dict, and `KeyRegistry` gains `enroll_record`, `verify`, `verify_at`, `verify_observed_at`. `Session.context_with(policy)` and `Session.graph(name)`.

## Coordination and callbacks

`src/coordination.rs` binds `FencedLeaseClient`, `PreparedMutation`, and `DedicatedKvTransport`, and `src/memory_handler.rs` binds `MemoryHandler`. Exceptions raised through a callback keep their SDK class. Cancelling an SDK task retires the asynchronous callback it is running. Context policies stay synchronous.

Query `rows()` and `rows_typed()` return lazy asynchronous iterators under `max_rows`, consumed with `async for`. The managed key registry takes `enroll(principal, verifying)` for an agent key and `enroll_record(record)` for lifecycle metadata. Both bridges expose asynchronous `handle_rpc(request)` returning response dicts.

Materialization setup lives in `sdk/src/materialize.rs`, `foreign/python/src/materialize.rs`, and `foreign/typescript/src/managed/materialize.ts`. The shared scenarios are `bdd/scenarios/materialization.feature` and `bdd/scenarios/operational_sql.feature`. Keep append and keyed history, rejection policies, captured-target readiness, and explicit raw SQL dialects aligned in every client. Read `docs/client-behavior.md` from the repository root for the public contract.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.