Storage Reference

Storage Reference

The storage interface provides tenant-isolated key-value storage backed by PostgreSQL JSONB. Data is automatically scoped to the current tenant, user, and pack.

Overview

from huitzo_sdk import command, Context

@command("storage-demo", namespace="demo")
async def storage_demo(args: Args, ctx: Context) -> dict:
    # Save data
    await ctx.storage.save("my-key", {"field": "value"})

    # Retrieve data
    data = await ctx.storage.get("my-key")

    return data

Automatic Scoping

All storage operations are automatically scoped. When you save data with key "my-key", it's actually stored as:

tenant:{tenant_id}:user:{user_id}:pack:{pack_id}:my-key

This means: - Different tenants can't see each other's data - Different users (in the same tenant) can have their own data - Different packs have isolated storage

{pack_id} is the pack's stable identity, not the published version. A pack keeps one keyspace across every version you publish, so tenant data survives an upgrade — republishing a pack never orphans the records written by an earlier version.

Core Methods

save(key, value, **options)

Save a value to storage.

# Simple save
await ctx.storage.save("settings", {"theme": "dark"})

# With TTL (expires in 1 hour)
await ctx.storage.save("cache/data", data, ttl=3600)

# Overwrite existing
await ctx.storage.save("counter", 0)
await ctx.storage.save("counter", 1)  # Replaces the value

Parameters:

Parameter Type Description
key str Storage key (max 256 chars)
value Any JSON-serializable value
ttl int Time-to-live in seconds (optional)
scope str Scope level: "user" (default), "tenant", "pack"

get(key, **options)

Retrieve a value from storage.

# Basic get
data = await ctx.storage.get("settings")

# With default value
data = await ctx.storage.get("settings", default={"theme": "light"})

# Returns None if not found (and no default)
data = await ctx.storage.get("nonexistent")  # None

Parameters:

Parameter Type Description
key str Storage key
default Any Default value if key not found

delete(key)

Delete a value from storage.

await ctx.storage.delete("temporary-data")

# No error if key doesn't exist
await ctx.storage.delete("nonexistent")

exists(key)

Check if a key exists.

if await ctx.storage.exists("user-preferences"):
    prefs = await ctx.storage.get("user-preferences")
else:
    prefs = default_preferences

list(prefix)

List keys matching a prefix.

# List all keys starting with "cache/"
keys = await ctx.storage.list(prefix="cache/")
# Returns: ["cache/users", "cache/products", "cache/orders"]

# List all keys (empty prefix)
all_keys = await ctx.storage.list()

Scope Levels

User Scope (Default)

Data is isolated per tenant + user + pack:

# Only this user in this tenant can see this data
await ctx.storage.save("my-settings", settings)
# Equivalent to:
await ctx.storage.save("my-settings", settings, scope="user")

Tenant Scope

Data is shared across all users in the tenant, within this pack. Tenant scope is partitioned per pack: another pack installed in the same tenant can never read, list, overwrite, or delete these keys, even with the same key name. Storage scoping is a function of the executing pack (ADR-031 S1, Pack Sovereignty; shared storage substrate).

# Every user of this tenant running this pack shares this data
await ctx.storage.save("jobs/1", job, scope="tenant")

# Good for: the crew's shared dataset (jobs, customers, technicians)

The tenant-scope key (tenant:{tid}:{key}) carries no pack component; the partition comes from the backend, which is bound to the executing pack:

  • Production (PostgresStorageBackend): every row carries pack_id, and every read and write filters on the executing pack, including the tenant sentinel rows.
  • Local (InMemoryBackend, used by huitzo dev and SDK tests; huitzo-sdk 1.9.0+): tenant-scope keys are stored in the bound pack's partition. StorageClient binds the backend to namespace.pack_id; bind one yourself with InMemoryBackend.for_pack(pack_id) when calling the backend directly.

There is no cross-pack shared storage scope. To share data between packs, call the owning pack's command (a cross-pack pipeline stage).

Pack Scope

Data is shared across all users in the tenant and isolated to this pack, the same visibility as tenant scope, in a separate key namespace (tenant:{tid}:pack:{pid}:{key}), so a pack key never collides with a tenant key of the same name.

# Shared within this pack across all users, isolated from other packs
await ctx.storage.save("pack-cache", cache, scope="pack")

# Good for: pack-level caches, computed lookups, pack-specific org settings

Scope-Bounded Listing

list() and query() return keys from exactly one scope: the one you pass. The scoped key shapes nest (a tenant key tenant:{tid}:{key} is a string prefix of every user and pack key in that tenant), so the backend, not the caller, enforces the boundary:

# pseudocode
await ctx.storage.list("", scope="tenant")   # tenant-shared keys only
await ctx.storage.query("", scope="tenant")  # same rows, with values
  • A scope="tenant" listing returns no user-scope keys (the caller's or anyone else's) and no pack-scope keys, whatever the prefix ("", "user", "pack").
  • A prefix may not contain : (the scope delimiter); ValueError otherwise.
  • Production (PostgresStorageProtocolAdapter): each scope is its own row partition (user_id is the caller or a scope sentinel), so another scope's rows are never read. The adapter also rejects any pre-scoped key (single or batch) that names another user's or pack's subtree instead of treating it as tenant scope, rejects a batch mixing scopes, and a tenant-scope list/query excludes the tenant:{tid}:user: and tenant:{tid}:pack: subtrees in SQL.
  • Local (InMemoryBackend, used by huitzo dev and SDK tests): an in-memory key-value store, so list/query match a key only when it has the same scope root as the prefix (huitzo_sdk.storage.namespace.scope_root), so a local listing never crosses the user/pack/tenant scope boundary. Tenant-scope keys are also partitioned by the bound pack (huitzo-sdk 1.9.0+) (tenant scope), so a tenant listing never returns another pack's keys.

Data Types

Storage accepts any JSON-serializable value:

# Primitives
await ctx.storage.save("string", "hello")
await ctx.storage.save("number", 42)
await ctx.storage.save("float", 3.14)
await ctx.storage.save("boolean", True)
await ctx.storage.save("null", None)

# Collections
await ctx.storage.save("list", [1, 2, 3])
await ctx.storage.save("dict", {"key": "value"})

# Nested structures
await ctx.storage.save("complex", {
    "users": [
        {"name": "Alice", "age": 30},
        {"name": "Bob", "age": 25}
    ],
    "metadata": {
        "created": "2024-01-01",
        "version": 1
    }
})

# Pydantic models (auto-serialized)
from pydantic import BaseModel

class UserData(BaseModel):
    name: str
    email: str

user = UserData(name="Alice", email="[email protected]")
await ctx.storage.save("user", user.model_dump())

Key Naming Conventions

Use Prefixes for Organization

# Good: Clear prefixes
await ctx.storage.save("user/preferences", prefs)
await ctx.storage.save("cache/products", products)
await ctx.storage.save("report/2024-01", report)

# Bad: Flat keys
await ctx.storage.save("preferences", prefs)
await ctx.storage.save("products", products)

Use IDs in Keys

# Good: Include IDs for specific records
await ctx.storage.save(f"order/{order_id}", order_data)
await ctx.storage.save(f"analysis/{analysis_id}/result", result)

# Retrieve by ID
order = await ctx.storage.get(f"order/{order_id}")

Avoid Special Characters

Keys may contain letters, digits, dash, underscore, dot and slash; colon is reserved as the internal scope delimiter (see Automatic Scoping) and is rejected.

# Good: Use slashes or dots to namespace keys
await ctx.storage.save("user/settings/theme", "dark")

# Bad: Colons (reserved scope delimiter) and spaces
await ctx.storage.save("user:settings", "dark")   # Don't do this
await ctx.storage.save("user settings", "dark")   # Don't do this

TTL (Time-to-Live)

Set expiration for temporary data:

# Expires in 1 hour (3600 seconds)
await ctx.storage.save("session/token", token, ttl=3600)

# Expires in 1 day
await ctx.storage.save("cache/daily-report", report, ttl=86400)

# Expires in 5 minutes
await ctx.storage.save("rate-limit/user123", counter, ttl=300)

Note: Expired keys are cleaned up asynchronously. A get() on an expired key returns None.

Transactions

Perform multiple operations atomically:

# pseudocode — atomic transaction

async with ctx.storage.transaction():
    # All operations inside this block are atomic
    val_a = await ctx.storage.get(key_a)
    val_b = await ctx.storage.get(key_b)

    # Validate business rules
    if not valid(val_a, val_b):
        raise ValidationError(...)

    # Update both — committed together or rolled back together
    await ctx.storage.save(key_a, new_val_a)
    await ctx.storage.save(key_b, new_val_b)

If the block raises, all changes made inside it are rolled back and the exception propagates. Otherwise they are kept, and they become durable with the rest of the command's writes when the command succeeds.

Behaviour What a command sees
Read-your-writes A get/list/query inside the block sees the block's own writes.
Exception in the block Every write since the block opened is undone, including writes from other tasks of the same execution, then the exception propagates.
Nesting A nested transaction() in the same task joins the outer one; there are no inner savepoints. An exception that escapes the inner block and is caught inside the outer block undoes nothing on its own. Only leaving the outer block with an exception rolls back.
Concurrent tasks A second task's transaction() waits until the first task's block ends.
Command failure A top-level command (REST, MCP or a queue) that fails, whether it raises, times out or is killed, keeps none of its storage writes, inside or outside a transaction.
Hosted runtime Same behaviour in the isolated (hosted) runtime. The transaction is held parent-side. If the command ends while one is still open (a background task that never left its block), it is rolled back and the command fails. See ADR-039.
Bounds In the hosted runtime, at most 30 seconds and 1,000 written or deleted keys per transaction. Crossing either rolls the transaction back and raises StorageError. Crossed inside the block, storage calls then fail until the block is left.
Pipelines ctx.pipeline cannot start or resume a pipeline inside the block. Start it before or after.

A transaction is scoped to one execution's own session. It does not lock keys against a different execution: two executions writing the same key still resolve last-write-wins.

Batch Operations

Efficiently work with multiple keys:

# pseudocode — batch operations

await ctx.storage.save_many({key1: val1, key2: val2, ...})
results = await ctx.storage.get_many([key1, key2, ...])   # returns dict, None for missing
await ctx.storage.delete_many([key1, key2, ...])

Query by Metadata

Add metadata for querying:

# Save with metadata
await ctx.storage.save(
    f"report/{report_id}",
    report_data,
    metadata={
        "type": "financial",
        "period": "2024-Q1",
        "status": "complete"
    }
)

# Query by metadata
reports = await ctx.storage.query(
    prefix="report/",
    metadata={"type": "financial", "status": "complete"}
)

Storage Limits

Limit Value
Key length 256 characters
Value size 16 MB
Keys per tenant 100,000
Total storage per tenant 1 GB

Best Practices

1. Use Meaningful Keys

# ✅ Good: Descriptive, hierarchical
await ctx.storage.save(f"customer/{customer_id}/orders/latest", order)

# ❌ Bad: Cryptic, flat
await ctx.storage.save("o1", order)

2. Use TTL for Caches

# ✅ Good: Cache with expiration
await ctx.storage.save("cache/exchange-rates", rates, ttl=3600)

# ❌ Bad: Cache without expiration (accumulates forever)
await ctx.storage.save("cache/exchange-rates", rates)

3. Use Appropriate Scope

# ✅ Good: Shared data at tenant level
await ctx.storage.save("lookup/products", products, scope="tenant")

# ❌ Bad: Duplicating shared data per user
await ctx.storage.save("lookup/products", products)  # Each user has a copy

4. Handle Missing Keys

# ✅ Good: Use defaults
settings = await ctx.storage.get("settings", default={})

# ❌ Bad: Assume key exists
settings = await ctx.storage.get("settings")
settings["theme"]  # KeyError if settings is None!

See Also