HITLConcepts

Tenants

One worker, many tenants: per-tenant policies, approvals, limits and grants, one receipt chain per tenant, and tenant-filtered reads.

Code blocks on this page are excerpts of tested programs; each block's title names its file in examples/, where the complete program runs.

An action's tenant partitions everything the gate keeps: approvals, limits, grants, invariant history and idempotency keys. Set it per action (tenant on the action) or for a whole gate (tenant= / { tenant }).

A policy per tenant

policy_resolver=fn / { policyResolver: fn } resolves the policy for each call from its tenant: fn(tenant) returns anything a gate accepts as a policy (a path, a folder, a document, a Policy), sync or async. Parsed policies are cached by content, never by tenant, so a tenant whose policy changes gets the new one on its next call. A resolver that throws, returns something invalid or times out (policy_resolver_timeout_ms / policyResolverTimeoutMs, 5 s by default, on the gate's clock) denies that tenant only, with hitl.policy_unavailable. gate.policy_for(tenant) / gate.policyFor(tenant) returns the resolved policy. Approvers and membership come from the approval's own tenant policy.

examples/python/multi-tenant/main.py (excerpt)
SAFE_TENANT = re.compile(r"^[a-z0-9_-]+$")


def tenant_policy(tenant: str | None) -> Path:
    # The tenant names a file, so accept only a safe name: never "../other" or an absolute path. A resolver that
    # raises denies that tenant (hitl.policy_unavailable).
    if tenant is None or not SAFE_TENANT.match(tenant):
        raise ValueError(f"unknown tenant {tenant!r}")
    return POLICIES / f"{tenant}.yaml"


gate = hitl.Gate(
    # One policy per tenant, resolved per call and cached by content. A tenant whose policy cannot be resolved is
    # denied (hitl.policy_unavailable); the others are unaffected.
    policy_resolver=tenant_policy,
    store=hitl.sqlite(DB),
    redact_key="store",  # development only: production sets VIEWPORT_REDACT_KEY from a secret manager
    receipts=True,  # one hash chain per tenant, in the store
    channels=[desk],
    clock=FakeClock("2026-11-25T10:00:00Z"),
)
examples/ts/multi-tenant/main.ts (excerpt)
// The tenant names a file, so accept only a safe name: never "../other" or an absolute path. A resolver that throws
// denies that tenant (hitl.policy_unavailable).
const tenantPolicy = (tenant: string | null): string => {
  if (tenant === null || !/^[a-z0-9_-]+$/.test(tenant)) throw new Error(`unknown tenant ${JSON.stringify(tenant)}`);
  return join(import.meta.dirname, "policies", `${tenant}.yaml`);
};

const gate = new Gate({
  // One policy per tenant, resolved per call and cached by content. A tenant whose policy cannot be resolved is
  // denied (hitl.policy_unavailable); the others are unaffected.
  policyResolver: tenantPolicy,
  store: sqlite(DB),
  redactKey: "store", // development only: production sets VIEWPORT_REDACT_KEY from a secret manager
  receipts: true, // one hash chain per tenant, in the store
  channels: [desk],
  clock: new FakeClock("2026-11-25T10:00:00Z"),
});
examples/python/multi-tenant/main.py (excerpt)
acme_small = await gate.authorize(refund("acme", 20, "a1"))  # allowed by Acme's policy
acme_large = await gate.authorize(refund("acme", 900, "a2"), wait=False)  # pending: Acme finance
globex = await gate.authorize(refund("globex", 20, "g1"))  # denied by Globex's policy

print(f"acme $20: {acme_small.status}, acme $900: {acme_large.status}, globex $20: {globex.status}")
# acme $20: allowed, acme $900: pending, globex $20: denied
print(f"request for tenant: {desk.requests[0].tenant}")  # request for tenant: acme
examples/ts/multi-tenant/main.ts (excerpt)
const acmeSmall = await gate.authorize(refund("acme", 20, "a1")); // allowed by Acme's policy
const acmeLarge = await gate.authorize(refund("acme", 900, "a2"), { wait: false }); // pending: Acme finance
const globex = await gate.authorize(refund("globex", 20, "g1")); // denied by Globex's policy

console.log(`acme $20: ${acmeSmall.status}, acme $900: ${acmeLarge.status}, globex $20: ${globex.status}`);
// acme $20: allowed, acme $900: pending, globex $20: denied
console.log(`request for tenant: ${requests[0]?.tenant}`); // request for tenant: acme

Channels see the tenant on every request, and approval events carry it.

One receipt chain per tenant

With receipts in the store, each tenant has its own hash chain, with its own sequence and head. Tenants never wait on one another's appends, and each chain verifies alone. Actions without a tenant go on the default chain.

examples/python/multi-tenant/main.py (excerpt)
# A dashboard opens the same file read-only: no migrations, no writes, tenant filters in the query.
view = hitl.sqlite(DB, readonly=True)
assert view.receipts is not None
print(f"chains: {await view.receipts.chains()}")  # chains: ['acme', 'globex']

for tenant in ("acme", "globex"):
    chain = [r async for r in view.receipts.read(chain=tenant)]
    result = await hitl.verify_receipts(chain)  # each chain verifies alone
    print(f"{tenant} chain: {len(chain)} entries, verified: {result.ok}")  # acme chain: 10 entries, verified: True
examples/ts/multi-tenant/main.ts (excerpt)
// A dashboard opens the same file read-only: no migrations, no writes, tenant filters in the query.
const view = sqlite(DB, { readonly: true });
console.log(`chains: ${(await view.receipts?.chains?.())?.join(", ")}`); // chains: acme, globex

for (const tenant of ["acme", "globex"]) {
  const chain: Receipt[] = [];
  for await (const r of view.receipts?.read({ chain: tenant }) ?? []) chain.push(r);
  const result = await verifyReceipts(chain); // each chain verifies alone
  console.log(`${tenant} chain: ${chain.length} entries, verified: ${result.ok}`); // acme chain: 10 entries, verified: true
}

From a shell:

viewport-hitl receipts verify .viewport/hitl.sqlite --chain acme
npx @viewportai/hitl receipts verify .viewport/hitl.sqlite --chain acme

Reads for dashboards

  • gate.pending(tenant=...) and the store's list({ tenant }) take one tenant, a list, or null for tenant-less approvals. The filter runs in the store query, never after fetching.
  • hitl.sqlite(path, readonly=True) / sqlite(path, { readonly: true }), and the same for Postgres, open a store without migrations and without writes (a write raises hitl.read_only). Receipt reads page with read(chain=, from_seq=, limit=) / read({ chain, fromSeq, limit }).

On this page