# Managed data

Code on this page comes in TypeScript, Rust, and Python. The same page with one language only: [Python](https://docs.laserdata.com/md/python/laser-sdk/advanced/managed-data.md), [TypeScript](https://docs.laserdata.com/md/typescript/laser-sdk/advanced/managed-data.md), [Rust](https://docs.laserdata.com/md/rust/laser-sdk/advanced/managed-data.md).

This page covers the managed backend that serves [Queries and views](/laser-sdk/views), [Key-value state](/laser-sdk/state), and the rest of the managed features. Read it when you run a managed deployment in production.

Streaming and managed calls share one authenticated Iggy connection. Iggy forwards managed requests, such as queries and key-value calls, to the managed backend. Projection and binding changes also use the authenticated managed endpoint, then enter the control log. Filtered group readers and the dedicated fenced-lease client open their own connections. [Laser Stack](/laser-sdk/laser-stack) runs both services locally, and LaserData Cloud runs them for you.

A managed command can return `LaserError::Command` in Rust, `CommandError` in Python, or `CommandExecutionError` in TypeScript. These errors keep the server's result code and message. Use the shared error classifiers to decide how to handle them.

## Check backend readiness

A connection to Iggy does not mean the managed backend is ready. A running backend can still be replaying or restoring data, and its managed operations stay unavailable until it reports ready. After startup, failover, or a backend restart, refresh the capabilities or wait for readiness with a deadline:

**TypeScript**

```ts
import { unreadyBackends } from "@laserdata/laser-sdk"

const caps = await laser.waitUntilReady(30_000)
console.log(caps.query.available, caps.kv.fencedLeases, unreadyBackends(caps).length)
```

**Rust**

```rust
use std::time::Duration;

let caps = laser.wait_until_ready(Duration::from_secs(30)).await?;
println!(
    "{} {} {}",
    caps.query.available,
    caps.kv.fenced_leases,
    caps.unready_backends().count()
);
```

**Python**

```python
caps = await laser.wait_until_ready(30_000)
print(caps.query.available, caps.kv.fenced_leases, len(caps.unready_backends()))
```

`refresh_capabilities()` (TypeScript: `refreshCapabilities()`) reads a fresh snapshot without waiting. `capabilities()` returns the held snapshot, and probes again by itself when that snapshot has no managed backend, or has an enabled backend that is not ready yet, and its last probe is at least one second old. A backend that finishes starting after the connection opened, or whose query identity becomes valid later, is picked up this way, so raw SQL and the other backend-served surfaces become available without a reconnect. The wait returns an unsupported error when the server has no managed backend descriptors. See [Connect](/laser-sdk/connect#managed-readiness) for the connection side.

Check the feature you need on its own. Query support does not imply fenced leases or every consistency level. The capability groups are objects in all three SDKs, with camelCase fields in TypeScript:

| Group | Fields |
| --- | --- |
| `caps.query` | `available`, `consistency` (the strongest level served), `keyword` |
| `caps.kv` | `available`, `cas`, `cas_fenced`, `fenced_leases` |
| `caps.filters` | `native`, `catalog`, `group_policy_reads`, `evaluation` |

The flags `managed`, `graph`, `forks`, `a2a_gateway`, `sessions`, `watch`, `authz`, and `stream_tenancy` sit directly on the capabilities, beside `versions`, `backends`, and `hello`. Every feature is off until the server reports it.

### Backend descriptors

Each backend descriptor names a resource ID, a mode (operational), a label, the `implementation` kind and version, the observed backend generation, the `runtime_configuration_revision`, the desired and observed state, the `readiness` state with reason codes, and the query, schema, and limit support. A descriptor reports what the deployment actually serves.

| Need | Rust and Python | TypeScript |
| --- | --- | --- |
| Backends that should be running | `caps.enabled_backends()` | `enabledBackends(caps)` |
| Enabled backends that are not ready | `caps.unready_backends()` | `unreadyBackends(caps)` |
| Why one backend is not ready | `caps.readiness_reasons(resource_id)` | `readinessReasons(caps, resourceId)` |
| One backend by ID | `caps.backend(resource_id)` | `backend(caps, resourceId)` |

Rust returns iterators from the first two. Python returns lists.

## Operational indexes

A projection names the fields to extract. Its binding selects a source and an `index`. A source feeds one index. Applying a binding for a source that is already bound replaces its binding, so a second `materialize().index(..)` on the same topic moves the topic to the new index: the earlier index stops receiving rows and keeps the ones it has, and the new index replays the retained log. An optional `backend` pins a resource ID and generation. Rotating the backend credentials or changing its tuning keeps the generation, so a pinned binding keeps working. A credential rotation reaches the running nodes without a restart. Each node first opens one connection with the new credentials, and keeps the old ones if that fails. Pointing the backend at another host, database or schema advances the generation, and a binding pinned to the old generation must be applied again. A binding belongs to the stream it was applied to. When that stream is deleted, or deleted and created again under the same name, the binding stops projecting and the managed backend removes it, so apply it again for the new stream. Without a `backend`, the binding uses replica-local operational storage. Moving an existing binding to another backend refills the new one from the source log. When the log no longer holds the source's whole history, the move is refused with `Conflict`, because the new backend would silently miss rows. To accept the incomplete history, remove the binding and apply it again. The managed backend then records the late start as a gap. `notify` adds the binding to the [change feed](/laser-sdk/advanced/change-feed). An optional `retention` sets how long rows live, independent of the source topic. Without it, the deployment default applies, which mirrors the log unless an operator changed it: rows go when Iggy removes the messages that produced them.

The serialized form of a binding, as Python and the protocol use it:

```json
{
  "source": { "stream": "telemetry", "topic": "readings" },
  "allowed_projections": ["readings_v1.v1"],
  "default_projection": "readings_v1.v1",
  "index": "readings_v1",
  "notify": true
}
```

TypeScript uses the same fields in camelCase. All three SDKs also have a binding builder. See [Queries and views in depth](/laser-sdk/advanced/views#bind-a-topic).

## Typed query results

A result contains `fields`, `rows`, `page`, and `context`. The values in each row follow the order of `fields`. Each value is a tagged typed value that keeps booleans, integers, longs, floats and doubles, decimals, dates in days, times and timestamps in microseconds, UUIDs, fixed and variable binary values, strings, lists, maps, structs, and nulls apart. A vector or lexical query also returns a `score` on each row.

The fields and their types come from the query and the projection, so every page of one query has the same schema. A field typed `int`, `float`, `bool`, or `text` is a long, double, boolean, or string, and a stored value that does not fit is null. A field without a type, a selected field no projection declares, and every raw SQL column have the type `variant`: each value keeps the type it was stored with, so check its tag before you read it as a number.

| Language | Read a field |
| --- | --- |
| TypeScript | `queryResultValue(result, row, "cpu")`, `queryResultValueU64(..)`, `queryResultValueI64(..)`, or `queryResultValueText(..)` |
| Rust | `result.value(row, "cpu")`, `result.value_u64(row, "cpu")`, `result.value_i64(row, "cpu")`, or `result.value_text(row, "cpu")` |
| Python | `result.value(row, "cpu")`, `result.value_u64(row, "cpu")`, `result.value_i64(row, "cpu")`, or `result.value_text(row, "cpu")` |

`field_index(name)` (TypeScript: `queryResultFieldIndex(result, name)`) returns a field's position. `typedValueDiagnosticText(value)` in TypeScript and `ls.typed_value_diagnostic_text(value)` in Python render any typed value as text.

Use typed accessors for logic and text accessors for display. The client rejects a result whose rows have the wrong number of values, or a value that does not match its field type. Every page stays bound to the execution ID of the query that asked for it. `context` records the engine, the target, backend identity and generations, the requested and delivered consistency, and resource use.

## Retry and recovery

Every managed mutation carries a stable operation identity, so the managed backend can return the saved outcome when the same mutation arrives twice. Reads can reconnect and retry. A read that every node refuses with `BackendUnavailable`, for example while the backend replays its logs after a restart, waits and is sent again until its deadline, 30 seconds by default, as [Managed requests](/laser-sdk/connect#managed-requests) describes. Mutations retry only with their original identity, and a deterministic rejection, such as invalid input, is never retried. A lost reply does not prove that the mutation failed.

Lease acquisition is the exception that needs care. The SDK never repeats a lease acquisition after an uncertain disconnect. Ordinary key-value lease calls wait out the requested lease lifetime and then report the uncertainty. Until that lifetime has passed, do not assume that no lease exists.

The fenced-lease client, `FencedLeaseClient` in all three SDKs, prepares each acquisition, renewal, release, or fenced write once. The prepared request keeps its operation ID and exact bytes. Repeat it only when its recovery action allows that: renew and release can repeat, an uncertain acquisition waits out the lease lifetime, and a fenced write needs to be checked against its target. Each attempt times out after 10 seconds by default. A renewal keeps the fencing token, and a release revokes it at once. Before planning a protected write, wait for a read that includes the lease's commit position. See [Key-value state in depth](/laser-sdk/advanced/state).

- [Queries and views in depth](/laser-sdk/advanced/views)
- [Key-value state in depth](/laser-sdk/advanced/state)
- [Connect](/laser-sdk/connect)
- [AGDX](/laser-sdk/advanced/agdx)

## Operational materialization and SQL

Use `topic.materialize().apply()` to create an operational view from a topic in Rust, Python, or TypeScript. The default preserves whole records. A typed projection selects fields. Keyed history keeps current state per key and supports deletion through a declared header. Readiness is measured against a captured source target, and complete historical coverage is reported separately. See [Queries and views](/laser-sdk/views) for bounded examples in all three clients.

Operational raw SQL requires an explicit dialect. Every relation must refer to an authorized index in the caller's stream and on the same backend. Turso serves SQLite, Postgres serves Postgres, and Doris and VeloDB serve MySQL. Inspect backend capabilities before sending. See [Raw SQL](/laser-sdk/advanced/views#raw-sql) for the calls and restrictions.

Source: https://docs.laserdata.com/laser-sdk/advanced/managed-data
