# Definite > Definite product documentation. ## Overview # Architecture ## Overview Definite on-prem is a single-tenant, self-hosted distribution of Definite, deployed via a Rust CLI that wraps Helm. One YAML config in, working deployment out. ``` ┌────────────────────────────────────────┐ │ Customer Kubernetes │ │ ┌────────────┐ ┌───────────────┐ │ │ │ Frontend │◄──►│ API │ │ │ │ (React) │ │ (FastAPI) │ │ │ └────────────┘ └───────┬───────┘ │ │ │ │ user ───https───► │ Ingress (cert-manager) │ │ │ ▼ │ │ ┌─────────────────────┐ │ │ │ Job Runner │ │ │ │ (Python pipelines) │ │ │ └─────────────────────┘ │ │ │ │ Embedded DuckDB + DuckLake run │ │ inside the API & Job Runner pods — │ │ no separate query server. │ └─────────────────┬─────────────┬────────┘ │ │ ┌────────────▼─┐ ┌─────▼──────┐ │ Postgres │ │ Object │ │ app DB + │ │ store │ │ DuckLake │ │ (parquet, │ │ catalog │ │ httpfs) │ └──────────────┘ └────────────┘ ``` ## Components ### CLI (Rust) Single static binary. Three jobs: 1. **Preflight** (`definite doctor`): probe Postgres, object store, Kubernetes, LLM provider. Fail loud and early. 2. **Deploy** (`definite init`, `definite upgrade`): map `config.yaml` → Helm values → `helm upgrade --install`. 3. **Helm export** (`definite export-helm`): emit the raw chart for operators who prefer to review or apply it with `helm` directly. The CLI never owns long-running state. It shells out to `kubectl` and `helm`. Everything it does is auditable. ### Helm chart The actual deployment artifact. Versioned alongside the CLI. Templates: - `api.yaml` - Deployment + Service for the FastAPI service - `frontend.yaml` - Deployment + Service for the React UI - `job-runner.yaml` - Deployment for the Postgres-backed pipeline scheduler - `ingress.yaml` - Routing + TLS - `secret.yaml` - Consolidated Secret (managed by chart) for inlined credentials - `configmap.yaml` - Non-secret runtime config ### API (Python + FastAPI) Single-tenant. No `team_id`, no RLS. Reads from Postgres for application state, runs lakehouse queries in an embedded DuckDB connection that attaches the DuckLake catalog, and calls the LLM provider for Fi. Access control is enforced here, in the API — it is the only gateway to the lakehouse. Three independent layers: application roles (viewer/editor/admin), per-resource content sharing, and table-level data-access roles. See [`permissions.md`](/docs/permissions). ### Frontend (React) Home, Fi, query, catalog, data apps, automations, docs, integrations, and settings. ### Lakehouse (embedded DuckDB + DuckLake, Postgres catalog) There is no separate lakehouse query pod. The DuckLake **catalog** lives in a dedicated Postgres database (`ducklake_catalog`, reusing the deployment's existing Postgres server). The API and job-runner each open an **embedded DuckDB** connection that attaches the catalog directly (`ATTACH 'ducklake:postgres:'`); the query plan runs locally in that process and **bulk parquet data is read from the configured object store over httpfs**. Compute therefore scales with whatever pod is running the query. ### Job runner Postgres-backed worker pool. Cron + retries + idempotency. **Not Temporal.** A SQL-only design keeps the operational surface small. ### Compute profiles (burst tiers) The three core deployments — api, frontend, job-runner — are small and always-on (the lakehouse is embedded DuckDB inside the api and job-runner pods, not a separate deployment). For workloads that need *bigger* compute on demand (heavy Python pipelines, Fi sessions crunching a large dataset, ad-hoc SQL benchmarks like TPC-H) the operator declares **compute profiles** in `config.yaml`: ```yaml compute_profiles: large: resources: requests: { cpu: "4", memory: "16Gi" } limits: { cpu: "8", memory: "32Gi" } node_selector: cloud.google.com/gke-nodepool: definite-burst tolerations: - { key: definite-app/burst, operator: Equal, value: "true", effect: NoSchedule } warm_pool_size: 0 # cold-start; pool scales to zero when idle ``` The chart renders each profile as a `SandboxTemplate` plus an optional `SandboxWarmPool`. At runtime a Fi thread or a pipeline Python step picks a profile by name; the workload runs on a Kubernetes pod sized for that tier, usually on a dedicated burst node pool that scales to zero when nobody's using it. A deployment with no `compute_profiles:` block uses the default sandbox sizing. **Where SQL compute lands** follows from the `postgres_catalog` lakehouse design: the DuckLake catalog lives in Postgres, every client attaches it directly in embedded DuckDB, and the SQL plan executes on whatever pod runs the query while parquet is read from object storage over httpfs. The `default` compute profile runs queries in the API or job-runner pod's embedded connection; a non-default profile dispatches the query to a burst sandbox that opens its own embedded DuckDB and attaches the same catalog. The full operator + user guide — including per-cloud node-pool setup (GKE / EKS / Karpenter / AKS) and a TPC-H benchmark recipe — is in [`compute-profiles.md`](/docs/compute-profiles). ## External dependencies (customer-provided) | Component | Why external | |---|---| | Postgres 15+ | Customer already runs Postgres or has a managed option. We avoid operating a stateful service. | | Object store | Cloud-native: S3, GCS, Azure Blob, MinIO. We avoid running storage. | | Kubernetes 1.28+ | Customer's preferred runtime. We don't ship a runtime. | | OIDC provider | Optional; local auth is the fallback. | | LLM credentials | BYO. Anthropic, Bedrock, Vertex, Azure OpenAI. | ## Product boundaries Definite on-prem is designed around these boundaries: - One organization per deployment; it is not a multi-tenant control plane. - Semantic modeling is built into the lakehouse workflow rather than a separate Cube-style service. - Data movement is built from integrations, sync steps, automations, and Fi-assisted connector workflows rather than a full packaged connector library. --- ## Self Host # On-Prem > Run Definite in your own cloud account. Definite ships an on-prem distribution you can run in your own AWS, GCP, or Azure account. You get the full platform (data lake, semantic layer, dashboards, Fi) inside your VPC, with your data never leaving your network. The install has three pieces: 1. **Cloud infrastructure**: a Kubernetes cluster, a Postgres database, and an object store. For AWS we publish a Terraform module that provisions these with sane defaults. For GCP and Azure, follow the per-cloud guide below; a Terraform module for each is on the roadmap. 2. **The `definite` CLI**: a single binary that installs the platform onto the cluster from a `config.yaml` you fill in with values from your infra. 3. **Day-2 operations**: upgrades, maintenance, license, and logs, all driven through the same CLI. ## Default URL and DNS The default install path uses **Definite-brokered DNS and TLS**. During setup, the `definite` CLI provisions a Definite-hosted URL for your deployment: ```text https://.onprem.definite.app ``` You do not need to configure customer-owned DNS before the first successful install. After the cloud load balancer exists, the CLI calls the Definite setup broker, receives the `*.onprem.definite.app` URL, waits for DNS/TLS readiness, and continues the install. Customer-owned DNS is still supported, but treat it as an advanced/custom production option after the system is healthy. Private or internal-only production deployments may need a customer-owned hostname plus a customer certificate or private CA. Do not use `nip.io`, cert-manager, or Let's Encrypt as the default first-run path. ## Install guides Provision with Terraform, install with the `definite` CLI. Provision with `gcloud`, install with the `definite` CLI. Provision with `az`, install with the `definite` CLI. Point Claude Code, Cursor, or Windsurf at a single runbook and let it drive the install. The agent asks the discovery questions, fills in `config.yaml`, and runs the CLI against your cloud account. ## Authentication Sign in with Google Workspace via OIDC. Works on any cloud. Email + password (default). The first admin is bootstrapped from your `config.yaml`. ## What you'll need before you start | Category | What | |---|---| | Cloud account | An account with permission to create a Kubernetes cluster, a managed Postgres, an object store bucket, and IAM resources | | Local tooling | `kubectl` 1.28+, `helm` 3.12+, and your cloud's CLI (`aws` / `gcloud` / `az`). AWS adds `terraform` 1.5+ | | LLM credentials | Anthropic, Bedrock (AWS), Vertex (GCP), or Azure OpenAI | | Optional | A [Google Workspace](/on-prem/sso) account if you want Sign in with Google instead of local auth; a customer-owned hostname only if you are intentionally using custom/private DNS | The CLI's `definite doctor` command verifies all of these against your `config.yaml` before deploying, so you don't have to keep this list in your head. ## Architecture An on-prem Definite deployment is one Kubernetes namespace with these workloads: - **API**: FastAPI service that all clients talk to. - **Frontend**: the Definite web UI. - **Lakehouse**: a single StatefulSet running our DuckLake query engine. Catalog file lives on a `ReadWriteOnce` PV; bulk data lives in your object store. - **Job runner**: executes scheduled syncs, Python pipelines, and webhook-triggered docs. - **Fi sandboxes**: ephemeral pods spun up per agent run via `agent-sandbox` CRDs. External dependencies you bring: - **Postgres 15+** for the application database (users, docs, automations). - **An object store** (S3, GCS, Azure Blob, or MinIO) for lakehouse Parquet files. - **An LLM provider** for Fi. See the [CLI reference](/on-prem/cli) for the full set of commands and flags. The config schema is documented inline in `config.yaml` and surfaced by `definite doctor`. --- # Agent setup > Point a coding agent (Claude Code, Cursor, Windsurf) at this page and it will walk a human through an on-prem Definite install end to end. This page is a runbook designed to be read by an AI agent (Claude Code, Cursor, Windsurf, or similar). The agent reads this page, asks the human user the intake questions below in order, and then executes the install against their cloud account. If you are a human reading this directly, you probably want the cloud-specific guide: [AWS](/on-prem/aws), [GCP](/on-prem/gcp), or [Azure](/on-prem/azure). Come back here when you'd rather have an agent drive. ## Quick-start: paste this into your agent Open a fresh session in Claude Code (or Cursor, Windsurf, etc.) in an empty working directory, and paste: ``` Help me set up Definite. Look at https://docs.definite.app/on-prem/agent-setup.md ``` That's it. The agent will fetch this page, ask the questions in the [Intake](#phase-1-intake) section, then drive Phases 2-5 against your cloud account. In the default path, the human should only need to provide cloud credentials and answer the intake questions. Do not ask them to pre-create DNS, paste a Definite setup token, or paste a Definite license key unless they explicitly choose customer-owned/manual mode. **For agents:** every page on this site is also published as plain Markdown by appending `.md` to the URL. Use the `.md` URL when you fetch a doc because it is smaller, has no JSX components, and is easier to parse. So `/on-prem/aws` is at `https://docs.definite.app/on-prem/aws.md`, `/on-prem/gcp` at `https://docs.definite.app/on-prem/gcp.md`, and so on. If your agent supports MCP, also add the Definite docs as a source so it can pull in the per-cloud guides on demand: `claude mcp add --transport http definite-docs https://docs.definite.app/mcp`. --- ## Before you begin: accounts, licensing, and login If you're a human about to point an agent at this page, these are the questions that usually come first. **Do I need a Definite account first?** No. You do **not** need an account at definite.app (the SaaS app) to run Definite on-prem. In the default flow the only things you bring are: - cloud credentials for AWS, GCP, or Azure; you stay signed into your own cloud CLI, and - answers to the [Intake](#phase-1-intake) questions below. **How do I get a license?** In the default **Definite-brokered** flow, you don't request or paste one. During `definite init`, the CLI proves control of your active cloud account to Definite: a presigned STS `GetCallerIdentity` request on AWS, a `gcloud` identity token on GCP, or an Entra access token (from `az` or the AKS managed identity) on Azure. Definite then issues a short-lived setup token, a `*.onprem.definite.app` hostname, and the license automatically, injecting all three into the install. Nothing to obtain ahead of time and nothing to copy into `config.yaml`. The deployment activates that license against Definite's control plane and caches a signed entitlement that it renews on its own. If you'd rather hold the key yourself (**customer-owned / manual** mode), Definite issues it to you directly. See [Q9](#q9-optional-customer-owned-license). Without a license the deployment still boots, but every product API route returns `403` until it activates. **How do I log in once it's up?** Your login to *your* instance is the initial admin you set in `config.yaml` (`auth.initial_admin_email` + `auth.initial_admin_password`). See [Bootstrap the initial admin](#bootstrap-the-initial-admin). That admin user is created inside your own deployment on first boot; it is not a definite.app account. From there you add more users locally or wire up [Google SSO](/on-prem/sso). **Who do I talk to at Definite?** The brokered self-serve path above needs nothing but cloud credentials and an agent. If you'd instead like Definite to scope or operate the deployment, or you need a manual license key, email [hello@definite.app](mailto:hello@definite.app). --- ## For the agent: how to use this page You are an AI coding agent helping a human install on-prem Definite into their own cloud account. Read this entire page before asking your first question. Follow these rules: 1. **Ask one question at a time.** Do not batch the intake questions. Wait for the human's answer before moving on. 2. **Offer a default the human can accept with a quick confirmation.** Most questions below have a recommended choice. State it explicitly and accept any short affirmation as "use the default": "yes", "ok", "sounds good", "go with that", and so on. Some chat-based agents (for example Claude's CLI) cannot send an empty turn, so do not rely on the human pressing Enter. When the human answers a question that has a default with anything affirmative or non-specific, take the default and move on. Only the questions with no safe default (region, admin email, credentials) require a specific answer. 3. **Present a plan, then ask a yes/no before you apply it.** Before any apply step (provisioning that costs money, writing or overwriting `config.yaml`, `terraform apply`, `definite init`/`definite upgrade`), summarize what you're about to do, then ask a yes/no question where "yes" proceeds and "no" means "not yet". Always invite changes on "no", for example: "Here's the plan: [short summary]. Ready for me to apply it? Reply "yes" to proceed, or "no" and tell me what to change." Treat anything that isn't a clear "yes" as "no": don't apply, fold in their comments, and re-confirm. 4. **Verify all prerequisites before you start, especially on a clean slate.** For a greenfield install (no cluster, DB, or bucket to reuse), confirm every dependency is satisfied before provisioning anything: your own tooling and versions (Phase 0), the cloud CLI installed and authenticated, the IAM permissions to create the resources, and LLM model access enabled in the chosen region. Surface anything missing and resolve it with the human up front rather than failing halfway through a 30-minute provision. 5. **Run real commands against the human's cloud account.** Do not just print them. Use your shell tool. Confirm before any destructive operation (delete, drop, force-destroy). 6. **Never invent values.** If the human hasn't given you a region, project ID, hostname, password, or credential, ask. Placeholders like `` must be replaced before any command runs. 7. **Capture every value into a single `config.yaml`** as you go. Don't ask the human to write the file; you write it, show it to them, and confirm before `definite init`. 8. **Run `definite doctor` before `definite init`.** Do not pass `--skip-preflight` unless `doctor` failed only on the Postgres reachability check from a laptop outside the VPC (private RDS / Cloud SQL / Postgres Flexible Server) and the per-cloud guide says that is expected. Never use `--skip-preflight` to mask Kubernetes, object-store, license, or LLM failures. 9. **Hand off to the per-cloud guide for the long shell sequences.** Phase 2 below tells you which page to fetch. 10. **Stop and escalate to a human at Definite** (`hello@definite.app`) if: the cloud lacks a permission you need, an LLM provider rejects the model, `definite doctor` fails for a reason you can't fix in three tries, the broker rejects cloud-attested setup-token acquisition, or the human asks for production support beyond install. Agent note: Do not stop the install to ask the user to configure customer DNS unless they explicitly selected customer-owned DNS mode. In the default flow, use Definite-brokered DNS. After provisioning the load balancer, call the Definite setup broker, use the returned `*.onprem.definite.app` URL, wait for DNS/TLS readiness, and continue the install. Customer-owned DNS can be configured after the system is healthy. Agent note: do not ask the user for a Definite setup token in the default flow on **any** cloud, including Azure. If `DEFINITE_ONPREM_SETUP_TOKEN` is not already present, the released `definite` CLI proves control of the user's cloud account to Definite and obtains a short-lived setup token automatically: a presigned STS `GetCallerIdentity` request on AWS, a `gcloud` identity token on GCP, and an Entra access token on Azure (minted from the user's `az login` session, or the AKS workload's managed identity via IMDS when run in-cluster). The raw token is not printed and expires quickly. The human only needs to supply a `DEFINITE_ONPREM_SETUP_TOKEN` if they explicitly opt out of automatic attestation; in that case they get one from Definite (`hello@definite.app`) and reference it in `config.yaml` under `broker.setupToken.env: DEFINITE_ONPREM_SETUP_TOKEN`. See [Azure guide → Set or skip the setup token](/on-prem/azure#3-set-or-skip-the-setup-token). --- ## Phase 0: Confirm prerequisites and the agent's environment Before asking the human anything, verify your own tooling. Run, in parallel: ```bash which kubectl helm kubectl version --client 2>/dev/null helm version --short 2>/dev/null ``` You need `kubectl` 1.28+ and `helm` 3.12+. If either is missing, install them before continuing. The cloud CLI (`aws`, `gcloud`, or `az`) is checked in Phase 2 once you know which cloud. **Clean-slate (greenfield) installs: confirm every prerequisite up front.** When the human has no existing cluster, database, or bucket to reuse (the common case, see [Q7](#q7-existing-infrastructure-to-reuse)), a provision takes 20-40 minutes, so verify the full dependency chain *before* you start, not halfway through. Walk this checklist and report each result to the human, resolving any gap before Phase 2: - **Agent tooling**: `kubectl` 1.28+ and `helm` 3.12+ on PATH (above). - **Cloud CLI installed and authenticated**: `aws sts get-caller-identity` / `gcloud config list account` / `az account show` returns the expected account. If the human isn't logged in, ask them to authenticate; never authenticate as them. - **Permissions to create resources**: the authenticated principal can create the cluster, managed Postgres, object store, and IAM bindings for the chosen cloud. If you can't verify a permission, say so and let the human confirm with their cloud admin rather than discovering it on a failed `apply`. - **LLM model access**: the chosen provider has the selected model enabled in the target region (Bedrock model access request, Vertex Model Garden enablement, or an Azure OpenAI deployment). On Azure, default to `gpt-5.6-terra` version `2026-07-09`, but treat the 5.6 family as a Preview, phased rollout. Verify both catalog presence and nonzero `GlobalStandard` quota on the new subscription before provisioning. See [Q5](#q5-llm-provider) and [Q6](#q6-region). - **`definite` CLI + cluster prereqs**: installed in Phase 4; `definite bootstrap` then installs ingress, cert-manager, and the agent-sandbox CRDs, and `definite doctor` re-checks the whole chain before install. If any prerequisite is unmet, surface it now and resolve it with the human before provisioning anything. --- ## Phase 1: Intake Ask the human these questions in order. Capture each answer into a working scratchpad you can refer back to in later phases. ### Q1. Which cloud? > "Which cloud are you installing on: **AWS**, **GCP**, or **Azure**?" Record as `CLOUD`. This drives every subsequent decision. | If `CLOUD =` | Per-cloud guide to fetch in Phase 2 | Cluster | Postgres | Object store | Default LLM | |---|---|---|---|---|---| | AWS | [/on-prem/aws](/on-prem/aws) | EKS | RDS Postgres 15 | S3 | Bedrock | | GCP | [/on-prem/gcp](/on-prem/gcp) | GKE (Autopilot) | Cloud SQL Postgres 15 | GCS (HMAC) | Vertex AI | | Azure | [/on-prem/azure](/on-prem/azure) | AKS | Postgres Flexible Server 15 | Blob Storage | Azure OpenAI | Azure is currently a **preliminary guide**. A clean-room public demo deployment validated AKS, Postgres Flexible Server, Blob Storage, local auth, brokered DNS and TLS, and Azure OpenAI, but it exposed release blockers in the generated lakehouse URI and runtime CA bundle path. Do not install v0.1.86 unmodified. Contact `hello@definite.app` and require a newer release that includes both fixes before proceeding. Private networking, customer-owned DNS, production high availability, and Entra SSO were not validated. AKS remains the only supported Azure compute platform; Azure Container Apps and Azure Container Instances do not expose the Kubernetes API access Definite requires. Setup-token acquisition works like the other clouds: the CLI attests the Azure tenant with an Entra access token from `az` or the AKS managed identity. ### Q2. Environment > "Is this a **demo / pilot** install (you'll throw it away in a few weeks), or a **production** install (real users, real data)?" Record as `ENV ∈ {demo, prod}`. This changes a handful of defaults: | Setting | Demo | Production | |---|---|---| | HA databases | single-AZ | multi-AZ / regional | | Deletion protection | off | on | | Hostname | Definite-brokered `https://.onprem.definite.app` | Definite-brokered `https://.onprem.definite.app` by default; customer-owned DNS is an advanced option after the system is healthy | | TLS | Definite-brokered TLS | Definite-brokered TLS by default; private/internal production may need customer certs or a private CA | | Backups | none | daily snapshots | | Lakehouse PVC size | 50Gi | size to expected data + 2x | Do not ask for DNS before first install unless the human explicitly chooses customer-owned DNS mode. The default first-run URL comes from Definite. ### Q3. DNS mode > "Should I use the default Definite-brokered DNS for the first install? Definite will provide a URL like `https://.onprem.definite.app`. Just say "yes" to accept, or choose customer-owned DNS only if you already need a private/internal hostname or custom certificate." Record as `DNS_MODE ∈ {definite-brokered, customer-owned}`. Default to `definite-brokered` if the human accepts or doesn't choose customer-owned. If `DNS_MODE = definite-brokered`, do not ask for a hostname yet. After the load balancer exists, call the Definite setup broker through the `definite` CLI, record the returned URL as `PUBLIC_URL`, and set `HOSTNAME` to the host portion, for example `.onprem.definite.app`. If `DNS_MODE = customer-owned`, ask: > "What customer-owned hostname should Definite be reachable at, like `definite.acme.com`?" Record as `HOSTNAME`, then follow the per-cloud guide's customer-owned DNS notes. Use the released CLI's customer-owned mode when it is available; the expected flag shape is `--dns-mode customer-owned --hostname `. Private/internal production deployments may require customer-owned DNS and a customer certificate or private CA. That is a custom production path, not the default first-run path. ### Q4. Authentication > "How should users sign in: **local auth** (email + password, recommended for the first install), or **Google Workspace SSO** (OIDC)?" Record as `AUTH ∈ {local, oidc}`. Google Workspace is the only OIDC provider supported today; Entra ID and other providers are on the roadmap. If the human is Entra-first, recommend local auth for now and switching to SSO when Entra support lands. If `AUTH = oidc`, confirm that the provider is Google Workspace and follow [/on-prem/sso](/on-prem/sso). Generic OIDC providers such as Microsoft Entra ID and Okta are not supported by the current release. Do not accept an issuer URL for one of those providers or imply that an Azure deployment supports Entra SSO. If they choose Google Workspace, ask for the OAuth client details required by the SSO guide. For Azure, recommend local auth for the first install and configure Google SSO only after the local-auth deployment is healthy. > "What are the Google OAuth client ID, client secret reference, and allowed Workspace domain?" ### Q5. LLM provider **Always lead with the cloud's native LLM and offer it as the default.** Bedrock uses IRSA on AWS, and Vertex uses Workload Identity on GCP, so those paths do not require static API keys. The current Azure OpenAI path uses an Azure OpenAI API key stored through a secret reference. Phrase the recommendation so the human can accept it with a quick "yes", for example on AWS: > "For AWS I recommend **Bedrock**, which authenticates with the cluster's IAM role (IRSA), so there are no API keys to manage. Want me to use Bedrock? Just say "yes", or pick Anthropic direct, Azure OpenAI, or Vertex." For Azure, recommend: > "For Azure I recommend **Azure OpenAI `gpt-5.6-terra` version `2026-07-09`** as Fi's default model, deployed as `GlobalStandard` with initial capacity `10`. Availability is phased, so I'll verify the model catalog and quota in this subscription first. Want me to use that default?" | `CLOUD` | Recommended default (offer this) | Alternatives | |---|---|---| | AWS | **Bedrock** (IRSA, no static creds) | Anthropic direct, Azure OpenAI, Vertex | | GCP | **Vertex AI** (Workload Identity, no static creds) | Anthropic direct, Bedrock, Azure OpenAI | | Azure | **Azure OpenAI `gpt-5.6-terra`** (Preview/phased; API key in the current release) | `gpt-5.6-luna` for lower-cost latency-sensitive work; `gpt-5.6-sol` for the hardest workloads; Anthropic direct, Bedrock, or Vertex | Record as `LLM_PROVIDER`. For Bedrock or Vertex, confirm the human has model access enabled in their account for the Claude model they want. For Azure OpenAI, default to `gpt-5.6-terra` version `2026-07-09`, `GlobalStandard`, capacity `10`. Use `gpt-5.6-luna` for lower-cost, latency-sensitive workloads, and use `gpt-5.6-sol` only for the hardest workloads. Because 5.6 access is Preview and phased, list the account's models and regional quota and require both the exact catalog entry and nonzero quota before deployment. Capture the Azure OpenAI API key as a secret reference. If they pick another provider that uses a key, capture that key reference for `config.yaml`. ### Q6. Region > "Which region? Pick whatever is closest to your users / source data. If you're not sure, [recommend their cloud's most-popular region]." Record as `REGION`. Cross-check that the chosen LLM model is available in this region. Bedrock and Vertex availability varies, and Azure OpenAI 5.6 catalog and quota rollout is phased by subscription and region. ### Q7. Existing infrastructure to reuse > "Are you starting fresh, or do you have existing infrastructure you want me to reuse: an existing Kubernetes cluster, an existing Postgres database, or an existing object-store bucket?" Most installs are greenfield. If the human says they want to reuse something, capture the connection details and note them for Phase 2: you'll skip provisioning that resource but still need it in `config.yaml`. ### Q8. Naming > "What name prefix should I use for the resources I create? Default is `definite`; just say "yes" to accept, or give me another." Record as `NAME_PREFIX`. This becomes part of cluster name, bucket name, DB name, etc. If the human confirms or doesn't give a specific prefix, use `definite`; don't make them type the word "default". ### Q9. Optional customer-owned license Do not ask for a manual license key in the default Definite-brokered flow. `definite init` requests a broker-issued license during setup and injects it for the install. Only ask this question if the human explicitly selected customer-owned/manual mode: > "On-prem Definite needs a license key, issued to you by Definite. Do you have it? It looks like `onprem_` followed by a long hex string." Record as `LICENSE_KEY` only for that manual path. If the human does not have a key for manual mode, stop and have them email `hello@definite.app`. --- ## Phase 2: Provision cloud infrastructure You now have enough information to provision. Fetch the per-cloud guide for `CLOUD` and execute Phase 1 ("Provision …") of that guide, substituting the answers from Intake. | `CLOUD` | Fetch (use the `.md` URL) and follow | |---|---| | AWS | [`/on-prem/aws.md`](https://docs.definite.app/on-prem/aws.md) - Phase 1 (first supported black-box path, Terraform module) | | GCP | [`/on-prem/gcp.md`](https://docs.definite.app/on-prem/gcp.md) - Phase 1 (`gcloud` sequence) | | Azure | [`/on-prem/azure.md`](https://docs.definite.app/on-prem/azure.md) - Phase 1 (`az` sequence; preliminary, fixed release required) | A few rules that apply across all three: - **Confirm the cloud CLI is authenticated** before running anything. `aws sts get-caller-identity` / `gcloud config list account` / `az account show`. If the human isn't logged in, ask them to authenticate; do not try to authenticate as them. - **Capture every output you'll need for `config.yaml`** as you go (cluster name, DB connection string, bucket name, access keys, service-account emails). Don't make the human re-run commands to find them. - **Get a yes/no before any command that costs money** (cluster create, RDS create, Cloud SQL create) or that writes IAM bindings. Summarize what will be created and its rough cost, then ask "Ready to apply? Reply "yes" to proceed, or "no" and tell me what to change." Anything that isn't a clear "yes" means stop and adjust. - **Do not create customer DNS in the default flow.** For `DNS_MODE = definite-brokered`, continue until the load balancer exists, then use the `definite` CLI to call the setup broker. The backend contract is `POST /onprem/v1/setup-sessions`, but the agent should not ask the human to run a direct `curl` by default. - **Provisioning takes 20-40 minutes**, mostly the managed Kubernetes cluster. Tell the human that up front. Run independent commands in parallel where possible. When Phase 1 of the per-cloud guide is done, return here for Phase 3. --- ## Phase 3: Assemble `config.yaml` Open a new file `config.yaml` in the human's working directory and fill it in from your scratchpad. The shape is the same across clouds; only `object_store`, `lakehouse.storage.storage_class_name`, and `llm` change. A canonical template (replace every `<...>` with a real value from Intake or Phase 2): ```yaml deployment: name: namespace: dns_mode: definite-brokered # default first-run mode # broker: # Omit this block on all clouds in the default flow. definite init acquires a # short-lived setup token by proving control of the active cloud credentials # (AWS STS presign, GCP identity token, or Azure Entra access token via az / # the AKS managed identity). Add it only for the manual token override: # setupToken: # env: DEFINITE_ONPREM_SETUP_TOKEN # Omit the license block in the default brokered flow. definite init injects # the broker-issued license for this install. Add license.key only for # customer-owned/manual mode. postgres: url: postgres://:${POSTGRES_PASSWORD}@:5432/ object_store: # `credentials` is REQUIRED on every cloud. If you omit it, definite doctor # fails with a bare `missing field 'credentials'` and no section pointer. # Uncomment the block for CLOUD: # # AWS (S3): HMAC access-key pair: # type: s3 # bucket: # region: # credentials: # key_id: { env: S3_ACCESS_KEY_ID } # secret: { env: S3_SECRET_ACCESS_KEY } # # GCP (GCS): HMAC interoperability pair: # type: gcs # bucket: # credentials: # key_id: { env: GCS_HMAC_KEY_ID } # secret: { env: GCS_HMAC_SECRET } # # Azure (Blob): single shared storage-account key, NOT an HMAC pair: # type: azure # account: # container: # credentials: # env: AZURE_STORAGE_KEY lakehouse: prefix: lake/ storage: size: 50Gi storage_class_name: auth: mode: initial_admin_email: initial_admin_password: env: INITIAL_ADMIN_PASSWORD # If oidc: configure Google Workspace using /on-prem/sso. Generic OIDC is not supported. llm: provider: # Provider-specific fields per the per-cloud guide. resources: api: { replicas: 2, cpu: "1", memory: 2Gi } lakehouse: { replicas: 1, cpu: "4", memory: 16Gi } frontend: { replicas: 2, cpu: 500m, memory: 512Mi } job_runner: { replicas: 1, cpu: 500m, memory: 1Gi } ``` Then **show the filled-in `config.yaml` to the human and ask a yes/no before you proceed**. Diff it against their answers and flag anything you had to guess, then ask, for example: "This is the config I'll install with. Ready to apply? Reply "yes" to proceed, or "no" and tell me what to change." Treat anything that isn't a clear "yes" as "no": edit the file per their comments and re-confirm. Export the secrets the file references: ```bash export POSTGRES_PASSWORD="..." export INITIAL_ADMIN_PASSWORD="$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 24)" # Object-store credentials (S3 access key, GCS HMAC pair, or Azure storage key) # OIDC_CLIENT_SECRET if using Google Workspace SSO ``` Pull these values from Phase 2's outputs. Never echo secrets back into the chat transcript; reference them by env var name only. On all clouds, the default brokered flow has no `LICENSE_KEY` env var and no `DEFINITE_ONPREM_SETUP_TOKEN` env var; the CLI acquires both broker authorization and license during `definite init`, attesting the active cloud credentials (including Azure via `az` / the AKS managed identity). Only export `DEFINITE_ONPREM_SETUP_TOKEN` if the human opts into the manual token override. Do not commit `config.yaml` to a public repo while the secret env vars are exported in your shell. For prod installs, recommend sourcing secrets from a secret manager (AWS Secrets Manager, GCP Secret Manager, Azure Key Vault, 1Password). --- ## Phase 4: Install Definite The CLI install is identical across clouds. Run, in order: ```bash # 1. Install the CLI curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/install.sh | sh definite version # 2. Bootstrap cluster-level prereqs (ingress, cert-manager, agent-sandbox CRDs) definite bootstrap # 3. Preflight definite doctor --config config.yaml # 4. Deploy. In the default mode, init discovers the ingress load balancer, # calls the Definite setup broker, waits for brokered DNS readiness, injects # the returned hostname/license into this install, and prints the final URL. # On all clouds, if no setup token is configured the CLI acquires one # automatically from the active cloud credentials (Azure mints an Entra access # token via az / the AKS managed identity). definite init --config config.yaml --dns-mode definite-brokered ``` On Azure, `definite doctor` performs a real PUT and DELETE of `lake/.preflight` in Blob Storage, but it does not exercise DuckDB's Azure extension or make an Azure OpenAI inference request in the current release. Before `init`, run the Azure guide's direct model request. After deployment, require the persistent-table and physical-Blob checks in Phase 5. Do not interpret a passing `.preflight` probe or `SELECT 1` as proof that lakehouse data reaches Blob Storage. If `DNS_MODE = customer-owned`, use `definite init --config config.yaml --dns-mode customer-owned --hostname ` instead. Do this only when the human explicitly selected customer-owned DNS; otherwise use Definite-brokered DNS. If `definite doctor` fails, **fix the failure before running `definite init`**. The most common failures and fixes are in the Troubleshooting section of each per-cloud guide. The one documented exception is the Postgres reachability check against a private DB endpoint from a laptop (RDS, Cloud SQL with private IP, Postgres Flexible Server). The in-cluster API pods may reach the DB fine while the laptop has no route. If `doctor` fails only on Postgres for this reason, follow the per-cloud guide's private-network workaround. Do not use `--skip-preflight` to mask any other failure. In the default Definite-brokered flow, `config.yaml` should not have a static `license` block. If `definite init` or post-install smoke tests still report `UNLICENSED`, brokered license acquisition or injection failed. Capture the CLI output and API logs, retry once after confirming cloud attestation still works, then escalate to Definite. For customer-owned/manual mode only, verify the provided `license.key` and re-run. ### Bootstrap the initial admin For local auth, include `auth.initial_admin_email` and `auth.initial_admin_password.env` in `config.yaml` before running `definite init`. The CLI passes those values into the Helm install, and the API creates the initial admin on first startup. **Print the admin password back to the human and tell them to save it in a password manager.** It is not recoverable. Do not manually patch `INITIAL_ADMIN_EMAIL` or `INITIAL_ADMIN_PASSWORD` onto the API Deployment after install unless you are repairing an older deployment. Do not restart the lakehouse unless logs show an unrelated lakehouse-specific failure. ### AWS Bedrock follow-up If `CLOUD = AWS` and `LLM_PROVIDER = bedrock`, confirm the `definite` ServiceAccount has the Bedrock IRSA role ARN. If it is not already present, annotate it after install: ```bash BEDROCK_ROLE_ARN=$(terraform output -raw bedrock_irsa_role_arn) kubectl annotate serviceaccount definite -n \ eks.amazonaws.com/role-arn="$BEDROCK_ROLE_ARN" --overwrite kubectl rollout restart deploy/definite-api -n kubectl rollout status deploy/definite-api -n ``` Without this annotation Fi can't call Bedrock and every Fi conversation fails. See [AWS guide → Bedrock IRSA](/on-prem/aws#bedrock-irsa). **If `REGION` is not a US region, expect extra Bedrock work.** Fi runs in per-run sandbox pods (the agent-sandbox CRDs from `definite bootstrap`), not in `definite-api`, and the sandbox client only normalizes `us.`/`anthropic.` model prefixes correctly. The module and chart also default to `us.`-prefixed inference profiles and a model that may be Legacy outside the US. Before declaring Fi healthy in a non-US region, work through [AWS guide → Choosing a Bedrock model](/on-prem/aws#choosing-a-bedrock-model-and-inference-profile) and the [Non-US LiteLLM proxy path](/on-prem/aws#non-us-regions-route-fi-through-the-litellm-proxy). The failures you'll hit and their fixes: - `ResourceNotFoundException: ... marked by provider as Legacy` → pick a current model ID for the region. - `AccessDenied` at invoke time → the cross-region profile (e.g. `au.*`) dispatches to a sibling region; add those region ARNs to the Bedrock IAM policy. - `The provided model identifier is invalid` / `No API key found for amazon-bedrock` → route Fi through the `definite-litellm` proxy with the region's profile IDs. These are advanced, manual steps the released CLI doesn't yet automate. If you hit them, tell the human and escalate to `hello@definite.app` rather than guessing; treat them as the kind of failure that warrants stopping per the escalation rules. --- ## Phase 5: Verify 1. `definite status --config config.yaml`: all pods `Running`, ingress has an address. 2. Open `https://` in a browser. In the default flow this is the Definite-brokered `https://.onprem.definite.app` URL; wait until the broker reports DNS/TLS ready before debugging the app. 3. Log in with the admin email + password from Phase 4. 4. Confirm core auth routes return 200 after login (`/login`, `/auth/me`, and the main app shell). 5. Run a simple query smoke, for example `SELECT 1 AS ok`. 6. Record the object count under the configured lakehouse prefix with the cloud CLI. Then create a uniquely named persistent table with at least 1,500 distinctive rows through the authenticated query API or query editor, read it back, and verify the exact row count and marker values. 7. List the object store again and identify the newly created `.parquet` object with a size greater than zero. SQL success is not proof of this check. On Azure, follow [Verify the Azure deployment](/on-prem/azure#verify-the-deployment) exactly and include the Blob object path and byte size in the handoff. 8. Drop the logical smoke-test table. DuckLake can retain its Parquet file for snapshot history, so do not delete physical objects by hand. 9. Open the authenticated data apps page and confirm it loads. 10. If Fi is configured, create a new Fi thread, send a unique test prompt, and follow the event stream to a terminal success state. On Azure OpenAI this is the post-install proof that the configured model works through Fi, not only through a direct provider request. If any of these fail, capture logs (`definite logs api --tail 200`) before debugging. --- ## Hand-off to the human When Phase 5 is green, summarize for the human: - The URL they sign in at - The admin email + a reminder where the password is saved - The path to `config.yaml` (they'll need it for `definite upgrade`) - The per-cloud guide's Day-2 section (`/on-prem/#day-2-operations`) - Next steps: [Connect a data source](/integrations), [set up the MCP server](/mcp), [add SSO](/on-prem/sso) if they started with local auth - For teardown later: the per-cloud guide's Phase 3. On AWS in particular, the ingress-nginx NLB must be deleted before `terraform destroy` or the destroy hangs on subnet `DependencyViolation`. --- ## When to escalate Stop and tell the human to email `hello@definite.app` if: - The cloud account is missing a permission you can't grant yourself, and the human can't grant it either. - The LLM provider rejects model access and the human's admin doesn't respond within an hour. - `definite doctor` fails three times for distinct reasons. - `definite init` succeeds but pods crash-loop with errors that aren't in the per-cloud Troubleshooting table. - The human asks for anything beyond install (capacity planning, custom registry mirrors, air-gapped install, FIPS compliance, custom sandbox network policies). Email [hello@definite.app](mailto:hello@definite.app) with reproducible bugs. --- # CLI > Install and use the `definite` CLI to operate and exercise an on-prem deployment. The `definite` CLI is a single static binary with two layers: - **Admin / cluster ops** — `init`, `upgrade`, `status`, `doctor`, `logs`, `bootstrap`, `export-helm`. Talks to `kubectl` and `helm` against your cluster. These are covered in [Agent setup](/on-prem/agent-setup) and the per-cloud guides ([AWS](/on-prem/aws), [GCP](/on-prem/gcp), [Azure](/on-prem/azure)). - **API client** — `definite run …`. Talks to the deployed API over HTTPS using a bearer token. This page is mostly about that layer: querying the lakehouse, loading files, kicking off Fi, managing data apps, and so on. --- ## Installation The CLI ships as a single static binary. The fastest install is the public installer script — it detects your OS + arch, downloads the matching release, verifies its SHA256, and drops the binary into `~/.local/bin/definite`. ```bash curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/install.sh | sh definite version ``` Supports macOS (Intel + Apple Silicon) and Linux (x86_64 + arm64). Override the defaults with env vars: ```bash # Pin a specific version DEFINITE_VERSION=v0.0.18 curl -fsSL .../install.sh | sh # Install somewhere other than ~/.local/bin DEFINITE_BIN_DIR=/usr/local/bin curl -fsSL .../install.sh | sudo sh ``` ### Run via Docker (Windows, CI, air-gapped) If you'd rather not install natively — Windows hosts, ephemeral CI runners, or an environment where you don't want a `~/.local/bin` mutation — the same binary is available as a public container image. The tag matches your deployment's API version. ```bash docker run --rm \ -e DEFINITE_API_URL -e DEFINITE_TOKEN \ us-central1-docker.pkg.dev/definite-quack-spike/definite-onprem/cli:0.0.18 \ run query "SELECT 1" ``` To make it feel like a local install, alias it and mount `~/.definite` so `definite login` (below) persists across runs: ```bash alias definite='docker run --rm -i \ -v ~/.definite:/root/.definite \ -e DEFINITE_API_URL -e DEFINITE_TOKEN \ us-central1-docker.pkg.dev/definite-quack-spike/definite-onprem/cli:0.0.18' ``` ### Pin to your deployment's exact tag To track whatever version the cluster is currently on: ```bash TAG=$(helm get values definite -n definite | awk '/^ tag:/ {print $2; exit}') DEFINITE_VERSION=v$TAG curl -fsSL \ https://storage.googleapis.com/definite-public/definite-onprem/install.sh | sh ``` --- ## Authenticate The API client uses bearer-token auth. Sessions are opaque ~43-character tokens with a ~14-day TTL. The recommended flow is `definite login`, which prompts for credentials and writes the session token to `~/.definite/credentials.json` (mode `0600`). Every subsequent `definite run …` call picks it up automatically — no flags or env vars needed. ```bash definite login https://your-deployment.example.com # Email: you@example.com # Password: ******** # ✓ logged in as you@example.com — credentials saved to ~/.definite/credentials.json ``` A bare hostname is assumed to be `https://`; pass an explicit `http://…` for a TLS-disabled deployment. Other useful forms: ```bash # Non-interactive (CI, scripts) — read the password from stdin echo "$DEFINITE_PASSWORD" | definite login your-deployment.example.com \ --email you@example.com --password-stdin ``` Verify you're logged in: ```bash definite run query "SELECT 1" ``` ### Without `definite login` (env-var fallback) When you can't (or don't want to) write a credentials file — ephemeral containers, sandboxes, one-off scripts — `definite run` also honors `DEFINITE_API_URL` + `DEFINITE_TOKEN`. Mint a token by calling `/api/v1/auth/login` directly: ```bash curl -sS -X POST "https://your-deployment.example.com/api/v1/auth/login" \ -H "Content-Type: application/json" \ -d '{"email": "you@example.com", "password": "..."}' ``` The response looks like: ```json { "token": "eyJhbGciOi...", "expires_at": "2026-06-10T18:42:11Z" } ``` ```bash export DEFINITE_API_URL=https://your-deployment.example.com export DEFINITE_TOKEN= ``` Explicit `--api-url` / `--token` flags on a `definite run` invocation override both env vars and the stored credentials file. ```bash curl -sS -H "Authorization: Bearer $DEFINITE_TOKEN" \ "$DEFINITE_API_URL/api/v1/auth/me" ``` A `200` with your user record means the token is good. A `401` means it expired or never validated — log in (or mint) again. --- ## Commands Every `definite run` subcommand respects `DEFINITE_API_URL` and `DEFINITE_TOKEN`. For an exhaustive list of flags, run: ```bash definite run --help ``` ### `run query` Execute SQL against the lakehouse. ```bash # Inline SQL definite run query "SELECT 1 AS one, 'hello' AS greeting" # From a file definite run query -f path/to/q.sql # JSON output for jq definite run query --format json "SELECT now()" | jq ``` `--format` defaults to `table` on a TTY and `json` when stdout is piped. `csv` is also valid. ### `run load` Upload a local file. Two modes: ```bash # Mode 1: just upload to Drive (object storage) definite run load ./mydata.csv # Mode 2: upload AND register as a lakehouse table definite run load ./sales.csv --table analytics.sales --mode replace definite run load ./more.parquet --table analytics.sales --mode append ``` When `--table` is set, `--mode` is required: either `replace` (drop and recreate) or `append` (insert into the existing table). Format auto-detects from the extension (`.csv`, `.parquet`, `.json`, `.ndjson`, `.jsonl`) and is overridable with `--file-format`. ### `run drive get` Fetch a file back from Drive. Accepts either a full `gs://…/drive//` URL or just the bare file id. ```bash definite run drive get gs://your-bucket/drive/abc123/sales.csv definite run drive get abc123 ``` ### `run app` Manage data apps. ```bash definite run app list definite run app upload ./index.html ./app.json definite run app delete definite run app scaffold ``` ### `run fi` Kick off the Fi agent in a new or existing thread. ```bash # Start a new thread definite run fi "summarize the orders table" --title "ad-hoc" # Continue an existing thread definite run fi "follow-up question" --thread-id ``` ### `run automation` Trigger a manual run of an automation pipeline by id. ```bash definite run automation run ``` ### `run integration` List, inspect, and test saved integrations. Secrets are never echoed back — `inspect` shows config shape only. ```bash definite run integration list definite run integration inspect definite run integration test ``` ### `run agent` Manage autonomous agents (long-running, scheduled, or event-driven Fi runners). ```bash definite run agent list definite run agent show ``` ### `run script` Manage reusable Python automation scripts. ```bash definite run script list definite run script run ``` ### `run maintenance` Run DuckLake table maintenance (compaction, vacuum, expire-snapshots). ```bash definite run maintenance compact . definite run maintenance vacuum .
``` ### `run event-source` Manage browser-safe event ingest sources. ```bash definite run event-source list definite run event-source show ``` ### `run permission` Manage app roles, sharing, and data-access roles. ```bash definite run permission list definite run permission grant ``` --- ## Output formats and scripting Most subcommands take `--format table|json|csv`. The default depends on context: - On a TTY (interactive shell): `table`. - Piped or redirected stdout (CI, scripts, agent sandboxes): `json`. That flip means you can pipe straight into `jq` without specifying `--format json` every time: ```bash definite run query "SELECT id, total FROM orders LIMIT 5" | jq '.[].total' ``` --- ## Troubleshooting Tokens expire after ~14 days. Run `definite login ` again — the new token overwrites the stored one. If you're on the env-var fallback, re-mint and re-export `DEFINITE_TOKEN`. Harmless. Only relevant if you ever build the CLI from source on a machine with a partially-shared `~/.cargo`. The shipped binary doesn't touch `~/.cargo` at runtime. Sanity-check `$DEFINITE_API_URL` resolves and is reachable from where you're running the CLI. If your deployment is on private DNS, run the CLI from inside the VPC (a bastion, or a one-off `kubectl run` pod). --- ## Next - [Agent setup](/on-prem/agent-setup) — let Claude Code, Cursor, or Windsurf drive a fresh install using the admin side of the CLI. - [AWS install guide](/on-prem/aws) — provision with Terraform, install with `definite init`. --- # Install on AWS > Stand up Definite in your own AWS account: EKS, RDS, S3, all driven by Terraform and the `definite` CLI. This guide walks you through a production-grade on-prem install of Definite on AWS. You'll provision the infrastructure with Terraform, install the platform with the `definite` CLI, and tear it down cleanly when you're done. By default, the install uses **Definite-brokered DNS and TLS**. Definite provides a URL like `https://.onprem.definite.app` during setup, so you do not need to configure Route 53 or any other customer DNS before the first successful install. End to end: about 30 to 40 minutes, most of which is `terraform apply` waiting on EKS and RDS. ## What gets created | Resource | Notes | |---|---| | VPC | Private subnets for nodes and the database, public subnets for NAT and load balancers | | EKS cluster | Kubernetes 1.30 (configurable), managed node group, OIDC provider enabled for IRSA | | RDS Postgres 15 | Private (not publicly accessible), reachable only from the cluster security group | | S3 bucket | Lakehouse data; public access blocked, encryption and versioning on | | IAM IRSA roles | Least-privilege roles for the lakehouse and for Fi's Bedrock access | | IAM user + access key | Static-credential fallback for the lakehouse (see [IRSA vs access key](#irsa-vs-access-key)) | | `gp3` StorageClass | Cluster-default StorageClass the lakehouse PVC needs | Every name, instance size, CIDR, and count is a Terraform variable with a sane default. Override only what you need to in `terraform.tfvars`. --- ## Prerequisites AWS credentials in your shell with permission to create VPC, EKS, RDS, S3, and IAM resources. The Terraform provider reads the standard AWS credential chain (env vars, shared config, SSO, instance profile). No secrets live in the Terraform code. Install the following on the machine you'll run `terraform` and `definite` from: | Tool | Version | Check | |---|---|---| | `terraform` | 1.5+ | `terraform version` | | `aws` CLI | recent | `aws --version` | | `kubectl` | 1.28+ | `kubectl version --client` | | `helm` | 3.12+ | `helm version` | Decide which LLM provider Fi will use. Bedrock is the most common choice for AWS deployments; this guide uses it as the default. Anthropic, Vertex, and Azure OpenAI are also supported. If you go with Bedrock, make sure you've requested model access for Claude in the target region, and pick a current (non-Legacy) model. If you're deploying **outside a US region**, also read [Choosing a Bedrock model and inference profile](#choosing-a-bedrock-model-and-inference-profile) first: the inference-profile prefix, cross-region IAM, and the Fi sandbox's model-ID handling all need attention there. In the default brokered flow, you do not need a manual Definite setup token or license key. `definite init` uses your active AWS credentials to create a short-lived, signed STS `GetCallerIdentity` proof, exchanges that proof with Definite for a setup token, then receives the brokered DNS name and license. If your organization requires a manual/customer-owned mode, contact [hello@definite.app](mailto:hello@definite.app). For team use, configure an S3 backend in `versions.tf` before applying. A backend stub is committed in the module. Single-operator installs can skip this and use local state. --- ## Phase 1: Provision AWS infrastructure with Terraform Download the AWS Terraform module from the public release bucket and unpack it: ```bash curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/latest/terraform-aws.tar.gz -o terraform-aws.tar.gz curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/latest/terraform-aws.tar.gz.sha256 | shasum -a 256 -c - tar -xzf terraform-aws.tar.gz cd definite-aws-terraform ``` To pin a specific release, replace `latest` with a version tag (for example `v0.0.11`). ### 1. Configure inputs Copy the example tfvars file and edit it: ```bash cp terraform.tfvars.example terraform.tfvars $EDITOR terraform.tfvars ``` A minimal `terraform.tfvars` is just two lines: ```hcl region = "" name_prefix = "" ``` Everything else has a default. Common overrides: ```hcl # Lock the EKS public API endpoint to your office or VPN CIDRs. cluster_endpoint_public_access_cidrs = ["/24"] # Production hardening. rds_multi_az = true rds_deletion_protection = true # Bedrock model access (must be enabled in the AWS console first). # Use current (non-Legacy) model IDs available in YOUR region. bedrock_model_ids = ["anthropic.claude-sonnet-4-6"] ``` **Non-US regions need extra Bedrock care.** The module and chart default to `us.`-prefixed inference profiles, and a cross-region profile dispatches compute to a sibling region (for example an `au.` profile in `ap-southeast-2` runs inference in `ap-southeast-4`). If you're deploying outside the US, read [Choosing a Bedrock model and inference profile](#choosing-a-bedrock-model-and-inference-profile) before you apply, so the IAM policy covers every region the profile routes to and you don't pick a Legacy model. See the `README.md` included in the module for the full list of variables. ### 2. Init, plan, apply ```bash terminal terraform init terraform plan terraform apply ``` `terraform apply` takes 20 to 25 minutes (mostly EKS and RDS). When it finishes, every value you need is in `terraform output`. ### 3. Read the outputs Inspect the non-sensitive outputs: ```bash terraform output ``` For sensitive values, read them explicitly with `-raw`: ```bash terraform output -raw rds_password terraform output -raw lakehouse_s3_secret_access_key terraform output -raw postgres_url ``` The values you'll feed into `config.yaml` are summarized here: | Terraform output | Goes into | |---|---| | `cluster_name` | `aws eks update-kubeconfig --name ...` | | `region` | `object_store.region`, `llm.region` | | `postgres_url` (sensitive) | `postgres.url` | | `rds_password` (sensitive) | `POSTGRES_PASSWORD` env var | | `lakehouse_bucket_name` | `object_store.bucket` | | `lakehouse_prefix` | `lakehouse.prefix` | | `lakehouse_s3_access_key_id` | `S3_ACCESS_KEY_ID` env var | | `lakehouse_s3_secret_access_key` (sensitive) | `S3_SECRET_ACCESS_KEY` env var | | `bedrock_irsa_role_arn` | Post-install `kubectl annotate` on the `definite` ServiceAccount (see [Bedrock IRSA](#bedrock-irsa)) | The module also emits a ready-to-paste, non-secret `config.yaml` snippet: ```bash terraform output -raw config_yaml_fragment ``` ### IRSA vs access key The module emits both an **IRSA role** and an **IAM user + access key** for lakehouse S3 access. Both share one identical least-privilege policy. | Option | When to use | |---|---| | **Access key** (`lakehouse_s3_access_key_id`, `lakehouse_s3_secret_access_key`) | **Use this today.** The lakehouse reads S3 through DuckDB's `httpfs` extension, which speaks the S3 API with static credentials, not the AWS SDK, so it can't assume an IRSA role yet. | | **IRSA role** (`lakehouse_irsa_role_arn`) | **The end state.** Once the lakehouse gains SDK-based S3 support, annotate the ServiceAccount with this role's ARN and delete the IAM user. No infra change needed. | Fi's Bedrock access uses IRSA today (no static credentials). --- ## Phase 2: Install Definite with the `definite` CLI ### 1. Install the CLI ```bash curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/install.sh | sh ``` The install script detects your OS and architecture, downloads the matching prebuilt binary from a public Google Cloud Storage bucket, verifies its SHA256 checksum, and places `definite` on your PATH (default: `$HOME/.local/bin`). Binaries are published for macOS and Linux (arm64 and x86_64), and are uploaded by the release workflow using short-lived Workload Identity Federation credentials (no long-lived keys). To pin a version, set `DEFINITE_VERSION` before piping to `sh`: ```bash curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/install.sh \ | DEFINITE_VERSION=v0.0.11 sh ``` Verify: ```bash definite version ``` ### 2. Point `kubectl` at the new cluster ```bash aws eks update-kubeconfig \ --region "$(terraform output -raw region)" \ --name "$(terraform output -raw cluster_name)" kubectl get nodes ``` You should see your managed node group's nodes in the `Ready` state. ### 3. Bootstrap cluster prerequisites `definite bootstrap` installs the cluster-level pieces that `definite init` assumes are already present: | Prerequisite | What it provides | |---|---| | Ingress controller | HTTP/S routing for the deployment's `Ingress` resource | | Definite-brokered DNS/TLS readiness | The default setup path uses the Definite setup broker and the returned `*.onprem.definite.app` URL | | agent-sandbox CRDs | Custom resources the Fi runtime uses to dispatch per-run sandboxes | Run it once against the fresh cluster: ```bash definite bootstrap ``` `--dry-run` prints what it would install without touching the cluster. The command is idempotent; safe to re-run. ### 4. Let `definite init` request Definite-brokered DNS The ingress controller provisions an AWS Network Load Balancer. Wait for it to land, then grab its hostname: ```bash LB_HOST=$(kubectl get svc ingress-nginx-controller -n ingress-nginx \ -o jsonpath='{.status.loadBalancer.ingress[0].hostname}' ) echo "$LB_HOST" ``` You'll get something like `.elb..amazonaws.com`. For the default path, do not stop here to ask the customer to create a CNAME. `definite init` calls the Definite setup broker for you, using the ingress target above. The backend contract is `POST /onprem/v1/setup-sessions`, but users and agents should not run a direct `curl` by default. ```bash definite init --config config.yaml --dns-mode definite-brokered ``` The CLI returns a URL like: ```text https://.onprem.definite.app ``` Customer-owned DNS is supported as an advanced/custom production option after the system is healthy. If the customer explicitly selected that mode, create a Route 53 or external CNAME from the customer hostname to `$LB_HOST` and use the released CLI's customer-owned mode. The expected flag shape is `--dns-mode customer-owned --hostname `. Private/internal production deployments may also need a customer certificate or private CA. Do not use `nip.io`, cert-manager, or Let's Encrypt as the default first-run path. ### 5. Build `config.yaml` Start from the EKS example config: [`minimal-eks.yaml`](https://storage.googleapis.com/definite-public/definite-onprem/examples/minimal-eks.yaml). The shape: ```yaml deployment: name: definite namespace: definite dns_mode: definite-brokered broker: # Optional. Omit for the default AWS path: definite init uses the active AWS # credential chain to acquire a short-lived setup token automatically. # setupToken: # env: DEFINITE_ONPREM_SETUP_TOKEN postgres: url: postgres://:${POSTGRES_PASSWORD}@:5432/ object_store: type: s3 bucket: # terraform output lakehouse_bucket_name region: # terraform output region credentials: key_id: env: S3_ACCESS_KEY_ID secret: env: S3_SECRET_ACCESS_KEY lakehouse: prefix: lake/ # terraform output lakehouse_prefix storage: size: 50Gi storage_class_name: gp3 auth: mode: oidc # or `local` for username/password auth issuer: https:// client_id: definite-onprem client_secret: env: OIDC_CLIENT_SECRET llm: provider: bedrock region: model: anthropic.claude-sonnet-4-6 # current, non-Legacy model in your region # Credentials via IRSA; no credentials block needed. # Non-US regions: the bedrock provider path may not resolve non-`us.` profiles; # see "Non-US regions: route Fi through the LiteLLM proxy" below. resources: api: replicas: 2 cpu: "1" memory: 2Gi lakehouse: replicas: 1 cpu: "4" memory: 16Gi frontend: replicas: 2 cpu: 500m memory: 512Mi job_runner: replicas: 1 cpu: 500m memory: 1Gi ``` The fastest way to fill in `postgres.url`, `object_store.bucket`, and friends is to paste the output of `terraform output -raw config_yaml_fragment` directly into your `config.yaml`. For the full list of knobs (image registry overrides, ingress class, sandbox configuration, etc.), see the config reference in Definite's built-in docs, available in-product once your deployment is running. ### 6. Export secrets `config.yaml` references env vars for every secret. Export them from Terraform outputs: ```bash export POSTGRES_PASSWORD=$(terraform output -raw rds_password) export S3_ACCESS_KEY_ID=$(terraform output -raw lakehouse_s3_access_key_id) export S3_SECRET_ACCESS_KEY=$(terraform output -raw lakehouse_s3_secret_access_key) export OIDC_CLIENT_SECRET=... # only if auth.mode: oidc ``` Do not export `LICENSE_KEY` or `DEFINITE_ONPREM_SETUP_TOKEN` for the default brokered flow. `definite init` obtains the setup token and license from Definite after proving control of the active AWS credentials. Don't commit `config.yaml`, `terraform.tfvars`, or `terraform.tfstate` to a public repo. The state file holds the RDS password and the S3 secret in cleartext. ### 7. Preflight with `definite doctor` ```bash definite doctor --config config.yaml ``` `doctor` runs a battery of preflight checks: it connects to Postgres and runs `SELECT version()`, validates the Kubernetes context, checks object-store config shape, and (for Anthropic) pings the LLM API. Fix anything it flags before moving on. ### 8. Deploy with `definite init` ```bash definite init --config config.yaml ``` `init` re-runs preflight, renders the bundled Helm chart with your values, and runs `helm upgrade --install`. It waits for pods to reach `Ready` by default. Useful flags: | Flag | Purpose | |---|---| | `--dry-run` | Render values, don't apply | | `--wait=false` | Return as soon as Helm finishes; don't wait for pods | | `--skip-preflight` | Skip `doctor`. Use only when the per-cloud troubleshooting path says a private-network check is expected to fail from your laptop | Watch the rollout in another terminal: ```bash definite status --config config.yaml definite logs api --follow ``` ### 9. Set the initial admin user The chart does not auto-create an initial admin. After `definite init` returns successfully and the pods are `Ready`, set `INITIAL_ADMIN_EMAIL` and `INITIAL_ADMIN_PASSWORD` on the api Deployment; the api creates the admin record on its next start. ```bash ADMIN_PASSWORD=$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 24) kubectl set env deploy/definite-api -n definite \ INITIAL_ADMIN_EMAIL= \ INITIAL_ADMIN_PASSWORD="$ADMIN_PASSWORD" kubectl rollout status deploy/definite-api -n definite echo "Admin password: $ADMIN_PASSWORD" ``` Save the password somewhere safe (1Password, Vault, etc.). The admin bootstrap env vars are only needed to create the initial admin. As of the v0.0.11 install path, this API rollout is expected to complete without a manual lakehouse restart. When the brokered URL reports DNS/TLS ready, open `https://` in a browser and log in with the admin email and password from above. **Want Google SSO instead of local auth?** See the [Google SSO guide](/on-prem/sso). You'll add an `auth.oidc` block to your `config.yaml` and re-run `definite upgrade` — no need to redo the install. ### Bedrock IRSA If you're using Bedrock as the LLM provider (the default for AWS), Fi authenticates to Bedrock via IRSA: the pod's `ServiceAccount` must carry an `eks.amazonaws.com/role-arn` annotation pointing at the IRSA role Terraform created. There is no API key for Bedrock; the coding agent resolves credentials from the AWS credential chain (the projected web-identity token from IRSA, plus a region). Confirm the annotation after `definite init`, and apply it if it is missing: ```bash BEDROCK_ROLE_ARN=$(terraform output -raw bedrock_irsa_role_arn) kubectl annotate serviceaccount definite -n definite \ eks.amazonaws.com/role-arn="$BEDROCK_ROLE_ARN" --overwrite # Restart the api pod so it picks up the projected token for the new role. kubectl rollout restart deploy/definite-api -n definite kubectl rollout status deploy/definite-api -n definite ``` A subsequent `definite upgrade` preserves the annotation (Helm's three-way merge leaves unmanaged fields alone), but re-apply it if anyone does a `helm uninstall` + reinstall. Fi doesn't run in `definite-api`. Each Fi conversation is dispatched into a short-lived sandbox pod (the agent-sandbox CRDs from `definite bootstrap`; you'll see `definite-fi-warm-*` pods pre-warmed and ready). Those sandbox pods are what call the model, so getting the **model ID and region right matters as much as the IRSA role**. The rest of this section covers the model-selection traps, which are the most common reason Fi fails after a clean install. ### Choosing a Bedrock model and inference profile Bedrock Claude access goes through a **cross-region inference profile**, not the bare foundation model ID. Inference profiles are prefixed by geography: | Prefix | Geography | Example region | |---|---|---| | `us.` | United States | `us-east-1`, `us-west-2` | | `eu.` | Europe | `eu-central-1`, `eu-west-1` | | `apac.` | Asia Pacific (broad) | several AP regions | | `au.` | Australia | `ap-southeast-2` (Sydney) | **You must use the prefix that matches your region.** The Terraform module and the bundled Helm chart default to `us.` everywhere, which only works in US regions. In other regions a `us.` profile either doesn't exist or the bare foundation ID is rejected with `on-demand throughput isn't supported`. Pick the profile prefix for your geography and a current (non-Legacy) model ID, for example: ```hcl # terraform.tfvars — example for ap-southeast-2 (Sydney) bedrock_model_ids = [ "anthropic.claude-sonnet-4-6", "anthropic.claude-opus-4-7", "anthropic.claude-sonnet-4-5-20250929-v1:0", "anthropic.claude-haiku-4-5-20251001-v1:0", ] ``` **Cross-region profiles dispatch compute to a sibling region.** An `au.*` profile invoked in `ap-southeast-2` (Sydney) routes the actual inference to `ap-southeast-4` (Melbourne). The IAM policy attached to the Bedrock IRSA role must therefore allow `bedrock:InvokeModel*` on the foundation model ARNs in **every** region the profile can route to, not just your primary region. Scoping the policy to only `ap-southeast-2` produces `AccessDenied` at invoke time even though the profile and model access look correct. Check the AWS docs for which regions your chosen profile fans out to, and add all of them to the policy (and to the inference-profile registration). **Legacy models are rejected outside US regions.** The upstream Terraform module has historically hardcoded `us.anthropic.claude-sonnet-4-20250514-v1:0`, which is marked **Legacy** in some regions and fails with `ResourceNotFoundException: Access denied. This Model is marked by provider as Legacy`. Use a current model ID for your region and confirm model access is granted in the Bedrock console **for that region** before installing. ### Non-US regions: route Fi through the LiteLLM proxy The Fi sandbox client (`@earendil-works/pi-ai`) normalizes Bedrock model IDs before calling Bedrock, and today it only understands two shapes: a `us.`-prefixed profile ID (passed through), or an `anthropic.`-prefixed foundation ID (it prepends `us.`). Any other prefix, including `au.`, `eu.`, and `apac.`, gets mangled (`au.anthropic.claude-sonnet-4-6` becomes `us.anthropic.au.anthropic.claude-sonnet-4-6`) and Fi fails with: ``` Run failed - failed to publish Pi events: Validation error: The provided model identifier is invalid. ``` You may also see this surface earlier as `No API key found for amazon-bedrock. Use /login ...` from `/opt/fi-agent/...`, which is the agent's generic fallback when it can't resolve a usable Bedrock target. Until the sandbox client handles non-US prefixes natively, the working path for non-US regions is to point Fi at the bundled **LiteLLM proxy** (the `definite-litellm` deployment), which does the model mapping and Bedrock auth for you. This is an advanced, manual path: 1. **Switch the chart to the `litellm` provider.** The `definite` CLI's `config.yaml` only accepts `provider: anthropic | bedrock | vertex | azure_openai`, so you can't select LiteLLM through the CLI. Apply it with a direct Helm override instead: ```yaml # litellm-override.yaml llm: provider: litellm model: claude-sonnet-4-6 region: ap-southeast-2 litellmUpstream: bedrock litellmImage: "ghcr.io/berriai/litellm:main-v1.82.0-stable" apiKey: "" # see step 3 ``` ```bash helm upgrade definite ~/.cache/definite/chart- -n definite \ --reuse-values -f litellm-override.yaml ``` 2. **Patch the LiteLLM ConfigMap to your region's profile IDs.** The chart ships `definite-litellm-config` hardcoded with `us.*` model IDs, so edit `definite-litellm-config` to map each `model_name` to the correct `bedrock/.anthropic....` target and `aws_region_name`, then restart the proxy: ```bash kubectl edit configmap definite-litellm-config -n definite # e.g. claude-sonnet-4-6 -> bedrock/au.anthropic.claude-sonnet-4-6, aws_region_name: ap-southeast-2 kubectl rollout restart deployment/definite-litellm -n definite ``` 3. **Set a LiteLLM master key.** With the `bedrock` provider the `llm-api-key` entry in `definite-secrets` is empty (Bedrock uses IRSA, not a key). LiteLLM needs one, so generate a key, reference it as `LITELLM_MASTER_KEY` (`general_settings.master_key`), and patch it into `definite-secrets`. Re-apply steps 2 and 3 after any `definite upgrade` or `helm upgrade` that re-renders the LiteLLM section, because the chart resets `definite-litellm-config` back to the `us.*` defaults. This manual path is a stopgap for non-US Bedrock; if you're standing up a non-US region, mention it to [hello@definite.app](mailto:hello@definite.app) so you get a chart build that parameterizes the inference-profile prefix. The path that should work end to end once configured is: **Fi sandbox → `definite-litellm` (port 4000) → Bedrock**. Smoke-test it from inside the cluster: ```bash kubectl run llm-smoke --rm -it --image=curlimages/curl -n definite --restart=Never -- \ curl -s http://definite-litellm.definite.svc.cluster.local:4000/v1/chat/completions \ -H "Authorization: Bearer " -H "Content-Type: application/json" \ -d '{"model":"claude-sonnet-4-6","messages":[{"role":"user","content":"say Ready"}]}' ``` --- ## Day-2 operations The same CLI handles upgrades, logs, license, and lakehouse maintenance. A few of the most common commands: ```bash definite status --config config.yaml # `kubectl get pods,svc,ingress` for the namespace definite logs api --follow # stream component logs definite upgrade --config config.yaml # re-render and re-apply with the current CLI version definite license status # show the deployment's live plan + activation status definite run maintenance stats # lakehouse file/snapshot stats ``` Definite's built-in docs include a full CLI reference for every command and flag. --- ## Phase 3: Teardown **Delete the ingress-nginx load balancer before running `terraform destroy`.** `definite bootstrap` provisions an AWS Network Load Balancer through a Kubernetes `Service: LoadBalancer`. The NLB is owned by Kubernetes, not Terraform, and its ENIs in the public subnets block `terraform destroy` with `DependencyViolation` errors after ~20 minutes of retry. First, delete the orphaned NLB so Terraform can clean up the VPC: ```bash VPC=$(terraform output -raw vpc_id) LB_ARN=$(aws elbv2 describe-load-balancers \ --query "LoadBalancers[?VpcId=='$VPC'].LoadBalancerArn" --output text) [ -n "$LB_ARN" ] && aws elbv2 delete-load-balancer --load-balancer-arn "$LB_ARN" ``` Wait 30 to 60 seconds for the ENIs to clear, then destroy the rest with Terraform: ```bash cd definite-aws-terraform terraform destroy ``` A couple of safety rails are on by default: | Variable | Default | Effect | |---|---|---| | `rds_deletion_protection` | `false` (set to `true` for production) | When `true`, RDS refuses to be deleted; flip it to `false` first | | `lakehouse_force_destroy` | `false` | Non-empty buckets won't be deleted; flip it to `true` if you really mean to remove the bucket and its contents | For production teardowns, snapshot RDS and back up the S3 bucket first; once Terraform deletes them, they're gone. --- ## Troubleshooting | Symptom | Likely cause | Fix | |---|---|---| | `terraform apply` hangs on EKS | Cluster takes 15-20 min to provision; this is normal | Wait | | Lakehouse pod stuck `Pending` on PVC | No default StorageClass | Confirm `gp3` StorageClass is present: `kubectl get storageclass`. The module creates it by default; set `create_gp3_storage_class = true` if you disabled it | | `definite doctor` Postgres check fails with "connect timeout" or "could not reach postgres" | RDS is not publicly accessible (no public endpoint); the check is running from a laptop outside the VPC | Expected for private RDS from a laptop. The in-cluster API pods reach RDS over the VPC's private network. To fully validate before install, run `definite doctor` from a bastion host or an in-cluster pod. Use `--skip-preflight` only for this known private-network check, not for object-store, Kubernetes, license, or LLM failures | | LB hostname never appears | Ingress controller isn't running, or the AWS Load Balancer Controller fights with `ingress-nginx` | `kubectl get pods -n ingress-nginx`; if you installed both controllers, pick one | | Brokered URL never becomes ready | The setup broker has not pointed `*.onprem.definite.app` at the NLB yet, or the NLB hostname is wrong | Re-run `definite init --config config.yaml --dns-mode definite-brokered`, confirm `$LB_HOST` matches the ingress Service, and retry before debugging the app | | Customer-owned hostname does not work | Customer-owned DNS was selected, but the CNAME does not point at the NLB or the custom cert/private CA path is incomplete | Fix the customer DNS/cert path or switch back to the default Definite-brokered DNS mode for first install | | Fi can't reach Bedrock | The `definite` ServiceAccount isn't annotated with the Bedrock IRSA role, or the model isn't enabled in the region | Annotate the SA with the Bedrock IRSA role ARN (see [Bedrock IRSA](#bedrock-irsa)), and request model access in the AWS Bedrock console | | `ResourceNotFoundException: ... This Model is marked by provider as Legacy` | The model ID (often the module's hardcoded `us.anthropic.claude-sonnet-4-20250514-v1:0`) is Legacy in your region | Set `bedrock_model_ids` / `llm.model` to a current model available in your region. See [Choosing a Bedrock model](#choosing-a-bedrock-model-and-inference-profile) | | Fi fails with `The provided model identifier is invalid` (or `No API key found for amazon-bedrock. Use /login ...` from `/opt/fi-agent/...`) | The Fi sandbox client only normalizes `us.`/`anthropic.` model prefixes; a non-US profile (`au.`, `eu.`, `apac.`) gets mangled | Route Fi through the LiteLLM proxy for non-US regions. See [Non-US regions](#non-us-regions-route-fi-through-the-litellm-proxy) | | Bedrock invoke returns `AccessDenied` even though model access is granted | A cross-region inference profile dispatches compute to a sibling region not covered by the IAM policy (e.g. `au.*` in `ap-southeast-2` runs in `ap-southeast-4`) | Add the foundation model ARNs for **all** regions the profile routes to, to the Bedrock IRSA policy | | `definite init`/`upgrade` fails with `unknown flag: --force-conflicts` | Some CLI builds pass `helm upgrade --install ... --force-conflicts`, which isn't a valid Helm flag | Known CLI bug. Report it to [hello@definite.app](mailto:hello@definite.app); as a stopgap, wrap `helm` with a script that strips `--force-conflicts` before calling the real binary | | `definite init` errors with `deployments.apps "definite-lakehouse" not found` | Stale CLI readiness check: in recent chart versions the lakehouse is embedded (DuckDB) in the API pod, not a separate deployment | Cosmetic. Confirm pods are `Running` with `definite status`; the install actually succeeded. Report the stale check to [hello@definite.app](mailto:hello@definite.app) | | You can log in, but every product page or API call returns HTTP 403 | The deployment is unlicensed: `config.yaml` has no `license` block, or the key is wrong | Add a `license` block with your Definite-issued key and run `definite upgrade --config config.yaml`. `definite init` prints an `UNLICENSED` warning when the block is missing | --- ## Next steps - [Connect a data source](/integrations) to start ingesting data. - [Set up the MCP server](/mcp) so Claude, Cursor, or Windsurf can query your deployment. - For deeper config (custom container registry, sandbox network policies, OIDC tuning), see the config reference in Definite's built-in docs. ## Support For issues or questions, contact [hello@definite.app](mailto:hello@definite.app). --- # Install on GCP > Stand up Definite in your own GCP project: GKE, Cloud SQL Postgres, GCS, driven by `gcloud` and the `definite` CLI. This guide walks you through an on-prem install of Definite on Google Cloud. You'll provision the infrastructure with `gcloud`, install the platform with the `definite` CLI, and tear it down cleanly when you're done. Unlike AWS, this is currently a scripted/manual provisioning path rather than a packaged Terraform module. By default, the install uses **Definite-brokered DNS and TLS**. Definite provides a URL like `https://.onprem.definite.app` during setup, so you do not need to configure Cloud DNS or any other customer DNS before the first successful install. End to end: about 30 to 40 minutes, most of which is GKE and Cloud SQL spinning up. Unlike the [AWS guide](/on-prem/aws), GCP does not yet ship a Terraform module. The steps below use `gcloud` directly. A GCP Terraform module (matching the AWS Terraform module) is on the roadmap. If you'd prefer to wait or want early access, contact [hello@definite.app](mailto:hello@definite.app). ## What gets created | Resource | Notes | |---|---| | VPC + subnet | Regional VPC with a subnet for the GKE nodes; private cluster recommended | | GKE cluster | Kubernetes 1.30 (configurable). Autopilot works; Standard is also supported | | Cloud SQL Postgres 15 | Private IP, reachable only from the VPC | | GCS bucket | Lakehouse data; uniform bucket-level access, versioning recommended | | GCS HMAC key | Service-account-bound HMAC key the lakehouse uses to read/write the bucket (see [HMAC vs Workload Identity](#hmac-vs-workload-identity)) | | Artifact Registry repo (optional) | Only needed if you mirror Definite images into your project | | `premium-rwo` StorageClass | GKE shorthand for PD-SSD; the lakehouse PVC binds to this by default | Every name, region, machine type, and CIDR below is something you choose. Set them once at the top of your shell session as env vars (`PROJECT_ID`, `REGION`, etc.) and reuse them. --- ## Prerequisites A GCP project where you have permission to create GKE clusters, Cloud SQL instances, GCS buckets, service accounts, and IAM bindings. The `gcloud` CLI must be authenticated (`gcloud auth login`) and the project set (`gcloud config set project `). Install the following on the machine you'll run `gcloud` and `definite` from: | Tool | Version | Check | |---|---|---| | `gcloud` | recent | `gcloud version` | | `kubectl` | 1.28+ | `kubectl version --client` | | `helm` | 3.12+ | `helm version` | | `gke-gcloud-auth-plugin` | recent | `gke-gcloud-auth-plugin --version` | Turn on the APIs the install touches: ```bash gcloud services enable \ container.googleapis.com \ sqladmin.googleapis.com \ compute.googleapis.com \ servicenetworking.googleapis.com \ iamcredentials.googleapis.com \ aiplatform.googleapis.com ``` The last one (`aiplatform.googleapis.com`) is only needed if Fi will use Vertex AI as its LLM provider. Decide which LLM provider Fi will use. **Vertex AI** is the most common choice for GKE deployments because it lives in the same project and authenticates via the cluster's identity. Anthropic, Bedrock, and Azure OpenAI are also supported. If you go with Vertex, make sure the Claude model you want is enabled for your project (Vertex Model Garden -> Anthropic models). In the default brokered flow, you do not need a manual Definite setup token or license key. `definite init` uses `gcloud auth print-identity-token` to prove the active GCP identity to Definite, exchanges that proof for a short-lived setup token, then receives the brokered DNS name and license. For production, prefer running the agent as a setup service account rather than a personal user account. If your organization requires a manual/customer-owned mode, contact [hello@definite.app](mailto:hello@definite.app). --- ## Phase 1: Provision GCP infrastructure The fastest path right now is to provision with `gcloud` directly. The shape mirrors what the AWS Terraform module produces. Set up shared env vars first: ```bash export PROJECT_ID="" export REGION="" # e.g. us-central1 export CLUSTER_NAME="" # e.g. definite export SQL_INSTANCE="" # e.g. definite-db export BUCKET="" # e.g. -definite-lake export SA_NAME="" # e.g. definite-lakehouse gcloud config set project "$PROJECT_ID" ``` ### 1. Create a GKE cluster Autopilot is the simplest option (Google manages nodes): ```bash gcloud container clusters create-auto "$CLUSTER_NAME" \ --region "$REGION" \ --release-channel regular ``` If you prefer Standard mode (more control over node pools, GPU, sole-tenant nodes), use `gcloud container clusters create` with a `--machine-type` like `e2-standard-4` and at least 3 nodes. Wire up `kubectl`: ```bash gcloud container clusters get-credentials "$CLUSTER_NAME" --region "$REGION" kubectl get nodes ``` ### 2. Create Cloud SQL Postgres ```bash gcloud sql instances create "$SQL_INSTANCE" \ --database-version=POSTGRES_15 \ --region="$REGION" \ --tier=db-custom-2-8192 \ --availability-type=REGIONAL gcloud sql databases create definite --instance="$SQL_INSTANCE" gcloud sql users create definite \ --instance="$SQL_INSTANCE" \ --password="" ``` Stash the connection name (used by the Cloud SQL Auth Proxy and by `postgres.url`): ```bash gcloud sql instances describe "$SQL_INSTANCE" --format='value(connectionName)' ``` For production, give the instance a **private IP** in your VPC (see [Private IP setup](https://cloud.google.com/sql/docs/postgres/configure-private-ip)) so the cluster can reach it without going through the auth proxy. If the instance is on the same VPC as the cluster, `postgres.url` looks like: ``` postgres://definite:${POSTGRES_PASSWORD}@:5432/definite ``` ### 3. Create a GCS bucket for the lakehouse ```bash gcloud storage buckets create "gs://${BUCKET}" \ --location="$REGION" \ --uniform-bucket-level-access \ --public-access-prevention ``` Versioning is recommended for production: ```bash gcloud storage buckets update "gs://${BUCKET}" --versioning ``` ### 4. Create a service account and HMAC key for the bucket The lakehouse reads and writes GCS through DuckDB's `httpfs` extension. `httpfs` speaks the S3 interop API, not native GCS, so it needs an **HMAC key pair** bound to a service account that has object-admin on the bucket. Workload Identity alone is not enough. ```bash # Create a dedicated service account for the lakehouse. gcloud iam service-accounts create "$SA_NAME" \ --display-name="Definite lakehouse" SA_EMAIL="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com" # Grant it object-admin on the lakehouse bucket only (least privilege). gcloud storage buckets add-iam-policy-binding "gs://${BUCKET}" \ --member="serviceAccount:${SA_EMAIL}" \ --role="roles/storage.objectAdmin" # Create the HMAC pair. The key + secret print once; capture them now. gcloud storage hmac create "$SA_EMAIL" ``` The output gives you `accessId` (the HMAC key ID) and `secret` (the HMAC secret). These are what you'll set as `GCS_HMAC_KEY_ID` and `GCS_HMAC_SECRET` before running `definite init`. ### 5. (If using Vertex AI for Fi) Grant Vertex access Bind the GKE workload identity for the API pod's service account to Vertex User on the project. The simplest way is to grant `roles/aiplatform.user` to the **node service account** the cluster runs as: ```bash NODE_SA=$(gcloud container clusters describe "$CLUSTER_NAME" \ --region "$REGION" \ --format='value(nodeConfig.serviceAccount)') # `default` resolves to the Compute Engine default SA; replace if you set one. [ "$NODE_SA" = "default" ] && \ NODE_SA="$(gcloud projects describe "$PROJECT_ID" --format='value(projectNumber)')-compute@developer.gserviceaccount.com" gcloud projects add-iam-policy-binding "$PROJECT_ID" \ --member="serviceAccount:${NODE_SA}" \ --role="roles/aiplatform.user" ``` For tighter scoping, set up Workload Identity on the deployment's API service account and bind `roles/aiplatform.user` to that specifically. ### HMAC vs Workload Identity | Option | When to use | |---|---| | **HMAC key** (`accessId`, `secret`) | **Use this today** for lakehouse bucket access. The lakehouse uses DuckDB's `httpfs` extension, which speaks the S3 interop API with static credentials. Workload Identity can't be used for the bucket. | | **Workload Identity** | **Use this** for Vertex AI access (and any other GCP API the deployment's pods call). The API pod runs as a Kubernetes ServiceAccount that's bound to a Google service account with `roles/aiplatform.user`. No static credentials. | --- ## Phase 2: Install Definite with the `definite` CLI ### 1. Install the CLI ```bash curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/install.sh | sh ``` The install script detects your OS and architecture, downloads the matching prebuilt binary from a public Google Cloud Storage bucket, verifies its SHA256 checksum, and places `definite` on your PATH (default: `$HOME/.local/bin`). Binaries are published for macOS and Linux (arm64 and x86_64), and are uploaded by the release workflow using short-lived Workload Identity Federation credentials (no long-lived keys). To pin a version, set `DEFINITE_VERSION` before piping to `sh`: ```bash curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/install.sh \ | DEFINITE_VERSION=v0.0.17 sh ``` Verify: ```bash definite version ``` ### 2. Bootstrap cluster prerequisites `definite bootstrap` installs the cluster-level pieces that `definite init` assumes are already present: | Prerequisite | What it provides | |---|---| | Ingress controller | HTTP/S routing for the deployment's `Ingress` resource | | Definite-brokered DNS/TLS readiness | The default setup path uses the Definite setup broker and the returned `*.onprem.definite.app` URL | | agent-sandbox CRDs | Custom resources the Fi runtime uses to dispatch per-run sandboxes | Run it once against the fresh cluster: ```bash definite bootstrap ``` On GKE Autopilot, `definite bootstrap` pins cert-manager's leader-election lease to the `cert-manager` namespace. The chart default of `kube-system` is Google-managed on Autopilot and rejects writes; without the override the webhook CA is never injected. The CLI applies this automatically. `--dry-run` prints what it would install without touching the cluster. The command is idempotent; safe to re-run. ### 3. Let `definite init` request Definite-brokered DNS The ingress controller provisions a Google Cloud Network Load Balancer. Wait for it to land, then grab its external IP: ```bash LB_IP=$(kubectl get svc ingress-nginx-controller -n ingress-nginx \ -o jsonpath='{.status.loadBalancer.ingress[0].ip}' ) echo "$LB_IP" ``` You'll get something like `34.x.y.z`. For the default path, do not stop here to ask the customer to create DNS. `definite init` calls the Definite setup broker for you, using the ingress target above when brokered DNS supports that target type. The backend contract is `POST /onprem/v1/setup-sessions`, but users and agents should not run a direct `curl` by default. ```bash definite init --config config.yaml --dns-mode definite-brokered ``` The CLI returns a URL like: ```text https://.onprem.definite.app ``` Customer-owned DNS is supported as an advanced/custom production option after the system is healthy. If the customer explicitly selected that mode, create a Cloud DNS or external A record from the customer hostname to `$LB_IP` and use the released CLI's customer-owned mode. The expected flag shape is `--dns-mode customer-owned --hostname `. Private/internal production deployments may also need a customer certificate or private CA. Do not use `nip.io`, cert-manager, or Let's Encrypt as the default first-run path. ### 4. Build `config.yaml` Start from the GKE example config: [`minimal-gke.yaml`](https://storage.googleapis.com/definite-public/definite-onprem/examples/minimal-gke.yaml). The shape: ```yaml deployment: name: definite namespace: definite dns_mode: definite-brokered broker: # Optional. Omit for the default GCP path: definite init uses gcloud to # acquire a short-lived setup token automatically. # setupToken: # env: DEFINITE_ONPREM_SETUP_TOKEN postgres: url: postgres://definite:${POSTGRES_PASSWORD}@:5432/definite object_store: type: gcs bucket: # GCS HMAC pair from `gcloud storage hmac create`. credentials: key_id: env: GCS_HMAC_KEY_ID secret: env: GCS_HMAC_SECRET lakehouse: prefix: lake/ storage: size: 50Gi storage_class_name: premium-rwo # GKE shorthand for PD-SSD auth: mode: local # or `oidc` for SSO initial_admin_email: admin@ initial_admin_password: env: INITIAL_ADMIN_PASSWORD llm: provider: vertex project: region: # Credentials via Workload Identity on the node SA; no credentials block needed. resources: api: replicas: 2 cpu: "1" memory: 2Gi lakehouse: replicas: 1 cpu: "4" memory: 16Gi frontend: replicas: 2 cpu: 500m memory: 512Mi job_runner: replicas: 1 cpu: 500m memory: 1Gi ``` GKE Autopilot uses `standard-rwo` (Balanced PD) and `premium-rwo` (SSD PD) as its two built-in StorageClasses. The lakehouse benefits from SSD, so `premium-rwo` is the default. Run `kubectl get storageclass` to see what your cluster has. For the full list of knobs (image registry overrides, ingress class, sandbox configuration, etc.), see the config reference in Definite's built-in docs, available in-product once your deployment is running. ### 5. Export secrets `config.yaml` references env vars for every secret: ```bash export POSTGRES_PASSWORD="" export GCS_HMAC_KEY_ID="" export GCS_HMAC_SECRET="" export INITIAL_ADMIN_PASSWORD="$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 24)" export OIDC_CLIENT_SECRET=... # only if auth.mode: oidc ``` Do not export `LICENSE_KEY` or `DEFINITE_ONPREM_SETUP_TOKEN` for the default brokered flow. `definite init` obtains the setup token and license from Definite after proving the active GCP identity. Don't commit `config.yaml` to a public repo while these env vars are exported into your shell history. If you want to script the install, source the values from a secret manager (e.g. `gcloud secrets versions access`). ### 6. (Optional) Use LiteLLM gateway If you want a single LLM gateway in front of Vertex (for rate limiting, request logging, model routing, etc.), deploy [LiteLLM](https://docs.litellm.ai/) into the cluster and set `llm.provider: anthropic` in `config.yaml` with `api_key` pointing at LiteLLM's master key. LiteLLM presents an Anthropic-shaped API while talking to Vertex behind the scenes. ### 7. Preflight with `definite doctor` ```bash definite doctor --config config.yaml ``` `doctor` runs a battery of preflight checks: it connects to Postgres and runs `SELECT version()`, validates the Kubernetes context, checks object-store config shape, and (for Anthropic) pings the LLM API. Fix anything it flags before moving on. ### 8. Deploy with `definite init` ```bash definite init --config config.yaml ``` `init` re-runs preflight, renders the bundled Helm chart with your values, and runs `helm upgrade --install`. It waits for pods to reach `Ready` by default. Useful flags: | Flag | Purpose | |---|---| | `--dry-run` | Render values, don't apply | | `--wait=false` | Return as soon as Helm finishes; don't wait for pods | | `--skip-preflight` | Skip `doctor`. Use only when the troubleshooting path says a private-network check is expected to fail from your laptop | Watch the rollout in another terminal: ```bash definite status --config config.yaml definite logs api --follow ``` ### 9. Log in as the initial admin For local auth, the `auth.initial_admin_email` and `auth.initial_admin_password.env` settings in `config.yaml` are passed into the Helm install. On first startup, the API creates the initial admin from those values; you do not need a follow-up `kubectl set env` rollout. Save the generated `INITIAL_ADMIN_PASSWORD` somewhere safe (1Password, Vault, etc.). When the brokered URL reports DNS/TLS ready, open `https://` in a browser and log in with the admin email and password from above. --- ## Day-2 operations The same CLI handles upgrades, logs, license, and lakehouse maintenance. A few of the most common commands: ```bash definite status --config config.yaml # `kubectl get pods,svc,ingress` for the namespace definite logs api --follow # stream component logs definite upgrade --config config.yaml # re-render and re-apply with the current CLI version definite license status # show the deployment's live plan + activation status definite run maintenance stats # lakehouse file/snapshot stats ``` Definite's built-in docs include a full CLI reference for every command and flag. --- ## Phase 3: Teardown `definite bootstrap` provisions a Google Cloud Load Balancer via a Kubernetes `Service: LoadBalancer` (owned by the cluster, not by `gcloud`). Delete the ingress Service first so the LB's forwarding rules and target pools are cleaned up before the cluster goes away. `gcloud container clusters delete` will usually clean orphans up, but deleting the Service first avoids a stuck LB you have to track down by hand. ```bash # Trigger Kubernetes to delete the cloud load balancer cleanly. kubectl delete svc ingress-nginx-controller -n ingress-nginx --ignore-not-found # Lakehouse bucket (snapshot first if you care about the data). gcloud storage rm -r "gs://${BUCKET}" # Service account + HMAC key. gcloud storage hmac list --service-account="$SA_EMAIL" gcloud storage hmac delete gcloud iam service-accounts delete "$SA_EMAIL" # Postgres (take a snapshot first if you want a backup). gcloud sql instances delete "$SQL_INSTANCE" # GKE cluster. gcloud container clusters delete "$CLUSTER_NAME" --region "$REGION" ``` For production teardowns, snapshot Cloud SQL and back up the GCS bucket first; once they're deleted, they're gone. --- ## Troubleshooting | Symptom | Likely cause | Fix | |---|---|---| | GKE cluster takes 10-15 min to provision | Normal for Autopilot regional clusters | Wait | | Lakehouse pod stuck `Pending` on PVC | No default StorageClass, or the name doesn't exist | `kubectl get storageclass`; set `lakehouse.storage.storage_class_name` to one that exists (`premium-rwo` on Autopilot) | | `definite doctor` Postgres check fails with "connect timeout" from a laptop | Cloud SQL is on a private IP; the laptop is outside the VPC | Expected for private Cloud SQL from a laptop. The in-cluster API pods reach Cloud SQL over the VPC's private network. To fully validate before install, run `definite doctor` from a pod in the cluster. Use `--skip-preflight` only for this known private-network check, not for object-store, Kubernetes, license, or LLM failures | | `definite doctor` Postgres check fails from in-cluster | Cloud SQL has no private IP, or the cluster can't reach it | Confirm Cloud SQL is on the same VPC as the cluster with a private IP | | LB IP never appears | Ingress controller isn't running, or the GKE ingress controller is fighting with `ingress-nginx` | `kubectl get pods -n ingress-nginx`; if you have both controllers, pick one | | Brokered URL never becomes ready | The setup broker has not pointed `*.onprem.definite.app` at the load balancer yet, or the ingress target is wrong | Re-run `definite init --config config.yaml --dns-mode definite-brokered`, confirm the ingress Service target, and retry before debugging the app | | Customer-owned hostname does not work | Customer-owned DNS was selected, but the A record does not point at the load balancer or the custom cert/private CA path is incomplete | Fix the customer DNS/cert path or switch back to the default Definite-brokered DNS mode for first install | | cert-manager webhook never ready (Autopilot) | Lease pinned to `kube-system`, which is Google-managed | `definite bootstrap` pins the lease to `cert-manager`; if you installed cert-manager by hand, set `--set global.leaderElection.namespace=cert-manager` | | Fi can't reach Vertex | Node SA missing `roles/aiplatform.user`, or model not enabled in your region | Confirm the binding (step 5 above) and enable the model in Vertex Model Garden | | Lakehouse can't read/write GCS | HMAC key was created against a service account without object-admin on the bucket | Re-grant `roles/storage.objectAdmin` to the SA, or regenerate the HMAC pair | | You can log in, but every product page or API call returns HTTP 403 | Brokered license injection failed, or customer-owned/manual mode has an invalid static license | In the default brokered flow, capture `definite init` output and API logs, confirm cloud attestation still works, then retry once before escalating to Definite. Only customer-owned/manual mode should add or rotate a static `license` block | --- ## Next steps - [Connect a data source](/integrations) to start ingesting data. - [Set up the MCP server](/mcp) so Claude, Cursor, or Windsurf can query your deployment. - For deeper config (custom container registry, sandbox network policies, OIDC tuning), see the config reference in Definite's built-in docs. ## Support For issues or questions, contact [hello@definite.app](mailto:hello@definite.app). --- # Install on Azure > Stand up Definite in your own Azure account: AKS, Azure Database for PostgreSQL, and Azure Blob Storage, driven by `az` and the `definite` CLI. This guide walks through a standard install: an AKS cluster, a Postgres Flexible Server, Azure Blob Storage, local authentication, Definite-brokered DNS and TLS, and Azure OpenAI. Use `definite` v0.1.89 or newer for Azure installs. **AKS Standard is the validated compute path for this guide.** Definite installs via Helm and runs a Kubernetes operator for AI sandboxing, both of which need direct Kubernetes API access. The commands below create an AKS Standard cluster. AKS Automatic still exposes Kubernetes and Helm, but its managed node, networking, and scaling defaults are not covered by this guide. Use Standard unless you have validated Automatic with Definite for your environment. Azure Container Apps and Azure Container Instances do not expose the required access and are not supported. Like AWS and GCP, the install uses **Definite-brokered DNS and TLS** by default: Definite provides a URL like `https://.onprem.definite.app` during setup, so you do not need to configure customer DNS before the first install. The **setup token** is also handled the same way as the other clouds. `definite init` proves control of your Azure tenant to the Definite broker with an Entra-issued access token (from your `az login` session, or the AKS workload's managed identity when you run it in-cluster) and the broker hands back a short-lived setup token automatically. No manual token step is required. If you'd rather not rely on automatic attestation, Definite can still issue a `DEFINITE_ONPREM_SETUP_TOKEN` by hand. See [Definite setup token](#prerequisites) below. ## DNS and TLS options You have two ways to expose Definite and terminate TLS. Pick one before you run `definite init`. | | Definite-managed DNS (recommended) | Customer-owned DNS | |---|---|---| | Hostname | `https://.onprem.definite.app`, issued by Definite | Your own hostname, such as `definite.yourco.com` | | TLS | Handled by the Definite broker, no cert-manager needed | You bring a certificate, a private CA, or cert-manager plus Let's Encrypt | | DNS records | None to create; the broker points the hostname at your load balancer | You create an A record to the load balancer IP | | Setup flag | `--dns-mode definite-brokered` (default) | `--dns-mode customer-owned --hostname ` | | Best for | The fastest path to a working, publicly reachable install | Private or internal hostnames, or strict domain requirements | **Definite-managed DNS is the default and the recommended starting point on Azure.** Definite provides the `*.onprem.definite.app` hostname and TLS during setup, so you do not need to configure Azure DNS, request a certificate, or run cert-manager before the first install. You can move to a customer-owned hostname later, once the system is healthy. Choose customer-owned DNS only if you need a private or internal hostname or your organization requires its own domain. The mechanics are covered in [step 4](#4-let-definite-init-request-definite-brokered-dns). Definite-managed DNS needs the cluster's load balancer to be reachable from the Definite broker so it can validate and route the brokered hostname. For a fully private or air-gapped cluster, use customer-owned DNS with an internal record and your own certificate instead. ## What you'll create | Resource | Notes | |---|---| | Resource group | Holds the AKS resource, database, storage account, and customer-managed networking | | AKS node resource group | Created and managed by AKS for node VMs, load balancers, disks, and related infrastructure; defaults to `MC___` | | AKS cluster | Kubernetes 1.28+ | | Azure Database for PostgreSQL (Flexible Server) | Postgres 15+; this demo walkthrough uses public access with a narrow firewall rule | | Azure Storage Account + Blob container | Lakehouse data | | (Optional) Google Workspace OAuth client | For OIDC SSO. Google Workspace is the supported provider today; Entra ID support is on the roadmap. | For production, use private networking and high availability according to your organization's Azure standards. Those configurations require additional VNet, subnet, private DNS, and endpoint work and are outside the scope of this guide. ### Plan governed or private AKS before provisioning The `az aks create` example below is intentionally a simple first-install path. In a governed subscription or a hub-and-spoke network, settle these choices before creating the cluster: - **Node resource group policy:** AKS creates and owns a second resource group for node infrastructure. Required-tag or deny policies can block cluster creation, scaling, or upgrades. Allow AKS to manage this group and its Azure-created tags. You can choose its name at cluster creation with `--node-resource-group`, but the name cannot be changed later and the target group must not already exist. See Microsoft's [AKS node resource group guidance](https://learn.microsoft.com/en-us/azure/aks/faq#why-are-two-resource-groups-created-with-aks). - **Address space and routing:** Without explicit networking flags, Azure chooses the cluster network. That address space may overlap a corporate VNet, on-prem network, ExpressRoute route, or Virtual WAN route. For an enterprise deployment, create the VNet and node subnet first, then pass `--vnet-subnet-id` and non-overlapping service/DNS CIDRs. Do not wait until after cluster creation; AKS cannot be moved to another VNet. - **Private control plane and DNS:** A private AKS cluster needs private DNS plus a route from the machine running `az`, `kubectl`, and `definite`. If you use centralized DNS, link or forward the AKS private zone before installation. Microsoft's [private AKS guide](https://learn.microsoft.com/en-us/azure/aks/private-clusters) covers the supported DNS shapes. - **Ingress and egress:** Definite needs outbound access to pull images from `ghcr.io/definite-app`, reach the chosen LLM provider, and connect to both internal and internet-hosted data sources. Definite-brokered DNS also needs a publicly reachable load balancer. For an internal-only deployment, use customer-owned DNS and TLS. If you later publish MCP through an Application Gateway or WAF, account for `/mcp`, its `/.well-known/` OAuth metadata, and `/api/v1/mcp-oauth/*`; exposing only `/mcp` is not enough for OAuth-based clients. You can provision AKS through the Azure portal, Terraform, Bicep, or your platform team's standard module instead of the command below. Phase 2 only requires a conformant AKS cluster, a working kubeconfig, Helm access, and enough capacity for Definite's resource requests. --- ## Prerequisites A subscription where you have permission to create AKS, Postgres Flexible Server, and Storage Accounts. The `az` CLI must be authenticated (`az login`) and the subscription set (`az account set --subscription `). Install the following on the machine you'll run `az` and `definite` from: | Tool | Version | Check | |---|---|---| | `az` | recent | `az version` | | `kubectl` | 1.28+ | `kubectl version --client` | | `kubelogin` | recent | `kubelogin --version` (Entra-integrated AKS only) | | `helm` | 3.12+ | `helm version` | | `jq` | recent | `jq --version` | Run `az`, `kubectl`, `helm`, and `definite` from the same shell and user profile. On WSL, do not mix a Windows Azure CLI kubeconfig with Linux `kubectl` unless you explicitly set the kubeconfig path as shown below. Decide which LLM provider Fi will use. **Azure OpenAI** is the most common choice for Azure deployments because it lives in the same subscription. Anthropic, Bedrock, and Vertex are also supported. If you go with Azure OpenAI, make sure you've requested model access and created a deployment (the URL is your `llm.endpoint`). `definite init` proves control of your cloud account to the Definite broker and the broker returns a short-lived setup token automatically. On Azure this attestation is an Entra-issued access token: the CLI mints one from your `az login` session (`az account get-access-token`), or from the AKS workload's managed identity via Azure IMDS when run in-cluster, and the broker verifies its signature, audience, expiry, and tenant before issuing the token. The signed-in principal just needs to belong to the Azure tenant; no extra Azure role or app registration is required. With that in place, `definite init --dns-mode definite-brokered` exchanges the token for your `*.onprem.definite.app` hostname and license and injects both into the install, so the deploy stays fully automated. If you prefer not to use automatic attestation, email [hello@definite.app](mailto:hello@definite.app) for a manual `DEFINITE_ONPREM_SETUP_TOKEN` and reference it from `config.yaml` instead (see [Set or skip the setup token](#3-set-or-skip-the-setup-token)). If your organization holds its own license instead of using the brokered flow, Definite issues you a key directly. It looks like `onprem_` followed by a long hex string, and you reference it from `config.yaml` as `license.key`. Until the license is activated the deployment comes up unlicensed and returns HTTP 403 on every product API route. --- ## Phase 1: Provision Azure infrastructure Set up shared env vars first: ```bash export RG="" export LOCATION="" # e.g. eastus export CLUSTER_NAME="" # e.g. definite export PG_NAME="" # lowercase, e.g. acme-pg export PG_USER="definite" export STORAGE_ACCOUNT="" # lowercase, 3-24 chars export BLOB_CONTAINER="definite" ``` ### 1. Create the resource group ```bash az group create --name "$RG" --location "$LOCATION" ``` ### 2. Create the AKS Standard cluster Check both the regional and VM-family vCPU quotas before creating the pool. The standard profile below needs 20 DSv2-family vCPUs. Azure enforces the family quota even when your total regional quota is higher. ```bash az vm list-usage --location "$LOCATION" \ --query "[?name.value=='cores' || name.value=='standardDSv2Family' || name.value=='standardDSv3Family'].{Quota:name.localizedValue,Used:currentValue,Limit:limit}" \ --output table ``` If either the regional quota or the selected VM-family quota is too low, request an increase before provisioning or use the pilot profile below. ```bash az aks create \ --resource-group "$RG" \ --name "$CLUSTER_NAME" \ --node-count 5 \ --node-vm-size Standard_DS3_v2 \ --enable-managed-identity \ --generate-ssh-keys az aks get-credentials --resource-group "$RG" --name "$CLUSTER_NAME" kubectl config current-context kubectl get nodes ``` Do not continue until the current context is the intended AKS cluster and all expected nodes are `Ready`. If `kubectl` tries `http://localhost:8080`, there is no usable current context; `definite bootstrap` would target the same invalid endpoint. For an Entra-integrated cluster, convert the kubeconfig to Azure CLI authentication before testing it: ```bash kubelogin convert-kubeconfig -l azurecli kubectl get nodes ``` If Azure CLI and `kubectl` disagree about the kubeconfig location, which is common when using WSL, install the Linux Azure CLI inside WSL and force both tools to the Linux path: ```bash mkdir -p "$HOME/.kube" export KUBECONFIG="$HOME/.kube/config" az aks get-credentials \ --resource-group "$RG" \ --name "$CLUSTER_NAME" \ --file "$KUBECONFIG" \ --overwrite-existing kubelogin convert-kubeconfig -l azurecli # Entra-integrated clusters only kubectl config current-context kubectl get nodes ``` **Size the pool for the chart's requests.** The default `resources.api` alone (2 replicas x 1 CPU guaranteed) plus frontend, job-runner, and the Fi warm pool do not fit on the old demo default of 3 x `Standard_DS2_v2` (2 vCPU each), and `definite-api` pods sit `Pending` on `Insufficient cpu`. Use at least **5 nodes** and a `Standard_DS3_v2` (4 vCPU) SKU as above, or lower the `resources.*` requests in `config.yaml` for a smaller demo. Check headroom with `kubectl describe node | grep -A5 Allocated` and `kubectl get pods -n definite` after install. **Pilot profile:** 5 x `Standard_D2s_v3` nodes (10 DSv3-family vCPUs) together with the reduced `resources` block in [Build `config.yaml`](#5-build-configyaml). This profile is for a demo or pilot only. It reduces replica count and resource requests and is not a production sizing recommendation. ```bash # Demo or pilot only. Use with the reduced resources block below. az aks create \ --resource-group "$RG" \ --name "$CLUSTER_NAME" \ --node-count 5 \ --node-vm-size Standard_D2s_v3 \ --enable-managed-identity \ --generate-ssh-keys ``` ### 3. Create Azure Database for PostgreSQL (Flexible Server) ```bash az postgres flexible-server create \ --resource-group "$RG" \ --name "$PG_NAME" \ --location "$LOCATION" \ --version 15 \ --admin-user "$PG_USER" \ --admin-password "" \ --tier GeneralPurpose \ --sku-name Standard_D2ds_v4 \ --yes az postgres flexible-server db create \ --resource-group "$RG" \ --server-name "$PG_NAME" \ --name definite # Definite's schema migrations depend on pgcrypto, which Flexible Server blocks # until you allow-list it. Enable it before the first install or migrations fail. az postgres flexible-server parameter set \ --resource-group "$RG" \ --server-name "$PG_NAME" \ --name azure.extensions \ --value pgcrypto ``` On recent `az` (2.80+) the database name flag is `--name`/`-n`; older versions used `--database-name`. If you see `unrecognized arguments: --database-name`, upgrade `az` or swap the flag. The migration itself runs `CREATE EXTENSION pgcrypto`; the parameter above only permits it. No server restart is required. If you created the Flexible Server with **public access** (the demo default above), `flexible-server create` auto-allows only the outbound IP of the machine running the CLI. The AKS cluster reaches Postgres from a different IP, so add a firewall rule for the cluster's outbound IP, or `definite-api` and `definite-job-runner` will `CrashLoopBackOff` on Postgres connection timeouts: ```bash # Read the effective outbound public IP resource from the AKS load balancer # profile. Do not search public IPs by name because Azure may use a UUID. AKS_OUTBOUND_IP_ID=$(az aks show \ --resource-group "$RG" \ --name "$CLUSTER_NAME" \ --query 'networkProfile.loadBalancerProfile.effectiveOutboundIPs[0].id' \ --output tsv) AKS_OUTBOUND_IP=$(az network public-ip show \ --ids "$AKS_OUTBOUND_IP_ID" \ --query ipAddress \ --output tsv) az postgres flexible-server firewall-rule create \ --resource-group "$RG" \ --server-name "$PG_NAME" \ --name allow-aks-outbound \ --start-ip-address "$AKS_OUTBOUND_IP" \ --end-ip-address "$AKS_OUTBOUND_IP" ``` The firewall flags above match Azure CLI 2.87: `--server-name` identifies the Flexible Server, and `--name` identifies the firewall rule. This bites hardest when the demo command leaves Postgres on **public access** and Postgres and AKS end up in different regions (see [region restrictions](#postgres-creation-is-rejected-in-a-region)): the public-endpoint firewall rule is still mandatory. Private access across regions is also possible, but you must provide VNet peering or Virtual WAN routing, private DNS resolution, and an allowed path from AKS to the delegated Postgres subnet. For production, prefer private access so traffic never traverses the public internet. ### 4. Create a Storage Account + Blob container ```bash az storage account create \ --resource-group "$RG" \ --name "$STORAGE_ACCOUNT" \ --location "$LOCATION" \ --sku Standard_LRS \ --kind StorageV2 \ --allow-blob-public-access false # Grab a storage account key (the lakehouse uses a single shared key, not an # HMAC pair like S3/GCS). STORAGE_KEY=$(az storage account keys list \ --resource-group "$RG" \ --account-name "$STORAGE_ACCOUNT" \ --query '[0].value' --output tsv) az storage container create \ --account-name "$STORAGE_ACCOUNT" \ --name "$BLOB_CONTAINER" \ --account-key "$STORAGE_KEY" ``` ### 5. (If using Azure OpenAI) Create the resource and a model deployment If Fi will use Azure OpenAI (the common Azure choice), provision the account and a model **deployment**. The config only references these; you have to create them here. Create the account as an **Azure AI Foundry** resource with `--kind AIServices`. That is where Microsoft launches new models and what most Azure shops standardize on. The classic `--kind OpenAI` account also works with the exact same commands below. On an `AIServices` account, `--allow-project-management` defaults to `true`, so no extra flag is needed, and the model endpoint is `https://.openai.azure.com/` for both kinds. This path is verified end to end: Definite resolves and runs gpt-5.6 models deployed on a Foundry resource with either the GlobalStandard or DataZoneStandard SKU. Use **`gpt-5.6-luna`** as the default Fi model: it is cost-effective and fast, and works well with Fi's guardrails. Step up to **`gpt-5.6-terra`** when answers need more depth, and reserve **`gpt-5.6-sol`** for the hardest workloads. Both the `GlobalStandard` and `DataZoneStandard` SKUs work; `DataZoneStandard` keeps data processing in-geo. Definite authenticates to the model endpoint with an API key, so **key-based authentication must remain enabled** on the resource. Entra-only (key-disabled) auth configurations are not supported for this connection today. Availability of new model families is phased and specific to the subscription and region. Before deploying, verify that the exact model, version, and SKU quota appear in the account catalog. Do not assume another subscription's availability applies. ```bash export AOAI_NAME="" # e.g. acme-aoai # Create the account as an Azure AI Foundry (AIServices) resource. # --kind OpenAI works too, with the same commands. --allow-project-management # defaults to true on AIServices, so no extra flag is needed. az cognitiveservices account create \ --resource-group "$RG" \ --name "$AOAI_NAME" \ --location "$LOCATION" \ --kind AIServices \ --sku S0 \ --custom-domain "$AOAI_NAME" # List the phased 5.6 family so you can confirm the model, its version, and SKUs. az cognitiveservices account list-models \ --resource-group "$RG" \ --name "$AOAI_NAME" \ --query "[?format=='OpenAI' && starts_with(name, 'gpt-5.6')].{Model:name,Version:version,Lifecycle:lifecycleStatus,SKUs:join(',', skus[].name)}" \ --output table # Default Fi deployment. The deployment name must match the model name because # Fi uses it as the model id. Use GlobalStandard, or DataZoneStandard to keep # processing in-geo. export AOAI_MODEL="gpt-5.6-luna" export AOAI_SKU="GlobalStandard" export AOAI_CAPACITY="50" # Derive the available model version from the catalog instead of pinning one. AOAI_MODEL_VERSION=$(az cognitiveservices account list-models \ --resource-group "$RG" \ --name "$AOAI_NAME" \ --query "[?name=='$AOAI_MODEL'] | [0].version" \ --output tsv) if [[ -z "$AOAI_MODEL_VERSION" ]]; then echo "$AOAI_MODEL is not in the catalog for $AOAI_NAME; request access or pick another 5.6 model" exit 1 fi # Confirm the chosen model and SKU have nonzero quota before deploying. AOAI_QUOTA_LIMIT=$(az cognitiveservices usage list \ --location "$LOCATION" \ --query "[?name.value=='OpenAI.$AOAI_SKU.$AOAI_MODEL'] | [0].limit" \ --output tsv) if [[ -z "$AOAI_QUOTA_LIMIT" || "$AOAI_QUOTA_LIMIT" == "0" || "$AOAI_QUOTA_LIMIT" == "0.0" ]]; then echo "$AOAI_MODEL $AOAI_SKU quota is unavailable in $LOCATION" exit 1 fi az cognitiveservices account deployment create \ --resource-group "$RG" \ --name "$AOAI_NAME" \ --deployment-name "$AOAI_MODEL" \ --model-name "$AOAI_MODEL" \ --model-version "$AOAI_MODEL_VERSION" \ --model-format OpenAI \ --sku-name "$AOAI_SKU" \ --sku-capacity "$AOAI_CAPACITY" # properties.endpoint can return the cognitiveservices or services.ai host on AIServices accounts; Definite needs the openai.azure.com form, which --custom-domain guarantees exists. AOAI_ENDPOINT="https://${AOAI_NAME}.openai.azure.com" AOAI_KEY=$(az cognitiveservices account keys list \ --resource-group "$RG" --name "$AOAI_NAME" \ --query key1 --output tsv) echo "$AOAI_ENDPOINT" ``` `--sku-capacity` is in units of 1,000 tokens per minute. A single Fi run uses roughly 20k tokens, so a capacity of `10` will rate-limit immediately under real use; start at `50` or higher and tune down deliberately. These map to `config.yaml` as `llm.endpoint` (`$AOAI_ENDPOINT`), `llm.deployment` (`$AOAI_MODEL`), and the `AZURE_OPENAI_API_KEY` env var (`$AOAI_KEY`). Use only the `https://.openai.azure.com/` base endpoint in `config.yaml`. Do not paste a model invocation URL containing `/openai/deployments/...`, `/responses`, or an `api-version` query string. A Foundry resource also answers on `.cognitiveservices.azure.com` (which works) and `.services.ai.azure.com` (which does not), so prefer the `openai.azure.com` host. A catalog entry and quota are separate checks. A model can appear in `list-models` while the subscription has zero usable quota for its SKU. If `gpt-5.6-luna` is absent or its selected-SKU limit is zero, stop and request access or quota. To use `gpt-5.6-terra` or `gpt-5.6-sol` instead, change `AOAI_MODEL` and repeat the catalog and quota checks for that exact model. Verify the deployment with a real inference request before installing Definite. `definite doctor` reports the configured Azure OpenAI endpoint and deployment, but it does not call Azure OpenAI in the current release. ```bash AOAI_TEST_RESPONSE=$(curl --fail-with-body --silent --show-error \ --request POST \ --header "Content-Type: application/json" \ --header "api-key: $AOAI_KEY" \ --data '{"messages":[{"role":"user","content":"Reply exactly azure-openai-ok"}],"max_completion_tokens":64}' \ "${AOAI_ENDPOINT%/}/openai/deployments/${AOAI_MODEL}/chat/completions?api-version=2025-01-01-preview") echo "$AOAI_TEST_RESPONSE" | jq -e \ '.choices[0].message.content | type == "string" and length > 0' ``` The final command must return `true`. Do not continue if the request returns an authorization, quota, model, or deployment error. ### 6. Choose authentication Use local authentication for the Azure install and bootstrap the initial admin in `config.yaml`. Google Workspace SSO is also supported and is cloud-agnostic; configure it after the local-auth deployment is healthy by following [Google SSO](/on-prem/sso). Google Workspace is the only OIDC provider supported today; Entra ID and other generic OIDC providers are on the roadmap. If your organization is Entra-first, use local auth for now and switch to SSO when Entra support lands. Do not create an Entra app registration or configure an Entra issuer in the current release. --- ## Phase 2: Install Definite with the `definite` CLI ### 1. Install the CLI ```bash curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/install.sh | sh definite version ``` Run `definite version` before relying on Azure Cloud Shell as the install host. If it reports a missing `GLIBC_2.39` symbol, use Ubuntu 24.04, WSL2 with Ubuntu 24.04, the Windows CLI, or a management VM instead. That error is a local binary/runtime mismatch, not an AKS or firewall failure. ### 2. Confirm the target cluster and bootstrap prerequisites Recheck the context even if AKS was created earlier or through the portal: ```bash az account show --query '{subscription:name,subscriptionId:id,tenantId:tenantId}' --output table kubectl config current-context kubectl get nodes ``` Then bootstrap the cluster: ```bash definite bootstrap ``` By default this installs an ingress controller, cert-manager plus the `letsencrypt-prod` ClusterIssuer, and the agent-sandbox CRDs the Fi runtime needs. The default brokered DNS path does not use cert-manager because the broker handles DNS and TLS for the `*.onprem.definite.app` hostname; leaving it installed is harmless, or you can omit it with `definite bootstrap --skip-cert-manager`. `--acme-email` is optional and only sets the Let's Encrypt contact on the `letsencrypt-prod` ClusterIssuer. It is not the Definite initial admin, an Azure service principal, or an Entra identity. On the customer-owned DNS path, set it explicitly with `definite bootstrap --acme-email ops@yourcompany.com` if you use Let's Encrypt. ### 3. Set or skip the setup token On the default path you can **skip this step**. As long as you're signed in with `az login` (or running inside an AKS workload that has a managed identity), `definite init` mints an Entra access token and the broker hands back a setup token automatically, just like AWS and GCP. Confirm you're authenticated: ```bash az account show # should print your subscription and tenant ``` Only if you'd rather supply a Definite-issued token by hand (no automatic attestation), email [hello@definite.app](mailto:hello@definite.app) for a short-lived token and export it: ```bash # Optional manual override: skip on the automatic path above. export DEFINITE_ONPREM_SETUP_TOKEN="" ``` The manual token is short-lived, so request it close to when you'll run `definite init`. When set, `config.yaml` references it by env var name (see the `broker` block below) and the CLI uses it instead of attesting; the raw token never needs to live in the file. The CLI requests the Entra token for the Azure Resource Manager audience (`https://management.azure.com`) by default, which any `az login` session or AKS managed identity can mint without admin consent. To scope the token to a dedicated Definite Entra app instead, set `DEFINITE_ONPREM_AZURE_ATTESTATION_RESOURCE` to that app's Application ID URI (coordinate with Definite so the broker accepts it). ### 4. Let `definite init` request Definite-brokered DNS The ingress controller provisions an Azure Standard Load Balancer. Wait for it to land, then grab its external IP: ```bash LB_IP=$(kubectl get svc ingress-nginx-controller -n ingress-nginx \ -o jsonpath='{.status.loadBalancer.ingress[0].ip}' ) echo "$LB_IP" ``` **The Azure LB health probe must return a 200, or Azure silently drops all external traffic.** By default the Standard Load Balancer probes the data-plane port at `/` with no Host header; nginx answers with a non-200 (a 404 from the default backend, or a 308 HTTPS redirect), so Azure marks every node unhealthy and drops inbound SYNs with no RST. Pods stay `Ready` and in-cluster curls succeed, so this is easy to misread as an app or Azure-networking problem. **On `definite` v0.1.69+ this is handled for you:** `definite bootstrap` sets `controller.service.externalTrafficPolicy=Local` on AKS, which makes Kubernetes publish a dedicated `healthCheckNodePort` that Azure wires the probe to (and it returns real 200s). If you ran an older CLI, apply the probe path manually instead: ```bash kubectl annotate svc ingress-nginx-controller -n ingress-nginx \ service.beta.kubernetes.io/azure-load-balancer-health-probe-request-path=/healthz \ --overwrite ``` For the default path, don't stop here to create DNS. `definite init --dns-mode definite-brokered` calls the Definite setup broker for you, using the ingress target above, and returns a URL like `https://.onprem.definite.app`. It acquires the setup token automatically from your `az` credentials, or uses `DEFINITE_ONPREM_SETUP_TOKEN` if you set one. Customer-owned DNS is supported as an advanced option. If you explicitly need a private/internal hostname, create an A record from your hostname to `$LB_IP`, keep cert-manager from `definite bootstrap` (or supply a custom cert/private CA), and use the released CLI's customer-owned mode: `--dns-mode customer-owned --hostname `. Don't use `nip.io` as a default first-run path. ### 5. Build `config.yaml` Start from the AKS example config: [`minimal-aks.yaml`](https://storage.googleapis.com/definite-public/definite-onprem/examples/minimal-aks.yaml). The shape: ```yaml deployment: name: definite namespace: definite dns_mode: definite-brokered # broker handles DNS + TLS # On the default path you can omit the `broker` block entirely: the CLI attests # your Azure identity and acquires the setup token automatically. Add it only to # supply a Definite-issued token by hand (manual override): # broker: # setupToken: # env: DEFINITE_ONPREM_SETUP_TOKEN # In the brokered flow the broker injects the license during init, so no license # block is needed. For customer-owned/manual mode instead, set your own key: # license: # key: !env LICENSE_KEY # your Definite-issued onprem_... key postgres: url: postgres://:${POSTGRES_PASSWORD}@.postgres.database.azure.com:5432/definite object_store: type: azure account: container: definite credentials: env: AZURE_STORAGE_KEY lakehouse: prefix: lake/ storage: size: 50Gi storage_class_name: managed-csi-premium auth: mode: local initial_admin_email: initial_admin_password: env: INITIAL_ADMIN_PASSWORD llm: provider: azure_openai endpoint: https://.openai.azure.com deployment: gpt-5.6-luna # default Fi model and Azure deployment name api_key: env: AZURE_OPENAI_API_KEY resources: api: replicas: 2 cpu: "1" memory: 2Gi lakehouse: replicas: 1 cpu: "4" memory: 16Gi ``` Secret references and string interpolation look similar but behave differently: - `env: AZURE_STORAGE_KEY` contains the **environment variable name**, not the storage key. Keep the name in YAML and export the actual value in the same shell before `doctor` and `init`. - `${POSTGRES_PASSWORD}` is expanded when the CLI reads `config.yaml`. Replace `` and ``, but keep the password out of the file. - Apply the same rule to `INITIAL_ADMIN_PASSWORD` and `AZURE_OPENAI_API_KEY`. Do not replace their `env:` values with plaintext secrets. For the 5 x `Standard_D2s_v3` demo or pilot pool, replace the `resources` block above with this reduced profile: ```yaml resources: api: replicas: 1 cpu: 500m memory: 1Gi lakehouse: replicas: 1 cpu: "1" memory: 4Gi frontend: replicas: 1 cpu: 250m memory: 512Mi job_runner: replicas: 1 cpu: 250m memory: 512Mi ``` This profile has no application-level redundancy and is not suitable for production. Azure uses a single shared storage key (not an HMAC pair). Pull it from the Storage Account's "Access keys" blade, or via `az storage account keys list` as shown above. Name your Azure OpenAI **deployment** exactly after the selected supported OpenAI model id, and use that same name in `llm.deployment`. Fi uses the deployment name as the model id when it calls Azure OpenAI, so a custom deployment name such as `prod-model` fails as an unknown model. Fi does not run on Claude models through Azure OpenAI. To use Claude, choose the `anthropic`, `bedrock`, or `vertex` provider instead. For the full list of knobs, see the config reference in Definite's built-in docs. ### 6. Export secrets ```bash export POSTGRES_PASSWORD="" export AZURE_STORAGE_KEY="" export AZURE_OPENAI_API_KEY="" export INITIAL_ADMIN_PASSWORD="$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 24)" # export DEFINITE_ONPREM_SETUP_TOKEN="" # only for the manual token override # export LICENSE_KEY="onprem_..." # only for customer-owned/manual mode ``` In the default brokered flow you do not export `DEFINITE_ONPREM_SETUP_TOKEN` or `LICENSE_KEY`: the CLI attests your Azure identity for the setup token, and the broker injects the license during `init`. Set `DEFINITE_ONPREM_SETUP_TOKEN` only if you're using the manual token override, and `LICENSE_KEY` only if you chose customer-owned/manual mode. ### 7. Preflight and deploy ```bash definite doctor --config config.yaml definite init --config config.yaml --dns-mode definite-brokered ``` If your Postgres Flexible Server is on private access, `definite doctor` and the `definite init` preflight cannot reach it from a laptop without a route into the VNet. Run `doctor` from inside the network. If Postgres reachability is the only failed check, you may pass `--skip-preflight` to the laptop-run `definite init`; do not use it to mask any other failure. `definite doctor` performs a real Azure Blob PUT and DELETE of a small `.preflight` object. That proves the configured key can write to the container, but it does not exercise DuckDB's Azure extension or prove that a lakehouse query creates Parquet data. Complete the physical Blob verification in [Verify the deployment](#verify-the-deployment) after install. `init` renders the bundled Helm chart and runs `helm upgrade --install`. Watch the rollout: ```bash definite status --config config.yaml definite logs api --follow ``` ### 8. Confirm the initial admin The `auth.initial_admin_email` and `auth.initial_admin_password.env` fields in `config.yaml` create the initial admin during the first API startup. Save `INITIAL_ADMIN_PASSWORD` in a password manager before closing the install shell. Do not patch the API Deployment with `kubectl set env`; a later Helm upgrade can discard manual Deployment changes. When the brokered URL reports DNS/TLS ready, open `https://.onprem.definite.app` in a browser and log in with the admin email and password from `config.yaml`. On the customer-owned path, open your own hostname once its certificate is ready. --- ## Known limitations on Azure A few Azure-specific things to know before you start: - **`definite run load` (file upload via the CLI)** is documented as **not supported on Azure** in v1; S3, GCS, and MinIO backends are. Browser-based Drive uploads still work via the configured Storage Account. - **`definite doctor`** PUTs and deletes a small `.preflight` object in Azure Blob Storage. It does not exercise the DuckDB Azure extension, create a DuckLake table, or verify a Parquet object. Run the lakehouse smoke test below after deployment. - **Azure OpenAI preflight** is warn-and-skip in the current CLI. Run the direct inference request in Phase 1 and a real Fi prompt after deployment. - **Workload Identity / Entra-bound credentials** for the lakehouse are not yet wired in; the storage account key is the supported path today. --- ## Verify the deployment Do not declare the install healthy based only on ready pods or `SELECT 1`. Complete every check below, including the physical Blob Storage check. 1. Confirm all pods are ready, HTTPS works, and the initial admin can sign in: ```bash definite status --config config.yaml curl --fail --silent --show-error --output /dev/null \ "https:///login" ``` 2. Record the number of objects under the lakehouse prefix before the write: ```bash BLOB_COUNT_BEFORE=$(az storage blob list \ --account-name "$STORAGE_ACCOUNT" \ --container-name "$BLOB_CONTAINER" \ --account-key "$AZURE_STORAGE_KEY" \ --prefix lake/ \ --num-results '*' \ --query 'length(@)' \ --output tsv) echo "Blob objects before: $BLOB_COUNT_BEFORE" ``` 3. In Definite's query editor, create and read back a persistent table with more than 1,000 rows. This row count is intentional because it forces the test past the small-result inlining threshold: ```sql DROP TABLE IF EXISTS azure_lakehouse_smoke; CREATE TABLE azure_lakehouse_smoke AS SELECT row_id, 'azure-blob-smoke' AS marker FROM range(1500) AS rows(row_id); SELECT COUNT(*) AS row_count, MIN(row_id) AS first_row, MAX(row_id) AS last_row, COUNT(DISTINCT marker) AS marker_count FROM azure_lakehouse_smoke; ``` The result must be `1500`, `0`, `1499`, and `1`. 4. Prove that the write created a nonempty Parquet object in Azure Blob Storage. SQL success alone is not sufficient: ```bash BLOB_COUNT_AFTER=$(az storage blob list \ --account-name "$STORAGE_ACCOUNT" \ --container-name "$BLOB_CONTAINER" \ --account-key "$AZURE_STORAGE_KEY" \ --prefix lake/ \ --num-results '*' \ --query 'length(@)' \ --output tsv) az storage blob list \ --account-name "$STORAGE_ACCOUNT" \ --container-name "$BLOB_CONTAINER" \ --account-key "$AZURE_STORAGE_KEY" \ --prefix lake/main/azure_lakehouse_smoke/ \ --num-results '*' \ --query "[?ends_with(name, '.parquet')].{Name:name,Bytes:properties.contentLength}" \ --output table test "$BLOB_COUNT_AFTER" -gt "$BLOB_COUNT_BEFORE" ``` The table output must include at least one `.parquet` object with `Bytes` greater than zero, and the final comparison must exit successfully. 5. Clean up the logical smoke-test table: ```sql DROP TABLE azure_lakehouse_smoke; ``` DuckLake can retain the physical Parquet object for snapshot history after the logical table is dropped. That retention is expected and preserves evidence that the data reached Blob Storage. 6. Run the remaining application smoke checks: confirm `/auth/me` returns the signed-in admin, run `SELECT 1 AS ok`, open the data apps page, and start a new Fi thread that produces a successful response through Azure OpenAI. If any check fails, capture `definite status --config config.yaml` and `definite logs api --tail 200` before changing the deployment. --- ## Troubleshooting Real issues we and early Azure installers have hit, with the fix for each. ### `definite bootstrap` connects to `localhost:8080` **Symptom:** `definite bootstrap` or `kubectl get nodes` fails with `connect: connection refused` against `127.0.0.1:8080` or `localhost:8080`. **Cause:** `kubectl` has no current AKS context, or `az aks get-credentials` wrote the kubeconfig for a different OS/user profile. This is common when Windows Azure CLI is invoked from WSL while Linux `kubectl` reads `$HOME/.kube/config`. **Fix:** repeat [Create the AKS Standard cluster](#2-create-the-aks-standard-cluster), force `az` and `kubectl` to the same `KUBECONFIG`, run `kubelogin convert-kubeconfig -l azurecli` for an Entra-integrated cluster, and verify `kubectl get nodes` before retrying bootstrap. ### Azure Cloud Shell reports `GLIBC_2.39 not found` **Symptom:** the install script succeeds in Azure Cloud Shell, but `definite version` fails immediately with a missing glibc symbol. **Cause:** that Cloud Shell image is older than the runtime used by the current Linux release binary. **Fix:** run the CLI from Ubuntu 24.04, WSL2 with Ubuntu 24.04, the Windows binary, or a management VM that can reach the AKS API. Keep `az`, `kubectl`, `helm`, and `definite` in that same environment. ### Lakehouse writes fail on `definite` releases before v0.1.88 **Symptom:** on a release before v0.1.88, ordinary SQL can work, but creating a persistent table either reports an invalid Azure storage URI or fails with `Problem with the SSL CA cert`. No nonempty Parquet object appears in the Blob container. **Cause:** those releases render the wrong Azure lakehouse URI shape and their runtime images do not expose the CA bundle at the path used by DuckDB's Azure client. Both were fixed in v0.1.88. **Fix:** upgrade to `definite` v0.1.89 or newer, then complete [Verify the deployment](#verify-the-deployment). Do not patch a customer cluster by hand or treat `SELECT 1` as a successful storage test. ### Postgres migrations fail on a blocked `pgcrypto` extension Azure Database for PostgreSQL Flexible Server blocks most extensions by default, and Definite's schema migrations depend on `pgcrypto`. Allow-list it before the first install (this is folded into [Phase 1, step 3](#3-create-azure-database-for-postgresql-flexible-server)): ```bash az postgres flexible-server parameter set \ --resource-group "$RG" \ --server-name "$PG_NAME" \ --name azure.extensions \ --value pgcrypto ``` The migration runs `CREATE EXTENSION pgcrypto` itself; the parameter only permits it. No server restart is required. ### External traffic drops and Azure marks every backend unhealthy **Symptom:** the external IP stops serving traffic and connections to ports 80/443 time out with no RST, even though `kubectl get pods` / `definite status` are all green and a `kubectl exec` curl to the IP *from inside the cluster* succeeds. (The in-cluster success is a kube-proxy shortcut that never exercises the real LB path.) This is the single most confusing AKS failure: it looks like an app bug or an Azure subscription/NSG block, but it is a Kubernetes-level probe misconfiguration. **Cause:** the Azure Standard Load Balancer health-probes the ingress data-plane port at `/` by default. nginx returns a non-200 for that probe (a 404 from the default backend, or a 308 HTTPS redirect), so Azure marks every node unhealthy and silently drops all inbound traffic. **Fix:** upgrade to `definite` v0.1.69+ and re-run `definite bootstrap`, which sets `controller.service.externalTrafficPolicy=Local` (a dedicated `healthCheckNodePort` Azure probes with real 200s). On older CLIs, point the probe at nginx's health endpoint by annotating the controller Service (also covered in [Phase 2, step 4](#4-let-definite-init-request-definite-brokered-dns)): ```bash # Either set externalTrafficPolicy=Local (preferred): kubectl patch svc ingress-nginx-controller -n ingress-nginx \ -p '{"spec":{"externalTrafficPolicy":"Local"}}' # ...or annotate the probe path: kubectl annotate svc ingress-nginx-controller -n ingress-nginx \ service.beta.kubernetes.io/azure-load-balancer-health-probe-request-path=/healthz \ --overwrite ``` ### Postgres creation is rejected in a region **Symptom:** `az postgres flexible-server create` fails with `The location is restricted from performing this operation ... open a support request` (commonly seen in `eastus`). **Cause:** Flexible Server capacity is restricted per subscription/region and can be unavailable even when other services in that region work. **Fix:** open an Azure support request for the subscription/region restriction, or create Postgres in a different region (for example `eastus2`) and continue. `az postgres flexible-server list-skus --location -o table` is a useful first check, but a populated SKU list or unused vCore quota does not prove that the subscription may provision there. The create request is authoritative. If Postgres lands in a different region than AKS, choose one connectivity path explicitly: add the public-access firewall rule from [Phase 1, step 3](#3-create-azure-database-for-postgresql-flexible-server), or keep Postgres private and configure cross-region VNet peering or Virtual WAN, private DNS, and routes. Validate the exact path from AKS before installing. For a production move back to the preferred region, restore or dump the Postgres database into a new Flexible Server and update the Definite config during the cutover. ### Retrying Postgres create fails with "server name is already used" **Symptom:** after a transient `InternalServerError` on `flexible-server create`, retrying with the same name fails with `Specified server name is already used`, but `az postgres flexible-server list` doesn't show the server. **Cause:** the failed attempt left the resource in a `Dropping` state that isn't immediately visible, and the name stays reserved until the drop completes. **Fix:** retry under a new server name (fastest), or wait a few minutes for the drop to finish and reuse the name. ### `definite doctor` fails the Postgres check against a TLS-required server **Symptom:** `doctor` reports a Postgres connect/`TLS handshake` failure even though the database is reachable and correct (a manual `psql "host=... sslmode=require"` connects fine). **Cause:** Azure Postgres Flexible Server enforces SSL by default, and the v0 `doctor` Postgres check connects without TLS, producing a false negative. **Fix:** upgrade to the latest `definite` CLI, whose Postgres preflight now negotiates TLS and honors `sslmode=require`. On an older CLI, verify reachability manually with `psql "host=.postgres.database.azure.com user=definite dbname=definite sslmode=require"`; if that succeeds the DB is fine, so pass `--skip-preflight` to `definite init` for this laptop run only (don't use it to mask other failures). ### cert-manager keeps a 2-hour backoff after a failed certificate (customer-owned DNS) **Symptom:** on the customer-owned DNS path, after a `Certificate` fails twice you see a ~2-hour backoff, and deleting the failed `CertificateRequest`/`Secret` doesn't trigger a fresh attempt. **Cause:** cert-manager tracks the backoff on the parent `Certificate` object, so recreating child resources doesn't reset the timer. **Fix:** delete the `Certificate` itself and let ingress-shim recreate it, which forces an immediate clean retry: ```bash kubectl delete certificate -n definite # ingress-shim recreates it from the Ingress annotation within seconds ``` ### Every Fi run fails with "model is not known to Pi" on Azure OpenAI **Symptom:** Fi runs fail immediately with `configured LLM model is not known to Pi`, even though `config.yaml` correctly sets `llm.provider: azure_openai` and `llm.deployment` to the selected Azure OpenAI model. **Cause:** Fi's runtime model selection is driven by the `fi_model_config` row in the app database, not the chart env vars. On older builds that row was always seeded with the platform default (`default_provider = anthropic`, `default_model = claude-sonnet-5`) regardless of `config.yaml`, so on a fresh Azure OpenAI install the stale Anthropic model got grafted onto the Azure provider, producing the impossible `azure-openai-responses/claude-sonnet-5` pair. **Fix:** upgrade to the latest chart. On install it now reconciles the untouched `fi_model_config` row to your configured `llm.provider` / `llm.deployment`, so Azure OpenAI works out of the box and Settings → Models shows the right model (an admin's later Settings change is still preserved). If you're on an older build, correct the row directly (the provider value must match the app's internal enum exactly, `azureOpenai` in camelCase, not `azure_openai`): ```sql UPDATE fi_model_config SET default_provider = 'azureOpenai', default_model = '' WHERE id = 1; ``` There is no `definite` CLI command for this; on older builds it's reachable only via a direct DB write or the in-app Settings → Models page. ### Fi fails with "Azure OpenAI base URL is required" **Symptom:** Fi runs fail with `failed to publish Pi events: Azure OpenAI base URL is required`. **Cause:** the Fi sandbox pods got `AZURE_OPENAI_ENDPOINT`, but pi-ai's `azure-openai-responses` provider reads `AZURE_OPENAI_BASE_URL` (or `AZURE_OPENAI_RESOURCE_NAME`). **Fix:** upgrade to the latest chart, which sets `AZURE_OPENAI_BASE_URL` on every Fi `SandboxTemplate`. On an older build, patch the templates (and roll existing pods, see below) to add `AZURE_OPENAI_BASE_URL` alongside `AZURE_OPENAI_ENDPOINT`. ### SandboxTemplate env changes don't reach running Fi pods **Symptom:** you edited a Fi `SandboxTemplate` (for example to add an env var) but Fi still behaves as before. **Cause:** a live `SandboxTemplate` edit is not retroactive. Warm-pool pods created before the edit keep their old env, and once a pod is bound by a `SandboxClaim` it stays pinned to that thread for the retention window, so deleting pods alone can leave a stale claimed instance behind. **Fix:** delete both the sandbox pods **and** any active `SandboxClaim` objects, then verify each pool member's env before considering it clean: ```bash kubectl delete sandboxclaim -n definite --all # release pinned pods kubectl delete pod -n definite -l app.kubernetes.io/component=fi-sandbox # the warm pool replenishes from the current template; then spot-check: kubectl get pod -n definite -l app.kubernetes.io/component=fi-sandbox \ -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[0].env}{"\n"}{end}' ``` ### The initial admin account isn't created **Symptom:** you can reach the login page, but no admin account exists. **Cause:** the config field is `initial_admin_email` (not `admin_email`), and the password must be supplied as a secret reference rather than inline. **Fix:** follow [Confirm the initial admin](#8-confirm-the-initial-admin). Set `auth.initial_admin_email` and `auth.initial_admin_password.env` in `config.yaml` before the first install. --- ## Day-2 operations Same CLI as AWS and GCP: ```bash definite status --config config.yaml definite logs api --follow definite upgrade --config config.yaml definite license status definite run maintenance stats ``` Definite's built-in docs include a full CLI reference. --- ## Phase 3: Teardown ```bash # Trigger Kubernetes to delete the Azure Standard Load Balancer cleanly # before the resource group goes away. kubectl delete svc ingress-nginx-controller -n ingress-nginx --ignore-not-found az group delete --name "$RG" --yes ``` Deleting the resource group removes the AKS cluster, Postgres server, storage account, and everything else in one shot. Snapshot or export anything you care about first. Deleting the ingress Service first lets Kubernetes release the cloud LB cleanly; `az group delete` will pick up anything you miss, but the explicit order avoids a stuck LB you'd otherwise have to clean up by hand. --- ## Support This install path is actively being matured. For issues or questions, contact [hello@definite.app](mailto:hello@definite.app). If you're planning an Azure install, we'd love to be in the room: design-partner support is free. --- # Google SSO > Sign in to your on-prem Definite deployment with Google Workspace via OIDC. Definite on-prem supports **Sign in with Google** via OIDC. Anyone in your Google Workspace domain can log in by clicking a button, and one named user is auto-provisioned as the first admin. This guide is cloud-agnostic — once your deployment is up on AWS, GCP, or Azure, the SSO setup is the same. ## What's supported - OIDC Authorization Code flow with PKCE against Google. - ID token validation (signature via Google's JWKS, plus `iss` / `aud` / `exp` / `nonce` checks). - Domain restriction via Google's `hd` claim — non-matching accounts are refused. - First login auto-provisions a user. The `initialAdminEmail` value lets one specific email land as `admin` on first login, so a fresh deployment can bootstrap its first human admin via SSO. - Password login keeps working side-by-side. The built-in `fi@definite.app` support user is unaffected. ## What's not supported yet - Group → role mapping from Google Workspace groups. Everyone lands as `defaultRole` (or `initialAdminEmail` lands as `admin`). - Auto-linking an existing password user to their Google account on first login. See [Email collisions](#email-collisions) below. - Generic / non-Google OIDC providers (Okta, Entra, etc.). The helm schema reserves `auth.oidc.provider: generic` as an extension point but the API refuses to start with it today. - MFA / step-up auth — Google's own 2FA covers this. - RP-initiated logout. Signing out of Definite does not sign the user out of Google. --- ## Step 1 — Create a Google OAuth 2.0 Client ID In the [Google Cloud Console](https://console.cloud.google.com), in the same GCP project (or any project — they don't have to match the project hosting your deployment): **APIs & Services → OAuth consent screen.** Pick **Internal** if the deployment is restricted to your Workspace org (the common case). With **External** you have to add every login email as a test user until the consent screen is verified. Fill in: - **App name:** e.g. `Definite (internal)` - **User support email:** an address in your Workspace - **Developer contact:** another address in your Workspace Add the non-sensitive scopes: `openid`, `.../auth/userinfo.email`, `.../auth/userinfo.profile`. Definite does not need any other Google API. **APIs & Services → Credentials → Create credentials → OAuth client ID.** - **Application type:** Web application - **Name:** e.g. `Definite on-prem` - **Authorized redirect URIs:** add exactly the deployment's callback URL: ``` https:///api/v1/auth/oidc/callback ``` The hostname is whatever you set in your helm values under `deployment.hostname`. Google only honors **exact** matches — `redirect_uri_mismatch` is the most common setup mistake. If your deployment is reachable at multiple URLs, add a redirect URI for each. Google shows you a **Client ID** (`*.apps.googleusercontent.com`) and a **Client Secret** (`GOCSPX-...`). Copy both. The secret is only shown once; if you lose it, regenerate from this same screen. ## Step 2 — Wire helm values Add this block to the `config.yaml` you pass to `definite init` (or your `values.yaml` overlay): ```yaml auth: mode: oidc oidc: provider: google # From the Google Cloud Console. clientId: "1234567890-abcdefghijklmnop.apps.googleusercontent.com" clientSecret: "GOCSPX-..." # Restrict logins to your Workspace domain(s). Verified via Google's # `hd` ID-token claim — personal gmail.com accounts will be refused. # Strongly recommended in production. allowedDomains: - "yourcompany.com" # Role assigned to a brand-new OIDC user on first login. One of # viewer / editor / admin. Existing users keep whatever role they # already have — defaultRole only fires on auto-provision. defaultRole: "viewer" # The first OIDC login from this email gets the `admin` role # regardless of `defaultRole`. Lets a fresh deployment bootstrap its # first admin via SSO. Leave empty to disable. initialAdminEmail: "you@yourcompany.com" ``` When `auth.mode: oidc`, **both** `clientId` and `clientSecret` are required — the chart fails fast with a clear message if either is empty. Keep `clientSecret` out of version control; pass it via an env var substitution in `config.yaml` (e.g. `clientSecret: ${OIDC_CLIENT_SECRET}`) or a secret-management tool. ## Step 3 — Apply and verify ```bash definite upgrade --config config.yaml ``` Or, if you're driving helm directly: ```bash helm upgrade definite ./helm --reuse-values \ --set auth.mode=oidc \ --set auth.oidc.provider=google \ --set-string auth.oidc.clientId="" \ --set-string auth.oidc.clientSecret="" \ --set 'auth.oidc.allowedDomains[0]=yourcompany.com' \ --set auth.oidc.defaultRole=viewer \ --set auth.oidc.initialAdminEmail=you@yourcompany.com ``` Open `https:///login` in a browser. You should see a **Sign in with Google** button above the email/password form. Click it. Google's consent screen opens. Accept, and you're bounced back to Definite logged in. If `initialAdminEmail` matched the email you signed in with, you'll have the `admin` role and full Settings access immediately. --- ## How it works under the hood ``` Browser Definite API Google | | | | GET /oidc/login | | |------------------->| | | | build PKCE + state | | | set httpOnly cookie | | 302 to Google's | | | consent screen | | |<-------------------| | | | | GET accounts.google.com/o/oauth2/v2/auth | |---------------------------------------------->| | | | User picks account + consents | | | | 302 back to /oidc/callback?code=...&state=...| |<----------------------------------------------| | | | GET /oidc/callback | |------------------->| | | | exchange code for | | | id_token + access_token | | |------------------------->| | | | | |<-------------------------| | | validate id_token | | | (JWKS, iss, aud, nonce, | | | exp, hd, email_verified) | | | | | upsert user, mint | | | session token | | | | | 302 /auth/oidc-complete#token=... | |<-------------------| | ``` - **State + PKCE.** Both are generated server-side and stored in an HttpOnly, short-lived (10 min) cookie. The callback validates the round-trip against the cookie before doing anything else — a missing or tampered cookie is a 400. - **Token validation.** The ID token signature is verified against Google's JWKS, fetched via the discovery document. Claims checked: `iss`, `aud`, `exp`, `sub`, `nonce`, `email_verified`. If `allowedDomains` is non-empty, `hd` must match one of them. - **Session token delivery.** On success, the API 302s the browser to `/auth/oidc-complete#token=...` — the token lives in the URL **fragment**, not the query string, so it never reaches nginx access logs. A small client page reads it out, writes it to `localStorage`, and forwards on. ## Email collisions If someone signs in via Google with an email that already belongs to a **password-mode** user (`auth_provider = 'local'`), the OIDC login is refused with HTTP 409 and a clear message. Definite doesn't auto-link the two accounts — silently associating a Google identity with a pre-existing password row would be a quiet security regression. To resolve, an admin must either: 1. **Delete or deactivate the existing password user** (Settings → Members), then have the Google user retry the SSO login. They get a fresh row with `auth_provider = 'google'` and the role from `defaultRole` / `initialAdminEmail`. 2. **Flip the existing row to SSO** by running `UPDATE definite.users SET auth_provider='google' WHERE email='...';` against the app database. This preserves the user's history (queries, automations, audit-log attribution) but disables password login on that row. An admin-friendly path (`definite admin link-sso ` and a Settings UI action) is on the roadmap so you don't have to delete or run SQL by hand. ## Audit log Every OIDC login writes entries to the workspace audit log: - `user.oidc.login` — on every successful sign-in. - `user.oidc.provision` — additionally, on the very first login. The `elevated_to_admin` field in the detail records whether the `initialAdminEmail` rule fired. Filter the Audit log page by `user.oidc.*` to see SSO activity. ## Troubleshooting | Symptom | Likely cause | Fix | |---|---|---| | **Sign in with Google** button doesn't appear on the login page | `auth.mode` isn't `oidc`, or `clientId` / `clientSecret` is empty | Check the api pod's env (`kubectl -n definite exec deploy/definite-api -- env | grep -E 'AUTH_MODE\|OIDC_'`). Re-run `definite upgrade` with the missing values. | | `Google rejected the login. Check that the OAuth client_id / client_secret in your values.yaml are correct.` | Wrong `clientSecret` (or it was regenerated in the console after deploy) | Regenerate the client secret in Google Cloud Console and re-apply. | | `state mismatch (CSRF check failed)` | Cookie was blocked, or the user took >10 min on Google's consent screen | Retry. If it persists, check for an aggressive cookie blocker or strict third-party cookie policy. | | `this Google account's domain is not allowed` | Personal `@gmail.com` or wrong workspace | Add the domain to `auth.oidc.allowedDomains`, or sign in with a matching account. | | `a non-SSO user already exists with the email '...'` | A password-mode user owns that address | See [Email collisions](#email-collisions). | | `redirect_uri_mismatch` (shown on Google's own error page) | The OAuth client's redirect URI doesn't match `https:///api/v1/auth/oidc/callback` exactly | Edit the OAuth client in Google Cloud Console and add the exact URI (including scheme and any trailing slash quirks). | ## Disabling SSO Set `auth.mode: local` (or remove the `auth.oidc` block) and redeploy. Password login continues to work; the **Sign in with Google** button disappears. Existing OIDC-provisioned users are NOT auto-removed — they survive as password-less rows. An admin can delete them via Settings → Members if desired. --- ## Deploy & Operate # Prerequisites A copy-pasteable checklist for standing up Definite On-Prem on a fresh cluster. Work top to bottom. `definite bootstrap` installs the cluster-side prerequisites for you; `definite doctor` verifies the external ones. This page is the manual reference behind both. ## At a glance | # | Prerequisite | Minimum | Installed by | Verified by | |---|---|---|---|---| | 1 | `kubectl` | 1.28+ | you | — | | 2 | `helm` | 3.12+ | you | — | | 3 | Kubernetes cluster | 1.28+ | you / cloud | `definite doctor` | | 4 | Ingress controller | any current | `definite bootstrap` | `definite doctor` | | 5 | cert-manager (+ CRDs) | 1.13+ | `definite bootstrap` | `definite doctor` | | 6 | `letsencrypt-prod` ClusterIssuer | — | `definite bootstrap` | `definite doctor` | | 7 | agent-sandbox CRDs | bundled version | `definite bootstrap` | `definite doctor` | | 8 | StorageClass | one default, supports `ReadWriteOnce` | you / cloud | `definite doctor` | | 9 | Postgres | 15+ | you | `definite doctor` | | 10 | Object store | S3 / GCS / Azure Blob / MinIO | you | `definite doctor` | ## Local tooling (on the machine running `definite`) The CLI shells out to `kubectl` and `helm`; both must be on `PATH`. - [ ] **`kubectl` 1.28+** — within one minor version of the cluster's control plane. Check: `kubectl version --client`. - [ ] **`helm` 3.12+** — Helm 3 only; Helm 2 is not supported. Check: `helm version`. - [ ] **A kubeconfig context** pointed at the target cluster, with permission to create namespaces, CRDs, and cluster-scoped RBAC. Check: `kubectl config current-context` and `kubectl auth can-i create namespace`. ## Kubernetes cluster - [ ] **Kubernetes 1.28 or newer.** GKE, EKS, AKS, or a conformant vanilla cluster. GKE is the primary tested target; EKS and AKS examples ship in `examples/` and are actively maturing. - [ ] **Outbound network access** for image pulls (`ghcr.io/definite-app` by default) and for the LLM provider. Air-gapped install is not supported in v1 — see `network-requirements.md` for data-source connectivity and `architecture.md` for the component map. If you mirror images into a private registry, set the `image:` block in your `config.yaml`. - [ ] **Enough headroom** for the default resource requests in your chosen `examples/minimal-*.yaml`. The lakehouse runs as embedded DuckDB inside the API and job-runner pods (no separate query pod), so the API and job-runner are the components to size for query memory; bump `resources.api` / `resources.jobRunner` for heavy steady-state SQL, or add a [compute profile](/docs/compute-profiles) for heavy bursty SQL. ## Cluster prerequisites (`definite bootstrap` installs these) Run `definite bootstrap` once against a fresh cluster, or `definite bootstrap --dry-run` to see what is missing first. Each item below can also be installed by hand with `helm` / `kubectl`. - [ ] **Ingress controller.** Provides HTTP/S routing for the deployment's `Ingress`. Any current controller works (ingress-nginx, or a cloud controller such as the AWS Load Balancer Controller or GKE ingress). - [ ] **cert-manager 1.13+ and its CRDs.** Required when `deployment.tls` is `cert_manager` so the ingress certificate can be issued automatically. The CRDs must be installed before cert-manager itself. `definite bootstrap` installs cert-manager with its leader-election lease pinned to the `cert-manager` namespace (`--set global.leaderElection.namespace=cert-manager`) — the chart default of `kube-system` is Google-managed on GKE Autopilot and rejects writes, so without the override the webhook CA is never injected. - [ ] **`letsencrypt-prod` ClusterIssuer.** A healthy cert-manager still issues nothing without an `Issuer`. The Helm chart annotates the `Ingress` with `cert-manager.io/cluster-issuer: letsencrypt-prod`, so that issuer must exist. `definite bootstrap` creates it (production Let's Encrypt ACME, `http01` solver) after cert-manager is up; the ACME contact email defaults to `hello@definite.app` and can be set with `--acme-email`. Use a real DNS hostname that you control. Shared convenience domains such as `*.nip.io` are globally rate-limited by Let's Encrypt and are rejected by `definite init` when `deployment.tls` is `cert_manager`. - [ ] **agent-sandbox CRDs.** Custom resources the Fi runtime uses to dispatch a fresh sandbox per agent run. `definite doctor` probes for these and will fail preflight if they are absent. ## Storage The lakehouse itself needs no persistent volume — its catalog lives in Postgres and its data lives in the object store. PVCs are only needed when Fi is enabled (each sandbox gets an ephemeral `/workspace` volume). - [ ] **A StorageClass for Fi sandbox workspaces** (only if `fi.enabled: true`). You need a StorageClass that provisions `ReadWriteOnce` volumes — e.g. `gp3` on EKS, `standard-rwo` / `premium-rwo` on GKE, `managed-csi` on AKS. Set it as `fi.sandbox.storage_class_name` (and per-profile `storage_class_name` on any [compute profiles](/docs/compute-profiles)). - [ ] **A sensible default StorageClass**, or an explicit name in config, so PVCs bind without manual intervention. Check: `kubectl get storageclass`. ## Postgres (customer-provided) The application database. Definite operates no stateful database itself. - [ ] **Postgres 15 or newer.** `definite doctor` runs `SELECT version()` and warns below 15. - [ ] **A dedicated database and a role** that owns it. Definite manages its own schema inside that database via migrations on first boot. - [ ] **`pgcrypto` available.** No extensions beyond `pgcrypto` are required. - [ ] **Reachable from inside the cluster** on its port (5432 by default). A connection that works from your laptop can still fail from the cluster — see `network-requirements.md`. Provide the connection string as `postgres.url` in your config. - [ ] **Automatic backups enabled.** The application database holds all durable state — users, integration credentials, automations, Fi history, data apps — and a bad migration or operator mistake with no backup is unrecoverable. Definite does not back up your Postgres for you, so the managed instance **must** have automatic daily backups and point-in-time recovery turned on before you deploy: - **Cloud SQL (GKE):** create the instance with `--backup-start-time=HH:MM` and `--enable-point-in-time-recovery` (transaction-log retention). On an existing instance: `gcloud sql instances patch --backup-start-time=07:00 --enable-point-in-time-recovery --retained-backups-count=7`. - **RDS (EKS):** the bundled Terraform (`deploy/terraform/aws`) and `scripts/install-eks.sh` already provision RDS with a 7-day `backup_retention_period` and a daily backup window — no extra step. - **Azure Database for PostgreSQL (AKS):** automated backups are on by default; confirm the retention period (7-35 days) and, for important deployments, enable geo-redundant backup. - **Self-managed Postgres:** schedule a daily `pg_dump` (or `pgBackRest`) to off-host storage — see [`backup-restore.md`](/docs/backup-restore). Take an on-demand backup immediately before every `definite upgrade`; see the upgrade note in [`backup-restore.md`](/docs/backup-restore). ## Object store (customer-provided) Bulk lakehouse parquet data lives here; the DuckLake catalog lives in the `ducklake_catalog` Postgres database (above). - [ ] **A bucket / container** on S3, GCS, Azure Blob, or MinIO, dedicated to this deployment. - [ ] **Credentials with read AND write** on that bucket. S3 on EKS can use IRSA (`object_store.credentials.mode: irsa`) so pods assume a scoped IAM role through the AWS credential chain. Static HMAC credentials remain supported for S3-compatible stores and customers that prefer them; see `examples/minimal-eks.yaml`. - [ ] **A prefix** for Definite's objects (`lakehouse.prefix`) if the bucket is shared with other workloads. - [ ] **Writability confirmed.** `definite doctor` validates object-store *config shape* but does not yet round-trip a real write. Confirm the credentials can `PutObject` into the bucket yourself before deploying. - [ ] **CORS rule for Drive.** The Drive feature uploads files straight from the browser to the bucket via presigned `PUT` URLs, so the bucket needs a CORS policy allowing `GET` and `PUT` from the deployment's web origin (the `https://…` URL users open). Without it, browser uploads fail with a CORS error while the headless `definite run load` flow keeps working. On Azure the storage account's CORS must also allow the `x-ms-blob-type` header, and a private-endpoint blob account must be reachable from end-user browsers. See `drive.md` for the exact rules. (No effect on API access; this is browser-only.) ## Optional - [ ] **OIDC provider** for SSO. Local Postgres auth is the shipped fallback; OIDC (Okta, Entra) is being hardened. - [ ] **LLM credentials.** Bring your own: Anthropic, Bedrock, Vertex, or Azure OpenAI. `definite doctor` does a real API ping for Anthropic and config-validation for the others. ## Next steps 1. `definite bootstrap --dry-run` — confirm what the cluster is missing. 2. `definite bootstrap` — install the cluster prerequisites. 3. `cp examples/minimal-.yaml ./config.yaml` and edit it. 4. `definite doctor --config config.yaml` — verify Postgres, Kubernetes, object store, and LLM. 5. `definite init --config config.yaml` — deploy. See [`cli.md`](/docs/cli) for the full command reference. --- # CLI Reference The `definite` CLI is the single control plane for an on-prem deployment. ## Install ```bash # prebuilt binary (recommended) curl -fsSL https://storage.googleapis.com/definite-public/definite-onprem/install.sh | sh ``` The install script detects your OS and architecture, downloads the matching prebuilt binary from GitHub Releases, verifies its checksum, and places `definite` on your PATH. Cross-platform binaries are published for macOS (arm64, x86_64) and Linux (arm64, x86_64) on every release. To pin a version or install behind a proxy, download the asset directly from the [Releases page](https://github.com/definite-app/definite-onprem/releases) and place it on your PATH yourself. ```bash # from source (for development) git clone https://github.com/definite-app/definite-onprem cd definite-onprem cargo build --release ./target/release/definite --help ``` The CLI shells out to `kubectl` and `helm`. Both must be installed and on PATH on the machine running `definite`. See [`prerequisites.md`](/docs/prerequisites) for the full dependency checklist. ## Commands ### `definite init` Deploy Definite from a `config.yaml`. ```bash definite init --config config.yaml DEFINITE_ONPREM_SETUP_TOKEN=... definite init --config config.yaml definite init --config config.yaml --requested-slug analytics definite init --config config.yaml --dns-mode customer-owned --hostname analytics.customer.com definite init --config config.yaml --dry-run # render values, don't apply definite init --config config.yaml --skip-preflight # not recommended definite init --config config.yaml --wait=false # don't wait for pods ready ``` By default, `init` uses Definite-brokered DNS and licensing: it discovers the ingress-nginx load-balancer target, sends it to the broker with the release version, optional requested slug, and setup token, waits for DNS readiness, then uses the returned FQDN and license key in the Helm install. If no setup token is configured, the CLI automatically acquires one from cloud credentials. On GCP, audience-bound setup attestation can use a service account from `DEFINITE_ONPREM_GCP_ATTESTATION_SERVICE_ACCOUNT`, `GOOGLE_IMPERSONATE_SERVICE_ACCOUNT`, `CLOUDSDK_AUTH_IMPERSONATE_SERVICE_ACCOUNT`, or gcloud's `auth/impersonate_service_account` config; the token is minted with an email claim for broker verification. Use `--dns-mode customer-owned --hostname ...` only when the customer will manage DNS themselves. Do not use `*.nip.io` for `tls: cert_manager`; the CLI rejects that combination because Let's Encrypt rate-limits `nip.io` globally. After DNS/license setup, `init` runs preflight checks, then `helm upgrade --install` with the rendered values. ### `definite doctor` Run preflight diagnostic checks without deploying. ```bash definite doctor --config config.yaml definite doctor --config config.yaml --skip postgres,object_store ``` Checks: | Category | What it does | |---|---| | `postgres` | Connects with `tokio-postgres`, runs `SELECT version()`, warns on <15 | | `kubernetes` | Runs `kubectl cluster-info`, reports the control plane endpoint | | `object_store` | Validates config shape (a real `PutObject` round-trip is not yet performed) | | `llm` | For Anthropic: real API ping. For others: config validation only | | `agent_sandbox` | Checks the agent-sandbox CRDs are installed | | `license` | Warns if `config.yaml` has no `license` block (the deployment would be unlicensed and product API routes disabled). A warning, never a hard failure. | ### `definite status` `kubectl get pods,svc,ingress` scoped to the deployment namespace. ```bash definite status --config config.yaml ``` ### `definite upgrade` Re-render and re-apply the chart with the current CLI's bundled version. ```bash definite upgrade --config config.yaml definite upgrade --config config.yaml --dry-run ``` > **Take an on-demand Postgres backup first.** An upgrade applies pending schema > migrations on API boot; a bad migration with no labelled restore point is > unrecoverable. Automatic daily backups should already be on (see > [`prerequisites.md`](/docs/prerequisites)), but take a fresh, named snapshot > immediately before upgrading: > - **RDS:** `aws rds create-db-snapshot --db-instance-identifier > --db-snapshot-identifier -preupgrade-$(date +%Y%m%d-%H%M%S)` > - **Cloud SQL:** `gcloud sql backups create --instance=` > - **Azure / self-managed:** trigger an on-demand backup or `pg_dump` per > [`backup-restore.md`](/docs/backup-restore). > **Row order after upgrade.** Releases that include #1207 run pipeline and > SDK DuckDB engines with `preserve_insertion_order = false`. If a pipeline > depends on row order without `ORDER BY` — including a table created with > `CREATE TABLE ... AS SELECT ... ORDER BY` and then read back without > `ORDER BY` — set `lakehouse.duckdb.preserveInsertionOrder: true`, or add > `ORDER BY` at read time. See > [`transformations.md`](/docs/transformations) for details. ### `definite logs` Stream logs from a component. ```bash definite logs api definite logs api --follow definite logs job-runner --tail 500 ``` Components: `api`, `frontend`, `job-runner`. Lakehouse queries run as embedded DuckDB inside the API and job-runner pods, so there is no separate `lakehouse` component to tail. ### `definite discover` Search the ontology and semantic layer together before answering an analytical question. Multiple unquoted terms are joined into one query. ```bash definite discover visitors sessions traffic website definite discover monthly visitors --format json ``` The response keeps ontology and semantic hits separate, bounds each result set, reports per-layer errors and truncation, and suggests next actions. A partial layer failure still exits successfully with the healthy layer's results; only failure of both layers makes the command fail. ### `definite run query` Run SQL against the lakehouse, or inspect query history. ```bash # Run a SQL statement (positional, a file, or '-' for stdin). definite run query "select count(*) from analytics.sales" definite run query --file ./report.sql # List recently-run queries — deduped by SQL text, newest first. definite run query history ``` `query history` is backed by `GET /api/v1/queries/recent`. Each row shows the run timestamp, status, author, row count, duration, and the SQL. Respects `--format` (`table` | `json` | `csv`). ### `definite run integration` List, inspect, create, update, and test saved integrations. ```bash definite run integration list definite run integration get supabase-prod --format json definite run integration test supabase-prod --format json cat > postgres-integration.json <<'JSON' { "public": { "host": "db.example.com", "port": "5432", "database": "postgres", "user": "postgres", "sslmode": "require" }, "secrets": { "password": "..." } } JSON definite run integration create \ --name supabase-prod \ --type postgres \ --config postgres-integration.json definite run integration update supabase-prod --config postgres-integration.json ``` `--config -` reads JSON from stdin. The config file may contain `public`, `secrets`, or both; each must be a JSON object. Secret values are sent in the request body and stored encrypted by the API. Do not pass passwords or API tokens as shell arguments. ### `definite connect` Open a local DuckDB session against the deployment. ```bash # Standard path. In postgres_catalog mode this starts a credential-free # localhost SQL relay and exposes R.query('') in local DuckDB. definite connect duckdb -init ~/.definite/connect-init.sql # Admin-only postgres_catalog escape hatch. Writes direct DuckLake ATTACH # credentials to a 0600 init file and exits; no relay stays running. definite connect --direct-attach duckdb -init ~/.definite/ducklake-direct-init.sql ``` In `postgres_catalog` mode the standard relay keeps the catalog DSN and object-store credentials server-side. It accepts read-only SQL through `R.query(...)` and uses the same table-access checks and query limits as the Query page: ```sql FROM R.query('SHOW TABLES'); FROM R.query('SELECT * FROM main.orders LIMIT 10'); ``` `--direct-attach` is available only to admins. It writes the deployment's DuckLake catalog DSN and object-store credentials to the local init script so DuckDB can `ATTACH 'ducklake:postgres:...'` directly; keep that file private. ### `definite run load` Upload a local file to the deployment's configured object store, and optionally register it as a lakehouse table in one shot. Bytes stream directly from the CLI to object storage via a presigned PUT URL — they do not traverse the API pod. ```bash # Upload only — prints the object_uri the lakehouse can read. definite run load ./sales.csv # Upload + register as a lakehouse table (replaces if it exists). definite run load ./sales.csv --table analytics.sales --mode replace # Append into an existing table (created on first call if missing). definite run load ./new-events.parquet --table raw.events --mode append # Explicit format override (auto-detect uses the file extension). definite run load ./events.log --file-format json --table raw.events --mode replace ``` **Flags:** | Flag | Meaning | |---|---| | `--table SCHEMA.NAME` | Register the staged file as a lakehouse table. Omit for stage-only. | | `--mode replace\|append` | **Required** when `--table` is set; no default. `replace` is `CREATE OR REPLACE TABLE`; `append` creates the table on first call then `INSERT INTO`. | | `--file-format csv\|parquet\|json` | Override format detection. Auto-detected from `.csv`, `.parquet`, `.json`/`.ndjson`/`.jsonl`. | **Requires:** the deployment must have `jobRunner.staging.uri` set in its values.yaml and matching object-store HMAC credentials. Azure backends are not supported in v1; S3, GCS, and MinIO are. When staging isn't configured, the command returns a 503 with a remediation message and leaves the rest of the API unaffected. ### `definite transform` Author a local folder of SQL models, persist its dependency graph server-side, inspect versioned lineage metadata, and run it through the automation runner. ```bash # Scaffold a starter project. definite transform init transformations # Parse the local SQL files and print the inferred graph and execution order. definite transform plan transformations # Persist the graph and create/update the linked automation pipeline. definite transform apply transformations --name core-models # List persisted transformation projects. definite transform list # Inspect the persisted project, graph, latest definition, and metadata. definite transform get core-models --format json # List immutable applied versions for the project. definite transform versions core-models --format json # Inspect a historical version; include the full AST only when needed. definite transform get core-models --version 3 --format json definite transform get core-models --version 3 --include-ast --format json # Show source/output lineage across projects, or filter it down. definite transform lineage --format json definite transform lineage --project core-models --source-table orders --format json # Queue a run through the linked automation pipeline. definite transform run core-models --format json ``` Common flags: | Flag | Meaning | |---|---| | `--name NAME` | Project display name. Defaults to the directory name for `plan` and `apply`. | | `--slug SLUG` | Stable project slug. Defaults to a slugified project name. | | `--default-schema SCHEMA` | Default destination schema for models without a header override. | | `--description TEXT` | Set the project description on `apply`. Omitted, the stored description is kept; `""` (or whitespace-only) clears it. | | `--compute-profile NAME` | Set the project's default compute profile. Omitted, the stored profile is kept; `default` resets. | | `--cron "M H DOM MON DOW"` | Set the linked pipeline's schedule. Omitted, an existing schedule is preserved. | | `--cron-timezone TZ` | IANA timezone for `--cron`. Omitted, the pipeline's stored timezone is kept (UTC for a new pipeline). | | `--clear-cron` | Remove the linked pipeline's existing schedule. | | `--disabled` | Create the linked automation disabled, or pause it on update. Omitted, the enabled state is preserved. | | `--enable` | Re-enable a paused pipeline on `apply`. | | `--version N` | With `transform get`, fetch a historical applied version instead of the current graph. | | `--include-ast` | With `transform get --version`, include full parser AST JSON for versioned model SQL. | | `--project SLUG_OR_ID` | With `transform lineage`, filter lineage to one transformation project. | | `--source-schema S` / `--source-table T` | With `transform lineage`, filter by upstream lakehouse source. | | `--output-schema S` / `--output-table T` | With `transform lineage`, filter by downstream transformation output. | | `--trigger-type TYPE` | Trigger label recorded by `transform run`; defaults to `manual`. | Use `--format json` for automation, Fi handoff, or audit workflows. Table output is intentionally compact; JSON preserves ids and metadata such as linked automation ids, version ids, run ids, source-lineage edges, source refs, parser status, AST summaries, and exact run SQL snapshots when those fields are present in the deployed API. `transform versions`, `transform lineage`, `transform get --version`, and `--include-ast` require a deployment API that exposes the matching version and lineage endpoints. Older API builds can still use the core plan/apply/list/get/run workflow, but may not return version history, source lineage, or full AST payloads. Transformation versioning has three distinct SQL concepts: | Concept | Meaning | |---|---| | Editable source | SQL model files in the local project folder or source editor. | | Applied version SQL | Server-side model definition saved by `transform apply`. | | Run SQL snapshot | Exact compiled SQL inside the automation run's snapshotted definition. Use this for debugging past runs. | The `/transformations` UI uses the same concepts: it filters projects by status, source table, and output table; shows project models, dependency edges, selected model SQL, source/output refs, versions, and linked automation metadata; and can queue a run or open the linked automation/run. Exact run SQL snapshots and full AST payloads are opt-in detail/debug payloads, not default list data. Full AST is available through `--include-ast` and the equivalent UI parser-debug expansion when that payload is exposed by the deployed API. See [SQL transformations](/docs/transformations) for the model-file format, lineage behavior, AST behavior, and current limits. ### `definite run maintenance` Inspect and run DuckLake table maintenance operations against a deployed API. All three subcommands respect `--format` (`table` | `json` | `csv`). ```bash # Show file/snapshot statistics for every lakehouse table. definite run maintenance stats # Dry-run a destructive op to see what it would remove. definite run maintenance preview --operation expire_snapshots --older-than-days 30 # Compact a single table (waits for the run to finish). definite run maintenance run --operation compact --schema analytics --table sales # Rewrite files whose delete ratio exceeds a threshold. definite run maintenance run --operation rewrite --schema analytics --table sales --delete-threshold 0.25 # Flush inlined event rows to Parquet files. definite run maintenance run --operation flush_inlined_data --schema raw --table events # Destructive ops require --yes (or --dry-run to plan safely). definite run maintenance run --operation cleanup_old_files --older-than-days 30 --yes definite run maintenance run --operation expire_snapshots --older-than-days 30 --dry-run ``` **Operations:** `compact`, `rewrite`, `flush_inlined_data`, `checkpoint`, `expire_snapshots`, `cleanup_old_files`, `delete_orphaned_files`, `full`. **Flags (`run`):** | Flag | Meaning | |---|---| | `--operation OP` | Maintenance operation to run. Required. | | `--schema S` / `--table T` | Optional together for `compact` and `rewrite` (omit both for whole-lake); optional for `flush_inlined_data` (`--table` requires `--schema`); rejected for other ops. | | `--delete-threshold F` | Delete-ratio threshold; only valid with `rewrite`. | | `--older-than-days N` | Age threshold. **Required** for `expire_snapshots`, `cleanup_old_files`, `delete_orphaned_files`; rejected for other ops. | | `--dry-run` | Plan the operation without applying changes. | | `--yes` | Confirm a destructive operation. Required for the three destructive ops unless `--dry-run` is set. | `preview` accepts only `--operation` (one of the three destructive ops) and `--older-than-days`. The `run` subcommand polls the run to a terminal state (`succeeded` / `failed` / `cancelled`), streaming step output and logs; it exits non-zero if the run fails. Use `--timeout-seconds` to bound the overall poll budget. ### `definite run event-source` Manage browser-safe public write keys for the event ingest collector. Every subcommand requires an admin token and respects `--format` (`table` | `json` | `csv`). ```bash # Create a source and print the full evpub_... key once. definite run event-source create \ --name "Marketing site" \ --schema raw \ --table events \ --origin https://www.example.com # Add several allowed browser origins. definite run event-source create \ --name "Product app" \ --schema raw \ --table product_events \ --origin https://app.example.com \ --origin https://admin.example.com \ --max-batch-rows 250 \ --max-payload-bytes 524288 # Create a server-kind source for SaaS webhook senders (e.g. Read.ai) that # can only set a URL. No --origin needed; the write key rides the URL. definite run event-source create \ --name "Read.ai webhooks" \ --schema readai \ --table raw_meetings \ --kind server \ --default-event-name meeting_end \ --max-payload-bytes 8388608 # Inspect, rotate, or revoke sources. definite run event-source list definite run event-source rotate definite run event-source revoke ``` Public event keys are append-only and scoped to the destination table configured on the source. Browser-kind keys are safe to embed in browser code for the listed origins; server-kind keys skip the Origin allowlist and are passed as a `?write_key=` query parameter by webhook senders. Normal Definite API tokens are neither. See [Event Ingest](/docs/event-ingest) for client-side and webhook examples. ### `definite run permission` Manage workspace access from the CLI. Covers all three layers of the permission model (see [Permissions](/docs/permissions) for the concepts): **application roles**, **content sharing**, and **data-access roles**. Every subcommand requires an admin token and respects `--format` (`table` | `json` | `csv`). ```bash # --- application roles --- definite run permission users # list users + role definite run permission set-role --role editor # viewer|editor|admin # --- content sharing (kind = app|thread|project|query|automation|integration|agent) --- definite run permission grants app # who can see it definite run permission share app --grantee --access edit definite run permission share app --grantee everyone --access view definite run permission unshare app --grantee # --- data-access roles --- definite run permission data-access roles # list roles definite run permission data-access create-role --name analyst --description "Sales read" --default definite run permission data-access update-role --name analysts --default false definite run permission data-access delete-role definite run permission data-access set-grants --grant sales.orders --grant marketing.* definite run permission data-access role-users # who holds the role definite run permission data-access assign --user definite run permission data-access unassign --user ``` **Notes:** - `share` takes `--grantee ` or the literal `everyone` (workspace-wide view). `--access` is `view` (default) or `edit`; integrations accept `view` only — credential changes stay admin-only. - `unshare`'s `--grantee` is a user ID or `everyone`. - `set-grants` **replaces** a role's whole grant set — always pass the full intended list. A grant is `schema.table`; `*` is the only wildcard (`sales.*` = every table in `sales`, `*.*` = every table). - `update-role` patches only the flags you pass (`--name`, `--description`, `--default `); omitted fields are left unchanged. - `set-role` refuses to demote the last remaining admin. These are the same operations available in the web UI under **Settings → Members & access** and in the Fi `permissions` skill. ### `definite run app` Manage **data apps** — single-file React + DuckDB-WASM dashboards served by the on-prem API at `/apps/`. The CLI handles scaffolding from a built-in template, uploading the built bundle, and basic lifecycle ops. ```bash # Scaffold a new app from a built-in template into .//. definite run app scaffold revenue-explorer # default: refined definite run app scaffold pipeline --template tufte-pipeline # Tufte-styled report # Iterate, then build + upload. cd revenue-explorer npm run build # → dist/index.html definite run app upload revenue-explorer . # snapshots src/ for the Source tab definite run app upload revenue-explorer . --force # intentional replace; saves prior version # Lifecycle. definite run app list # slug, name, updated_at definite run app get revenue-explorer # metadata definite run app get revenue-explorer --source # download editable source definite run app delete revenue-explorer ``` Uploads are create-only by default and reject an existing slug. Use `--force` only when you intentionally want to replace an app; the previous HTML/source is kept in the app's version history for restore. **Built-in templates** (selected via `--template`): - **`refined`** *(default)* — SaaS-style dashboard: KPI tiles, charts, a sortable `DataTable`, dark theme, runtime's `SaasKpiCard` + `EChart` + `DataTable`. Use for plain "show me X" dashboards. - **`tufte-pipeline`** — dense, document-style analytical report: sparklines, small multiples, range-frame bars, drillable inline numerics, EB Garamond + IBM Plex typography. Use when the user wants an executive report or anything that should look more like a report than a tile grid. See [`frontend/templates/tufte-pipeline/README.md`](https://github.com/definite-app/definite-onprem/blob/main/frontend/templates/tufte-pipeline/README.md) for the design vocab + the resource shapes its starter app expects. Both templates compile to a single self-contained `dist/index.html` via `npm run build` and share the same node_modules layout (pre-baked at `/opt/data-apps-template/node_modules` in the fi-sandbox image so there's no `npm install` round trip in the agent). ### `definite export-helm` Print the rendered Helm values or full chart to stdout. Escape hatch for SREs who want to take over with raw `helm`. ```bash definite export-helm --config config.yaml --format yaml # values only definite export-helm --config config.yaml --format chart # `helm template` output ``` ### `definite version` Print the CLI and bundled chart version. ### `definite bootstrap` Install the cluster-level prerequisites that `definite init` assumes are already present. Run this once against a fresh cluster, before `definite doctor` / `definite init`. ```bash definite bootstrap # install missing prerequisites definite bootstrap --dry-run # print what would be installed, change nothing definite bootstrap --acme-email ops@acme.com # ClusterIssuer ACME contact email ``` `bootstrap` installs, in order: | Prerequisite | What it provides | |---|---| | Ingress controller | HTTP/S routing for the deployment's `Ingress` resource. | | cert-manager (+ CRDs) | TLS certificate issuance for `tls: cert_manager` deployments. | | `letsencrypt-prod` ClusterIssuer | The issuer the ingress references for automatic Let's Encrypt certs. | | agent-sandbox CRDs | Custom resources the Fi runtime uses to dispatch per-run sandboxes. | cert-manager is installed with its leader-election lease pinned to the `cert-manager` namespace (`--set global.leaderElection.namespace=cert-manager`). The chart defaults this lease to `kube-system`, which is Google-managed on GKE Autopilot and rejects writes — without the override cainjector never acquires the lease and the webhook CA is never injected. The override is harmless on non-Autopilot clusters, so it is always applied. After cert-manager is healthy, `bootstrap` creates the `letsencrypt-prod` `ClusterIssuer` (production Let's Encrypt ACME, `http01` solver). The Helm chart's `Ingress` is annotated `cert-manager.io/cluster-issuer: letsencrypt-prod`, so without this issuer TLS certs never provision. The ACME contact email defaults to `hello@definite.app`; override it with `--acme-email`. Use `--ingress-class` (default `nginx`) if your ingress controller uses a different class. `--skip-cert-manager` skips both cert-manager and the ClusterIssuer (use it for `tls: disabled` / `manual`). Production Let's Encrypt is for real DNS names that you control. Avoid convenience wildcard domains such as `*.nip.io` with `tls: cert_manager`: Let's Encrypt rate-limits `nip.io` globally at the registered-domain level, and cert-manager will loop on 429 errors instead of issuing a trusted cert. `definite init` rejects that combination; use real DNS, `tls: manual`, or `tls: disabled` for local/no-trust testing. The command is idempotent: `helm upgrade --install` and `kubectl apply` both converge on re-run. `--dry-run` reports the planned actions — every helm and kubectl command, plus the full ClusterIssuer manifest — without touching the cluster. Anything `bootstrap` installs can also be installed by hand with `helm` / `kubectl`; it is a convenience, not a hard dependency. `definite doctor` re-checks for these prerequisites and points back here when one is missing. ### `definite login` Authenticate the CLI against a running deployment so subsequent commands (`definite run …`) can act on your behalf without re-entering credentials. ```bash definite login deployment.acme.internal # prompts for password definite login deployment.acme.internal --password "$PW" echo "$PW" | definite login deployment.acme.internal --password-stdin ``` `login` authenticates against the deployment's **local Postgres auth** path. It prompts interactively for a password by default; `--password` takes it as a flag (visible in shell history — prefer `--password-stdin` for scripts and CI). On success the issued token is written to `~/.definite/credentials.json` with file mode `0600` (owner read/write only). The file stores the current `api_url`, `token`, `email`, and `expires_at`; running `definite login` against another deployment overwrites the saved credentials. `definite run` resolves credentials in this order: an explicit `--token` flag, then the `DEFINITE_TOKEN` environment variable, then the stored credentials for the target hostname. If none resolve, the command fails with a message telling you to run `definite login`. OIDC/SSO deployments authenticate through the browser-based web login rather than `definite login`; CLI login covers the local Postgres auth path. ### `definite license` Inspect a deployment's live license entitlement. ```bash definite license status # plan + activation status definite license status --config config.yaml definite license status --api-url http://localhost:8000 --token "$TOKEN" ``` `license status` calls `GET /api/v1/license` on the deployment and prints the plan, activation status, expiry, and enabled features. This is the live entitlement the API obtained by activating against the central Definite API. It requires a bearer token (`--token` or `DEFINITE_TOKEN`). A deployment is licensed by **one** mechanism: a license key in the `definite-secrets` Kubernetes Secret under `license-key`. In the default brokered install flow, `definite init` obtains that key from the broker. For customer-owned/manual flows, add a `license` block to `config.yaml`; the CLI renders it into the Secret, and the API reads it as `LICENSE_KEY` and activates against the central Definite API. Advanced installs may leave the `license` block unset and have an external secret store sync `license-key` into the same Secret; the API env is still wired, but the pod must restart after secret rotation. There is no separate "apply a key to the CLI" step. To license — or re-license — a running deployment, add a `license` block to `config.yaml` (see [`config.md`](/docs/config)) and run `definite upgrade`. ## Environment variables | Variable | Purpose | |---|---| | `DEFINITE_LOG` | tracing-subscriber filter, e.g. `debug` or `definite=debug,reqwest=info`. Default: `info`. | | `DEFINITE_CHART_PATH` | Override the bundled Helm chart location. Useful for development. | | `DEFINITE_ONPREM_SETUP_TOKEN` | Broker setup token for the default DNS/license flow. Secret; never printed. | | `DEFINITE_SETUP_TOKEN` | Legacy/fallback broker setup token env var. | | `DEFINITE_BROKER_API_URL` | Override the broker API base URL. | | `DEFINITE_BROKER_REQUESTED_SLUG` | Optional preferred brokered DNS slug. | | `DEFINITE_ONPREM_GCP_ATTESTATION_SERVICE_ACCOUNT` | Optional GCP service account to impersonate when minting broker setup attestation identity tokens. | | `DEFINITE_TOKEN` | Auth token for `definite run`. Checked after `--token` and before stored credentials from `definite login`. | | `${ANY_VAR}` (in config.yaml) | Substituted at config load time. `${VAR}` must be set or load fails loud. | ## Exit codes | Code | Meaning | |---|---| | 0 | Success | | 1 | Generic failure (config error, preflight failed, helm error) | --- # API Reference Every Definite on-prem deployment exposes an HTTP API under `/api/v1`. It is the same surface the web UI and the [`definite` CLI](/docs/cli) use — the CLI's `definite run …` subcommands are thin wrappers over these endpoints. Anything you can do in the UI or the CLI you can do directly over HTTP, which is how you drive the deployment from a script, a notebook, or a CI job. ## Base URL The API is served at your deployment's hostname: ``` https:///api/v1 ``` Behind the production ingress, only `/api/*`, `/health`, `/mcp`, and the OAuth `/.well-known/*` paths reach the API; everything else serves the web UI. (The FastAPI app also generates an OpenAPI schema at `/openapi.json` and interactive docs at `/docs`, but those sit at the root and are shadowed by the UI through the ingress — they're only reachable when you talk to the API container directly, e.g. a `kubectl port-forward` to `http://localhost:8000`. Treat the tables below as the canonical reference.) ## Conventions - Requests and responses are JSON. Send `Content-Type: application/json` on any request with a body. - Authentication is a bearer token in the `Authorization` header (see below). - Errors use standard HTTP status codes with a JSON body `{"detail": "..."}`. Common codes: `400` bad request, `401` missing/expired token, `403` not permitted, `404` not found, `413` response too large, `422` validation error. ## Authentication All endpoints except `POST /api/v1/auth/login` require a bearer token: ``` Authorization: Bearer ``` There are two kinds of token. Both are validated the same way, so either works on any authenticated endpoint. ### Session tokens (interactive) Exchange an email and password for a session token. Sessions are opaque (~43 chars) and expire after about two weeks. ```bash curl -sS -X POST https:///api/v1/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"you@example.com","password":"..."}' # → {"token":"...","email":"you@example.com","expires_at":"2026-06-12T..."} ``` This is the local-Postgres auth path. On OIDC/SSO deployments, users sign in through the browser; for programmatic access on those deployments, use an API token (below). `definite login` stores a session token in `~/.definite/credentials.json` for the CLI — see [CLI reference](/docs/cli). ### API tokens (long-lived, for scripts & CI) API tokens are long-lived bearer keys, prefixed `def_`, ideal for automation that shouldn't re-enter a password or babysit a 2-week expiry. Create one in the UI under **Settings → API tokens**, or over the API: ```bash # Authenticated with a session token (or another API token): curl -sS -X POST https:///api/v1/auth/tokens \ -H "Authorization: Bearer $SESSION_TOKEN" \ -H "Content-Type: application/json" \ -d '{"name":"ci-pipeline","expires_at":null}' # → {"token":"def_<32 hex>", "record":{"id":"...","name":"ci-pipeline","prefix":"def_xxxxxxxx",...}} ``` The full `def_…` string is shown **once**, at creation — store it somewhere safe. `expires_at` is optional; `null` means the key never expires. Use the returned token exactly like a session token: ```bash curl -sS https:///api/v1/queries \ -H "Authorization: Bearer def_..." \ -H "Content-Type: application/json" \ -d '{"sql":"SELECT 1 AS ok"}' ``` | Method | Path | Purpose | |---|---|---| | `GET` | `/api/v1/auth/tokens` | List your API tokens (metadata only — never the secret) | | `POST` | `/api/v1/auth/tokens` | Create a token; body `{name, scopes?, expires_at?}`; returns the secret once | | `DELETE` | `/api/v1/auth/tokens/{id}` | Revoke a token immediately | #### Scopes A token's optional `scopes` array restricts what it can do. **Leave it empty for full access** (the token carries its creator's role, the historical behavior). A non-empty set **narrows** the token: it may only reach routes whose scope it holds, and never more than the owner's role allows (effective access is role AND scope — a scope can't grant something the owner's role wouldn't). Unknown scope names are rejected with `422`. Scopes are coarse and router-level; for per-resource limits, prefer a dedicated low-role user plus content grants. | Scope | Grants | |---|---| | `query:read` | Run SQL queries and read the data catalog | | `pipelines:read` | View automation pipelines, transformations, scripts, agents, and their runs | | `pipelines:write` | Create, edit, archive, and delete pipelines, transformations, scripts, and agents | | `pipelines:run` | Trigger and cancel pipeline, transformation, and agent runs | | `integrations:read` | View integrations and connector metadata | | `integrations:manage` | Create, edit, test, and reveal integration credentials; manage event sources and OAuth | | `docs:read` | View docs, data apps, drive files, and projects | | `docs:write` | Create and edit docs, data apps, drive files, and projects; load data | | `semantic:read` | Read and query the semantic layer and ontology | | `fi:use` | Use Fi (threads, runs, memories) and the Fi sandbox | | `admin` | Administer the workspace: settings, users, tokens, license, and infrastructure | ```bash # A read + trigger token for a pipeline chain (nothing else): curl -sS -X POST https:///api/v1/auth/tokens \ -H "Authorization: Bearer $SESSION_TOKEN" \ -H "Content-Type: application/json" \ -d '{"name":"reconcile-bot","scopes":["pipelines:read","pipelines:run"]}' ``` A scoped token hitting a route outside its scopes gets `403` naming the missing scope. The same scopes apply to the [MCP server](/docs/mcp): an unscoped `def_` key keeps working unchanged, and a scoped one may only call tools its scopes cover. > **Back-compat.** Tokens minted before scope enforcement shipped keep full > access — their stored scopes (if any) are ignored, not retroactively enforced. > Only tokens created after this release enforce their scopes. > **Permissions caveat.** An unscoped API token inherits the **full permissions > of the user who created it** — an admin's token is an admin token, including > DDL/DML through the query endpoint. Treat a `def_` key as equivalent to its > owner's password and revoke it the moment it's no longer needed. ### Identity ```bash curl -sS https:///api/v1/auth/me -H "Authorization: Bearer $TOKEN" # → {"user_id":"...","email":"...","is_admin":true,"role":"admin","actor_kind":"api_token","client_side_query":false} ``` `actor_kind` is `login` for a session token and `api_token` for a `def_` key. | Method | Path | Purpose | |---|---|---| | `POST` | `/api/v1/auth/login` | Email + password → session token (the only unauthenticated endpoint) | | `GET` | `/api/v1/auth/me` | The user behind the current token | | `POST` | `/api/v1/auth/logout` | Revoke the current session token | | `POST` | `/api/v1/auth/me/password` | Change your own password | ## Running SQL The core data endpoint. Runs one statement against the lakehouse and returns JSON rows. ```bash curl -sS https:///api/v1/queries \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"sql":"SELECT count(*) AS n FROM main.orders"}' ``` ```json { "columns": ["n"], "rows": [{"n": 42}], "row_count": 1, "truncated": false, "row_limit": 200000, "duration_ms": 37 } ``` - Request body: `{"sql": "...", "compute_profile": ""}`. `compute_profile` is optional and routes the query through a declared [compute profile](/docs/compute-profiles); omit it for the default. - Read-only `SELECT` statements are open to any authenticated user (subject to table-level [data-access grants](/docs/permissions)). DDL/DML (`CREATE`/`INSERT`/`UPDATE`/…) is **admin-only** through this endpoint and returns empty `rows`/`columns`. - Responses are capped at **200,000 rows / 100 MB**; a larger result is truncated (`truncated: true`) or rejected with `413`. Narrow the query. - `duration_ms` is measured server-side around query execution and result materialization. It does not include client network latency. | Method | Path | Purpose | |---|---|---| | `POST` | `/api/v1/queries` | Run one SQL statement; body `{sql, compute_profile?}` | | `GET` | `/api/v1/queries/recent` | Recently-run statements (deduped by SQL) | | `GET` | `/api/v1/queries/saved` | List saved queries | | `POST` | `/api/v1/queries/saved` | Save a query; body `{name, sql}` | | `PATCH` | `/api/v1/queries/saved/{id}` | Rename / edit a saved query | | `DELETE` | `/api/v1/queries/saved/{id}` | Delete a saved query | ### Browsing the catalog | Method | Path | Purpose | |---|---|---| | `GET` | `/api/v1/catalog/tables` | List lakehouse schemas + tables | | `GET` | `/api/v1/catalog/tables/{schema}/{name}` | Table columns + metadata | | `GET` | `/api/v1/catalog/tables/{schema}/{name}/preview` | A small sample of rows | ## Automations Scheduled / triggered pipelines. See [Automations](/docs/automations). | Method | Path | Purpose | |---|---|---| | `GET` | `/api/v1/automations/pipelines` | List pipelines (`?include=last_runs&limit_runs=1` for recent runs) | | `POST` | `/api/v1/automations/pipelines` | Create a pipeline; body `{name, definition, enabled, cron_schedule?, run_after_pipeline_id?, ...}` | | `GET` | `/api/v1/automations/pipelines/{id}` | Get one pipeline (full definition) | | `PATCH` | `/api/v1/automations/pipelines/{id}` | Update name / definition / schedule / run-after dependency / enabled | | `DELETE` | `/api/v1/automations/pipelines/{id}` | Delete a pipeline | | `POST` | `/api/v1/automations/pipelines/{id}/runs` | Queue a manual run; body `{trigger_type, lane?}` | | `GET` | `/api/v1/automations/runs/{run_id}` | Run status, per-step output, and logs | | `POST` | `/api/v1/automations/runs/{run_id}/cancel` | Cancel a queued/running run (kills in-flight python steps) | Reusable Python scripts that pipeline steps reference live under `/api/v1/automation-scripts` (`GET`/`POST`/`GET {id}`/`PATCH {id}`/`DELETE {id}`). ## Integrations Saved source/destination connections. Secrets are write-only — list and get never return them. See [Integrations](/docs/integrations). | Method | Path | Purpose | |---|---|---| | `GET` | `/api/v1/integrations/types` | Available integration types + their config schema | | `GET` | `/api/v1/integrations` | List saved integrations (metadata only) | | `POST` | `/api/v1/integrations` | Create an integration | | `GET` | `/api/v1/integrations/{id_or_name}` | Get one integration's public config | | `PATCH` | `/api/v1/integrations/{id_or_name}` | Update config / secrets | | `DELETE` | `/api/v1/integrations/{id_or_name}` | Delete an integration | | `POST` | `/api/v1/integrations/{id_or_name}/test` | Run the server-side connection test | ## Autonomous agents Probe → decide → act agents. See [Autonomous Agents](/docs/agents). | Method | Path | Purpose | |---|---|---| | `GET` | `/api/v1/agents` | List agents | | `POST` | `/api/v1/agents` | Create an agent | | `GET` | `/api/v1/agents/{id}` | Get one agent | | `PATCH` | `/api/v1/agents/{id}` | Update an agent | | `DELETE` | `/api/v1/agents/{id}` | Delete an agent | | `POST` | `/api/v1/agents/{id}/runs` | Queue a manual run | | `GET` | `/api/v1/agents/{id}/runs` | List recent runs for an agent | | `GET` | `/api/v1/agent-runs/{run_id}` | One run's probe result, decision, and action | ## Fi (the agent) Fi runs follow a **thread → run → poll** lifecycle. Dispatching a run is fire-and-forget; poll the thread for results. ```bash # 1. New thread TID=$(curl -sS https:///api/v1/fi/threads -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" -d '{}' | jq -r .thread.id) # 2. Dispatch a run curl -sS https:///api/v1/fi/threads/$TID/runs -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" -d '{"prompt":"how many rows are in main.orders?"}' # 3. Poll the thread (or stream events, below) curl -sS https:///api/v1/fi/threads/$TID -H "Authorization: Bearer $TOKEN" ``` | Method | Path | Purpose | |---|---|---| | `POST` | `/api/v1/fi/threads` | Create a thread; body `{title?}` | | `GET` | `/api/v1/fi/threads` | List threads | | `GET` | `/api/v1/fi/threads/{id}` | Get a thread (messages, title, status) | | `POST` | `/api/v1/fi/threads/{id}/runs` | Dispatch a run; body `{prompt}` | | `GET` | `/api/v1/fi/threads/{id}/runs/{run_id}` | One run's status (`queued`, `running`, `succeeded`, `failed`, `stopped`) | | `GET` | `/api/v1/fi/threads/{id}/events` | **SSE stream** of lifecycle events (not JSON — use `curl -sN --max-time N`) | | `POST` | `/api/v1/fi/threads/{id}/stop` | Stop the active run | ## Data apps Single-file React dashboards. See [Data Apps](/docs/data-apps) for the lifecycle and manifest, and [Data App Embedding](/docs/data-app-embedding) for iframe sharing. | Method | Path | Purpose | |---|---|---| | `GET` | `/api/v1/data-apps` | List data apps | | `GET` | `/api/v1/data-apps?stale=true` | List data apps built against an older runtime | | `POST` | `/api/v1/data-apps` | Upload an app; body includes the built `index.html` + manifest | | `GET` | `/api/v1/data-apps/{slug}` | App metadata | | `GET` | `/api/v1/data-apps/{slug}/source` | Download the app's stored source | | `POST` | `/api/v1/data-apps/{slug}/query` | Run one of the app's named SQL resources | | `POST` | `/api/v1/data-apps/{slug}/rebuild` | Rebuild an app with stored source against the current runtime | | `POST` | `/api/v1/admin/data-apps/rebuild-all` | Admin-only bulk rebuild for apps with stored source | | `DELETE` | `/api/v1/data-apps/{slug}` | Delete an app | ## Files & loading data Upload a local file to object storage, optionally registering it as a lakehouse table. The CLI wraps this as `definite run load`. | Method | Path | Purpose | |---|---|---| | `POST` | `/api/v1/loads/presign` | Get a presigned upload URL for a file | | `POST` | `/api/v1/loads/register` | Register an uploaded file as a lakehouse table | | `POST` | `/api/v1/drive/presign` | Presigned upload URL for a Drive file | | `GET` | `/api/v1/drive/files` | List Drive files | | `GET` | `/api/v1/drive/files/{id}/download-url` | Presigned download URL | ## Stream ingest Land JSON rows into any lakehouse table with real, typed columns, with `append` / `merge` / `replace` semantics and optional table autocreate. See [Stream Ingest](/docs/stream-ingest). For append-only product events into a fixed schema, use [Event Ingest](/docs/event-ingest) instead. | Method | Path | Purpose | |---|---|---| | `POST` | `/api/v1/stream` | Ingest rows into a table; body `{data, config:{table, mode?, primary_key?, create?}}` | ## Email Send a one-off transactional email through the deployment's configured email service (`EMAIL_MODE=smtp` or `definite_cloud`; see [config → email]( /docs/config#email)). Any valid bearer token works — a session token or a `def_` API token — the same auth as stream ingest; it is not admin-gated. If email is disabled or unconfigured the route returns `503` with a clear message (not a `500`); a delivery failure from the underlying mailer returns `502`. | Method | Path | Purpose | |---|---|---| | `POST` | `/api/v1/email/send` | Send an email; body `{to:[…], subject, html_body?, text_body?, attachments?}` | | `POST` | `/v3/email/message` | SDK-compat alias; body `{toEmails:[…], subject, body}` (`body` is HTML) | Caps mirror the cloud relay: 1 to 10 recipients, subject ≤ 200 chars, each body ≤ 1 000 000 chars, ≤ 5 attachments. At least one of `html_body` / `text_body` is required. Each attachment is `{filename, content_type?, content_base64}`. ```bash curl -sS -X POST "$BASE_URL/api/v1/email/send" \ -H "Authorization: Bearer $DEFINITE_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{"to":["ops@example.com"],"subject":"Nightly load done","html_body":"

All green.

"}' # → {"ok": true} ``` `POST /v3/email/message` is a **compatibility alias** for the cloud `POST /v3/email/message` route the Definite Python SDK's `send_email_message()` calls. A cloud pipeline becomes portable by pointing the SDK at this deployment's base URL with an on-prem `def_` token — no code change: ```python from definite_sdk.client import DefiniteClient client = DefiniteClient(api_key="def_…", api_url="https://") client.message_client().send_email_message( to_emails=["ops@example.com"], subject="Hi", body="

Hi

" ) ``` To send email from inside an automation pipeline, use the [`send_email` step](/docs/automations#send_email) instead — it delivers through the same service without an HTTP hop or a token. ## Lakehouse maintenance Compaction, snapshot expiry, and orphan cleanup on the DuckLake tables. See [Backup & Restore](/docs/backup-restore). | Method | Path | Purpose | |---|---|---| | `GET` | `/api/v1/lakehouse/maintenance/stats` | File / snapshot statistics | | `POST` | `/api/v1/lakehouse/maintenance/preview` | Dry-run a maintenance operation | | `POST` | `/api/v1/lakehouse/maintenance/runs` | Run an operation and poll it | | `GET`/`PUT` | `/api/v1/lakehouse/maintenance/schedule` | Read / set the maintenance schedule | ## Event ingest sources Browser-safe event ingest uses a separate **public write key**, not a `def_` token — see [Event Ingest](/docs/event-ingest). The management endpoints are admin-only and bearer-authed: | Method | Path | Purpose | |---|---|---| | `GET` | `/api/v1/events/sources` | List event sources | | `POST` | `/api/v1/events/sources` | Create a source (returns its write key once) | | `POST` | `/api/v1/events/sources/{id}/rotate` | Rotate the write key | | `DELETE` | `/api/v1/events/sources/{id}` | Revoke a source | ## Other surfaces | Area | Prefix | Notes | |---|---|---| | License | `/api/v1/license` | `GET` the live entitlement (plan, expiry, features) | | Workspace settings | `/api/v1/workspace` | Workspace info, branding, support access (admin) | | Members & roles | `/api/v1/auth/users` | List/manage users and app roles (admin) | | Permissions & sharing | `/api/v1/grants`, `/api/v1/data-access` | Content ACLs and table-level data-access roles | | Semantic layer | `/api/v1/semantic` | Semantic models and queries | | Transformations | `/api/v1/transformations` | SQL transformation models | | MCP server | `/mcp` | Model Context Protocol endpoint (separate from `/api`) — see [MCP Server](/docs/mcp) | ## Example: a benchmark script in Python No CLI, no subprocess — just `httpx` against the API. Mirrors what `definite run query` does under the hood. ```python import os import time import httpx BASE = os.environ["DEFINITE_API_URL"].rstrip("/") # https:// TOKEN = os.environ["DEFINITE_TOKEN"] # a def_ API token or session token def run_query(sql: str) -> dict: with httpx.Client(timeout=600.0) as client: resp = client.post( f"{BASE}/api/v1/queries", headers={"Authorization": f"Bearer {TOKEN}"}, json={"sql": sql}, ) resp.raise_for_status() # 401 bad token · 400 bad SQL · 413 result too large return resp.json() if __name__ == "__main__": t0 = time.perf_counter() result = run_query("SELECT count(*) AS n FROM main.orders") print(result["rows"], f"({time.perf_counter() - t0:.3f}s)") ``` ## See also - [CLI reference](/docs/cli) — the `definite` CLI wraps these endpoints - [Permissions](/docs/permissions) — app roles, content sharing, table-level data access - [MCP Server](/docs/mcp) — connect an LLM client over the Model Context Protocol --- # config.yaml Reference Full schema for the file you pass to `definite init`. See `examples/` for working starting points. ## Top-level shape ```yaml deployment: { ... } # required broker: { ... } # optional, used by default brokered DNS/license setup postgres: { ... } # required object_store: { ... } # required lakehouse: { ... } # optional, defaults to postgres_catalog mode events: { ... } # optional, defaults to enabled fi: { ... } # optional, defaults to disabled auth: { ... } # optional, defaults to local auth llm: { ... } # required resources: { ... } # optional license: { ... } # required for a usable deployment (see `license`) telemetry: { ... } # optional, defaults to disabled ``` ## `deployment` | Field | Type | Required | Default | Notes | |---|---|---|---|---| | `name` | string | yes | | Kubernetes-safe name. Lowercase alphanumeric + hyphens, max 63 chars. | | `namespace` | string | no | `definite` | Created if missing. | | `dns_mode` | enum | no | `definite-brokered` | `definite-brokered` or `customer-owned`. | | `hostname` | string | conditional | | Required only for `dns_mode: customer-owned`; brokered installs receive this from Definite during `definite init`. | | `tls` | enum | no | `cert_manager` | `cert_manager`, `manual`, or `disabled`. | Default installs use Definite-brokered DNS, so the customer does not need to create a DNS record before `definite init`. To manage DNS yourself, set `dns_mode: customer-owned` and provide `hostname`, or pass `--dns-mode customer-owned --hostname analytics.customer.com` to `definite init`. `tls: cert_manager` uses the production Let's Encrypt issuer created by `definite bootstrap`. For customer-owned DNS, use a real DNS hostname that you control. Do not use `*.nip.io` with `tls: cert_manager`: Let's Encrypt applies a global registered-domain rate limit to `nip.io`, so new certs for any `nip.io` hostname are commonly rejected. The CLI rejects that combination before install; for local/no-trust testing use `tls: disabled` or bring your own cert with `tls: manual`. ## `broker` Used by the default `deployment.dns_mode: definite-brokered` flow. The CLI discovers the ingress controller's load-balancer target, calls the Definite broker, waits for brokered DNS readiness, then uses the returned FQDN and license key for the Helm install. ```yaml broker: api_url: https://api.definite.app setup_token: { env: DEFINITE_ONPREM_SETUP_TOKEN } requested_slug: analytics # optional ``` | Field | Type | Required | Default | Notes | |---|---|---|---|---| | `api_url` | string | no | `https://api.definite.app` | Broker API base URL. Can also be overridden with `DEFINITE_BROKER_API_URL`. | | `setup_token` | SecretRef | no | | Optional one-time setup token issued by Definite. If omitted, the CLI falls back to `DEFINITE_ONPREM_SETUP_TOKEN`, then `DEFINITE_SETUP_TOKEN`, then automatic cloud attestation. Never printed by the CLI. | | `requested_slug` | string | no | | Optional preferred subdomain slug. Can also be passed with `--requested-slug` or `DEFINITE_BROKER_REQUESTED_SLUG`. | If no setup token is configured, brokered installs automatically acquire one from cloud credentials. On GCP, set `DEFINITE_ONPREM_GCP_ATTESTATION_SERVICE_ACCOUNT` or gcloud `auth/impersonate_service_account` when the active account must impersonate a service account to mint an audience-bound identity token with an email claim. ## `postgres` | Field | Type | Required | Default | |---|---|---|---| | `url` | string | yes | | Full Postgres connection URL. Supports `${ENV_VAR}` substitution. | | `pool_size` | uint | no | `20` | | `schema` | string | no | `definite` | > **Backups are a prerequisite, not a config field.** Definite does not back up > the application database — the managed instance behind `url` must have > automatic daily backups and point-in-time recovery enabled before you deploy. > The bundled AWS Terraform and `scripts/install-eks.sh` do this for RDS by > default; for Cloud SQL and Azure see [`prerequisites.md`](/docs/prerequisites) > and the backup runbook [`backup-restore.md`](/docs/backup-restore). ## `object_store` Tagged union by `type`: ### S3 ```yaml object_store: type: s3 bucket: my-bucket region: us-east-1 endpoint: null # optional, for S3-compatible non-AWS credentials: mode: irsa role_arn: arn:aws:iam::123456789012:role/definite-lakehouse-irsa # Static fallback: # credentials: # key_id: { env: S3_ACCESS_KEY_ID } # secret: { env: S3_SECRET_ACCESS_KEY } ``` ### GCS ```yaml object_store: type: gcs bucket: my-bucket credentials: null # optional; prefer Workload Identity ``` ### Azure ```yaml object_store: type: azure account: mystorageaccount container: definite credentials: null ``` ### MinIO ```yaml object_store: type: minio bucket: definite-lake endpoint: https://minio.internal:9000 credentials: literal: "accesskey:secretkey" ``` ## `lakehouse` Optional. The lakehouse is **`postgres_catalog`**: the DuckLake catalog lives in a dedicated Postgres database, query plans run client-side in embedded DuckDB (`ATTACH 'ducklake:postgres:'`), and parquet is read from the object store over httpfs. There is no separate query server. This block only tunes the catalog connection and a few persistence knobs — omit it entirely to keep defaults. ```yaml lakehouse: data_inlining_row_limit: 1000 # catalog_dsn: derived from postgres.url by default; set only to override. ``` | Field | Type | Default | Notes | |---|---|---|---| | `catalog_dsn` | string | derived from `postgres.url` | libpq keyword/value connection string for the DuckLake catalog database, e.g. `dbname=ducklake_catalog host=H port=5432 user=U password=P`. When omitted, the CLI derives it from `postgres.url` by changing only the database name to `ducklake_catalog`. Reuse the deployment's existing Postgres server but keep this as a **dedicated database** (not the application database). Supports `${ENV_VAR}` substitution when provided explicitly. | | `data_inlining_row_limit` | uint | `1000` | DuckLake row threshold for inlining small inserts/deletes into the metadata catalog. Keep this at least as high as `events.max_batch_rows` if event batches should inline; `0` disables inlining. | | `prefix` | string | `lake/` | Object-store prefix where lakehouse parquet data lives. | ## `events` Small-batch event ingestion endpoint (`POST /api/v1/events/{schema}/{table}`). Defaults are tuned so event writes fit under DuckLake's inlining threshold. ```yaml events: enabled: true max_batch_rows: 1000 max_payload_bytes: 1048576 ``` | Field | Type | Default | Notes | |---|---|---|---| | `enabled` | bool | `true` | Enables the event ingest API. | | `max_batch_rows` | uint | `1000` | Maximum events accepted in one request. Keep this less than or equal to `lakehouse.data_inlining_row_limit` for inline writes. | | `max_payload_bytes` | uint | `1048576` | Maximum request body size. | ## `fi` Fi is disabled by default. Enabling it requires kubernetes-sigs Agent Sandbox v0.4.5 CRDs/controller to already be installed in the cluster; `definite doctor` verifies that prerequisite. ```yaml fi: enabled: true web_access: enabled: true # optional; default true web_search: provider: duckduckgo # optional; default duckduckgo api_key: { ... } # SecretRef; required for brave/tavily/serpapi url: https://searxng.internal # searxng provider only sandbox: template_name: definite-fi image: ghcr.io/definite-app/fi-sandbox:0.0.4 runtime_class_name: gvisor # optional; omit for default runtime workspace_size: 10Gi storage_class_name: gp3 # optional max_active_threads: 5 idle_ttl_seconds: 604800 resources: request_cpu: "1" request_memory: 2Gi limit_cpu: "4" limit_memory: 8Gi egress: public_ports: [] # optional; [] = all ports allowed private_cidrs: [] # optional; exact private CIDRs to allow private_ports: [5432] # optional; TCP ports for private_cidrs ``` The API creates one Agent Sandbox `SandboxClaim` per Fi thread and reuses its PVC-backed `/workspace` across runs. Interactive Fi chat sandboxes do not receive object-store or Postgres credentials; query/catalog access goes through the API and lakehouse. Compute-profile SQL workers use the same sandbox template, but receive the lakehouse/object-store query environment they need to run SQL inside the worker pod. For v1, sandbox pods do receive the configured LLM credentials so the Fi agent can call the customer's provider directly from inside the sandbox. ### `fi.sandbox.egress` A Kubernetes `NetworkPolicy` governs what the Fi sandbox can reach. In-cluster traffic (the API pod, DNS, the LiteLLM proxy, the GCP metadata server) is fixed. The default tunable knob is which ports the sandbox may open to the **public internet** — any public IP outside the RFC1918 ranges, which stay blocked so the sandbox cannot dial internal cluster pods/services on arbitrary ports. Operators can also opt in to exact private CIDRs when a sandbox or compute-profile worker must reach a private dependency such as the DuckLake Postgres catalog. | Field | Type | Required | Default | Notes | |---|---|---|---|---| | `egress.public_ports` | list[int] | no | `[]` | Ports the sandbox may reach on public IPs. **Empty list = all ports allowed**, so the agent can connect directly to external databases (Postgres `5432`, MySQL `3306`, etc.) and arbitrary APIs. Set an explicit allowlist (e.g. `[443]`) to restrict it. | | `egress.private_cidrs` | list[string] | no | `[]` | RFC1918 IPv4 or IPv6 ULA CIDRs the sandbox may reach. Empty keeps private ranges blocked. Set exact CIDRs such as `["10.224.0.3/32"]` when compute-profile workers need a private catalog endpoint. | | `egress.private_ports` | list[int] | no | `[5432]` | TCP ports allowed for `private_cidrs`. Defaults to Postgres. | The default is intentionally open: the Fi agent often needs a direct connection to a customer's source database. To lock the sandbox down to HTTPS only, set `public_ports: [443]`. ### `fi.web_access` / `fi.web_search` Fi can search the public web and fetch URLs via two tools — `definite_web_search` and `definite_fetch`. Both run **server-side in the API pod**, not the sandbox, so the API owns egress, size caps, and timeouts. | Field | Type | Required | Default | Notes | |---|---|---|---|---| | `web_access.enabled` | bool | no | `true` | Set `false` for air-gapped installs; the tools are then not registered. | | `web_search.provider` | enum | no | `duckduckgo` | `duckduckgo` \| `searxng` \| `brave` \| `tavily` \| `serpapi`. | | `web_search.api_key` | SecretRef | for keyed providers | — | Required for `brave` / `tavily` / `serpapi`. | | `web_search.url` | string | for `searxng` | — | Base URL of a self-hosted SearXNG instance. | `duckduckgo` is the default because it is free and needs no API key — web search works on a fresh install with nothing to configure. ## `auth` Tagged union by `mode`: ### Local ```yaml auth: mode: local initial_admin_email: admin@example.com # optional initial_admin_password: # optional; enables first admin password login env: INITIAL_ADMIN_PASSWORD ``` ### OIDC ```yaml auth: mode: oidc issuer: https://issuer.example.com client_id: my-client-id client_secret: env: OIDC_CLIENT_SECRET scopes: [openid, email, profile] # optional ``` ## `email` Optional transactional email settings. When configured, `/login` shows a self-service password reset flow, and automation pipelines can send rendered data-app reports with attachments. When unset, `/login` shows the workspace-admin and operator recovery paths instead. ```yaml email: mode: smtp # disabled | smtp | definite_cloud enabled: true from: "Definite " reply_to: "support@example.com" # optional smtp: host: smtp.example.com port: 587 username: smtp-user # optional for trusted relays password: env: EMAIL_SMTP_PASSWORD # optional for trusted relays starttls: true ssl: false definiteCloud: centralApiUrl: https://api.definite.app deploymentId: "" # defaults to license.deploymentId from: hello@definite.app ``` `definite_cloud` is for Definite-managed hosted deployments. Self-managed installs should use `smtp` with a customer-owned relay. See [password-recovery.md](/docs/password-recovery) for behavior and fallback recovery details. ## `llm` Tagged union by `provider`: ```yaml llm: provider: anthropic model: claude-sonnet-5 api_key: { env: ANTHROPIC_API_KEY } # or llm: provider: bedrock region: us-east-1 model: claude-sonnet-4-6 inference_profile_prefix: us # geo prefix of the cross-region profile; # us (default) | eu | apac | au | ... # or llm: provider: vertex project: my-project region: global model: claude-sonnet-5 # or llm: provider: azure_openai endpoint: https://acme.openai.azure.com deployment: gpt-4o api_key: { env: AZURE_OPENAI_API_KEY } ``` ## `serviceAccount` Optional Helm ServiceAccount settings. The chart names the shared ServiceAccount after `deployment.name`; annotations here are rendered onto that shared ServiceAccount. On EKS Bedrock installs, set the IRSA role annotation from Terraform: ```yaml serviceAccount: annotations: eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/definite-bedrock-irsa ``` When S3 uses `object_store.credentials.mode: irsa`, the chart also creates a dedicated `-lakehouse` ServiceAccount for the API and job-runner pods and annotates it with `object_store.credentials.role_arn`. ## `resources` Per-component sizing. All fields optional. ```yaml resources: api: { replicas: 2, cpu: "1", memory: 4Gi } frontend: { replicas: 2, cpu: 500m, memory: 512Mi } job_runner: { replicas: 1, cpu: 500m, memory: 2Gi } ``` There is no separate lakehouse component to size: lakehouse queries run as embedded DuckDB **inside the API and job-runner pods**. Size `api.memory` for interactive Query-page / data-app SQL and `job_runner.memory` for automation and maintenance SQL. For heavy bursty SQL, prefer a [compute profile](/docs/compute-profiles) over permanently fattening these pods. ### Sizing for heavy SQL Lakehouse queries run as embedded DuckDB **inside the API and job-runner pods** (`ATTACH 'ducklake:postgres:'`, parquet over httpfs) — there is no separate lakehouse query pod to size or pin. For steady-state query memory, raise `resources.api.memory` (interactive Query-page / data-app SQL) and `resources.job_runner.memory` (automation + maintenance SQL). For **bursty** heavy SQL — one-off migrations, big joins, full-table re-materializations — prefer a [`compute_profiles`](#compute_profiles) block over permanently fattening the always-on pods. A burst profile spawns a fresh sandbox pod per call (so the upstream DuckDB connection-scoped memory leak does not accumulate) and can pin that pod to a dedicated, scale-to-zero node pool. See [`compute-profiles.md`](/docs/compute-profiles) for the per-cloud node-pool setup (GKE / EKS / Karpenter / AKS) and when to raise the always-on pods vs. add a burst profile. ## `compute_profiles` Named **burst tiers** a user, Fi thread, or pipeline Python step can pick at runtime to land on a bigger pod. Each entry renders its own `SandboxTemplate` and an optional `SandboxWarmPool`. Empty / omitted uses the default sandbox settings from `fi.sandbox.*`. ```yaml compute_profiles: large: resources: requests: { cpu: "4", memory: "16Gi" } limits: { cpu: "8", memory: "32Gi" } node_selector: cloud.google.com/gke-nodepool: definite-burst # EKS / AKS keys differ tolerations: - { key: definite-app/burst, operator: Equal, value: "true", effect: NoSchedule } warm_pool_size: 0 # cold-start; node pool can scale to zero max_concurrent: 2 # attached SQL worker slots worker_idle_ttl_seconds: 300 ``` | Field | Type | Default | Notes | |---|---|---|---| | `resources` | K8s resources map | inherit `fi.sandbox.resources` | Standard `{requests, limits}`. GPUs etc. flow through. | | `node_selector` | `{label: value}` | none | Pins to a specific node pool. See [`compute-profiles.md`](/docs/compute-profiles) for per-cloud label keys. | | `tolerations` | list | none | Required when the pool carries a taint. | | `warm_pool_size` | int | `fi.sandbox.warmPoolSize` | `0` = cold-start; bigger numbers reserve idle pods at the profile's cost. | | `worker_idle_ttl_seconds` | int | `fi.workerTier.idleTtlSeconds` | How long an attached SQL worker stays warm after the last query before the API reaper deletes its claim. | | `workspace_size` | string | `fi.sandbox.workspaceSize` | Per-pod ephemeral PVC. | | `storage_class_name` | string | `fi.sandbox.storageClassName` | StorageClass for the workspace PVC. | | `max_concurrent` | int | none | Maximum attached SQL workers for the profile when worker tier is enabled. Excess queries queue briefly, then return 503. | Profile names must be DNS-label safe (lowercase alphanumeric + hyphens, max 40 chars). The `default` profile is always present — declare it explicitly to override defaults, or omit it to fall back to `fi.sandbox.*`. See [`compute-profiles.md`](/docs/compute-profiles) for the full guide including node-pool setup and a TPC-H recipe. ## `license` ```yaml license: key: { env: DEFINITE_LICENSE_KEY } # Optional. Leave unset unless Definite support tells you to preserve a # known deployment identity during restore or test automation. deploymentId: "00000000-0000-4000-8000-000000000000" # Optional restore/test hook. Must be signed by a key trusted through # telemetry.publicKey or the image-bundled Definite public keys. initialEntitlementJwt: { env: DEFINITE_INITIAL_ENTITLEMENT_JWT } ``` Required for customer-owned/manual licensing. In the default brokered install flow, `definite init` receives a license key from the broker and uses it for the install without printing it. Otherwise, the CLI renders `license.key` into the `definite-secrets` Kubernetes Secret; the `definite-api` pod reads the Secret's `license-key` entry as `LICENSE_KEY` and activates against the central Definite API. **Without a `license` block or externally managed `license-key` Secret entry, the deployment still boots, but it comes up unlicensed and every product API route returns HTTP 403.** `definite init` will print a warning, and `definite doctor` flags the missing block. Advanced installs that use an external secret store may leave `license.key` unset and sync `license-key` into the chart-managed `definite-secrets` Secret instead. The chart wires `LICENSE_KEY` and `LICENSE_INITIAL_ENTITLEMENT_JWT` from that Secret with optional `secretKeyRef`s, so an unlicensed install still starts. Kubernetes reads env vars only at container startup; make sure your external secret controller or a reloader rolls the API pod when the synced license changes. The key is issued by Definite (internally, via `pybe onprem issue-license`). `key` is a [`SecretRef`](#secretref-used-by-many-fields) — supply it as an env var, a file, or (not recommended) an inline literal. The `k8s_secret` SecretRef form is not supported for license fields; external secret store installs should sync `license-key` into `definite-secrets` instead. To license or re-license a running deployment, add or update this block and run `definite upgrade`. Check the live entitlement with `definite license status`. `deploymentId` is an advanced restore/test hook. On a fresh application database, the API adopts it as the stable deployment UUID before activation. Once the deployment has activated, changing `deploymentId` is ignored so the central license binding is not silently moved. `initialEntitlementJwt` is also advanced. On a fresh database, the API verifies the JWT and persists it before trying central activation. This is for restore or controlled test automation, not the normal customer licensing path. ## `telemetry` ```yaml telemetry: enabled: false # opt-in ``` ## `image` Override the container image source for all Definite components. Useful when you've mirrored images into your own registry (Artifact Registry, ECR, ACR, Harbor, etc.). All fields are optional; omit the block entirely to use the release defaults. | Field | Type | Default | Notes | |---|---|---|---| | `registry` | string | release default | Registry + repo prefix; the chart appends `/:`. | | `tag` | string | CLI version | Image tag. Defaults to the version of the `definite` CLI itself, so chart and CLI ship in lockstep. | | `pull_policy` | string | `IfNotPresent` | Kubernetes `imagePullPolicy`. | | `pull_secrets` | string[] | `[]` | Names of `imagePullSecrets` in the deployment namespace. | ```yaml image: registry: us-central1-docker.pkg.dev/acme-prod/definite tag: 0.0.4 pull_policy: IfNotPresent pull_secrets: - artifact-registry-pull ``` ## `SecretRef` (used by many fields) A SecretRef is a tagged union telling the CLI where to find a sensitive value: ```yaml # Read from an environment variable at deploy time field: { env: SOME_ENV_VAR } # Read from a file at deploy time field: { file: /etc/secrets/postgres-password } # Reference an existing Kubernetes Secret field: k8s_secret: name: my-existing-secret key: password # Inline literal (NOT RECOMMENDED — value ends up in Helm release) field: { literal: "plaintext-value" } ``` For `env`, `file`, and `literal` refs the CLI resolves the value to plaintext at deploy time and the chart writes it to a Kubernetes Secret it manages. `k8s_secret` refs point the chart at an existing Secret you already manage with your own tooling (External Secrets Operator, Vault sync, etc.) — note that end-to-end passthrough for `k8s_secret` is partial today; some fields still require `env` / `file` / `literal`. ## Environment variable substitution Anywhere in the config, `${VAR}` is replaced by the value of `VAR` at config load time. Missing variables fail loud — they don't silently produce empty values. ```yaml postgres: url: postgres://definite:${POSTGRES_PASSWORD}@db.internal:5432/definite ``` --- # Network Requirements When you connect a data source — a Postgres database, an HTTP API, a warehouse — the **onprem deployment itself** is the client that opens the connection. The data source must therefore be reachable *from the deployment's network*, not from your laptop. A connection that works from your machine can still fail from the cluster. This is the single most common first-connection failure, and it is invisible: a firewall that silently drops packets looks identical to a slow database. If a connection test hangs and then reports a **timeout**, suspect network reachability before credentials. ## The intra-VPC case (usually fine) If the data source lives in the **same VPC / network as the deployment** — e.g. an RDS instance or a Cloud SQL database in the same project, peered network, or subnet — it is normally reachable with no extra configuration. Internal traffic stays inside the VPC and is not subject to public-internet firewalls. You may still need to: - allow the database's **security group / firewall** to accept traffic from the deployment's subnet or pod CIDR, and - ensure the database listens on an address routable from the cluster (a private IP, not only `localhost`). This is the recommended topology: no public exposure, lowest latency. ## The cross-network case (allowlisting required) If the data source is **outside** the deployment's network — a managed database in a different cloud account, an on-prem database reached over the internet, a third-party API — the deployment's outbound traffic must be permitted to reach it. ### Egress IP The deployment connects out from one or more **egress IP addresses** (the NAT gateway / load balancer IP of the cluster). The data source's firewall must allowlist these IPs. On **Definite-hosted** deployments the egress IP is a reserved static address, shown in **Settings → Workspace → General** (and as a hint when setting up a database integration). It is safe to allowlist permanently — it is reserved for your deployment alone and survives cluster upgrades. On **self-hosted** installs, find the egress IP by running, from inside the deployment, an outbound request to an IP-echo service, or by reading it from your cloud provider's NAT gateway configuration. Treat it as **stable but not permanent** — re-check it if you rebuild networking. To surface it in Settings the same way hosted deployments do, set the `deployment.egressIp` Helm value (comma-separated if several). ### Firewall / security-group allowlisting On the data source side, add an inbound rule that allows the deployment's egress IP(s) to reach the database port (Postgres defaults to `5432`). Without this rule the connection attempt is dropped and surfaces as a timeout. ### VPC peering / private connectivity For production, prefer **VPC peering**, a private link, or a VPN over public-internet allowlisting: - no database port is exposed to the internet, - traffic uses private IPs, and - you avoid maintaining IP allowlists as egress IPs change. Once peered, the connection behaves like the intra-VPC case above. ## SSH bastion / jump host If the database is only reachable through an **SSH bastion** (a jump host with network access to the database, but the database itself is not directly routable), use the Postgres integration's SSH tunnel fields: | Field | Notes | |---|---| | `ssh_host` | Bastion hostname. Setting this enables the tunnel. | | `ssh_port` | Bastion SSH port. Defaults to `22`. | | `ssh_user` | SSH login user on the bastion. Required when `ssh_host` is set. | | `ssh_private_key` | PEM-encoded SSH private key. Required when `ssh_host` is set. Stored encrypted. | | `ssh_key_passphrase` | Optional passphrase if the private key is encrypted. | When configured, the deployment opens an SSH local port-forward to the bastion and connects to the database through it. The bastion must allowlist the deployment's egress IP on its SSH port; the database only needs to be reachable **from the bastion**. Leave all SSH fields blank for directly reachable databases — the tunnel is opened only when `ssh_host` is set. ## TLS / SSL to the database For `sslmode=verify-ca` or `verify-full` against a database that uses a private certificate authority, paste the CA certificate (and, for mutual TLS, the client certificate and key) into the Postgres integration's `sslrootcert` / `sslcert` / `sslkey` fields. These are PEM contents, not file paths; the deployment writes them to short-lived private temp files for the duration of each connection. They have no bearing on network reachability — a `verify-full` connection still needs the firewall rules above. ## Checklist when a connection fails 1. **Timeout / "could not connect"** → network reachability. Check the data source's firewall / security group allowlists the deployment's egress IP, or that intra-VPC routing and security groups permit the cluster's subnet. If access is via a bastion, set the SSH tunnel fields. 2. **"could not translate host name" / DNS error** → the hostname does not resolve from inside the cluster. Use an IP or a name resolvable by the deployment's DNS. 3. **Authentication / permission errors** → the connection *succeeded*; the problem is credentials or grants, not the network. 4. **TLS / certificate errors** → the connection reached the database but certificate verification failed. Check `sslmode` and the `sslrootcert` / `sslcert` / `sslkey` fields. --- # Permissions Definite on-prem has a layered permission model. The layers are independent — a user's application role does not grant data access, and sharing a resource does not change anyone's role. 1. **Application roles** — what a user can *do* in the app. 2. **Content permissions** — who can see and edit each app, thread, project, query, automation, agent, or integration. 3. **Data access** — which lakehouse tables a user's queries may read. 4. **Per-user query capabilities** — whether a user may submit raw SQL or use Fast Explorer. The deployment is single-tenant: one workspace, no teams. Every check is enforced server-side in the API — the API is the only gateway to the lakehouse, so there is no way around it. **Admins bypass all content and data-access checks.** All three layers are managed from three equivalent surfaces: the web UI (**Settings → Members & access**), the [`definite run permission`](/docs/cli) CLI, and Fi's `permissions` skill (admin sessions only). ## 1. Application roles Every user has exactly one role: | Role | Can do | |---|---| | `viewer` | Read and run content shared with them. Can create and operate their own read-only Fi threads, but cannot create or modify other content. | | `editor` | Everything a viewer can, plus create, edit, and share their own apps, threads, projects, saved queries, automations, and agents. | | `admin` | Everything. Manages members and roles, integrations and their credentials, data-access roles, and workspace settings. Bypasses all content and data-access checks. | The role is fixed per user — there is no custom-role builder. Only admins can change roles, and the system refuses to demote the **last** remaining admin. - **UI:** Settings → Members & access → Members. Each row has a role selector (your own row is locked to prevent self-lockout). - **CLI:** `definite run permission users`, then `definite run permission set-role --role editor`. ## 2. Content permissions Every user-facing resource — **app, thread, project, saved query, automation, agent, integration** — is **private to its creator** (plus admins) when created. Sharing is per-resource: - **Private** — only the creator and admins can see it. - **Shared with a user** — `view` (open/run) or `edit` (also modify and re-share). The creator always keeps edit access. - **Workspace-visible** — every authenticated user can `view` it. The workspace grant carries its own access level: `view`, or `edit`, which also lets users with the `editor` or `admin` role modify and run the resource. Users with the `viewer` role never gain edit from the workspace grant. Integrations are a special case: they can be shared `view` only — their public metadata becomes visible, but **decrypting or testing credentials, and creating/editing integrations, stays admin-only** regardless of any grant. A workspace `edit` grant on a **project** applies to the project itself only. It does not cascade edit access to the project's linked contents — those still require an elevated project membership or a named grant. The default for *newly created* content is configurable per deployment — see [Deployment settings](#deployment-settings). **Support-authored content is an exception.** Content created by the built-in support user (`fi@definite.app`, used by Fi support sessions) is always created workspace-shared with `edit` access (`view` for integrations), regardless of `DEFAULT_CONTENT_VISIBILITY`. Support builds content for the customer, so customer editors can run and maintain it. Admins can demote the workspace grant to `view` or remove it from the Share dialog. On upgrade, a one-shot startup repair applies the same rule to support-authored content that already exists; the repair runs exactly once, so it never re-upgrades a grant an admin demoted. - **UI:** every resource page has a **Share** button that opens a dialog — toggle private ⇄ workspace, set the workspace access level (Viewer/Editor), add/remove people, set each person's access level. (Agents are shareable via the API and CLI but do not yet have a Share button in the UI.) - **CLI:** `definite run permission grants ` to see current access; `share` / `unshare` to change it. `` is one of `app`, `thread`, `project`, `query`, `automation`, `integration`, `agent`; `` is the resource's primary-key id. ## 3. Data access Data access controls which **lakehouse tables** a user's SQL can read. It is **default-deny**: a user with no data-access grant can query nothing. Grants are grouped into named **data-access roles**: - A **data-access role** holds a set of `(schema, table)` grants. `*` is the only wildcard — `sales.*` is every table in the `sales` schema, `*.*` is every table. - A user may hold **multiple** data-access roles; their effective access is the **union** of all their roles' grants. - One role can be marked **default** — new users are auto-assigned it. These roles are entirely separate from the viewer/editor/admin application roles above. ### How it is enforced When a non-admin runs SQL (the Query page, a Fi run, the catalog), the API parses the statement with DuckDB's own parser before executing it: - Non-`SELECT` statements (INSERT/CREATE/ATTACH/COPY/…) are rejected outright. - Every base table the query references is checked against the caller's resolved grants; the query is refused if any table is not granted. - The catalog (`/catalog/tables`) is filtered to the tables the caller may read, so the data catalog only shows what they can actually query. Admins bypass all of this. `information_schema` / `pg_catalog` are always readable; DuckLake internal metadata is admin-only. - **UI:** Settings → Members & access → Data Access — create roles, edit their table grants, assign users. - **CLI:** `definite run permission data-access roles | create-role | update-role | delete-role | set-grants | role-users | assign | unassign`. ## 4. Per-user query capabilities Administrators can independently toggle two capabilities from each active member's overflow menu in **Settings → Members & access**: - **Raw SQL** controls direct user-authored SQL through Query and CSV export, `definite run query`, `definite connect`, Fi, and MCP. It defaults on for existing and new users. When off, semantic queries and shared data apps remain available; Fi uses only certified semantic models. - **Fast Explorer** controls the browser-side Arrow/DuckDB table explorer. It remains independent from Raw SQL, so changing one never changes the other. Raw-SQL denials are recorded in the audit log as `query.raw_sql.denied` without storing the submitted SQL text. The Raw SQL capability applies to all application roles, including admins and API tokens owned by the user. ## Deployment settings Three process-level settings tune the defaults. They are read from environment variables on the `definite-api` container (pydantic-settings). They are **not** yet first-class `config.yaml` keys — set them via a Helm values override on the api Deployment's env, or leave the defaults. | Env var | Default | Effect | |---|---|---| | `DEFAULT_CONTENT_VISIBILITY` | `private` | Visibility for newly created content. `private` = creator + admins only; `workspace` = an everyone-`view` grant is added on creation. Support-authored content ignores this setting and is always workspace-shared with `edit` (see above). | | `DATA_ACCESS_DEFAULT_ROLE` | _(empty)_ | Name of the data-access role auto-assigned to new users. Empty = new users get no data access until an admin grants a role. Created on startup if it does not exist. | | `DATA_ACCESS_DEFAULT_SCHEMA` | `main` | Schema used to resolve unqualified table names when checking data-access grants. | Content that existed before the permission system was introduced is backfilled workspace-visible, so an upgrade never hides anything that was previously visible. ## Fi Viewers can create their own Fi threads. Viewer runs use a read-only tool set: semantic queries, documentation, optional web access, and presentation tools; they never receive shell/file mutation, integration-secret, or platform- mutation tools. If Raw SQL is enabled for that viewer, bounded SQL and grant-filtered catalog tools are also available. When an **admin** uses Fi, Fi can manage all permission layers conversationally — "make Priya an editor", "share the revenue app with the team", "let the analysts query `sales.orders`". Fi drives the same `definite run permission` CLI under the hood. The skill is surfaced only to admin sessions; for any other user the underlying API calls are rejected anyway. See also: [CLI reference → `definite run permission`](/docs/cli). --- # Compute Profiles Compute profiles are **named burst tiers** the operator declares in `config.yaml`. A user, a Fi thread, or a pipeline Python step picks a profile by name at run time, and the workload runs on a Kubernetes pod sized for that tier — usually on a dedicated node pool that scales to zero when idle, so big compute costs nothing while nobody's using it. The deployment ships with one profile, **`default`**, sized at the small always-on `fi.sandbox.resources` defaults. The operator adds bigger profiles (`large`, `xlarge`, `gpu`, …) by declaring them in `config.yaml`. ## When to use a profile | Use case | Profile path | What runs where | |---|---|---| | Heavy Python step in an automation (pandas joins, ML training, dbt-style transforms) | `python` step `config.compute_profile` | Job-runner leases a Sandbox of that profile and POSTs the script + requirements to it; the script runs on the burst pod, not in the job-runner. | | SQL transformation model or automation SQL step | Transformation project/model **Compute** setting, or `sql` step `config.compute_profile` | The generated automation step carries the profile. Default runs on the job-runner's attached DuckLake connection; non-default dispatches through the burst SQL sandbox path. | | Scheduled / ad-hoc DuckLake maintenance (expire_snapshots, cleanup_old_files, compact, …) | **Settings → Maintenance → Compute profile** (schedule-level), or `compute_profile` on `POST /api/v1/lakehouse/maintenance/runs` | The profile is stamped onto every maintenance step. Default runs in the job-runner pod's attached DuckLake connection; non-default runs each `ducklake_*` / `CHECKPOINT` statement on a disposable sandbox. | | Heavy data-app dashboard query | App-level `"compute_profile"` in the app's `app.json` manifest | Each SQL resource query dispatches to a burst sandbox of that tier (requires Fi). Falls back to the API pod's attached DuckLake connection when the profile can't be honored. **Interactive** — see the cold-start caveat below. | | Fi session that crunches a big dataset in the agent's `bash` tool | Thread menu **Compute profile**, or `compute_profile` field on `POST /api/v1/fi/threads/{id}/runs` | A fresh Fi sandbox is bound to the profile's `SandboxTemplate`; the agent's `bash` and tool calls run on that pod for the active sandbox session. Existing live sandboxes keep their current profile until released, restarted, or reaped. | | Heavy ad-hoc SQL — TPC-H joins, migrations, full-table re-materializations | `compute_profile` field on `POST /api/v1/queries` | Burst pod runs DuckDB directly against the lake catalog (`ATTACH 'ducklake:postgres:'`); each call gets a fresh process so DuckDB's connection-scoped memory leak (duckdb/duckdb#15176, #18031) cannot accumulate. | The `/api/v1/queries` endpoint accepts `compute_profile` from every caller (SDK, frontend dropdown, CLI). Default profile runs on the API pod's embedded DuckLake connection — which attaches the Postgres catalog and reads parquet directly from object storage over httpfs. A non-default profile **dispatches the query to a disposable burst sandbox** chosen by `compute_profiles.` (issue #458). See [Running heavy SQL workloads](#running-heavy-sql-workloads) for the cold-start / warm-pool tradeoff and when to bump the API/job-runner sizing vs. add a burst profile. > **Note** — `sql`, `python`, and `maintenance` automation steps honor > `config.compute_profile` via the burst-sandbox path. The three sync step > types (`pg_sync`, `adbc_sync`, `mssql_sync`) honor it differently: a > non-default profile runs the **whole sync step as a dedicated Kubernetes > Job** sized by the profile — see [Sync-executor Jobs](#sync-executor-jobs) > below. (With `jobRunner.syncJobs.enabled: false`, pg_sync falls back to > its older burst-sandbox path for portable sources, and `adbc_sync` / > `mssql_sync` fall back to running in-pod.) ### Sync-executor Jobs Sync steps are where the *run-to-completion* workloads live (full-history backfills, big catch-ups, forced full refreshes), and they get a different surface than the *service-like* burst sandboxes: a `batch/v1` Job per step (#710). The profile contributes the same scheduling triple — `resources`, `node_selector`, `tolerations` — so a profile name means the same hardware on either surface. The pool/lifecycle knobs (`warm_pool_size`, `worker_idle_ttl_seconds`, `max_concurrent`) don't apply to Jobs: there is no warm pool to keep (cold-start is noise against a multi-hour run) and no idle state to reap — the pod ends when the sync ends, and the burst node pool scales back to zero. What this buys over running the same sync on a burst sandbox: - no sandbox idle reaper and no single multi-hour RPC to hold open; - pod-death restarts come free (`backoffLimit`) and resume from the sync's persisted chunk checkpoint / watermark; - it works with Fi disabled (core Kubernetes only), and with SSH-bastion / pasted-cert sources (the tunnel opens inside the executor pod); - DuckDB inside the executor is memory-bounded by the *profile's* limits. Job-level knobs (`jobRunner.syncJobs.{enabled,activeDeadlineSeconds,backoffLimit}`) live in `values.yaml`; see `docs/automations.md` → "Sync-executor Jobs" for the full behavior. ### Maintenance jobs The managed maintenance schedule and ad-hoc maintenance runs are **schedule-level**: one profile applies to every step in the run (set it in **Settings → Maintenance → Compute profile**, or pass `compute_profile` to `POST /api/v1/lakehouse/maintenance/runs`). The API validates the name against the registry at write time and stamps it onto each step's `config`. At run time the job-runner dispatches each maintenance statement to a disposable sandbox of that tier, exactly like a `sql` step. Leave it on `default` to keep maintenance running in-pod on the job-runner's attached DuckLake connection. ### Data apps A data app opts into burst by adding a top-level `"compute_profile"` to its `app.json` manifest: ```json { "version": 2, "name": "Heavy Dashboard", "compute_profile": "large", "resources": { "...": "..." } } ``` Every SQL resource the app serves then runs on a `large` sandbox instead of the API pod's embedded DuckLake connection. The name is validated against the registry on upload. Two caveats specific to data apps: - **Cold-start latency.** Dashboard queries are interactive (they fire on load and on filter changes). With `warm_pool_size: 0` the first query after an idle period pays the pod cold-start. Give a data-app profile a `warm_pool_size` ≥ 1 if responsiveness matters. - **Type fidelity.** The burst sandbox returns JSON rows, which are converted back to Arrow with inferred types — a `DATE` column comes back as a string, not a date. Prefer the default profile for apps whose charts depend on precise column types, or cast columns explicitly in the resource SQL. When the profile can't be honored (Fi disabled or unknown name) the query silently falls back to the API pod's embedded DuckLake connection so a dashboard never hard-fails over its profile choice. ## Declaring profiles (operator) `compute_profiles:` is a top-level map in `config.yaml`. Each entry is a name plus the resources, scheduling hints, and warm-pool size that should back it. ```yaml compute_profiles: large: resources: requests: { cpu: "4", memory: "16Gi" } limits: { cpu: "8", memory: "32Gi" } node_selector: # Whatever label identifies your burst node pool — see below. cloud.google.com/gke-nodepool: definite-burst tolerations: - { key: definite-app/burst, operator: Equal, value: "true", effect: NoSchedule } warm_pool_size: 0 # cold-start; pool scales to zero when idle max_concurrent: 2 # SQL worker slots for this profile worker_idle_ttl_seconds: 300 xlarge: resources: requests: { cpu: "16", memory: "64Gi" } limits: { cpu: "32", memory: "128Gi" } node_selector: cloud.google.com/gke-nodepool: definite-burst-xl tolerations: - { key: definite-app/burst-xl, operator: Equal, value: "true", effect: NoSchedule } warm_pool_size: 0 max_concurrent: 1 worker_idle_ttl_seconds: 300 ``` Apply with `definite upgrade --config config.yaml`. The chart renders one `SandboxTemplate` per profile and one optional `SandboxWarmPool`. Profile names must be DNS-label safe (lowercase alphanumeric + hyphens, max 40 chars). ### Field reference | Field | Type | Default | Notes | |---|---|---|---| | `resources` | K8s resources map | `fi.sandbox.resources` | Standard `{requests, limits}` map. GPUs etc. flow through unchanged — the chart `toYaml`s it. | | `node_selector` | `{label: value}` | none | Pins the pod to a specific node pool. See [Per-cloud node pool setup](#per-cloud-node-pool-setup). | | `tolerations` | list | none | Required when the pool carries a taint. Standard K8s shape. | | `warm_pool_size` | int | `fi.sandbox.warmPoolSize` | `0` = cold-start (no pre-warmed pods, pool scales to zero). Bigger numbers reserve idle pods at this profile's cost — usually keep at `0` for non-default profiles. | | `worker_idle_ttl_seconds` | int | `fi.workerTier.idleTtlSeconds` | How long an on-demand attached SQL worker stays warm after its last query before the API reaper deletes its SandboxClaim. Separate from warm pools. | | `workspace_size` | string | `fi.sandbox.workspaceSize` | Per-pod ephemeral PVC for `/workspace`. Bump for jobs that write large intermediate files. | | `storage_class_name` | string | `fi.sandbox.storageClassName` | StorageClass for the workspace PVC. | | `max_concurrent` | int | none | Maximum attached SQL workers for the profile. When the worker tier is enabled, concurrent profiled queries fan out across these slots; excess queries queue briefly, then return 503. | A profile with no `node_selector` schedules on the default node pool — useful for a slightly bigger sandbox that doesn't need its own pool. ## Editing a profile's size at runtime (Settings → Compute) `config.yaml` is the source of truth for *which* profiles exist and their baseline size. For a quick CPU/memory change without a redeploy, an **admin** can override a profile's `resources` from **Settings → Compute** (or the API). `node_selector`, `tolerations`, warm-pool size, and the profile *set* remain Helm-only — runtime overrides cover sizing only. ```bash # Set large to 3→6 CPU / 12→24Gi. At least one of requests/limits cpu/memory # is required. Admin token only. curl -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -d '{"requests":{"cpu":"3","memory":"12Gi"},"limits":{"cpu":"6","memory":"24Gi"}}' \ https://onprem.example.com/api/v1/compute-profiles/large/resources # → {"profile":{...,"resources_overridden":true}, "reconciled":true, "detail":null} # Revert large to its config.yaml size. curl -X DELETE -H "Authorization: Bearer $TOKEN" \ https://onprem.example.com/api/v1/compute-profiles/large/resources ``` How it works: - The override is **persisted in Postgres** (`definite.compute_profile_overrides`) — it is the source of truth, not the live cluster object. - The API immediately **reconciles** it onto the profile's live `SandboxTemplate` (`spec.podTemplate.spec.containers[0].resources`). `reconciled:false` (with a `detail` note) means Fi is disabled or the template isn't rendered yet — the size is still saved and applies later. - Only **new** sandboxes pick up the change; warm/running pods keep their current size. With `warm_pool_size: 0` (the burst default) there are no warm pods, so the next claim gets the new size. - On **API startup** the persisted overrides are re-applied onto the templates, so they survive a `helm upgrade` (see below). ### Overrides and `helm upgrade` Because the API takes server-side-apply ownership of the overridden `resources` field, a plain `helm upgrade` (Helm v4 / SSA) **fails with a field-ownership conflict** on that field. `definite upgrade` already passes `--force-conflicts`, which lets the chart reclaim the field (resetting it to the `config.yaml` size); the API's boot-time reconcile then re-applies the persisted override seconds later. If you invoke `helm upgrade` directly, add `--force-conflicts` when any compute-profile size override is active. ## Per-cloud node pool setup The feature is cloud-agnostic — the chart uses standard `nodeSelector` / `tolerations`. Only the **label keys** for `node_selector` change per cloud. ### GKE (managed node pool) ```bash gcloud container node-pools create definite-burst \ --cluster=definite --region=us-central1 \ --machine-type=n2-standard-16 \ --node-taints=definite-app/burst=true:NoSchedule \ --enable-autoscaling --num-nodes=0 --min-nodes=0 --max-nodes=4 ``` In `config.yaml`: ```yaml node_selector: cloud.google.com/gke-nodepool: definite-burst ``` GKE Autopilot autoscales managed node pools down to zero — the burst pool costs nothing while idle and cold-starts in ~2 minutes the first time it's used in a day. ### EKS (managed node group) ```bash eksctl create nodegroup --cluster=definite \ --name=definite-burst --instance-types=m5.4xlarge \ --node-taints=definite-app/burst=true:NoSchedule \ --asg-access --node-min=0 --node-max=4 ``` In `config.yaml`: ```yaml node_selector: eks.amazonaws.com/nodegroup: definite-burst ``` ### EKS (Karpenter — recommended for burst) Karpenter spins nodes up in ~30s and tears them down when the last pod schedules off, which is the best fit for "burst, scale fully to zero". `NodePool` CR: ```yaml apiVersion: karpenter.sh/v1 kind: NodePool metadata: name: definite-burst spec: template: spec: taints: - key: definite-app/burst value: "true" effect: NoSchedule requirements: - { key: karpenter.sh/capacity-type, operator: In, values: [on-demand] } - { key: node.kubernetes.io/instance-type, operator: In, values: [m5.4xlarge, m5.8xlarge] } disruption: consolidationPolicy: WhenEmpty consolidateAfter: 30s ``` In `config.yaml`: ```yaml node_selector: karpenter.sh/nodepool: definite-burst ``` ### AKS (managed node pool) ```bash az aks nodepool add --cluster-name definite \ --name burst --node-vm-size Standard_D16s_v5 \ --node-taints definite-app/burst=true:NoSchedule \ --enable-cluster-autoscaler --min-count 0 --max-count 4 ``` In `config.yaml`: ```yaml node_selector: agentpool: burst ``` The chart will happily render a profile even if no matching node pool exists yet — the sandbox pods just sit `Pending` until you create one. `kubectl get pods -n definite -l app.kubernetes.io/component=fi-sandbox` makes it obvious. ## Using a profile at runtime ### CLI ```bash # SQL — non-default profiles run the query on a burst sandbox pod. definite run query --profile large 'SELECT count(*) FROM giant_table' ``` ### Transformation projects On the Transformations page, deployments with more than one profile show a project-level **Compute** dropdown and per-model overrides. Saving either setting writes a new transformation manifest version and recompiles the linked automation so each generated SQL step contains the actual `config.compute_profile` it will run with. The CLI can set the same project default at apply time: ```bash definite transform apply transformations --name finance-marts --compute-profile large ``` Manifest/API callers can set the same fields directly: ```json { "name": "finance marts", "compute_profile": "large", "models": [ { "name": "stg_orders", "sql": "select * from raw.orders" }, { "name": "orders", "sql": "select * from staging.stg_orders", "depends_on": ["stg_orders"], "compute_profile": "xlarge" } ] } ``` ### HTTP API ```bash # Listing — workspace-wide; any authenticated user can see the registry. # Each profile carries its effective `resources` (the admin override when set, # else the chart-rendered size) and `resources_overridden`. `editable` is true # when this deployment can persist per-profile size overrides. curl -H "Authorization: Bearer $TOKEN" \ https://onprem.example.com/api/v1/compute-profiles # → {"profiles":[ # {"name":"default","is_default":true,"max_concurrent":null, # "resources":{"requests":{"cpu":"250m","memory":"1Gi"}, # "limits":{"cpu":"4","memory":"8Gi"}}, # "resources_overridden":false}, # {"name":"large","is_default":false,"max_concurrent":2, # "resources":{"requests":{"cpu":"4","memory":"16Gi"}, # "limits":{"cpu":"8","memory":"32Gi"}}, # "resources_overridden":false}], # "default":"default","editable":true} # Set a Fi thread's preferred profile. The next fresh sandbox for that thread # uses the matching SandboxTemplate. curl -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -X PATCH \ -d '{"compute_profile":"large"}' \ https://onprem.example.com/api/v1/fi/threads/$TID # One-off Fi run override on a large sandbox. curl -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -d '{"prompt":"crunch a big dataset", "compute_profile":"large"}' \ https://onprem.example.com/api/v1/fi/threads/$TID/runs # Unknown profiles 400 with a helpful message: # {"detail":"unknown compute profile 'xxlarge'. Known: default, large"} ``` ### Pipeline Python step A `python` step gains an optional `config.compute_profile`. When set to a non-default profile, the job-runner skips the in-pod subprocess path and instead leases a Sandbox of that profile, POSTs the script + requirements to its `/python-jobs` RPC, and tears the claim down when the step finishes. Set `config.attach_lake: true` when the script needs `definite_lakehouse.query()`, `write_table()`, or a direct DuckDB/DuckLake attach. That opt-in forwards `LAKEHOUSE_*` and the active object-store credentials to the sandbox. Python steps without it can still burst onto a compute profile, but they do not receive lake credentials unless the field is omitted and the resolved script imports or mentions `definite_lakehouse` (backward compatibility for older generated sync definitions). ```json { "id": "tpch-queries", "type": "python", "config": { "script_name": "tpch_q1_q22", "compute_profile": "large", "attach_lake": true } } ``` ### Frontend The Query page shows a small **Compute** dropdown next to the Run button **when more than one profile is configured**. Single-tier deployments (no `compute_profiles:` in `config.yaml`) see no UI change. ## Running heavy SQL workloads `POST /api/v1/queries` with a non-default `compute_profile` dispatches the query to a disposable burst sandbox (issue #458). Each call: 1. Leases a fresh `SandboxClaim` against the profile's `SandboxTemplate` (`definite-fi-`, label `definite.app/compute-profile=`). 2. Waits for the pod's RPC to come up, then POSTs the SQL to `/sql-queries`. 3. Inside the pod, **spawns a fresh `python` subprocess** that opens its own embedded DuckDB connection, attaches the lake (`ATTACH 'ducklake:postgres:'`), runs the query, prints a JSON envelope, and exits. 4. Tears the claim down on the way out — success, SQL error, or pod failure all hit the same `delete_claim` in `finally`. The subprocess-per-call isolation is the key: DuckDB's connection-scoped memory leak ([duckdb/duckdb#15176][leak-1], [#18031][leak-2]) accumulates ~564 MiB per `INSERT … SELECT` batch on a long-lived connection. A fresh process every call gives it nowhere to accumulate, which is the leg the opinionroute `transactiondata` migration was missing. ### How burst SQL runs the query Because the lakehouse runs the query plan on the caller, the burst pod `ATTACH 'ducklake:postgres:'` reads catalog metadata straight from the dedicated `ducklake_catalog` Postgres database and runs the query plan **locally in its own embedded DuckDB process**, reading parquet over httpfs. That client-side-compute model is what gives burst SQL its leak isolation: a fresh process per call has nowhere for the connection-scoped leak to accumulate. > **Credential note.** Because the query plan runs on the caller, the burst > compute pods need both **object-store credentials** (httpfs parquet reads) > and the **catalog connection** (the `catalog_dsn`). The API forwards these to > the sandbox automatically. On EKS, S3 IRSA removes static keys from the > API/job-runner pods; if you also run burst compute against S3, make sure the > shared Fi sandbox ServiceAccount can read the lakehouse bucket too, or keep > using the static S3 fallback for those sandbox workloads. | Cold-start surface | What to do | |---|---| | First call to an unused profile (no warm pod) | 5–30 s of pod scheduling + image pull. Fine for migrations; rough for an interactive Query page. | | You want interactive burst SQL with low latency | Set `warm_pool_size: N` on the profile so claims bind in milliseconds. Each call still spawns a fresh subprocess inside the pod, so the leak isolation is preserved even though the pod is reused. | | One-off heavy job, no concurrency | `warm_pool_size: 0`. Pool scales to zero between jobs. | [leak-1]: https://github.com/duckdb/duckdb/issues/15176 [leak-2]: https://github.com/duckdb/duckdb/issues/18031 ### Worker tier The dispatch above spawns a **fresh `python` subprocess per call** inside the burst pod — a new DuckDB connection that re-`ATTACH`es the lake and re-warms its parquet/metadata cache every query. That's exactly what defeats the connection-scoped leak, but it also throws away the warm cache and pays the ATTACH cost on every query. The **worker tier** trades a little of that isolation back for warmth. With ```yaml fi: workerTier: enabled: true idleTtlSeconds: 300 reaperIntervalSeconds: 60 ``` a non-default `compute_profile` query routes to a bounded pool of **long-lived attached workers** in the sandbox. Each worker `ATTACH`es the lake **once** and serves queries against the same warm connection, so repeat queries skip the ATTACH and reuse cached parquet/metadata. `max_concurrent` controls how many worker slots a profile may have; a profile with `max_concurrent: 4` can run four profiled queries at once before later queries queue. The worker tier is enabled by the default Helm values. Set `fi.workerTier.enabled: false` to keep the one-shot subprocess-per-call path. The credential model is identical — the lake env is still forwarded per request exactly as today. On-demand workers are not permanent. After the last query, a worker stays warm for `worker_idle_ttl_seconds` (or `fi.workerTier.idleTtlSeconds`, default 300s), then the API reaper deletes its SandboxClaim. With `warm_pool_size: 0`, this gives cold-start-on-first-use, warm-through-burst, then scale-back-to-zero when idle. To stay safe against DuckDB's connection-scoped leak, the worker **recycles its connection on a cadence** (between queries, never mid-query): it closes and re-`ATTACH`es once it has served enough queries, scanned enough bytes, or grown its RSS past a fraction of the pod's memory limit. The thresholds are chart defaults (`fi.workerTier.recycleQueries` / `recycleBytes` / `recycleRssFraction`) rendered onto the sandbox pod and rarely need tuning. ### Warm schedules (business-hours warm windows) Scale-to-zero means the **first** query after an idle gap pays the full cold start — on autoscaled clusters that's node provisioning plus a fresh workspace volume, often 1–2 minutes for big profiles. When a team hits the same profile every weekday morning (a heavy data app on `large`, say), declare a **warm schedule** instead of eating that cold start daily: ```bash # Keep one large worker pre-started Mon–Fri 6:00–18:00 New York time. curl -sS -X PUT "$BASE/api/v1/compute-profiles/large/warm-schedule" \ -H "Authorization: Bearer $ADMIN_TOKEN" -H "Content-Type: application/json" \ -d '{ "windows": [{"days": ["mon","tue","wed","thu","fri"], "start": "06:00", "end": "18:00"}], "timezone": "America/New_York", "min_warm": 1 }' # → {"profile":"large","warm_schedule":{...},"active":true, # "detail":"Saved. The warm keeper applies this on its next tick (~1 minute)."} # Read it back (any authenticated user; `active` = a window is open now). curl -sS "$BASE/api/v1/compute-profiles/large/warm-schedule" \ -H "Authorization: Bearer $TOKEN" # Remove it — workers drain via the normal idle TTL. curl -sS -X DELETE "$BASE/api/v1/compute-profiles/large/warm-schedule" \ -H "Authorization: Bearer $ADMIN_TOKEN" ``` While any window is active, the API's warm-schedule keeper (same cadence as the worker reaper) **pre-starts `min_warm` worker slots** for the profile and the idle reaper will not reap them; the first query of the morning lands on an already-attached warm worker. Outside every window nothing is protected — the normal `worker_idle_ttl_seconds` drains the tier back to zero after the last real query, so a query still running at the window's end is never killed mid-flight. Semantics worth knowing: - **Windows are same-day** (`start < end`, minute precision, `HH:MM` 24h) and evaluated in the schedule's IANA `timezone` (DST handled). Express an overnight span as two windows. Up to 16 windows per profile. - **`min_warm` is clamped to the profile's `max_concurrent`.** PUT rejects a floor above capacity; if capacity later shrinks, the keeper clamps at enforcement time. - **Admin-only to write; anyone can read.** Writes are audited (`compute.profile.warm_schedule.*`). The schedule also appears on `GET /api/v1/compute-profiles` (`warm_schedule`, `warm_schedule_active`) and the live floor on `GET …/{name}/worker-status` (`warm_floor`). - **It's declarative, not fired.** There is no missed-run state: a restarted API re-evaluates the window on the next keeper tick (~60s) and converges — same model as the reaper itself. - **Cost:** a warm window is billed like any running worker pod for the whole window. One `large` (8 CPU / 32Gi) worker kept warm 6:00–18:00 Mon–Fri is ~60 pod-hours/week — size `min_warm` and the window accordingly. - The `default` profile takes no schedule (it runs inside the API pod; there is nothing to pre-start). ### When to bump the always-on pods vs add a burst profile Lakehouse queries run as embedded DuckDB inside the API and job-runner pods, so the "baseline" knob is those pods' memory, not a separate lakehouse pod. | Symptom | Right knob | |---|---| | Steady-state interactive query load is hitting the API pod's `memory` limit | Raise `resources.api.memory` (and `cpu` if needed). Sizes the interactive baseline. | | Steady-state automation / maintenance SQL is hitting the job-runner's `memory` limit | Raise `resources.job_runner.memory` (and `cpu` if needed). | | One job (migration, big join) blows the pod when it runs but the baseline is fine | Add a `compute_profiles.` block sized for that job, then call it from `/api/v1/queries` (or from the script). The always-on pods stay cheap, and the burst pod can pin a bigger, scale-to-zero node pool (see [per-cloud setup](#per-cloud-node-pool-setup)). | | Long-running `INSERT … SELECT` loops OOM a pod after a few batches | The DuckDB connection-scoped leak. Move each batch to a burst profile — fresh subprocess per call resets the leak. | ### How SQL compute lands What determines where SQL compute lands is the ATTACH the *client* uses. The lakehouse is `postgres_catalog`: - **`ATTACH 'ducklake:postgres:' AS LAKE (DATA_PATH '...')`** — DuckLake is attached on the client with its **Postgres catalog backend**: catalog metadata lives in a dedicated `ducklake_catalog` Postgres database (reusing the deploy's existing Postgres server), and parquet reads + the query plan run *locally on the caller* in embedded DuckDB via httpfs. Compute scales with whatever pod runs the query. The CLI derives `lakehouse.catalog_dsn` from `postgres.url` when omitted, changing only dbname to `ducklake_catalog`. This is the pattern [ducklake#1151][ducklake-1151] added on 2026-05-12 and [DuckDB 1.5.3][duckdb-153] (released 2026-05-20) wires up end-to-end. Because the query plan always runs on the caller, **burst SQL and compute profiles do not require a separate lakehouse service** — the API/job-runner pod runs `default`, and a non-default profile runs the same ATTACH in a sandbox pod. The worker tier reuses attached workers when enabled; one-shot burst SQL leases a fresh pod per query when the worker tier is disabled. The CLI derives the catalog DSN and the chart wires the API + job-runner setup SQL to this ATTACH form (plus a `CREATE SECRET store_creds (...)` for httpfs reads). See the [`config.md` lakehouse section](/docs/config#lakehouse). If the DuckLake Postgres catalog resolves to a private RFC1918 or IPv6 ULA IP, add an exact sandbox egress allowlist in `fi.sandbox.egress.private_cidrs` so the profile's sandbox or worker pod can reach it. The chart does not derive this from the secret DSN; NetworkPolicy `ipBlock` rules need operator-supplied CIDRs. The DuckLake Postgres catalog is multi-writer and battle-tested, so there are no concurrency/maintenance beta gaps to work around. [ducklake-1151]: https://github.com/duckdb/ducklake/pull/1151 [duckdb-153]: https://duckdb.org/2026/05/20/announcing-duckdb-153 ### Run heavy SQL with a profile-bound Python step Another way to run a heavy SQL workload is to wrap it in a Python step (or Fi run) with `compute_profile: large`. The sandbox image has DuckDB available, and Python steps can opt into lake access with `attach_lake: true`. The SDK (`definite_lakehouse`) exposes a `write_table` that handles >50k-row writes through staging. The script runs on the burst node, attaches the DuckLake Postgres catalog, reads inputs straight from object storage over httpfs, and writes results back to the lake. ### Example: TPC-H benchmarks Generate TPC-H data once, then run the 22 queries on a burst pod: ```python # automation_scripts/tpch_gen.py — generates SF=10 TPC-H data and writes it # to the lake. Run this once as a pipeline step with compute_profile: large. import duckdb from definite_lakehouse import write_table con = duckdb.connect(":memory:", config={"memory_limit": "28GB"}) con.execute("INSTALL tpch; LOAD tpch; CALL dbgen(sf=10)") for table in ("nation", "region", "part", "supplier", "partsupp", "customer", "orders", "lineitem"): df = con.execute(f"SELECT * FROM {table}").fetch_arrow_table() write_table(name=f"tpch.{table}", arrow_table=df, mode="replace") print("TPC-H SF=10 written to lake") ``` ```python # automation_scripts/tpch_run.py — runs the 22 TPC-H queries against the # DuckLake-backed tables, on the same burst profile. We attach the DuckLake # Postgres catalog directly (the same path the API uses) and read parquet # from the object store over httpfs, then time each query. # # Easiest path: let the SDK build the attach for you, which reads # LAKEHOUSE_CATALOG_DSN / LAKEHOUSE_DATA_PATH and the active store creds # (all forwarded when attach_lake: true) and wires up the store secret. import json, time from definite_lakehouse import attach # returns the configured DuckDB conn with LAKE attached con = attach() # Postgres DuckLake catalog + httpfs parquet, SQL runs in this process con.execute("INSTALL tpch; LOAD tpch") # provides tpch_queries() timings = [] for q in con.execute("FROM tpch_queries()").fetchall(): qid, sql = q[0], q[1].replace("FROM ", "FROM LAKE.tpch.") t0 = time.perf_counter() con.execute(sql).fetchall() timings.append({"query": f"q{qid}", "ms": round((time.perf_counter() - t0) * 1000)}) print(json.dumps({"timings": timings}, indent=2)) ``` Register both as automation scripts (`definite run script create --name tpch_gen --content tpch_gen.py`, same for `tpch_run`), then drop them into a pipeline: ```yaml # pipeline.yaml — create with: definite run automation create --definition pipeline.yaml steps: - id: generate type: python config: script_name: tpch_gen compute_profile: large attach_lake: true - id: bench type: python config: script_name: tpch_run compute_profile: large attach_lake: true ``` A burst-pool node spins up on the first step, both steps reuse the same pool, and the node scales back down ~30s after the second step's sandbox lease is torn down. For genuinely ad-hoc beefy SQL (one-off exploration, no pipeline overhead), open a Fi thread with `compute_profile: large` and ask the agent to run the query. Fi's `bash` tool inside the sandbox can invoke `duckdb` directly — same compute path, no automation plumbing. ## Limits (v1) - **Lake access from Python steps is explicit.** A compute-profile Python step only receives `LAKEHOUSE_*` and object-store credentials when `config.attach_lake: true` is set. Set `attach_lake: false` to force no lake env. - **`adbc_sync` / `mssql_sync` steps do not route to burst sandboxes yet.** They accept `config.compute_profile` for forward compatibility but run on their existing executor paths. `pg_sync` honors a non-default profile when the source connection is portable (no SSH bastion, no pasted SSL certs); non-portable sources stay in-pod and log that the profile was ignored. - **Burst SQL needs the Fi sandbox subsystem.** If the deployment has Fi disabled (`fi.enabled: false`), a non-default `compute_profile` on `/api/v1/queries` returns 503 rather than silently falling back to the API pod's embedded connection — silent fallback would defeat the leak-isolation guarantee the feature exists to provide. - **No authorization gating.** Any authenticated user can pick any declared profile. Cost is controlled by what the operator declares in `config.yaml`, and the worker tier enforces `max_concurrent` as the attached SQL worker slot count for each profile. ## Default deployments A deployment with no `compute_profiles:` block uses the default sandbox settings from `fi.sandbox.*`. Add named profiles only when specific workloads need different resources, scheduling hints, or warm-pool behavior. ## Troubleshooting | Symptom | Cause | Fix | |---|---|---| | `SandboxClaim` stuck `Pending`, no pod scheduled | Node pool for the profile doesn't exist or its taint doesn't match the profile's `tolerations` | `kubectl get nodes -L cloud.google.com/gke-nodepool` (etc.) to confirm the pool exists; compare the pool's taint to `compute_profiles..tolerations` | | Worker query times out attaching `ducklake:postgres` while the default query path works | The profile's sandbox/worker pod cannot reach a private Postgres catalog endpoint because sandbox NetworkPolicy excludes RFC1918 by default | Add `fi.sandbox.egress.private_cidrs: ["/32"]` and keep `private_ports` at `[5432]` unless your catalog uses a custom port, then re-run `definite upgrade` | | `GET /api/v1/compute-profiles` returns only `default` after adding a profile | Helm release wasn't re-rendered, or `FI_COMPUTE_PROFILES_JSON` wasn't refreshed | `definite upgrade --config config.yaml`, then `kubectl rollout restart deploy/definite-api -n definite` | | Warm-pool sandboxes still on the old image after `helm upgrade` | Known agent-sandbox footgun — the controller keeps the warm pool's bound pods until the SandboxClaim is deleted | `kubectl delete sandboxes.agents.x-k8s.io -n definite -l app.kubernetes.io/component=fi-sandbox` — the pool refills with the new image. | | `400: unknown compute profile 'foo'. Known: default, large` | The frontend or CLI sent a profile name not in the chart-rendered registry | Check `config.yaml`'s `compute_profiles:` keys and re-run `definite upgrade` if you added one but didn't deploy it. | --- # Image Mirroring (Air-Gapped) Definite on-prem publishes its container images to the public GitHub Container Registry (`ghcr.io/definite-app`). Many regulated environments — banks, government, healthcare — will not let Kubernetes workloads pull from a public registry. They deploy only from an **internal registry** (Amazon ECR, Google Artifact Registry, Azure Container Registry, Harbor, Nexus, Quay, …) that runs image scanning and policy enforcement. This page is the supported path for those environments: copy the Definite image set into your private registry, then point the Helm chart at it. --- ## The image set A Definite on-prem release ships these images. All container images are `linux/amd64` only. | Image | Purpose | |---|---| | `api` | API service | | `frontend` | React web UI | | `fi-sandbox` | Agent Sandbox runtime for Fi | | `job-runner` | Postgres-backed pipeline scheduler | | `cli` | Build-time CLI image consumed by `fi-sandbox` during Definite's release build | The default mirror set is the four runtime images the chart can pull: `api`, `frontend`, `fi-sandbox`, and `job-runner`. The `cli` image is published with the same release tag for build provenance, but the runtime chart does not pull it directly. Source references are `ghcr.io/definite-app/:`. The `` is the bare release version such as `0.0.4` (the Git tag is `v0.0.4`), or a `git-sha-` tag. Use the exact tag Definite gave you for your release. --- ## Step 1 — Mirror the images `scripts/mirror-images.sh` pulls each image from `ghcr.io/definite-app` and pushes it into your registry under the same tag. It is **idempotent**: it compares source and destination manifest digests and skips anything already in sync, so re-running after a partial failure only moves what is missing. ### Prerequisites - `docker` running locally, **or** `skopeo` (set `USE_SKOPEO=1` — skopeo needs no daemon and does not stage layers on local disk, which is nicer for CI runners and air-gap bastion hosts). - You are logged in to your **destination** registry (see per-registry commands below). - `ghcr.io` is public; no source login is needed unless your network proxies it behind auth, in which case run `docker login ghcr.io` first. ### Run it ```bash # Amazon ECR — also create the destination repos (ECR will not auto-create): aws ecr get-login-password --region us-east-1 \ | docker login --username AWS --password-stdin \ 123456789012.dkr.ecr.us-east-1.amazonaws.com ./scripts/mirror-images.sh \ --dest 123456789012.dkr.ecr.us-east-1.amazonaws.com/definite \ --tag 0.0.4 \ --create-ecr-repos ``` ```bash # Google Artifact Registry: gcloud auth configure-docker us-central1-docker.pkg.dev ./scripts/mirror-images.sh \ --dest us-central1-docker.pkg.dev/acme-prod/definite \ --tag 0.0.4 ``` ```bash # Azure Container Registry: az acr login --name acmecorp ./scripts/mirror-images.sh \ --dest acmecorp.azurecr.io/definite \ --tag 0.0.4 ``` ```bash # Harbor (or any registry) via skopeo — daemonless, good for CI: docker login harbor.acme.internal # or: skopeo login harbor.acme.internal USE_SKOPEO=1 ./scripts/mirror-images.sh \ --dest harbor.acme.internal/definite \ --tag 0.0.4 ``` Use `--dry-run` to print exactly what would be copied without copying anything, and `--force` to re-push even images already in sync. `--help` prints the full option reference. `--dest` is the registry host **plus the namespace** Definite images should live under, with no trailing slash and no image name. The script appends `/:` to it. So `--dest .../definite --tag 0.0.4` produces `.../definite/api:0.0.4`, `.../definite/frontend:0.0.4`, and so on. ### ECR note ECR does not create repositories on push. Either pass `--create-ecr-repos` (the script then creates each missing repo with `scanOnPush=true` and `IMMUTABLE` tags via the `aws` CLI), or pre-create the repos yourself: ```bash for img in api frontend fi-sandbox job-runner; do aws ecr create-repository --region us-east-1 \ --repository-name "definite/${img}" \ --image-scanning-configuration scanOnPush=true \ --image-tag-mutability IMMUTABLE done ``` GAR, ACR, and Harbor create repositories implicitly on first push, so `--create-ecr-repos` is ECR-only. --- ## Step 2 — Create an image pull Secret Unless your nodes have ambient access to the registry (for example, EKS nodes with an instance role that grants ECR pull, or GKE nodes with the Artifact Registry scope), Kubernetes needs a `docker-registry` Secret to authenticate the pull. Create it **in the deployment namespace**: ```bash kubectl create namespace definite # if it does not exist yet # Amazon ECR — the password is a 12-hour token, so for long-lived clusters # prefer node IAM (no Secret needed) or a controller that refreshes it. kubectl create secret docker-registry registry-pull \ --namespace definite \ --docker-server=123456789012.dkr.ecr.us-east-1.amazonaws.com \ --docker-username=AWS \ --docker-password="$(aws ecr get-login-password --region us-east-1)" # Google Artifact Registry with a service-account key file: kubectl create secret docker-registry registry-pull \ --namespace definite \ --docker-server=us-central1-docker.pkg.dev \ --docker-username=_json_key \ --docker-password="$(cat gar-pull-sa.json)" # Azure Container Registry with a token / service principal: kubectl create secret docker-registry registry-pull \ --namespace definite \ --docker-server=acmecorp.azurecr.io \ --docker-username= \ --docker-password= # Harbor / Nexus / Quay with a robot or service account: kubectl create secret docker-registry registry-pull \ --namespace definite \ --docker-server=harbor.acme.internal \ --docker-username='robot$definite' \ --docker-password= ``` If your nodes already have pull access to the registry you can skip this step and leave `pull_secrets` empty in the next step. --- ## Step 3 — Point Definite at your registry Definite's `config.yaml` (consumed by `definite init`, or fed straight to Helm as values) has an `image:` block that overrides the registry, tag, pull policy, and pull Secrets for the `api`, `frontend`, and `job-runner` images. The `examples/*.yaml` files ship it commented out. ```yaml # config.yaml image: # Registry + namespace you mirrored into — the SAME value you passed to # mirror-images.sh as --dest. The chart appends /:. registry: 123456789012.dkr.ecr.us-east-1.amazonaws.com/definite tag: 0.0.4 pull_policy: IfNotPresent # Name(s) of the docker-registry Secret(s) from Step 2. Omit / leave # empty if your nodes have ambient registry access. pull_secrets: - registry-pull ``` ### fi-sandbox is configured separately The Fi sandbox pod is launched through an Agent Sandbox template, not the shared `image:` block, so its image is set under `fi.sandbox.image` as a **full image reference** (registry + name + tag). Point it at the mirrored `fi-sandbox` image. The sandbox pod still reuses `image.pull_policy` and `image.pull_secrets` from the block above, so the same Secret covers it. ```yaml # config.yaml (continued) fi: sandbox: image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/definite/fi-sandbox:0.0.4 ``` > Keep `fi.sandbox.image`'s tag in lockstep with `image.tag`. They are set > in two places only because the sandbox launches via a different > mechanism; they should always reference the same release. `mirror-images.sh` prints both of these snippets, pre-filled with your `--dest` and `--tag`, when it finishes. ### Using Helm directly If you drive Helm yourself instead of the `definite` CLI, the same values in `values.yaml` shape are: ```yaml image: registry: 123456789012.dkr.ecr.us-east-1.amazonaws.com/definite tag: "0.0.4" pullPolicy: IfNotPresent pullSecrets: - registry-pull fi: sandbox: image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/definite/fi-sandbox:0.0.4 ``` --- ## Step 4 — Deploy and verify Run `definite init --config config.yaml` (or `helm upgrade --install`) as normal. Confirm every pod is pulling from your registry, not `ghcr.io`: ```bash kubectl get pods -n definite \ -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].image}{"\n"}{end}' ``` Every image should be prefixed with your private registry host. If any pod is stuck in `ImagePullBackOff`, `kubectl describe pod -n definite` shows the pull error — usually a missing pull Secret (Step 2), a Secret in the wrong namespace, or a tag that was never mirrored. --- ## Upgrades For each new Definite release, re-run Step 1 with the new `--tag`, then bump `image.tag` (and `fi.sandbox.image`'s tag) in `config.yaml` and redeploy. Because `mirror-images.sh` is idempotent, re-running it only transfers images that changed. --- ## Toward a fully air-gapped install Mirroring covers the **runtime images**. A deployment with *no* egress to the public internet also needs: 1. **The `definite` CLI binary.** The quick-start `curl | sh` installer reaches `storage.googleapis.com`. For an air-gapped host, obtain the release binary out of band and place it on `PATH` directly — it is a single static binary with no runtime dependencies. 2. **The Helm chart.** Either run from a checkout of this repository inside the network, or `helm pull` the chart into a local chart repository / OCI registry. 3. **A reachable Kubernetes registry mirror.** Steps 1–3 above already point every workload at your internal registry. Make sure `pull_policy` resolves without contacting `ghcr.io` — `IfNotPresent` is correct once the images are mirrored. 4. **LLM connectivity.** Fi and automations need an LLM endpoint. In an air-gapped environment this is typically AWS Bedrock / Azure OpenAI / Vertex over a private link, or the self-hosted LiteLLM proxy pointed at an in-network model. There is no Definite-hosted LLM fallback. 5. **Published images.** A mirrored install uses the published release images. You do not need to build images from source to deploy from a private registry. --- # Backup & Restore How to back up a Definite On-Prem deployment and restore it. This is a first-version runbook — validate it against your own environment and bake it into your normal DR process. ## What state exists, and who owns it Definite On-Prem keeps durable state in three places. The deployment itself — the API, frontend, and job-runner pods — is **stateless** and re-created from the Helm chart, so it does not need backing up. | State | Where it lives | Owner | Back this up | |---|---|---|---| | Application database | External Postgres 15+ (`definite`) | Customer | **Yes** | | DuckLake catalog metadata | External Postgres 15+ (`ducklake_catalog`) | Customer | **Yes** | | Lakehouse bulk data | Object store (S3 / GCS / Azure / MinIO) | Customer | **Yes** | | Deployment config | `config.yaml` + secret env vars | Customer | **Yes** (off-cluster) | | Pods / chart | Helm release | `definite` CLI | No — re-deployable | The two halves of the lakehouse must be backed up **as a consistent set**: the object store holds the Parquet data files, and the DuckLake catalog holds the metadata — snapshots, table definitions, and the file manifest — that makes those Parquet files queryable. The catalog is the dedicated `ducklake_catalog` Postgres database, so both lakehouse halves are external state. A backup of one without the other is not restorable. See `architecture.md` for the component map. > **There is no app-managed backup job.** Definite does not ship a backup > CronJob or any in-cluster backup component. Backup and DR are an > **infrastructure** concern: back up your **Postgres instance** (it holds both > the application `definite` database and the `ducklake_catalog` catalog > database) with your provider's automated backups / PITR, and rely on > object-store durability + versioning for the Parquet data. ## Before you back up A point-in-time-consistent backup is easiest when nothing is writing. For a clean backup: 1. Pause scheduled work — stop the job runner so automations and agent runs do not write mid-backup: ```bash kubectl scale deploy/definite-job-runner --replicas=0 -n definite ``` 2. Optionally scale the API to zero as well for a fully quiesced backup. For a hot backup, skip this and accept that in-flight queries may not be captured; Postgres dumps and object stores are individually consistent, but the catalog/data set is only guaranteed consistent when writes are paused. 3. Run a DuckLake checkpoint so catalog state is flushed cleanly: ```bash definite run maintenance run --operation checkpoint ``` ## Backup procedure ### 1. Postgres (application and DuckLake catalog databases) Use `pg_dump`. Run it from a host that can reach the database (a jump pod, or your laptop if Postgres is routable). ```bash pg_dump \ --format=custom \ --no-owner \ --no-privileges \ --file=definite-pg-$(date +%Y%m%d-%H%M%S).dump \ "postgres://definite:${POSTGRES_PASSWORD}@:5432/definite" pg_dump \ --format=custom \ --no-owner \ --no-privileges \ --file=ducklake-catalog-pg-$(date +%Y%m%d-%H%M%S).dump \ "postgres://definite:${POSTGRES_PASSWORD}@:5432/ducklake_catalog" ``` Store the `.dump` file off-cluster. If your Postgres is a managed service (RDS, Cloud SQL, Azure), the provider's automated daily snapshots are an acceptable alternative — and on a correctly provisioned deployment they are **already on by default** (see [`prerequisites.md`](/docs/prerequisites) for the per-provider setup). Verify the automated backups include both the `definite` and `ducklake_catalog` databases and have a non-zero retention period. ### 2. Object store (lakehouse bulk data) Copy the deployment's prefix to a separate backup location. Use the same prefix you set as `lakehouse.prefix`. ```bash # S3 / MinIO aws s3 sync s3://acme-definite-lake/lake/ s3://acme-definite-backup/lake-$(date +%Y%m%d)/ # GCS gsutil -m rsync -r gs://acme-definite-lake/lake/ gs://acme-definite-backup/lake-$(date +%Y%m%d)/ ``` Object-store versioning or a lifecycle-managed backup bucket is the most robust option — enable it if you can. ### 3. DuckLake catalog metadata No separate step. The DuckLake catalog lives in the `ducklake_catalog` Postgres database, so it is captured by the Postgres dump in step 1 — back it up **together with** the application database (or in the same low-write window) so the catalog and the object-store data stay a consistent set. ### 4. Config Keep a copy of `config.yaml` and the values of every secret env var it references (`POSTGRES_PASSWORD`, `S3_ACCESS_KEY_ID`, `OIDC_CLIENT_SECRET`, …) in your secrets manager. Without these you cannot re-deploy. ### 5. Resume ```bash kubectl scale deploy/definite-job-runner --replicas=1 -n definite # and the API if you scaled it down ``` ## Before an upgrade `definite upgrade` (and `definite init` on an existing deployment) applies any pending schema migrations to the application database on API boot. A failed migration can leave the schema in a half-applied state, so **always take an on-demand Postgres backup immediately before upgrading** — a fresh, named snapshot, independent of the rolling automatic-backup retention. ```bash # RDS aws rds create-db-snapshot \ --db-instance-identifier \ --db-snapshot-identifier -preupgrade-$(date +%Y%m%d-%H%M%S) # Cloud SQL gcloud sql backups create --instance= \ --description="pre-upgrade $(date +%Y%m%d-%H%M%S)" # Azure Database for PostgreSQL — trigger an on-demand backup from the portal # or `az postgres flexible-server backup create`. # Self-managed — run the pg_dump from "Backup procedure" step 1 above. ``` Keep the snapshot until the upgraded deployment has been verified healthy (`definite status`, a known query, and a spot-check of application data). ## Restore procedure Restore in dependency order: external state first, then the catalog, then bring the deployment up. ### 1. Restore Postgres Into clean, empty `definite` and `ducklake_catalog` databases: ```bash pg_restore \ --no-owner \ --no-privileges \ --dbname="postgres://definite:${POSTGRES_PASSWORD}@:5432/definite" \ definite-pg-.dump pg_restore \ --no-owner \ --no-privileges \ --dbname="postgres://definite:${POSTGRES_PASSWORD}@:5432/ducklake_catalog" \ ducklake-catalog-pg-.dump ``` ### 2. Restore the object store Sync the backed-up prefix back to the bucket the new deployment will use. The object paths must match what the catalog expects — restore to the **same prefix** the catalog was taken with, or you must rewrite catalog paths. ### 3. Restore the DuckLake catalog The catalog and the object-store data must come from the **same backup point**. The catalog is the `ducklake_catalog` Postgres database, so it was restored in Postgres step 1 — no separate catalog restore is needed. ### 4. Re-deploy ```bash definite doctor --config config.yaml definite init --config config.yaml ``` `definite init` runs `helm upgrade --install`; the API applies any pending schema migrations on boot. ### 5. Verify - `definite status --config config.yaml` — all pods `Running`/`Ready`. - `definite run maintenance stats` — every expected lakehouse table is listed with sane snapshot counts. - A known query through the UI or `definite run` returns expected rows. - Spot-check application data: recent automations, saved queries, integrations. ## Recovery objectives & cadence Set these with your customer; sane starting points: - **Postgres:** dump at least daily; managed-service PITR if available. This covers both the application and `ducklake_catalog` databases. - **Object store:** enable bucket versioning and/or sync the bucket on the same schedule as the Postgres backup, ideally during a low-write window so the catalog and the data stay consistent. - **Test restores quarterly** into a scratch namespace. A backup you have never restored is not a backup. ## Back up your Postgres instance (the catalog story) The DuckLake catalog is the `ducklake_catalog` Postgres database, living on the **same Postgres instance** as the application `definite` database. There is **no app-managed catalog backup job** — the catalog is covered by whatever you use to back up that Postgres instance, exactly as for the application database: - **Managed Postgres (RDS / Cloud SQL / Azure):** automated daily backups and point-in-time recovery cover **both** databases on the instance. On a correctly provisioned deployment these are already on by default — see [`prerequisites.md`](/docs/prerequisites) for the per-provider setup. Verify the retention is non-zero and that the snapshots include the whole instance (so both `definite` and `ducklake_catalog`). - **Self-managed Postgres:** run the `pg_dump` of both databases from step 1 of the manual procedure above (or use `pgBackRest` / WAL archiving for PITR). To restore the catalog, restore the Postgres instance (or PITR it to a point in time) — the `ducklake_catalog` database comes back with it. See the restore procedure above; no separate catalog-restore step is needed. ### Don't forget the object store The catalog references the Parquet data files by path. Keep the bulk data durable independently of Postgres: - Enable **bucket versioning** (or a lifecycle-managed backup bucket) on the prefix that holds the lake's Parquet files. Without versioning, a delete (or a partial sync) makes a catalog backup non-restorable — the catalog points at files that no longer exist. - For a strict point-in-time set, line up the Postgres snapshot/PITR target and any bucket-versioning checkpoint in the same low-write window so the catalog and the data stay a consistent pair. ## Notes & limitations - There is **no app-managed backup job and no backup component** in the chart. Postgres and bulk-data backups are an infrastructure responsibility — use managed-Postgres automated backups / PITR (covers both the application and catalog databases) plus object-store versioning, as described above. - There is no single `definite backup` CLI command yet — for a fully manual point-in-time backup of all pieces, the documented procedure above remains the authoritative path. - Air-gapped restore is out of scope for v1. - If catalog and object-store backups drift out of sync, the catalog is the source of truth for *which* files should exist; a `definite run maintenance` pass (`stats`, then `delete_orphaned_files`) can help reconcile a partially restored object store. - For escalation when a restore does not come up clean, see [`support.md`](/docs/support). --- # Password Recovery Definite supports two password-recovery paths for local password accounts. ## Self-service reset with email If `email.mode` is `smtp` or `definite_cloud`, users can click **Forgot password?** on `/login`, enter their email, and receive a single-use reset link. The link expires after 24 hours. When the password is changed, all existing sessions for that user are revoked. Definite uses a generic SMTP relay. Common choices are Amazon SES, Postmark, SendGrid, Mailgun, Google Workspace relay, Exchange Online relay, or an internal company SMTP relay. ```yaml email: mode: smtp enabled: true from: "Definite " smtp: host: "smtp.example.com" port: 587 username: "smtp-user" password: env: EMAIL_SMTP_PASSWORD starttls: true ssl: false ``` Definite-managed hosted deployments use `email.mode: definite_cloud`, which relays through Definite Cloud instead of storing a provider credential in the customer deployment. Password reset is only available for active local-password users. SSO users recover access through their identity provider. ## No-email recovery If email is disabled or incomplete, `/login` shows recovery instructions instead of a reset-link form. If another workspace admin can sign in, they can reset the user's password from **Settings -> Members** and share the temporary password out-of-band. If all admins are locked out, an operator with Kubernetes access can run: ```sh kubectl -n exec -it -- \ definite admin reset-password user@example.com ``` See operator-recovery.md for the full lockout runbook. --- # LLM Setup Fi, Pi, and autonomous [agents](/docs/agents) all call an LLM. The provider is configured by the `llm:` block in `config.yaml` and resolved at deploy time — when it's misconfigured (no key, model name the provider doesn't host, IAM not yet approved) Fi surfaces an "LLM not reachable" banner in the thread and points you here. This page covers the three supported providers (Anthropic direct, AWS Bedrock, Google Vertex), how to switch between them, the model IDs the deployment ships with, and the most common reasons Fi can't reach an LLM on a fresh install. ## The `llm:` block The `llm:` block in [`config.yaml`](/docs/config#llm) is a tagged union by `provider`. On a fresh deploy the simplest working configuration is: ```yaml llm: provider: anthropic model: claude-sonnet-5 api_key: { env: ANTHROPIC_API_KEY } ``` `provider` defaults to `anthropic` and `model` defaults to `claude-sonnet-5` when omitted, so the only required field is `api_key`. `api_key` is a [SecretRef](/docs/config#secretref-used-by-many-fields) — supply it as an env var (`{ env: ANTHROPIC_API_KEY }`), a file (`{ file: /etc/secrets/... }`), or a pre-created Kubernetes Secret. ## Anthropic — the easiest path The fastest way to get Fi working is an Anthropic API key. 1. Sign in at [console.anthropic.com](https://console.anthropic.com/) and create a key under **Settings → API keys**. 2. Set the key in your environment before running `definite init` / `definite upgrade`: ```bash export ANTHROPIC_API_KEY=sk-ant-... ``` 3. Confirm the `llm:` block references it: ```yaml llm: provider: anthropic model: claude-sonnet-5 api_key: { env: ANTHROPIC_API_KEY } ``` 4. Apply the change: ```bash definite upgrade ``` The new key reaches the `definite-secrets` Kubernetes Secret on the next helm apply. Fi and Pi pick it up on the next run — no pod restart needed. > You can also paste an Anthropic (or OpenAI) key directly from > **Settings → Models → Providers** on a self-hosted deployment: it is stored > encrypted and takes effect on the next Fi run, no `definite upgrade` needed. > On hosted (managed-proxy / `litellm`) deployments those key fields do not > apply — models are served through the in-cluster LiteLLM proxy, so pick your > Fi model from the **Settings → Models** catalog instead. ### Rotating the key To rotate, update the env var to the new key and run `definite upgrade`. The chart re-renders the Secret in place; the next Fi/Pi run uses the new value. ## AWS Bedrock Bedrock is the right choice when the deployment lives inside an AWS account that already has IAM/IRSA wired up. There is no API key — auth flows through the chart's ServiceAccount + an IRSA-bound IAM role. ### 1. Request model access Bedrock requires explicit model-access approval per region. Open the console and request access to the Claude models the deployment uses: > [`https://console.aws.amazon.com/bedrock/home#/modelaccess`](https://console.aws.amazon.com/bedrock/home#/modelaccess) Switch the region picker to the same region you'll set in `llm.region` (e.g. `us-east-1`). Request access to **Anthropic Claude Sonnet** and **Anthropic Claude Haiku** — approval is usually instant for paying accounts but can take hours on a new one. Until it's approved every `InvokeModel` call returns `AccessDeniedException` and Fi shows the banner. ### 2. IAM / IRSA The chart's ServiceAccount must be annotated with `eks.amazonaws.com/role-arn=`. The role's trust policy must bind your EKS OIDC provider to `system:serviceaccount::`, and its permissions must allow `bedrock:InvokeModel` on the inference profile ARNs **plus** the underlying foundation models the profile dispatches to. (Cross-region inference profiles route between regional endpoints, so the policy needs both ARNs.) ### 3. `config.yaml` ```yaml llm: provider: bedrock region: us-east-1 model: claude-sonnet-4-6 inference_profile_prefix: us # geo prefix; see "Non-US regions" below ``` Set `llm.litellmUpstream: bedrock` if you're using the in-cluster LiteLLM proxy (the default `litellm` provider path). Direct Bedrock uses a cross-region inference profile. The proxy accepts the friendly model name and maps it to the profile ID — see the model table below. ### Non-US regions Claude on Bedrock is only invocable through a **cross-region inference profile** whose geo prefix must match your region: `us` (United States), `eu` (Europe), `apac`/`au` (Asia Pacific / Australia). The default is `us`. For a non-US region, set the prefix in both Terraform and `config.yaml` (the API, Fi sandbox, and LiteLLM all re-base model IDs onto it; you can leave `llm.model` as a friendly name like `claude-sonnet-4-6`): ```yaml llm: provider: bedrock region: ap-southeast-2 model: claude-sonnet-4-6 inference_profile_prefix: au ``` ```hcl # terraform.tfvars — the `au` profile dispatches compute to ap-southeast-4, # so the IAM policy must allow both regions' foundation-model ARNs. bedrock_inference_profile_prefix = "au" bedrock_inference_profile_regions = ["ap-southeast-2", "ap-southeast-4"] ``` Check the AWS docs for which regions your chosen profile fans out to, and make sure model access is granted in the Bedrock console for that region. ### Bedrock model IDs shipped with the deployment The LiteLLM template ships these mappings. Friendly names are kept stable across providers so changing upstream doesn't break `LLM_MODEL`. | Friendly name (`llm.model`) | Bedrock model ID | |---|---| | `claude-opus-5` | `bedrock/us.anthropic.claude-opus-5` | | `claude-opus-4-8` | `bedrock/us.anthropic.claude-opus-4-8` | | `claude-opus-4-7` | `bedrock/us.anthropic.claude-opus-4-7` | | `claude-sonnet-5` | `bedrock/us.anthropic.claude-sonnet-5` | | `claude-sonnet-4-6` | `bedrock/us.anthropic.claude-sonnet-4-6` | | `claude-sonnet-4` | `bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0` | | `claude-haiku-4-5` | `bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0` | | `gpt-5.6-sol` | `bedrock_mantle/openai.gpt-5.6-sol` (Responses API) | | `gpt-5.6-terra` | `bedrock_mantle/openai.gpt-5.6-terra` (Responses API) | | `gpt-5.6-luna` | `bedrock_mantle/openai.gpt-5.6-luna` (Responses API) | Gemini (`gemini-3-5-flash`) is Vertex-only and is not offered on Bedrock hosted installs (central `onprem.hosted_llm_model.upstreams` filters the Settings picker by `llm.litellmUpstream`). The `us.` prefix shown above is the default; it routes the call across the US regional Bedrock endpoints (cross-region inference profile). For non-US regions set `llm.inference_profile_prefix` (see [Non-US regions](#non-us-regions)) and the prefix is swapped accordingly. Bedrock has deprecated the legacy on-demand foundation-model IDs for these models — only the inference-profile ARN is invocable. ## Google Vertex AI Vertex is the right choice when the deployment lives inside a GCP project with Workload Identity wired up. ### 1. Enable the API and grant access In your GCP project, enable the **Vertex AI API**. Grant the chart's GCP service account `roles/aiplatform.user` on the project. The chart's Kubernetes ServiceAccount must carry the `iam.gke.io/gcp-service-account=@.iam.gserviceaccount.com` annotation so Workload Identity binds the two. For Claude on Vertex you must also enable each model in the **Model Garden** of the region you'll use — the per-model "Enable" button issues the publisher binding the call needs. ### 2. `config.yaml` ```yaml llm: provider: vertex project: my-gcp-project region: global model: claude-sonnet-5 ``` For Gemini and current Claude defaults, use `region: global`; some regional endpoints return 404 even with the right publisher ID if that model is not enabled there. ### Vertex model IDs shipped with the deployment | Friendly name (`llm.model`) | Vertex publisher path | |---|---| | `gemini-3-5-flash` | `vertex_ai/gemini-3.5-flash` (location `global`) | | `claude-opus-5` | `vertex_ai/claude-opus-5` (location `global`) | | `claude-opus-4-8` | `vertex_ai/claude-opus-4-8` (location `global`) | | `claude-sonnet-5` | `vertex_ai/claude-sonnet-5` (location `global`) | | `claude-sonnet-4-6` | `vertex_ai/claude-sonnet-4-6` | | `claude-sonnet-4` | `vertex_ai/claude-sonnet-4@20250514` | | `claude-haiku-4-5` | `vertex_ai/claude-haiku-4-5@20251001` | Friendly model names use dashes (k8s/env-var friendly). The upstream Vertex path keeps the dot between version digits — e.g. `gemini-3.5-flash`, not `gemini-3-5-flash`. The dashes-only form 404s. ## Azure OpenAI Azure OpenAI is the right choice when the deployment lives in an Azure subscription with an Azure OpenAI resource. Auth is an API key (the resource's key), not IAM. ```yaml llm: provider: azure_openai endpoint: https://acme.openai.azure.com deployment: gpt-4o api_key: { env: AZURE_OPENAI_API_KEY } ``` Unlike the other providers, there is no separate `model` field. Fi uses the **deployment name as the model id** when it calls Azure (the request path is `{endpoint}/openai/deployments/{deployment}/responses`), so two rules apply: - Name your Azure OpenAI deployment after a supported OpenAI model id, e.g. `gpt-4o`. A deployment named anything else fails with `azure-openai-responses/: unknown to pi-ai`. - Azure OpenAI serves only OpenAI models. Claude friendly names like `claude-sonnet-4-6` do not work here; pick `anthropic`, `bedrock`, or `vertex` if you need Claude. The chart wires `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_API_KEY` into the Fi sandbox from the `llm:` block, so no other setup is needed once the deployment is named correctly. > Autonomous agent decisions and automations that fall back to the deployment > LLM (rather than a per-agent `decision_integration`) currently support > `anthropic`, `openai`, and `litellm` only. Interactive Fi works on Azure > OpenAI; agent-decision fallback on Azure is a known follow-on. ## Switching providers or changing models The `llm.provider` and `llm.model` fields in `config.yaml` are the ground-truth — change them and run `definite upgrade`. The provider switch restarts the LiteLLM proxy (which re-renders its model list); the model switch takes effect on the next Fi run. On a fresh install the API reconciles the `fi_model_config` singleton to `config.yaml`'s `llm.provider` / `llm.model` on startup, so `config.yaml` is authoritative out of the box (the 007 seed's `anthropic` / `claude-sonnet-5` default doesn't leak onto a non-anthropic deployment). It only rewrites the row while it's still untouched (`updated_by IS NULL`), so an admin's later Settings → Models choice survives restarts. For a per-deployment runtime model override (no `definite upgrade` needed), admins can change the default in [Settings → Models][settings-models]. That writes to the `fi_model_config` row in the app DB; the next Fi run reads it and routes the call through the in-cluster LiteLLM proxy. The chart-level `api_key` / IAM remains the auth source — the UI just picks the model. [settings-models]: /settings/fi-models ## Capping daily LLM spend `llm.budget` puts a hard ceiling on what this deployment can spend on model calls in a day. It is off by default: ```yaml llm: provider: litellm budget: enabled: true dailyUsd: 250 ``` Run `definite upgrade` to apply it. The cap is enforced by the in-cluster LiteLLM proxy, which every model call on the deployment goes through — Fi, automations, and agent decisions alike. Once the day's spend passes `dailyUsd`, the proxy rejects further calls with HTTP 429 **before** they reach the provider, and Fi shows "This deployment has used its daily LLM budget" instead of a provider error. The API logs one line when spend crosses 80% of the cap and one when it hits the cap. Details worth knowing before you turn it on: - **It requires Postgres.** The running total lives in a `litellm` schema on the database from `postgres.url`, which is what makes one cap hold across both proxy replicas and survive a restart. The proxy creates the schema on first boot; that boot is slower than usual. - **It fails open.** If Postgres is unreachable, model calls keep working and spend is briefly unmetered. A database problem will not take Fi down. - **The window resets at 00:00 UTC**, on a fixed daily grid that does not drift. The reset is applied by a periodic job rather than a clock trigger, so the counter can take a few minutes past midnight to zero. - **Cost is measured, not estimated.** LiteLLM prices each response from its own cost map, which rates fresh input, output, cache writes, and cache reads separately per model. - **The cap can be overshot slightly.** Spend is written every ~10s and read through a ~60s cache, so a burst can cross the line before the gate closes. That bounds a runaway to minutes rather than hours. Raise `dailyUsd` (or set `enabled: false`) and run `definite upgrade` to lift a cap that is blocking legitimate work. ## Troubleshooting ### "Fi can't reach an LLM yet" banner This banner appears in the Fi thread whenever the most recent run failed with an LLM error code. The most common causes on a fresh deploy: - **No `ANTHROPIC_API_KEY` set, or the key was rotated.** Re-export the env var and run `definite upgrade`. Test with a short prompt in Fi. - **Bedrock model access pending.** Check [`https://console.aws.amazon.com/bedrock/home#/modelaccess`](https://console.aws.amazon.com/bedrock/home#/modelaccess) — the requested models must show **Access granted** in your `llm.region`. - **Vertex API not enabled, or `roles/aiplatform.user` missing.** Confirm the GCP service account, the Workload Identity binding, and the per-model Model Garden enable. - **Wrong `llm.model` name.** Must match one of the friendly names in the tables above. Anything else returns "configured LLM model is not known to Pi" from the sandbox. Click **Configure in Settings** on the banner to jump to [Settings → Models][settings-models] for a model swap, or **Setup guide** to come back to this page. The banner clears on the first successful run. ### Other Fi failures If the banner doesn't appear and Fi is still failing, the error is unlikely to be LLM-related. Open the run from the Fi sidebar, expand the activity strip, and read the error string — it often points at a missing integration secret, a SQL syntax error, or a sandbox networking issue (see [`fi.sandbox.egress`](/docs/config#fisandboxegress)). --- # Support How to get help with a Definite On-Prem deployment, what to try first, and what to attach when you open a ticket. A first-version runbook — adjust the contacts and SLAs to match your support agreement. ## Contacts | Channel | Use for | Address | |---|---|---| | Email | Support, questions, security issues, bugs | hello@definite.app | | Shared channel | Design-partner deployments (if provisioned) | per your onboarding | Always include your **deployment identifier** (`deployment.name` from `config.yaml`) and the **CLI / chart version** (`definite version`) in the first message. ## Severity & response Set real SLAs with your account contact; these are defaults. | Severity | Definition | Target first response | |---|---|---| | **SEV-1** | Production down, data loss, or a security incident. | < 4 business hours | | **SEV-2** | Major feature broken, no workaround; deployment degraded. | < 1 business day | | **SEV-3** | Minor bug, workaround exists, or a question. | < 3 business days | For a suspected **security issue**, email hello@definite.app directly and do not post details in shared channels. ## Triage before you escalate Most issues are diagnosable from the cluster. Run these first and attach the output — it shortens every ticket. ### 1. Health snapshot ```bash definite version definite status --config config.yaml ``` `status` is `kubectl get pods,svc,ingress` for the deployment namespace. Look for pods not `Running`/`Ready`, restart counts, and `CrashLoopBackOff`. ### 2. Re-run preflight ```bash definite doctor --config config.yaml ``` `doctor` re-checks Postgres, Kubernetes, object store, and the LLM provider. A failure here usually means an **external dependency** changed — see `prerequisites.md` and `network-requirements.md` — not a Definite bug. ### 3. Component logs ```bash definite logs api --tail 500 definite logs job-runner --tail 500 definite logs frontend --tail 200 ``` Add `--follow` to watch live. Components: `api`, `frontend`, `job-runner`. (Lakehouse queries run as embedded DuckDB inside the API and job-runner pods — there is no separate `lakehouse` pod or log stream.) ### 4. Common causes | Symptom | Likely cause | First action | |---|---|---| | Pods `Pending` | No bindable PVC / no StorageClass | `kubectl get pvc,storageclass -n definite`; see `prerequisites.md` | | API `CrashLoopBackOff` on boot | Postgres unreachable or migration failure | `definite doctor`; check `definite logs api` | | `503` from `definite run load` | `jobRunner.staging.uri` not set | Configure staging in `config.yaml`; see `cli.md` | | Data-source connection times out | Network reachability from the cluster | See `network-requirements.md` | | TLS certificate not issued | cert-manager / ingress missing | `definite bootstrap`; check cert-manager logs | | Fi runs fail to start | agent-sandbox CRDs missing | `definite bootstrap`; `definite doctor` | | LLM calls failing | Bad or expired LLM credentials | `definite doctor` (LLM check) | | Usage tokens stay at zero | LiteLLM callback or Fi terminal metering is not reaching the API | Check the API and LiteLLM pod logs; run a short Fi request and refresh **Settings → Usage** | | Central usage is stale | Daily telemetry CronJob has not completed | Inspect the telemetry CronJob and its latest Job with the commands below | | Product API routes return `403` | Deployment unlicensed, or license suspended/expired | `definite license status`; if no license block, add one to `config.yaml` and run `definite upgrade` | | Automations stay `queued` and never start | Same: the job runner pauses execution while the license is suspended/expired/revoked | `definite license status`; restore the license and paused runs resume from the step they stopped on | ### Usage and telemetry **Settings → Usage** reads the deployment's local Postgres records for the last 30 days. It shows successful query and data-app compute plus fresh-input, cache-read, cache-write, and output LLM tokens. The local AI-credit figure is a raw-token estimate for visibility, not an invoice: managed hosted billing weights those four provider-priced classes centrally. The daily telemetry CronJob sends the raw 24-hour classes to Definite when telemetry is enabled. To verify that the daily job is completing: ```bash kubectl get cronjob,job -n definite -l app.kubernetes.io/component=telemetry kubectl get pods -n definite -l app.kubernetes.io/component=telemetry kubectl logs -n definite -l app.kubernetes.io/component=telemetry --tail=200 ``` The daily job uses only the application Postgres database. It does not attach DuckLake or read object-storage credentials; DuckLake data-scale metadata is collected separately by the already-running API process. ### 5. Restart safely The deployment is stateless; restarting a component does not lose data. ```bash kubectl rollout restart deploy/definite-api -n definite kubectl rollout restart deploy/definite-job-runner -n definite ``` If a bad config or upgrade is the cause, re-render and re-apply: ```bash definite upgrade --config config.yaml --dry-run # inspect first definite upgrade --config config.yaml ``` ### API-down recovery channel The chart runs a small `support-recovery` pod separately from the API. If the API is crash-looping or no longer serving HTTP, Definite support can queue one short-lived, audited command: restart this release's API Deployment. The watchdog cannot run shell commands, read logs, or mutate any other workload; its namespace Role is restricted to `get` and `patch` on the exact API Deployment name. The existing **Settings → Support access** toggle is authoritative. The watchdog reads it directly from the deployment's Postgres database before polling and again before executing. Turning support access off therefore shuts the channel even when the API itself is unavailable; a database read failure also fails closed. Operators that require a chart-level hard disable can set: ```yaml supportRecovery: enabled: false ``` External uptime checks should use `/readyz`. The ingress routes that path to the real API readiness handler rather than the frontend fallback. ## What to attach to a ticket Bundle these into the ticket so the first reply can be a fix, not a request for more data: 1. **`definite version`** — CLI and chart version. 2. **`definite status --config config.yaml`** output. 3. **`definite doctor --config config.yaml`** output. 4. **Logs** from the affected component(s) — `definite logs --tail 500`. Redact secrets and any sensitive data. 5. **What changed** — recent `definite upgrade`, a config edit, a cluster or Postgres change, a credential rotation. 6. **Severity** and business impact. 7. **`config.yaml`** with all secrets removed (`postgres.url` password, object store keys, OIDC secret, LLM keys). The CLI substitutes `${VAR}` env vars — never send their values. ### Collecting logs without the CLI If the `definite` CLI is unavailable, raw `kubectl` works: ```bash kubectl get pods,svc,ingress,pvc -n definite kubectl describe pod -n definite kubectl logs -n definite --tail 500 --previous # --previous for a crashed pod kubectl get events -n definite --sort-by=.lastTimestamp ``` ## Security & privacy when sharing diagnostics - **Never** send Postgres passwords, object-store keys, OIDC client secrets, or LLM API keys. Redact them from configs and logs before attaching. - Logs can contain query text and table/column names. Redact anything sensitive under your data policy before sharing externally. - For a confirmed or suspected breach, email hello@definite.app and treat it as SEV-1. ## Escalation path 1. **Triage** — run the steps above; check `prerequisites.md`, `network-requirements.md`, and `architecture.md`. 2. **Open a ticket** — email hello@definite.app with the attachments above and a severity. 3. **SEV-1** — flag the email subject `[SEV-1]` and, if you have one, post in your shared channel for fastest pickup. 4. **Data-loss / restore** — follow [`backup-restore.md`](/docs/backup-restore); loop in support before destructive restore steps if the data is irreplaceable. 5. **Feature requests / non-blocking bugs** — file via your support contact; they are triaged into the next release window. ## Related docs - [`cli.md`](/docs/cli) — full CLI reference. - [`prerequisites.md`](/docs/prerequisites) — dependency checklist. - [`network-requirements.md`](/docs/network-requirements) — data-source connectivity troubleshooting. - [`backup-restore.md`](/docs/backup-restore) — backup and disaster recovery. - [`architecture.md`](/docs/architecture) — component map. --- ## Build # Event Ingest Use the event ingest API for frequent, small product-event batches such as page views, clicks, signups, and tracking data from an internal app or website. > To write arbitrary real columns into any lakehouse table, or to upsert / > replace rows, use [Stream Ingest](/docs/stream-ingest) instead. Event Ingest is > append-only into the fixed product-event schema below. There are three write paths: - Server-side writers use a normal Definite session token or API token with `POST /api/v1/events/{schema}/{table}`. - Browser/client-side writers use a public event write key (`evpub_...`) with `POST /api/v1/events/collect`. - SaaS webhook senders that can only set a URL use a `server`-kind event source: the same `evpub_...` key, passed as a `?write_key=` query parameter on `POST /api/v1/events/collect`. Do not put a normal Definite API token in browser code. Public event write keys are safe to expose because they are append-only, scoped to one destination table, limited by an origin allowlist (for browser sources), and can be rotated or revoked. ## Event Table Shape Both endpoints append rows directly to a DuckLake table: ```text POST /api/v1/events/{schema}/{table} Authorization: Bearer ``` The destination table is created if it does not exist. The table shape is stable so changing event properties do not require migrations: | Column | Type | Notes | |---|---|---| | `event_id` | `VARCHAR` | Caller-provided `event_id` or `id`; generated when omitted. | | `event_time` | `TIMESTAMPTZ` | Caller-provided `event_time` or `timestamp`; ingestion time when omitted. | | `event_name` | `VARCHAR` | Required. Also accepts `event` or `name`. | | `distinct_id` | `VARCHAR` | Optional. Also accepts `user_id` or `anonymous_id`. | | `properties` | `VARCHAR` | JSON string containing event properties and extra top-level fields. | | `ingested_at` | `TIMESTAMPTZ` | Server ingestion time. | The destination table is created if it does not exist. ## Server-Side Writers Use `Authorization: Bearer ` where `` is a normal Definite session token or API token. This endpoint is for trusted servers, scripts, and backend collectors. Send a JSON array for normal batching: ```bash curl -sS "$DEFINITE_API_URL/api/v1/events/raw/events" \ -H "Authorization: Bearer $DEFINITE_TOKEN" \ -H "Content-Type: application/json" \ -d '[ { "event_id": "evt_001", "event_name": "pageview", "event_time": "2026-05-20T14:30:00Z", "distinct_id": "anon_123", "properties": { "path": "/pricing", "utm_source": "newsletter" } } ]' ``` The API also accepts a single JSON object or an envelope shaped as `{"events": [...]}`. ### NDJSON Use NDJSON when a collector already buffers one event per line: ```bash curl -sS "$DEFINITE_API_URL/api/v1/events/raw/clicks" \ -H "Authorization: Bearer $DEFINITE_TOKEN" \ -H "Content-Type: application/x-ndjson" \ --data-binary $'{"event":"click","user_id":"u_1","properties":{"button":"buy"}}\n{"event":"scroll","user_id":"u_1","properties":{"depth":75}}\n' ``` ## Browser Writers Create a public event source in **Settings -> Event Sources**, or with the CLI: ```bash definite run event-source create \ --name "Marketing site" \ --schema raw \ --table events \ --origin https://www.example.com ``` The create and rotate commands print the full `evpub_...` key once. Store it in the client app configuration for that allowed origin. The settings page keeps only the display prefix after the key is dismissed. Send browser events to the fixed collector endpoint: ```js await fetch('https://definite.example.com/api/v1/events/collect', { method: 'POST', headers: { Authorization: 'Bearer evpub_...', 'Content-Type': 'application/json', }, body: JSON.stringify({ events: [ { event: 'pageview', distinct_id: 'anon_123', properties: { path: location.pathname }, }, ], }), }) ``` For `navigator.sendBeacon`, put the write key in the JSON envelope because beacon calls cannot set the `Authorization` header: ```js navigator.sendBeacon( 'https://definite.example.com/api/v1/events/collect', new Blob([ JSON.stringify({ write_key: 'evpub_...', events: [{ event: 'pagehide', properties: { path: location.pathname } }], }), ], { type: 'text/plain' }), ) ``` The API checks the browser `Origin` header against the event source allowlist before writing. Add every exact application origin that will send events, such as `https://www.example.com` and `https://app.example.com`. Wildcards are not accepted. Manage sources from Settings or the CLI: ```bash definite run event-source list definite run event-source rotate definite run event-source revoke ``` ## Server Webhook Writers Use a `server`-kind event source when a SaaS product pushes webhooks and the only thing you control is the destination URL: no custom headers, no body shape. Read.ai meeting-transcript webhooks are the canonical example. Create the source with the CLI: ```bash definite run event-source create \ --name "Read.ai webhooks" \ --schema readai \ --table raw_meetings \ --kind server \ --default-event-name meeting_end \ --max-payload-bytes 8388608 ``` `--origin` is not required for server sources. Origins are meaningless here: server-to-server posts carry no `Origin` header, so the Origin allowlist check is skipped entirely for `server`-kind sources. Browser-kind sources still hard-require an allowlisted Origin. Paste the collector URL with the write key as a query parameter into the SaaS product's webhook configuration: ```text https://definite.example.com/api/v1/events/collect?write_key=evpub_... ``` The collector accepts the write key from the `Authorization` header, the JSON body `write_key` field, or the `write_key` query parameter, in that order of precedence. A webhook post needs nothing beyond the URL: ```bash curl -X POST 'https://definite.example.com/api/v1/events/collect?write_key=evpub_...' \ -H 'Content-Type: application/json' \ -d '{"session_id":"abc","trigger":"meeting_end","title":"Weekly sync","transcript":{"speaker_blocks":[]}}' ``` ### Default event name Webhook payloads arrive in the sender's own shape and usually have no `event_name`, `event`, or `name` key. Set `--default-event-name` on the source and it is applied to any incoming event that lacks one; events that do carry a name keep it. Without a source default, an event with no name is still rejected with a 400. All other fields land in the `properties` JSON column as usual. ### Payload limits for server sources Server sources are admin-created and trusted, so the source's own `max_payload_bytes` governs, capped by a hard 32 MiB ceiling, instead of being limited by the global `events.max_payload_bytes` deployment setting. This lets a single deployment accept large webhook payloads (meeting transcripts run to several MB) on one source without raising the global limit for every writer. `max_batch_rows` keeps the min(source, global) behavior for both kinds. ### Key placement in the URL Putting the write key in a URL is acceptable for this use case: the key is append-only, scoped to a single destination table, and can be rotated (`definite run event-source rotate `) or revoked at any time. It cannot read, query, or administer anything. If a webhook URL leaks, rotate the key and update the sender's configuration. ## Limits and Inlining Event ingest is intentionally bounded for small, frequent batches: | Config | Default | Meaning | |---|---:|---| | `events.max_batch_rows` | `1000` | Maximum events accepted in one request. | | `events.max_payload_bytes` | `1048576` | Maximum request body size. | | `lakehouse.data_inlining_row_limit` | `1000` | DuckLake row threshold for inlining small writes. | Browser event sources can set lower per-source `max_batch_rows` and `max_payload_bytes` limits. The effective limit is the lower of the global deployment setting and the source-specific setting. The exception is `max_payload_bytes` on `server`-kind sources, where the per-source value governs up to a hard 32 MiB ceiling (see "Server Webhook Writers" above). Keep `events.max_batch_rows` less than or equal to `lakehouse.data_inlining_row_limit` when event writes should stay in DuckLake's metadata catalog instead of producing tiny Parquet files. Set `lakehouse.data_inlining_row_limit: 0` to disable DuckLake inlining. ## Flushing Inlined Data Inlined rows are queryable immediately. To materialize them into Parquet files, run the maintenance operation: ```bash # Flush all inlined rows in the lake. definite run maintenance run --operation flush_inlined_data # Flush one event schema. definite run maintenance run --operation flush_inlined_data --schema raw # Flush one event table. definite run maintenance run --operation flush_inlined_data --schema raw --table events ``` `checkpoint` also flushes inlined data as part of DuckLake maintenance, but the targeted `flush_inlined_data` operation is usually easier to schedule for event tables. --- # Stream Ingest Use the stream ingest API to land JSON rows into any lakehouse table with real, typed columns. It is the general-purpose write path: a single endpoint that can append, upsert, or fully replace a table, autocreate the table if it does not exist, and grow its schema as the incoming data grows. It is the on-prem equivalent of the Definite cloud stream API, so a client repoints by changing only the URL and the token. ```text POST /api/v1/stream Authorization: Bearer ``` Use a normal Definite session token or a `def_` API token (see [API reference](/docs/api#authentication)). The endpoint is open to any authenticated user, not admin-only. The token writes with the full permissions of the user behind it. ## When to use this vs Event Ingest Stream and [Event Ingest](/docs/event-ingest) both append JSON to a DuckLake table, but they are shaped for different jobs: - **Stream** writes arbitrary **real columns**. Each top-level key in a row becomes its own typed column, and the endpoint supports `merge` (upsert on a primary key) and `replace` (full overwrite) in addition to `append`. Reach for it when you are syncing records from another system and want them queryable as first-class columns, or when you need upsert/replace semantics. - **Event Ingest** is **append-only** into a fixed six-column product-event schema (`event_id`, `event_time`, `event_name`, `distinct_id`, `properties`, `ingested_at`); everything that is not one of those lands in the `properties` JSON blob. Reach for it for high-frequency event tracking (page views, clicks, signups) and for browser/webhook writers that use a public `evpub_...` write key. In short: Event Ingest for product events into one stable schema; Stream for arbitrary tables with merge/replace. ## Request shape The body is a JSON object with `data` and `config`: ```json { "data": { }, "config": { "table": "schema.table", "mode": "append" } } ``` `data` is either a single JSON object (one row) or an array of objects (a batch). Each top-level key in a row becomes a column. Nested objects and arrays are encoded as JSON strings and stored in a `VARCHAR` column, so a heterogeneous nested shape will not break type inference. ### Config fields | Field | Type | Default | Notes | |---|---|---|---| | `table` | string | (required) | Target table as `schema.table` (e.g. `crm.contacts`). A three-part `lake.schema.table` is also accepted; the leading catalog segment must match the deployment's lake name (case-insensitive). | | `mode` | string | `append` | One of `append`, `merge`, `replace` (see below). | | `primary_key` | string array | `null` | **Required when `mode` is `merge`.** One or more key columns; a list of more than one column is a composite key. Ignored by `append` and `replace`. | | `create` | boolean | `true` | Autocreate the schema and table (column types inferred from the data) and add any new columns the data carries. Additive only. Set `false` to require the table to already exist. | An invalid `mode`, or `merge` without a non-empty `primary_key`, is rejected as a `422` validation error before any write. ## Modes | Mode | Semantics | |---|---| | `append` (default) | Insert the incoming rows. Nothing is read or deleted first. | | `merge` | Partial-column upsert keyed on `primary_key`. For a row whose key already exists, **only the columns present in the payload are updated**; every other column of that row keeps its current value. A row whose key is new is inserted. Composite keys (more than one column) are supported. | | `replace` | Full overwrite: delete every row in the destination, then insert the incoming rows. | `merge` and `replace` run inside a single transaction (`BEGIN … COMMIT`), so a reader never sees a half-applied batch. ### What `merge` preserves vs. overwrites `merge` only touches the columns your payload actually sends, so you can update a subset of a wide row without wiping the rest: - A column **absent** from the payload keeps its current value on an existing row. This is the key difference from a full-row replace: derived or system-managed columns (for example a `first_name_lower` you never send) are no longer nulled out by a merge that omits them. - A column **present** with an explicit `null` (`"col": null`) *does* set that column to `NULL`. "Absent" and "explicitly null" are different: only absent columns are preserved. - For a **new** key (an insert), columns the payload omits land as `NULL` — the row did not exist, so there is nothing to preserve. - The column set is **batch-level**: the union of keys across every row in the payload. If one row in a batch carries a key that another row omits, the omitting row gets `NULL` for that cell (standard for a JSON batch). - A payload that carries only the primary-key column(s) has nothing to update, so existing rows are left untouched and only brand-new keys are inserted. ### Merge validation `merge` validates the whole batch before writing and rejects it with a `400` if: - any row is missing a value for one of the `primary_key` columns (or the value is `null`), or - two rows in the same batch collide on the same key (the tuple of key columns for a composite key). Deduplicate within a batch before sending, and make sure every row carries a non-null key. ## Table autocreate and schema evolution With `create: true` (the default): - The schema and table are created if they do not exist (`CREATE SCHEMA IF NOT EXISTS` + `CREATE TABLE IF NOT EXISTS`). Column types are inferred from the data: booleans become `BOOLEAN`, integers `BIGINT`, floats `DOUBLE`, decimals `DECIMAL`, timestamps/dates/times their matching types, and everything else (strings, and the JSON-stringified nested values) `VARCHAR`. - Schema evolution is **additive**. If a later batch carries a column the table does not have, the column is added with `ALTER TABLE … ADD COLUMN`; rows that predate it stay `NULL`. Columns are never dropped or retyped: a column absent from a later batch simply stays `NULL` for the new rows, and an incoming type that differs from the existing column is logged and left to the insert's implicit cast (so a genuinely incompatible change still fails loudly). With `create: false`, no schema or table is created. If the target table does not exist the insert fails and the request returns a `400`. ## Identifiers, batch caps, and errors - **Identifiers.** `schema` and `table` must each match `^[A-Za-z_][A-Za-z0-9_]{0,62}$` (a letter or underscore, then up to 62 letters, digits, or underscores). Uppercase is allowed. Column names follow the same rule. Anything outside it (a dash, a dot inside a segment, a quote) is rejected with a `400`, and identifiers are double-quoted before they reach SQL. - **Batch caps.** A batch is capped at **10,000 rows** and **8 MiB** of request body. Exceeding either returns a `413`. An empty `data` (missing, `null`, or `[]`) returns a `400`. The endpoint serializes writes through the lakehouse writer and retries on a DuckLake commit/write conflict, so concurrent `/stream` calls to the same table are safe. ## Response A successful write returns `200` with: ```json { "success": true, "request_id": "req_0a1b2c3d4e5f", "stream_id": "st_9f8e7d6c5b4a", "table": "crm.contacts", "successful_rows": 3, "rejected_rows": 0, "snapshot_id": null } ``` | Field | Notes | |---|---| | `success` | `true` on a completed write. | | `request_id` | Unique per request (`req_` prefix). | | `stream_id` | Unique per request (`st_` prefix). | | `table` | The fully qualified `schema.table` that was written. | | `successful_rows` | Number of rows written. | | `rejected_rows` | Always `0`: a batch either fully validates and writes, or the request fails with a `400`/`413` and writes nothing. | | `snapshot_id` | Always `null` on-prem; kept for cloud parity. | ## Examples The examples use `$DEFINITE_API_URL` (your deployment, e.g. `https://definite.example.com`) and `$DEFINITE_TOKEN` (a session or `def_` token). ### Append Insert rows into `crm.contacts`, creating the table on the first call: ```bash curl -sS "$DEFINITE_API_URL/api/v1/stream" \ -H "Authorization: Bearer $DEFINITE_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "data": [ {"id": 1, "name": "Ada Lovelace", "email": "ada@example.com"}, {"id": 2, "name": "Alan Turing", "email": "alan@example.com"} ], "config": {"table": "crm.contacts"} }' ``` ### Merge (upsert) Upsert on `id`: an existing contact has the sent columns updated, a new one is inserted, and contacts not in the batch are left untouched. Any column the payload omits (say a `created_at` or a derived `name_lower`) keeps its current value on the updated rows — merge only writes the columns you send: ```bash curl -sS "$DEFINITE_API_URL/api/v1/stream" \ -H "Authorization: Bearer $DEFINITE_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "data": [ {"id": 2, "name": "Alan Turing", "email": "alan.turing@example.com"}, {"id": 3, "name": "Grace Hopper", "email": "grace@example.com"} ], "config": {"table": "crm.contacts", "mode": "merge", "primary_key": ["id"]} }' ``` For a composite key, pass more than one column, e.g. `"primary_key": ["org_id", "id"]`. ### Replace Overwrite the table with a fresh snapshot (every existing row is deleted, then the incoming rows are inserted): ```bash curl -sS "$DEFINITE_API_URL/api/v1/stream" \ -H "Authorization: Bearer $DEFINITE_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "data": [ {"id": 1, "name": "Ada Lovelace", "email": "ada@example.com"}, {"id": 2, "name": "Alan Turing", "email": "alan@example.com"} ], "config": {"table": "crm.contacts", "mode": "replace"} }' ``` ## See also - [Event Ingest](/docs/event-ingest): append-only product events into a fixed schema - [API reference](/docs/api): auth, the full endpoint surface, and SQL queries - [Permissions](/docs/permissions): table-level data access --- # Integrations An **integration** is a stored, reusable connection to an external system — a Postgres database, a SaaS API, a Slack workspace, an LLM provider. It holds the connection details and credentials in one place so automations, syncs, and Fi can reference the source by name without anyone re-pasting a secret. Data flows in one direction: a source integration → an automation pipeline → the lakehouse. The integration is the credential; the [automation](/docs/automations) is the work that uses it to pull rows. ## The integration-type system Every integration has a **type** (`postgres`, `hubspot`, `slack_webhook`, `oauth2`, `custom`, …). The type is a schema: it declares the form fields the customer fills in, split into two halves. - **`public_fields`** — non-secret configuration. Stored in plaintext and visible in the UI: a database host, a port, an SSL mode, an OAuth provider profile. - **`secret_fields`** — credentials. **Encrypted at rest** (Fernet) and never returned to the UI or to Fi after they are saved: a password, an API key, an OAuth client secret, a PEM-encoded private key. Because the type *is* the schema, the Settings → Integrations form is generated from it — there is no hand-written form per source. Each field carries a label, a type (`string`, `url`, `email`, `password`, `number`, `select`), a `required` flag, and an optional description, and the API validates the submitted payload against that schema before it stores anything. ### Worked example: Postgres The `postgres` type connects a Postgres database with username/password auth. | Field | Half | Notes | |---|---|---| | `host`, `port`, `database`, `user` | public | The connection target. | | `sslmode` | public | `require` (default), `disable`, `prefer`, `verify-ca`, `verify-full`. | | `password` | secret | Encrypted at rest. | | `sslrootcert`, `sslcert`, `sslkey` | secret | PEM contents (not file paths) for `verify-ca`/`verify-full` against a private CA, or mutual TLS. | | `ssh_host`, `ssh_port`, `ssh_user` | public | Optional — set to tunnel through an SSH bastion / jump host. | | `ssh_private_key`, `ssh_key_passphrase` | secret | The bastion key material. | A database inside the deployment's own VPC needs only the first five fields; the SSH-tunnel fields exist for sources reachable only through a bastion. After you save, **Test connection** runs a real `SELECT 1` and, on a network timeout, reminds you to allowlist the deployment's egress IP — shown in **Settings → Workspace → General** (and as a hint on this form) when the deployment has a reserved egress address. See [Network Requirements](/docs/network-requirements). Postgres tables are then synced with a [`pg_sync`](/docs/automations#pg_sync) automation step, which streams rows directly from the source into the lakehouse. ### Worked example: SQL Server The `sqlserver` type connects to Microsoft SQL Server with username/password auth and syncs through the DuckDB `mssql` extension. | Field | Half | Notes | |---|---|---| | `host`, `port`, `database`, `user` | public | The connection target. Port defaults to `1433`. | | `schema` | public | Optional schema filter for source discovery. | | `use_encrypt` | public | TLS encryption. Defaults to `true`; set `false` only for legacy servers with no TLS support. | | `trust_server_certificate` | public | Defaults to `false`. Set `true` for internal SQL Servers using a self-signed certificate or private CA that the deployment does not trust. Requires `use_encrypt=true`. | | `password` | secret | Encrypted at rest. | After saving, **Test connection** runs a real `SELECT 1`. Certificate failures are reported with the `trust_server_certificate` remediation instead of a raw TLS stack trace. SQL Server tables are synced with an [`mssql_sync`](/docs/automations#mssql_sync) automation step. ### Worked example: HubSpot HubSpot uses the `hubspot` integration type: a single Bearer token in the `api_key` secret field. HubSpot now recommends a **Service Key** for single-account API access like this (backend integrations, ETL or warehouse syncs, and BI tools), so that is what Definite recommends. The token behaves like the standard HubSpot Bearer token, so syncs work the same way. 1. Sign in to HubSpot. You need **Super Admin** or **Developer tools access** permission to create a service key. 2. Go to **Development → Keys → Service keys**, click **Create service key**, and name it (for example, `Definite`). 3. Click **Add new scope**, search for `.read` to filter, then select the read scopes you need (`crm.objects.contacts.read`, `crm.objects.companies.read`, `crm.objects.deals.read`, `crm.objects.tickets.read`). Add `sales-email-read` and `tickets` if your syncs use them. Use read-only scopes for sync-only pipelines. 4. Click **Create** and confirm, then open the new key, click **Show**, and **Copy** the token (it looks like `pat-na1-...`). 5. In Definite, **Add integration → HubSpot** and paste the token into the **Service key** field. It is encrypted at rest and never shown to Fi. If Service Keys are not available in your account yet, a legacy private app token still works as a fallback: create one under **Development → Legacy apps** and copy its access token into the same field. See the [HubSpot service keys docs](https://developers.hubspot.com/docs/apps/developer-platform/build-apps/authentication/account-service-keys) for details. ## The connector catalog For SaaS sources there is a **connector catalog** — roughly 125 pre-built connectors (HubSpot, Stripe, Salesforce, Shopify, Jira, Notion, and many more). A connector packages everything needed to sync a source: the integration form, the list of syncable objects (with primary keys and incremental watermarks), and the loader that calls the source API. Connectors come in two flavours: - **Declarative `rest` connectors** (~80) — the connector's `connector.json` manifest fully describes the API: base URL, auth, pagination, and each object's path and record selector. These run on one shared REST loader; no per-source code. - **Dedicated-loader connectors** (~45) — sources whose API does not fit the declarative shape (unusual pagination, GraphQL, multi-step calls) ship a small purpose-built `loader.py` alongside the manifest. Either way the customer experience is the same: pick the connector, pick the objects, schedule it. To add one, ask **Fi** to set up the pipeline ("sync my HubSpot contacts") or use the Settings → Integrations page directly. Fi's pipeline-builder skill collects the credentials in a secure panel, creates the integration, and builds a scheduled automation that loads the chosen objects. ## OAuth connectors Sources that authenticate with OAuth 2.0 — Google Sheets, Salesforce, QuickBooks, Xero, LinkedIn, Microsoft, and the rest of the authorization-code providers — use the generic **`oauth2`** integration type. One type backs every such provider; per-provider differences (token endpoints, default scopes, refresh quirks) live in provider *profiles*. ### Mode B — bring-your-own OAuth app (available today) The mode that ships today is **Mode B**: you register your own OAuth application with the provider, and the deployment runs the consent and token-refresh flow itself. No credential ever leaves your network. Connecting an OAuth source, end to end: 1. **Register an OAuth app** with the provider (e.g. in the Google Cloud Console). Set its redirect URI to `/api/v1/oauth/callback`. Use the deployment's stable public hostname — most providers reject `nip.io` hosts, bare IPs, and non-https URLs, so set `PUBLIC_BASE_URL` accordingly. 2. **Create an `oauth2` integration** in **Settings → Integrations → Add integration → OAuth 2.0**. The form shows the exact callback URL to paste into your provider's OAuth app and flags common misconfigurations (no `PUBLIC_BASE_URL` set, callback host on a provider-rejected URL pattern). Pick the provider profile, enter your app's **client ID** and **client secret** (both encrypted at rest), and any provider-specific extras (Google Ads needs a `developer_token` here; Salesforce lets you pick between production and sandbox). 3. **Authorize** — click **Authorize now** in the modal after saving, or open `GET /api/v1/oauth/authorize?name=` directly. The deployment mints a CSRF `state` + PKCE pair and redirects you to the provider's consent screen. On approval the provider calls back to `/api/v1/oauth/callback`, the code is exchanged for tokens, and the access and refresh tokens are stored encrypted on the integration. 4. **Tokens auto-refresh.** A fetch-time *refresh-on-read* hook checks the access token whenever the integration is used. A background worker also passes over every `oauth2` integration on a 15-minute cadence so integrations referenced only by infrequent automations don't lapse past a provider's refresh-token expiry window (Outreach rotates with a ~100-day life; an unverified Google app's refresh tokens die in 7 days). When refresh becomes impossible the integration surfaces a "Reconnect" state — re-run the authorize step to fix it. The most recent `last_refresh_at` timestamp is visible under **Test** in the integration detail. A few providers are not authorization-code flows at all. NetSuite uses its own Token-Based Authentication integration type; ADP, Amazon Selling Partner, and Microsoft Ads are out of scope for the `oauth2` type entirely. ### Worked example: Salesforce 1. In Salesforce (or your sandbox org), go to **Setup → App Manager → New Connected App**. Enable **OAuth Settings**. 2. Set the **Callback URL** to the exact value shown on the Definite integrations form (typically `https:///api/v1/oauth/callback`). 3. Add at least the `api` and `refresh_token` scopes. The Definite profile requests these by default. 4. Save the Connected App and copy the **Consumer Key** (client ID) and **Consumer Secret** (client secret). 5. In Definite, **Add integration → OAuth 2.0**. Pick provider profile `salesforce`. For a sandbox org, set the auth domain to `test.salesforce.com`; leave it at `login.salesforce.com` for production. Paste the Consumer Key and Consumer Secret. 6. Click **Authorize now** to complete the consent flow. After approval, the integration stores the access token, refresh token, and the org's `instance_url` (used by syncs as the REST API base). ### Worked example: Google Ads 1. In the [Google Cloud Console](https://console.cloud.google.com/), create an OAuth 2.0 client of type **Web application** under **APIs & Services → Credentials**. Add the Definite callback URL as an authorized redirect URI. 2. Enable the **Google Ads API** for the same project. 3. In your Google Ads MCC (manager account), apply for an **Approved developer token** (Basic access or higher). Every Google Ads API request needs this `developer-token` header in addition to the OAuth token. 4. In Definite, **Add integration → OAuth 2.0**. Pick provider profile `googleads`. Paste the OAuth client ID and secret, plus the developer token and (optionally) the `customer_id` / `login_customer_id` of the MCC. 5. Click **Authorize now**. Google will only return a refresh token if the consent screen is fully re-approved with `access_type=offline` + `prompt=consent` — the Definite profile requests both, so the first consent works; do not skip Google's "Are you sure?" page. ## Syncs run as automations An integration on its own moves no data — it is the credential. The actual ingestion runs as an [automation pipeline](/docs/automations): a `pg_sync` step for Postgres, or a `python` step (driven by a connector loader) for SaaS sources. Pipelines can run on a cron schedule, so a configured integration plus a scheduled automation gives you a source that refreshes into the lakehouse on its own. See [Automations](/docs/automations) for step types, scheduling, and run history. --- # Source Control Definite can export workspace object definitions to a customer-owned GitHub repository through a GitHub App installation. Definite remains the source of truth in v1; GitHub receives pull requests with reviewable files. ## GitHub App setup Create a GitHub App in the GitHub organization that owns the destination repository. Grant the app access only to the repository Definite should write. Required repository permissions: | Permission | Access | |------------|--------| | Metadata | Read | | Contents | Read and write | | Pull requests | Read and write | Generate a private key for the app, install the app on the selected repository, and record the app ID, client ID, client secret, installation ID, owner, repo, and default branch. In Definite, open **Settings -> Source Control** and enter the GitHub App and repository details. Definite encrypts the private key and client secret at rest with the same key-rotation path used for integration secrets. ## Exported objects The first sync version exports these objects under the configured path prefix (`Definite/` by default): | Object | Path | |--------|------| | Semantic models | `semantic/.yaml` | | Transformation projects | `transformations//manifest.json` | | Data apps | `data-apps//app.json` and `data-apps//source/**` | | Automation pipelines | `automations/.json` | Use **Preview** to see generated files without contacting GitHub. Use **Compare** to compare those files with the configured GitHub branch. Use **Open PR** to create or update the `definite-object-sync` branch and open a pull request against the configured base branch. ## Scope V1 is export-only. Editing files in GitHub does not automatically apply changes back into Definite. Use the existing CLI/API flows to apply semantic models, transformation projects, data apps, and automations back into the deployment. --- # Automations Automations are ordered workflows for ingest, transforms, alerts, and agent tasks. > For a scheduled monitor that runs a SQL probe, asks an LLM whether to act, > and then acts — see [Autonomous Agents](/docs/agents). An automation can make > a one-shot LLM judgment too (the [`llm_decision`](#llm_decision) step plus a > [`when`](#step-guards-when) guard), but an agent additionally remembers > across runs, has a cooldown, and feeds its run history back to the model. V1 shape: ```text pipeline definition -> queued run -> ordered run steps -> logs + outputs ``` The API stores definitions and run history in Postgres. The `job-runner` Deployment polls Postgres, claims queued runs, and executes each run's steps in order. Runs execute concurrently — up to `jobRunner.maxConcurrentRuns` (default 3) at a time per runner pod — but never two runs of the same pipeline at once, so watermarks and sync state stay serial per pipeline. ## Pipeline Definition ```json { "name": "Flight count alert", "description": "Query the lakehouse and notify Slack.", "definition": { "steps": [ { "id": "summarize", "type": "sql", "config": { "sql": "SELECT COUNT(*) AS flights FROM flights" } }, { "id": "notify", "type": "slack_webhook", "config": { "integration": "slack-mjr-onprem", "text": "Automation finished: {{ run.id }}. Rows: {{ steps.summarize.rows_json }}" } } ] } } ``` Besides `steps`, a definition may set `"lane": "backfill"` to mark the pipeline's runs as long full-history syncs — see [Concurrency, lanes, and cancelling runs](#concurrency-lanes-and-cancelling-runs). The default lane is `default`. At the pipeline level, `run_after_pipeline_id` may name one upstream pipeline. Each successful upstream run then enqueues this pipeline; see [Run-after dependencies](#run-after-dependencies). ## Step Types Full set: [`sql`](#sql), [`python`](#python), [`slack_webhook`](#slack_webhook), [`send_email`](#send_email), [`email_report`](#email_report), [`pg_sync`](#pg_sync), [`adbc_sync`](#adbc_sync), [`mssql_sync`](#mssql_sync), [`assert_unique`](#assert_unique), [`agent`](#agent), [`llm_decision`](#llm_decision), [`maintenance`](#maintenance), and [`data_app_export`](#data_app_export). Three of these deliver something to a person, and picking the wrong one is the usual mistake: | Want | Step | |---|---| | A data app emailed as a PDF or PNG attachment | [`email_report`](#email_report) | | An email whose body you write (digest, alert, threshold breach) | [`send_email`](#send_email) | | A message in a Slack channel | [`slack_webhook`](#slack_webhook) | | A query's rows as a CSV in object storage | [`data_app_export`](#data_app_export) | All of them authenticate themselves from the pipeline. None of them takes an API token, and you never need to create one to schedule a report. ### `sql` Runs SQL against the lakehouse. ```json { "id": "transform_orders", "type": "sql", "config": { "sql": "CREATE OR REPLACE TABLE marts.orders AS SELECT * FROM raw.orders", "max_output_rows": 100 } } ``` ### `python` Runs a Python script inside the job-runner container, or in a burst sandbox when `config.compute_profile` names a non-default profile. The script receives `AUTOMATION_RUN_ID`, `AUTOMATION_STEP_ID`, and `AUTOMATION_CONTEXT_JSON` plus anything declared on `config.env`. Set `config.attach_lake: true` when the script needs `definite_lakehouse.query()`, `write_table()`, or direct DuckDB/DuckLake access. For compatibility with definitions created before this flag existed, scripts that import or mention `definite_lakehouse` are also treated as attached when the field is omitted. Set `attach_lake: false` to disable that inference. The script body is specified in **exactly one** of three ways: - `script_id` — reference a stored script by its hex id. - `script_name` — reference a stored script by its unique name. - `script` — inline source, useful for one-liners or ad-hoc steps. Prefer `script_id` / `script_name`: scripts are managed via the `/api/v1/automation-scripts` endpoint and edited in the frontend with a Monaco editor, so non-trivial Python doesn't have to be JSON-escaped into the pipeline definition. Every python step runs via `uv run --python 3.12 --no-project` in an ephemeral venv. When the step (or stored script) declares `requirements`, the executor writes them to a `requirements.txt` and adds `--with-requirements `, so the listed packages are installed for that run only. Resolved wheels are cached on the job-runner's `uv` cache volume (see `helm/values.yaml: jobRunner.uvCache`), so the second run with the same deps starts in seconds. Baked-in libs: `pyarrow`, `duckdb`, `polars`, `httpx`, `requests`, `psycopg2`. For pandas, scikit-learn, or any other lib, add it to your step's or stored script's `requirements` and uv will install it per-run. #### Stored script (recommended) ```json { "id": "load_api", "type": "python", "config": { "script_name": "load_hubspot" } } ``` The job-runner resolves the reference, runs the latest `content`, and installs the row's `requirements` list before execution. The step output includes `script_id`, `script_name`, `script_version`, `script_requirements`, `resolved_requirements`, and `uv_command` for traceability. #### Inline script (escape hatch) ```json { "id": "load_api", "type": "python", "config": { "timeout_seconds": 900, "env": { "SOURCE_NAME": "hubspot" }, "requirements": ["httpx>=0.27", "polars>=0.20"], "script": "import os, httpx\nprint('load', os.environ['SOURCE_NAME'])" } } ``` `config.requirements` is optional. Each entry must be a non-empty string; the format is whatever `uv pip install` accepts (PEP 508 specifiers, VCS URLs, etc.). It's only valid on inline scripts — stored scripts carry their own `requirements` column. #### Automation scripts API ```text GET /api/v1/automation-scripts/ # list (no body content) POST /api/v1/automation-scripts/ # create GET /api/v1/automation-scripts/{id_or_name} # full record, including content PATCH /api/v1/automation-scripts/{id_or_name} # update content/description/requirements; bumps version DELETE /api/v1/automation-scripts/{id_or_name} # 409 if any pipeline references it POST /api/v1/automation-scripts/{id_or_name}/fork # copy to a custom script, optionally repointing pipelines GET /api/v1/automation-scripts/{id_or_name}/versions # placeholder for v1.5 GET /api/v1/connector-catalog/{connector_id}/loader # current shipped core connector loader ``` Create payload: ```json { "name": "hubspot_loader", "description": "Pull contacts from HubSpot into raw.hubspot_contacts.", "content": "import os\nprint('loading', os.environ['SOURCE_NAME'])\n", "requirements": ["requests==2.32.0"] } ``` `version` bumps on every PATCH. The integer is included in each step's output payload so a run's logs can be traced back to the exact script body that executed. Names are unique — pick something stable, since pipeline definitions reference scripts by name (or id), and renaming a referenced script will break pipelines that use the old name. #### Core connector scripts Connector-catalog pipelines reference a deployment-managed script named `connector__loader` by default. On API startup, the shipped connector catalog is reconciled into `automation_scripts` rows with `origin: "core_connector"`, `managed: true`, `connector_id`, and an `upstream_hash`. These rows are the blessed connector loaders for the deployment and receive updates when a new API image ships a changed catalog. Managed core connector scripts are read-only: `PATCH` and `DELETE` return `409` with guidance to fork first. Use `POST /api/v1/automation-scripts/{id_or_name}/fork` to create a custom copy. The fork keeps the connector metadata, records `forked_from_hash`, clears `managed`, and can take `pipeline_ids` to repoint those pipeline steps from the core script to the forked script name in the same transaction. After a fork, upstream updates no longer overwrite the custom script. Use `GET /api/v1/connector-catalog/{connector_id}/loader` to fetch the current blessed loader when comparing or manually merging upstream changes. #### Runtime requirements The job-runner pod needs outbound network access to `pypi.org` (and `files.pythonhosted.org`) to install declared dependencies on the first run with a given dep set. The `uvCache` PVC keeps subsequent runs offline for the same versions. For air-gapped deployments, either point `uv` at a private index via `UV_INDEX_URL` (set in `jobRunner.extraEnv`) or omit `requirements` and bake the packages into a custom job-runner image. #### Environment contract The python subprocess receives an explicitly-constructed environment. Nothing else from the runner pod's environment leaks in. Scripts can rely on: | Variable | Source | Purpose | |---|---|---| | `AUTOMATION_RUN_ID` | runner | The current run's id. | | `AUTOMATION_STEP_ID` | runner | The current step's id. | | `AUTOMATION_CONTEXT_JSON` | runner | JSON-encoded prior step outputs (`{"run": {...}, "steps": {...}}`). Bounded to 64 KiB: env strings are kernel-capped at 128 KiB and a spawn past that fails with `E2BIG`. The run's `definition` snapshot is excluded (a multi-object connector definition alone can exceed the cap), each prior step's `stdout`/`stderr` keeps only its last 2,000 chars, and if the payload is still over, that free text is dropped entirely oldest-step-first. A step whose output was shortened carries `"context_truncated": true`; the full output stays on the run's step records and in template rendering. | | `LAKEHOUSE_CATALOG_DSN` | `get_settings()` when `attach_lake` is true | libpq DSN for the `ducklake_catalog` Postgres database; `definite_lakehouse` attaches `ducklake:postgres:` with it. | | `LAKEHOUSE_LAKE_ALIAS` | `get_settings()` when `attach_lake` is true | Defaults to `LAKE`. | | `LAKEHOUSE_QUERY_TIMEOUT_SECONDS` | `get_settings()` when `attach_lake` is true | Query timeout used by the SDK. | | `LAKEHOUSE_DATA_PATH` | `get_settings()` when `attach_lake` is true | Object-store data path the DuckLake attach reads parquet from over httpfs. | | `LAKEHOUSE_STORE_TYPE` | `get_settings()` when `attach_lake` is true | Active store backend (`gcs`, `s3`, `minio`, `azure`). | | `DEFINITE_INTEGRATIONS_JSON` | runner (optional) | JSON object of the integrations the step declared in `config.integrations`, decrypted. Read via `get_integration()`; only set when the step declares integrations. | | `DEFINITE_STEP_KV_API_URL`, `DEFINITE_STEP_KV_TOKEN` | runner | Internal, short-lived capability used by `definite_lakehouse` KV helpers. The token is scoped to KV calls and revoked when the step exits; scripts should use the SDK rather than read these directly. | | `LAKEHOUSE_STAGING_URI` | runner when `attach_lake` is true | Bucket prefix `write_parquet_to_lake` stages to. Defaults to a `_staging/` subpath of the lake's data path; override with `jobRunner.staging.uri`. | | Active store credentials | runner when `attach_lake` is true | `GCS_HMAC_*`, `S3_*`, or `AZURE_STORAGE_*`, depending on `lakehouse.storeType`. | | `PATH`, `HOME`, `LANG`, `LC_ALL` | runner | Minimal shell bootstrap so uv works. | | `UV_*` | runner | Forwarded so `UV_CACHE_DIR` / `UV_INDEX_URL` flow through. | | `config.env.*` | step config | Anything declared on the step. | Anything else (e.g. `AWS_SECRET_ACCESS_KEY` or arbitrary operator-set vars on the runner pod) does NOT propagate. Put values you want available in either `config.env` for the step or `jobRunner.extraEnv` with a recognized prefix (today: `UV_*`). For sandboxed compute-profile steps, lake and store keys from `config.env` are still dropped unless `attach_lake` resolves to true. #### Writing to the lakehouse Every python step has `definite_lakehouse` preinstalled (the wheel is baked into the job-runner and fi-sandbox images and passed via `uv run --with`). The same wheel also provides `connector_streaming` — the connector-building layer the catalog loaders use. Custom sync scripts can import it instead of hand-rolling batching, checkpoint cursors, or OAuth token refresh: ```python from connector_streaming import write_stream, read_checkpoint from connector_streaming import OAuthTokenProvider, request_with_retries from definite_lakehouse import retry_commit_conflicts ``` `write_stream` writes a row iterable in bounded batches with commit-conflict retry; `read_checkpoint`/`commit_checkpoint` persist sync cursors in the queryable `__definite_internal.connector_checkpoints` table. Use the checkpoint helpers for sync cursors you want to inspect with SQL; use `kv_get`/`kv_set` (below) for small opaque state such as rotated tokens. The common shape is to opt into lake access and then import the SDK: ```json { "id": "load_lake", "type": "python", "config": { "attach_lake": true, "script_name": "load_lake" } } ``` ```python import polars as pl from definite_lakehouse import write_table, query df = pl.DataFrame({"id": [1, 2, 3], "v": ["a", "b", "c"]}) write_table(df, "main.hello", mode="replace") # or mode="append" count = query("SELECT count(*) FROM main.hello").to_pylist() print(count) ``` `write_table` accepts polars / pyarrow / pandas inputs (duck-typed — pandas is supported as input but isn't shipped in the image; declare it on `config.requirements` if your script also imports it directly). It inlines rows as a `VALUES` literal up to a 50k-row cap. #### Using a stored integration — `config.integrations` A python step can use a stored integration's credentials without fetching them over the API. Declare the integrations the step needs by name in `config.integrations`: ```json { "id": "ingest", "type": "python", "config": { "script_name": "hubspot-contacts-ingest", "attach_lake": true, "integrations": ["hubspot"] } } ``` `config.integrations` is a list of integration names; it is only valid on `python` steps. At run time the job-runner resolves each declared integration in-process (decrypted, audited as an `automation_run` secret access — the same path `pg_sync` uses) and injects them into the subprocess as `DEFINITE_INTEGRATIONS_JSON`. The script reads them with `get_integration()`: ```python from definite_lakehouse import get_integration, write_table hs = get_integration("hubspot") api_key = hs["secrets"]["api_key"] # decrypted secret half portal = hs["public"]["portal_id"] # non-secret config half # ... call the HubSpot API, build an arrow table ... write_table(tbl, "main.hubspot_contacts", mode="replace") ``` `get_integration(name)` returns `{"name", "type", "public", "secrets"}`. It raises a clear error if the step did not declare that integration in `config.integrations`. This replaces the old anti-pattern of passing an admin token through `config.env` and calling `GET /api/v1/integrations/{id}/reveal` from the script. #### Durable step state — KV Every Python step can persist small JSON values in the application Postgres without putting security-sensitive state in a queryable lakehouse table. Values are encrypted at rest with the deployment's rotatable application key. The runner gives each executing step a short-lived capability that authorizes only KV calls and revokes it when the step exits; no user API token or Postgres credential is exposed to the script. For new code, read and write individual keys directly: ```python from definite_lakehouse import kv_get, kv_set refresh_token = kv_get("xero-sync", "refresh_token") # ... refresh OAuth credentials ... kv_set("xero-sync", "refresh_token", rotated_refresh_token) ``` Values may be strings, numbers, booleans, null, lists, or objects, up to 64 KiB serialized. Namespaces are deployment-wide, so choose a stable, pipeline-specific name. Writes are last-write-wins; normal automation runs are already serialized per pipeline, so one namespace should have one pipeline as its writer. Cloud SDK ports can keep the familiar buffered store pattern with a one-line construction change: ```python from definite_lakehouse import get_kv_store state = get_kv_store("xero-sync") token = state.get("refresh_token") state["refresh_token"] = rotated_refresh_token state.commit() ``` The compatibility store buffers assignments until `commit()`. It does not provide cloud store-wide optimistic versioning; each key is persisted with last-write-wins semantics. #### Large writes — `write_parquet_to_lake` For writes above the inline cap the SDK stages parquet to the object store and drives one `CREATE … AS SELECT * FROM read_parquet('')` on the lakehouse. This happens transparently — `write_table` auto-routes any call larger than 50k rows. Staging works out of the box: when `jobRunner.staging.uri` is left unset the chart derives a default (`/_staging/`), so it lives in the same bucket the lake already uses and the existing object-store credentials cover it. Set `jobRunner.staging.uri` explicitly to stage somewhere else. You can also call the helper directly: ```python from definite_lakehouse import write_parquet_to_lake write_parquet_to_lake( df, "main.big_table", mode="replace", # or "append" # staging_prefix="gs://acme-lake/staging/", # overrides LAKEHOUSE_STAGING_URI # cleanup=True, ) ``` Required env (Helm wires these from the lake's object-store config): - `LAKEHOUSE_STAGING_URI`: a URI on the lake's own object store, matching `lakehouse.storeType`. `gs://bucket/prefix/` for GCS, `s3://bucket/prefix/` for S3/MinIO, or `az://account.blob.core.windows.net/container/prefix/` (or legacy `azure://…`) for Azure Blob. Defaults to `/_staging/`; override with `jobRunner.staging.uri`. - The lake's object-store credentials, the same ones the embedded DuckLake connection uses: `GCS_HMAC_*` for GCS, `S3_*` or IRSA for S3/MinIO, `AZURE_STORAGE_*` for Azure. The chart mounts them per `lakehouse.storeType`. The parquet upload goes through DuckDB's native object-store client, using the same `store_creds` secret and signing path the lake reads parquet with, so it works on every store the lake supports, not just GCS. Staging files are **not** cleaned up inline (DuckDB's httpfs/azure extensions don't expose an object-store delete), so configure a lifecycle rule on the staging prefix (e.g. 1-day expiration) to reap files after the lake has loaded them. ### `slack_webhook` Posts a message to Slack. ```json { "id": "notify", "type": "slack_webhook", "config": { "integration": "slack-mjr-onprem", "text": "Finished run {{ run.id }}. Rows: {{ steps.summarize.rows_json }}" } } ``` `integration`, `integration_name`, and `integration_id` all resolve a stored `slack_webhook` integration. For local/debug use, `webhook_url_env` and `webhook_url` are still supported, but stored integrations are preferred so secrets stay encrypted in Postgres. #### Template variables in `text` `config.text` is rendered as a Jinja2 template against the run context, so any expression you can write in Jinja works: | Reference | Resolves to | |---|---| | `{{ run.id }}` | the run's UUID | | `{{ steps..rows }}` | the step's rows (a list of dicts) | | `{{ steps..rows[0].my_col }}` | a single value from the first row | | `{{ steps..row_count }}` | how many rows the step returned | | `{{ steps..rows_json }}` | the rows array, JSON-encoded as a single string | | `{{ steps..output_json }}` | the full step output, JSON-encoded | | `{{ steps..stdout }}` | stdout from a `python` step | Standard Jinja filters (`| tojson`, `| format`, `| upper`, …) and control structures (`{% if %}`, `{% for %}`) are available. Unknown variables fail the step at render time rather than silently leak `{{ … }}` into the message — fix the typo and re-run. The renderer uses Jinja2's `SandboxedEnvironment` (attribute access on private (`_…`) and dunder (`__…`) names is blocked), so step text is safe to evaluate even when authored by less-trusted users. #### When to reach for a `python` step instead Jinja in `config.text` is for pulling one or two values out of a prior step's first row. Anything beyond that belongs in a [`python`](#python) step that queries the lakehouse and posts to Slack itself. Signals that you're past what `text` should do: - The message body branches (`{% if %}` deciding whether to alert, or which channel to hit). - You're formatting a multi-row table, looping over rows, or accumulating state across them. - You need values from more than one integration in the same message. - You want to call an LLM, retry on failure, or rate-limit yourself. - The SQL needs a follow-up call (enrichment, lookup, second query) before the message is built. - You catch yourself reaching for `| tojson` and then parsing it back in your head to figure out what the message will look like. In a `python` step you have the lakehouse, the integration's secrets, and the full standard library; there's no template language to fight. ##### The same alert, both ways A "Stripe revenue dropped below $100k" alert as a SQL probe plus a templated `slack_webhook`. The probe's `HAVING` clause returns a row **only when** the total is below the threshold, so the notify step can guard on [`rows_nonempty`](#step-guards-when): ```json { "steps": [ { "id": "stripe_total", "type": "sql", "config": { "sql": "SELECT SUM(amount) / 100.0 AS total FROM stripe.charges WHERE status = 'succeeded' HAVING SUM(amount) / 100.0 < 100000" } }, { "id": "notify", "type": "slack_webhook", "when": { "step": "stripe_total", "expr": "rows_nonempty" }, "config": { "integration": "slack-mjr-onprem", "text": "Stripe revenue is ${{ '%.2f' | format(steps.stripe_total.rows[0].total) }}, below the $100k threshold." } } ] } ``` That works, and for a single-value threshold it's the right tool. The moment the alert needs to also list the top failing customers, hit a second integration, or skip if you already pinged today, collapse it into one `python` step: ```json { "steps": [ { "id": "stripe_alert", "type": "python", "config": { "attach_lake": true, "integrations": ["slack-mjr-onprem"], "script": "import requests\nfrom definite_lakehouse import query, get_integration\n\nTHRESHOLD = 100_000\nrows = query(\"SELECT SUM(amount) / 100.0 AS total FROM stripe.charges WHERE status = 'succeeded'\").to_pylist()\ntotal = rows[0]['total'] or 0\nif total >= THRESHOLD:\n print(f'ok: ${total:,.2f}')\nelse:\n slack = get_integration('slack-mjr-onprem')\n url = slack['secrets']['webhook_url']\n requests.post(url, json={'text': f'Stripe revenue is ${total:,.2f}, below the ${THRESHOLD:,} threshold.'}, timeout=10).raise_for_status()\n print(f'alerted: ${total:,.2f}')\n" } } ] } ``` `definite_lakehouse` is preinstalled, `requests` is baked into the image, and `config.integrations` decrypts the Slack webhook in-process — no template, no `when` clause, no second step to keep in sync. See [`python`](#python) for the full environment contract and the stored-script workflow. For a worked recipe that applies these pieces to data-freshness monitoring (alert when a table stops updating), see [Staleness Checks](/docs/staleness-check). ### `send_email` Sends a plain templated email through the deployment's configured email service (`EMAIL_MODE=smtp` or `definite_cloud`; see the [email configuration]( /docs/config#email)). Unlike the [`email_report`](#email_report) step — which renders a data app to a PDF/PNG attachment — `send_email` just sends a message body, so it's the step to use for digests, alerts, and any pipeline that used to call the cloud SDK's `send_email_message()`. ```json { "id": "notify", "type": "send_email", "config": { "to": ["alerts@example.com"], "subject": "Daily revenue: ${{ steps.total.rows[0].revenue }}", "html_body": "

Revenue today was ${{ steps.total.rows[0].revenue }}.

", "text_body": "Revenue today was ${{ steps.total.rows[0].revenue }}." } } ``` | Field | Required | Notes | |---|---|---| | `to` | yes | List of recipient addresses, 1 to 10. | | `subject` | yes | Rendered as a Jinja2 template (see below). | | `html_body` | one of the two | HTML body, rendered as a Jinja2 template. | | `text_body` | one of the two | Plain-text body, rendered as a Jinja2 template. | At least one of `html_body` / `text_body` is required; providing both sends a multipart message so clients that can't render HTML fall back to the text part. `subject`, `html_body`, and `text_body` are rendered with the same Jinja2 context and `SandboxedEnvironment` as [`slack_webhook`](#template-variables-in-text), so `{{ steps..rows[0].my_col }}`, `{{ run.id }}`, standard filters, and `{% if %}` / `{% for %}` all work, and an unknown variable fails the step at render time. If the deployment's email service is disabled or unconfigured, the step fails with a clear "requires configured email delivery" error rather than silently dropping the message. To send an email from outside a pipeline (a script, an ad-hoc job, a migrated cloud service), use the [`POST /api/v1/email/send`](/docs/api#email) HTTP route instead — it delivers through the same email service. ### `email_report` Renders an existing [data app](/docs/data-apps) in a headless browser and emails it as a PDF or PNG attachment. This is the step for "email me this dashboard every month": one step, no SQL, no scripting, and **no API token**. ```json { "id": "mail", "type": "email_report", "config": { "to": ["exec-team@example.com"], "app_slug": "second-look-trend", "subject": "Second Look dealer mix — {{ run.started_at }}", "format": "pdf", "pdf_orientation": "landscape", "viewport": { "width": 1440, "height": 1000 } } } ``` | Field | Required | Notes | |---|---|---| | `to` | yes | List of recipient addresses, 1 to 10. | | `app_slug` | yes | Slug of the data app to render, as it appears in `/apps/`. | | `subject` | yes | Rendered as a Jinja2 template, same context as `send_email`. | | `format` | no | `pdf` (default) or `png`. | | `body` | no | HTML message body. Templated. Defaults to a one-line "Attached is your Definite report." | | `pdf_orientation` | no | `portrait` or `landscape`. Only swaps the page dimensions; it never scales the app. | | `viewport` | no | `{"width": ..., "height": ...}`, each 320 to 4000. Defaults to 1440x1000. | **Authentication is automatic, and this is the point of the step.** The job-runner mints a short-lived render token for the pipeline's owner (the user who created the pipeline) and loads the app as them. Recipients get a flat attachment, not a link, so they need no Definite account. There is nothing to paste, store, or rotate — if a workflow is asking anyone for an API token in order to email a report, it has taken a wrong turn. Because the render runs as the pipeline owner, the report shows exactly what that person can see. A pipeline owned by someone without access to the app's underlying tables produces an empty or partial report, so create the pipeline as a user who can open the app. Prerequisites: - The deployment has email delivery configured (`EMAIL_MODE=smtp` or `definite_cloud`). Otherwise the step fails with "email_report step requires configured email delivery". This is an admin setting; see [email configuration](/docs/config#email). - The data app already exists and renders. Build it first, open it once, then schedule it. - The job-runner can reach the frontend. It uses `EMAIL_REPORT_BASE_URL`, `FRONTEND_INTERNAL_BASE_URL`, or `PUBLIC_BASE_URL`, in that order. The renderer waits for the app's charts to finish loading before it captures the page, up to `EMAIL_REPORT_READY_TIMEOUT_MS` (default 120000). An app whose queries never resolve fails the step with "email_report render timed out" rather than mailing a picture of a loading spinner. If reports start timing out, the app itself is slow — profile its queries rather than raising the timeout. Widening `viewport.width` fits more of a dense dashboard on the page; it does not re-flow the app to a narrower layout. For a tall dashboard prefer `format: "png"`, which captures the full scroll height, over a PDF that has to pick one page size. #### Recipe: email a data app every month The whole pipeline, ready to `POST /api/v1/automations/pipelines`. `0 13 1 * *` is 13:00 on the 1st of each month, in `cron_timezone`. ```json { "name": "Monthly Second Look report", "description": "PDF of the Second Look dealer-mix app, 1st of the month.", "enabled": true, "cron_schedule": "0 13 1 * *", "cron_timezone": "America/New_York", "definition": { "steps": [ { "id": "mail", "type": "email_report", "config": { "to": ["exec-team@example.com"], "app_slug": "second-look-trend", "subject": "Second Look dealer mix — monthly", "format": "pdf", "pdf_orientation": "landscape" } } ] } } ``` Weekly instead is `0 13 * * 1` (Mondays at 13:00). Use a real timezone rather than UTC so the send does not drift an hour across daylight saving. Before trusting the schedule, trigger it once by hand with `POST /api/v1/automations/pipelines/{id}/runs` and open the attachment. That one run confirms the three things a schedule cannot: email delivery is configured, the pipeline owner can see the app, and the app renders. If the report should reflect data that a sync or transform produces, do not race them on two crons. Put the `email_report` step last in the same pipeline, or point the report pipeline's `run_after_pipeline_id` at the pipeline that refreshes the data — see [Run-after dependencies](#run-after-dependencies). ### `pg_sync` Pulls a single table from a stored `postgres` integration into the lakehouse. Runs in the job-runner's embedded DuckDB connection: it ATTACHes the source Postgres via DuckDB's `postgres` extension and streams rows directly into DuckLake (the Postgres-catalog lake). ```json { "id": "pull_orders", "type": "pg_sync", "config": { "integration": "pg-prod", "source_table": "public.orders", "destination_table": "main.orders", "mode": "incremental", "watermark_column": "updated_at", "primary_key": ["id"] } } ``` Modes: - `full_refresh` — drops and recreates the destination on every run. Simple, always correct, but rescans the entire source table each time. - `incremental` — pulls rows where `watermark_column > last_seen_value`. If `primary_key` is provided, rows are upserted (DELETE-then-INSERT by key); otherwise they're appended. Watermarks are persisted in `automation_pg_sync_state` keyed by `(integration_id, source_table, destination_table)`, so the next run resumes from the last successful sync. On the first run the watermark is null and the full table is loaded. There is deliberately **no separate "backfill" mode**: a backfill is just the first run of an `incremental` sync (empty watermark state → full history, chunked and checkpoint-resumable), or a `full_refresh`. For a large initial load, configure `incremental` from day one, give the step a non-default `compute_profile` (it runs as a dedicated sync-executor Job — see [Sync-executor Jobs](#sync-executor-jobs)), and put the pipeline in `"lane": "backfill"`; when the first run finishes, the watermark is already seeded and the same pipeline is your steady-state sync. Full-refresh resume (#710): the chunked, key-windowed `full_refresh` path checkpoints each staged window in `automation_pg_full_refresh_state`. A run killed mid-backfill (pod OOM, node loss, helm roll) resumes from the last committed window on its next attempt instead of restarting — a crash costs at most one window. The checkpoint is fingerprinted to the extraction (`source_sql`, chunk key, chunk size); changing any of them starts clean. The staging table still swaps in atomically at the end, so the destination is never observed half-populated. The keyless (`ctid`-paged) fallback stays non-resumable — `ctid` order isn't stable across restarts. Postgres type/customization controls: - `column_casts` — optional object mapping source column names to Postgres cast types. `pg_sync` already casts Postgres enums and other source-defined types to `text`; use this for explicit choices like `"column_casts": {"status": "text", "payload": "jsonb"}`. - `source_sql` — optional Postgres `SELECT`/`WITH` query to read instead of `SELECT * FROM source_table`. Use it for casts, joins, computed columns, or source-side filters. It must be a single semicolon-free read query. For incremental syncs, `watermark_column` and `primary_key` must refer to columns returned by this query. Schema drift (applies to `pg_sync`, `adbc_sync`, and `mssql_sync` alike): - A column **added** on the source is added to the destination automatically before the next incremental load (`ALTER TABLE ... ADD COLUMN`, logged, and reported in the step output as `columns_added`). Rows synced before the column existed hold NULL — run a one-off `full_refresh` to backfill them. - A column **dropped** on the source stays on the destination; new rows hold NULL there. Synced data is never dropped automatically. - A **type change** on an existing column is logged as a warning and left to the insert's implicit cast; an incompatible change fails the run with the column named. Switch the step to `full_refresh` once to rebuild. Limitations: - Deletes on the source are not detected. Use `full_refresh` for tables where rows can be hard-deleted. - The customer's Postgres must be reachable from the job-runner pod. Lock down with NetworkPolicy + a least-privilege read-only role. - Credentials live in the stored `postgres` integration (encrypted at rest); the connection string is interpolated into the SQL the job-runner runs, so the job-runner pod sees them in plaintext at run time. ### `adbc_sync` Pulls a single table from a stored `snowflake` integration into the lakehouse. The ADBC counterpart of `pg_sync`. There is no Snowflake DuckDB extension, so unlike `pg_sync` (which streams directly through DuckDB's `postgres` extension) this cannot stream in-engine: the job-runner opens an ADBC connection, fetches the result as Apache Arrow, stages it as a parquet file to the lake's object store, and reads it back into DuckLake with `read_parquet()` on its embedded DuckDB connection. ```json { "id": "pull_orders", "type": "adbc_sync", "config": { "integration": "snowflake-prod", "source_table": "ANALYTICS.ORDERS", "destination_table": "main.orders", "mode": "incremental", "watermark_column": "UPDATED_AT", "primary_key": ["ID"] } } ``` Modes: - `full_refresh` — replaces the destination on every run. - `incremental` — pulls rows where `watermark_column > last_seen_value`. If `primary_key` is provided rows are upserted (DELETE-then-INSERT by key); otherwise they are appended. Watermarks are persisted in `automation_adbc_sync_state` keyed by `(integration_id, source_table, destination_table)`. On the first run the watermark is null and the full table is loaded. An incremental run that finds no new rows is a no-op and leaves the watermark unchanged. Customization: - `source_sql` — optional Snowflake `SELECT` to read instead of `SELECT * FROM source_table`. Use it for casts, joins, computed columns, or quoted/lower-case identifiers. For incremental syncs `watermark_column` and `primary_key` must refer to columns it returns. Limitations: - `source_table` identifiers are emitted verbatim and unquoted — Snowflake folds them to upper case. Use `source_sql` for quoted or lower-case names. - The whole result set is buffered as one Arrow table in the job-runner. Incremental deltas are small; a `full_refresh` of a very large table is the one heavy case (range-chunking it is a planned follow-on). - Deletes on the source are not detected — use `full_refresh` for tables where rows can be hard-deleted. - Requires object-store staging: `LAKEHOUSE_STAGING_URI` must be set (Helm sets it when `jobRunner.staging.uri` / the lake data path is configured). Staged parquet files are reaped by the object store's lifecycle rule. - Credentials live in the stored `snowflake` integration (encrypted at rest). Password and key-pair (JWT) auth are both supported; key-pair is preferred for service accounts. ### `mssql_sync` Pulls a single table from a stored `sqlserver` integration into the lakehouse. SQL Server has no ADBC driver and no built-in DuckDB extension, so the job-runner opens an in-process DuckDB connection, attaches the source through the DuckDB `mssql` community extension, stages the result as parquet, and has the lakehouse read it back. ```json { "id": "pull_loans", "type": "mssql_sync", "config": { "integration": "sqlserver-prod", "source_table": "dbo.Loans", "destination_table": "main.loans", "mode": "incremental", "watermark_column": "updated_at", "primary_key": ["id"] } } ``` Modes: - `full_refresh` — replaces the destination on every run. - `incremental` — pulls rows where `watermark_column > last_seen_value`. If `primary_key` is provided rows are upserted (DELETE-then-INSERT by key); otherwise they are appended. Watermarks are persisted in `automation_mssql_sync_state` keyed by `(integration_id, source_table, destination_table)`. Connection defaults: - The `sqlserver` integration uses `use_encrypt=true` by default. - Set `trust_server_certificate=true` only when the SQL Server presents a self-signed certificate or a certificate from an internal CA that the deployment does not trust. The test-connection path names this toggle when certificate validation fails. Customization: - `source_sql` — optional `SELECT` to read instead of `SELECT * FROM source_table`. It should reference the attached source as `mssql_src..
`. For incremental syncs `watermark_column` and `primary_key` must refer to columns it returns. Limitations: - The whole result set is buffered as one Arrow table in the job-runner. Incremental deltas are small; a `full_refresh` of a very large table is the heavy case. Range-chunked full refresh is a planned follow-on. - Deletes on the source are not detected — use `full_refresh` for tables where rows can be hard-deleted. - Requires object-store staging: `LAKEHOUSE_STAGING_URI` must be set (Helm sets it when `jobRunner.staging.uri` / the lake data path is configured). - Credentials live in the stored `sqlserver` integration (encrypted at rest). ### `assert_unique` Asserts that a lakehouse table holds at most one row per key. On a pass the step records the row/key counts and the run continues; on a violation the step (and the run) **fails** with the duplicate count and a sample of up to 10 offending keys, so a poisoned load is caught at write time instead of silently fanning out every downstream join. ```json { "id": "verify_keys", "type": "assert_unique", "config": { "table": "redshift_cleanid.transactiondata", "key": "transactionid" } } ``` Config: - `table` (required) — the table to check, as `schema.table` or a bare table name. Parts must be plain identifiers (letters, digits, underscores). - `key` (required) — a single column name, or a list of column names for a composite key. The check is one aggregate scan — `count(*)` vs `count(DISTINCT ())` — so it stays cheap even on 100M+-row tables. Only when the counts disagree does the step run a second `GROUP BY HAVING count(*) > 1` probe to capture the worst offenders (key values plus their row counts) into the step error and logs. NULL key values count toward `count(*)` but not `count(DISTINCT ...)`, so NULL keys also fail the assertion (a merge key must be non-null); when no key value occurs twice the error says the violation is NULLs. Step output on a pass: ```json { "table": "redshift_cleanid.transactiondata", "key": ["transactionid"], "total_rows": 134300000, "distinct_keys": 134300000, "duplicate_rows": 0, "passed": true } ``` #### The backfill invariant The incremental syncs write **merge-by-pk** (DELETE incoming keys, then INSERT incoming rows), so a synced table holds one row per key *going forward by construction* — downstream models may rely on that instead of re-deduplicating. But bulk-import paths (replace+append staging loads, parquet manifest copies, chunked full-refresh backfills) bypass merge, and sources do not necessarily enforce primary-key uniqueness — Redshift, for one, does not enforce declared PKs at all. The merge *maintains* uniqueness for every key it pulls but **cannot create it**: a backfill that copies source-side duplicates poisons the table indefinitely, and no scheduled incremental run will ever repair it. **Every bulk-import or backfill must therefore end with an `assert_unique` step (or a dedup-repair) on the merge key.** Chaining the step after the load is one cheap scan; scheduling it weekly on its own also works as insurance for tables whose downstream models depend on the invariant. #### Repairing a table that already has duplicates When `assert_unique` fails on an already-loaded table, repair just the duplicated keys — delete those keys, then reinsert exactly one surviving row per key — instead of re-running the whole backfill: ```sql -- 1. Capture the offending keys (the step's failure log holds a sample; -- this captures all of them). CREATE OR REPLACE TABLE main.dupe_keys AS SELECT transactionid FROM redshift_cleanid.transactiondata GROUP BY transactionid HAVING count(*) > 1; -- 2. Stash one surviving row per duplicated key. Pick a deterministic -- tiebreak (a watermark column, or re-select from the source when it -- holds the authoritative row). CREATE OR REPLACE TABLE main.dupe_repair AS SELECT * FROM redshift_cleanid.transactiondata WHERE transactionid IN (SELECT transactionid FROM main.dupe_keys) QUALIFY row_number() OVER ( PARTITION BY transactionid ORDER BY updated_at DESC ) = 1; -- 3. Delete every row for those keys, then reinsert the deduped survivors. DELETE FROM redshift_cleanid.transactiondata WHERE transactionid IN (SELECT transactionid FROM main.dupe_keys); INSERT INTO redshift_cleanid.transactiondata SELECT * FROM main.dupe_repair; DROP TABLE main.dupe_repair; DROP TABLE main.dupe_keys; ``` Scoped to just the duplicated keys, the repair touches thousands of rows instead of rewriting a 100M+-row table. Chain an `assert_unique` step after the repair to prove it worked. ### `agent` Runs a Fi/Pi agent step when Fi is enabled. ```json { "id": "agent_check", "type": "agent", "config": { "prompt": "Inspect the mart tables and summarize anything unusual.", "timeout_seconds": 1800 } } ``` ### `llm_decision` Makes one structured LLM call and returns the decision as the step output, so later steps can guard on it with a [`when`](#step-guards-when) clause. It is the building block for *"run this SQL, ask an LLM whether it's worth alerting on, and only then post to Slack."* ```json { "id": "judge", "type": "llm_decision", "config": { "instructions": "Decide if the flight count in `summarize` is anomalous.", "inputs": ["summarize"], "decision_integration": "anthropic-prod", "decision_model": "claude-sonnet-4-6" } } ``` Config: - `instructions` (required) — the system prompt; what the model should judge. - `inputs` (optional) — a list of earlier step ids whose outputs are fed to the model. Omit it to pass every prior step's output. - `decision_integration` (optional) — a stored `anthropic` / `openai` integration to call. Omitted, the step uses the **deployment LLM** (the same `llm:` block in `config.yaml` that Fi uses) — no second credential needed. - `decision_model` (required only when `decision_integration` is set) — an integration carries just an API key, so the model must be named alongside it. With no integration, the model falls back to the deployment `LLM_MODEL`. The step output is the decision dict: ```json { "should_act": true, "reasoning": "...", "action_args": { "text": "..." }, "model": "..." } ``` A downstream step guards on it with `"when": { "step": "judge", "expr": "output_truthy:should_act" }`. Unlike an [agent](/docs/agents), an `llm_decision` step is single-shot and memoryless — it sees no prior runs and keeps no durable state. Reach for an agent when you need cross-run memory, a cooldown, or run history fed back to the model. ### `maintenance` Runs one DuckLake maintenance operation against the lake. ```json { "id": "compact_orders", "type": "maintenance", "config": { "operation": "compact", "schema": "analytics", "table": "orders" } } ``` `config.operation` is one of `compact`, `rewrite`, `flush_inlined_data`, `checkpoint`, `expire_snapshots`, `cleanup_old_files`, `delete_orphaned_files`, `vacuum_catalog`, or `full`. Table-scoped operations require `schema` and `table` together; `compact` accepts both or neither (neither compacts the whole lake). Most deployments should not hand-author these. The product keeps a reserved `ducklake-maintenance` pipeline covering the whole schedule in one place — see [Managed maintenance schedule](#managed-maintenance-schedule). Write an explicit `maintenance` step only to attach one operation to a pipeline of your own, such as compacting a table right after the sync that rewrote it. ### `data_app_export` Internal. The product enqueues this step itself when someone exports a data app's data to CSV; it carries a pre-signed `object_uri` under `data-app-exports//` plus row and byte caps, and the URI format is validated on save. Do not hand-author it, and do not reach for it to deliver a report — it writes a CSV into object storage and emails nobody. To email a dashboard use [`email_report`](#email_report); to email numbers in a message body run a [`sql`](#sql) step and pass its output to [`send_email`](#send_email). ### Step guards — `when` Any step may carry an optional `when` clause. A step whose `when` evaluates **false** is *skipped* — it is not run, not failed, and the run continues to the next step. Steps still execute in their declared order; `when` only short-circuits an individual step, it is not a jump target or a branch. ```json { "id": "notify", "type": "slack_webhook", "when": { "step": "summarize", "expr": "rows_nonempty" }, "config": { "integration": "slack-ops", "text": "Found rows!" } } ``` `when.step` must reference an **earlier** step's id. `when.expr` is a small, closed vocabulary evaluated against that step's output — not an expression language: | `expr` | true when | |---|---| | `rows_nonempty` | the referenced step's `output.row_count` > 0 | | `rows_empty` | the referenced step's `output.row_count` == 0 | | `succeeded` | the referenced step ran and recorded an output | | `output_truthy:` | the referenced step's `output[]` is truthy | A `failed` expr is **reserved but unreachable today**: the executor aborts the whole run on a step failure, so no later step could ever observe a failed one. It is accepted by the definition validator (so a definition written against a future continue-on-error mode still validates) but a `failed` guard always evaluates false in the current linear executor. A guard that references a step which itself was skipped (and so produced no output) evaluates false — the guarded step is skipped in turn. ### Step status Each run step ends in one terminal status: - `succeeded` — the step ran and finished cleanly. - `failed` — the step raised; the whole run is failed and stops here. - `skipped` — the step's `when` guard evaluated false; the run continued. ### Step timing `GET /api/v1/automations/runs/{run_id}` returns each step row with its raw timing columns plus a computed `duration_ms`. The contract: - **`started_at` is the start of the step's *last* attempt.** It is reset on every attempt, not just the first. A run whose job-runner died mid-step is automatically requeued up to the configured stale-recovery budget (see *Runner death recovery* below) and re-executes every step, so a re-run step's timestamps always bracket the attempt that actually produced its result — never the span across the requeue gap. - **`attempts` counts the starts.** `attempts > 1` means the step was re-executed by a requeued run. - **`duration_ms` = `finished_at − started_at`**, i.e. the wall time of the last attempt. It is `null` while the step is unfinished: still `running` (compute live elapsed from `started_at`), still `queued`, or `skipped` (a `when`-skipped step never starts). - **An absent `finished_at` on a terminal run means the runner died mid-step** and the run had exhausted its stale-recovery budget. The reaper stamps such steps `failed` with `finished_at` set at *reap* time, so their duration includes the ~3-minute detection window; until the reaper acts, a `running` step row under a dead runner is indistinguishable from live work except via the run's stale `heartbeat_at`. Transformation runs additionally return `model_durations` — one record per `transformation_model` (each compiled step is one model), sorted by duration descending — so "which model is eating the run?" is one API call: ```json { "model_durations": [ { "model": "fct_transactions_all", "step_id": "model_fct_transactions_all", "status": "succeeded", "duration_ms": 6222000, "attempts": 1 }, { "model": "stg_payments", "step_id": "model_stg_payments", "status": "succeeded", "duration_ms": 41000, "attempts": 1 } ] } ``` ### CLI status JSON `definite run automation status --format json` returns the API run payload inside the standard CLI envelope: ```json { "ok": true, "data": { "run": { "id": "run-1", "status": "succeeded" }, "steps": [], "logs": [] }, "meta": { "elapsed_ms": 12 } } ``` The canonical run status path is `data.run.status` (jq: `.data.run.status`). Polling code should read that nested path. ## API ```text GET /api/v1/automations/pipelines POST /api/v1/automations/pipelines GET /api/v1/automations/pipelines/{pipeline_id} PATCH /api/v1/automations/pipelines/{pipeline_id} POST /api/v1/automations/pipelines/{pipeline_id}/runs POST /api/v1/automations/pipelines/{pipeline_id}/trigger-schedule POST /api/v1/automations/pipelines/{pipeline_id}/runs/{run_id}/cancel GET /api/v1/automations/runs GET /api/v1/automations/runs/{run_id} POST /api/v1/automations/runs/{run_id}/cancel ``` All routes require the same bearer token auth as the rest of the API. `trigger-schedule` requires admin. ### Concurrency, lanes, and cancelling runs The job-runner executes up to `jobRunner.maxConcurrentRuns` (Helm value, default 3) runs at once on a thread pool; set it to 1 for the old strictly serial behavior. Two guarantees hold regardless of the setting: - **One active run per pipeline.** A queued run whose pipeline already has a running or `awaiting_external` run is skipped (later runs of *other* pipelines still claim), so per-pipeline sync state never races. This also holds across multiple job-runner replicas. - **Backfills can't monopolize the pool.** A pipeline definition (or a single `POST .../runs` body) may set `"lane": "backfill"` to mark long full-history syncs. With two or more slots, at most `slots − 1` backfill in-runner runs execute at once — one slot is always reserved for normal runs. Profile-bound durable Jobs hold zero runner slots, so their number does not reduce business-as-usual runner capacity at all. Cancel one run — instead of every non-terminal run of a pipeline — with either `POST /api/v1/automations/runs/{run_id}/cancel` (by run id) or the pipeline-scoped `POST /api/v1/automations/pipelines/{pipeline_id}/runs/{run_id}/cancel`, which 404s if the run doesn't belong to that pipeline. From the CLI: `definite run automation cancel `. A queued run is never claimed; a running run stops between steps, and an in-flight **python** step is killed mid-flight — the runner polls the run status every few seconds and terminates the step subprocess (or tears down its burst sandbox) on cancel. A sync step running as a **sync-executor Job** (below) is also killed mid-flight: the runner deletes the Job, and the persisted chunk checkpoint survives for the next run. The run finishes as `cancelled`, the interrupted step is marked `cancelled`, and a log line records the termination. Other in-flight step types (`sql`, in-pod `pg_sync`, …) finish their current statement first and stop at the next between-steps checkpoint. ## External compute-profile Jobs A `pg_sync` / `adbc_sync` / `mssql_sync` step that requests a **non-default `compute_profile`** runs as a dedicated Kubernetes `batch/v1` Job sized by that profile, instead of inside the job-runner pod or on a burst sandbox (#710). This is the execution surface for full-history backfills and any other long sync: - **Sized by the profile.** The Job's pod carries the profile's `resources`, `node_selector`, and `tolerations` — the same scheduling triple burst sandboxes use, typically landing on a scale-to-zero burst node pool. The pod's embedded DuckDB is bounded by the *profile's* memory limit (the chart's downward-API sizing follows the executor container). - **No idle reaper, held RPC, or runner slot.** The executor clones the job-runner's container (image, env, secrets, scratch volume) and re-enters it as `python -m job_runner.sync_executor`; progress flows through the `automation_sync_jobs` handshake row and the run log, not a long-lived HTTP connection. After launch the automation enters `awaiting_external` and releases its thread-pool slot. Sandbox idle reaping cannot kill it, and a 12-hour run consumes no job-runner execution capacity. - **Restart-safe.** `restartPolicy: OnFailure` with a bounded `backoffLimit` (default 3) restarts a dead executor pod; the restarted attempt resumes from the persisted full-refresh checkpoint or incremental watermark. `activeDeadlineSeconds` (default 48 h) is the overall wall-clock cap. If the *job-runner* dies instead, the reaper requeues the run and the new the parked run and its deterministic Job remain intact; the new runner reconciles them without replaying the step. - **Visible.** The executor writes chunk progress into the normal run log (`automation status `), heartbeats the handshake row, and pod failures surface with their real reason (e.g. `OOMKilled` → raise the profile's memory). - **Works without Fi.** The surface needs only core Kubernetes RBAC (shipped with the chart) — unlike burst sandboxes it does not require the agent-sandbox controller. It also lifts the burst path's portability restriction: SSH-bastion / pasted-cert sources work, because the tunnel opens inside the executor pod itself. Operator knobs live under `jobRunner.syncJobs` in `values.yaml` (`enabled`, `activeDeadlineSeconds`, `backoffLimit`). With `enabled: false` — or in environments without cluster credentials — sync steps fall back to their previous behavior (in-pod, or pg_sync's burst sandbox path). Python steps with a non-default profile can use the same durable lifecycle by setting `jobRunner.pythonJobs.enabled: true`. This is off by default for a backwards-compatible rollout. The Job uses the profile's CPU, memory, `workspaceSize`, node selector, and tolerations; arbitrary Python defaults to `backoffLimit: 0` so Kubernetes never silently replays a non-idempotent script. Stored-script requirements are merged with step-level `config.requirements`, with the step's distribution pin winning. Stdout/stderr lines stream into the normal run log, and the final captured tails remain in step output. The user subprocess receives the existing allowlisted step environment rather than the executor pod's platform environment, so values such as `POSTGRES_URL` and `APP_ENCRYPTION_KEY` are not inherited. Cancellation deletes the Job. **Runner death recovery.** Claimed runs carry a liveness lease: the runner heartbeats its in-flight runs every poll cycle, and a reaper (also ticked every cycle, replica-safe) recovers `running` runs whose heartbeat has gone stale for ~3 minutes — the signature of an OOM-killed pod, a lost node, or a helm roll mid-run. Recovery **requeues** the run up to `jobRunner.staleRunMaxRequeues` times (default `1`; catalog connectors checkpoint-resume, so an interrupted backfill picks up where it left off); a run that keeps killing its runner fails terminally instead of crash-looping. `jobRunner.runLeaseSeconds` controls the stale detection window. The run log records each recovery. **Concurrent writes to the lake.** DuckLake snapshot commits are global, so parallel runs writing the lake can conflict even on disjoint tables. The SDK raises DuckLake's internal retry budget (`ducklake_max_retry_count = 100`), the catalog connectors' shared checkpoint/write helpers retry commit conflicts with exponential backoff, and the SDK's own `write_table` / `write_parquet_to_lake` retry them too — including the race two concurrent first-writes have on auto-creating the same new schema. Concurrent connector runs and plain SDK writes are safe out of the box; only scripts issuing hand-written DDL through `query()` need their own `TransactionException` retry. ### Scheduling Pipelines can run on a cron schedule by setting `cron_schedule` (a standard 5-field expression) and optionally `cron_timezone` (IANA name, defaults to `UTC`) at create or update time. The job-runner runs a scheduler tick every ~5s on a **dedicated thread**, isolated from run claiming and execution — a multi-hour step occupying every run slot cannot delay a cron fire. Overdue scheduled pipelines are enqueued with `trigger_type = "scheduled"` (note: `"scheduled"`, not `"cron"` — filter run history on that) and `next_fire_at` is advanced to the next future tick. Every tick logs one `scheduler_tick: … last_ticked_at=…` line with fired/skipped counts; that line going quiet in the job-runner's logs means the scheduler itself is wedged. ```json { "name": "Refresh hourly", "cron_schedule": "*/15 * * * *", "cron_timezone": "UTC", "definition": { "steps": [ /* ... */ ] } } ``` Rules and limits: - 5 fields only — `minute hour day month weekday`. 6-field (seconds-precision) expressions are rejected; the runner polls every ~5s, so the minimum useful interval is once per minute. - Schedules that would fire more often than once per minute are rejected with a 400 at create/update. - Invalid cron syntax or unknown IANA timezones return 400. - Manual triggering still works via `POST /pipelines/{id}/runs`. It does not interfere with the next scheduled fire. - No missed-run replay. If the job-runner is down and `next_fire_at` falls more than an hour behind, the next tick skips the backlog, logs a warning, and jumps `next_fire_at` to the next future tick. - Re-enabling a scheduled pipeline recomputes `next_fire_at` from "now", even when the update carries no cron fields (clients that PATCH `{"enabled": true}` alone included) — a pipeline whose `next_fire_at` went stale while disabled fires again within one tick of being enabled, it never silently stays dead. - Multiple job-runner replicas are safe — the tick uses `FOR UPDATE SKIP LOCKED`, so each scheduled fire enqueues exactly one run. - `POST /pipelines/{id}/trigger-schedule` (admin-only) manually advances `next_fire_at` by one tick without enqueueing — useful for testing the schedule on a long-period cron. ### Run-after dependencies Set `run_after_pipeline_id` to run one pipeline after another succeeds. The relationship is success-only, single-parent, and fan-out: pipeline B can name pipeline A, and any number of other pipelines can also name A. Cron and manual triggers remain available alongside it. ```json { "name": "Build attributed events", "run_after_pipeline_id": "", "definition": { "steps": [ /* ... */ ] } } ``` The API rejects missing or archived upstream pipelines and rejects direct or transitive cycles at save time. On success, the upstream run and downstream enqueue commit atomically. If the downstream pipeline already has a queued or running run, the event is coalesced instead of adding another queued run. Runs created this way have `trigger_type = "upstream"`. This chains whole linear pipelines; it does not add branching steps, loops, or multi-parent AND dependencies within a pipeline. ### Managed maintenance schedule A convenience endpoint for the single most common automation a lake needs: a periodic DuckLake maintenance pass. It owns a single reserved pipeline named `ducklake-maintenance` (one per deployment) so the entire schedule can be inspected and replaced with one request, no per-step pipeline authoring required. ```text GET /api/v1/lakehouse/maintenance/schedule # any user PUT /api/v1/lakehouse/maintenance/schedule # admin only ``` `GET` returns `{ "schedule": null }` if no schedule has been configured. Otherwise it returns the current `cron`, `timezone`, `enabled` flag, resolved `next_fire_at`, and the flattened `steps` list (one entry per maintenance op). **Auto-provisioning.** On API startup the lifespan calls `bootstrap_managed_maintenance_schedule`: if no pipeline exists with the reserved name (any state — enabled, archived, even an operator-created collision) it inserts the default schedule (cron `0 2 * * 0` UTC, the default step list below, enabled). After first boot the operator owns the row: edit / disable / archive / delete are all respected — with one exception: an untouched schedule from a recognized prior default generation is upgraded in place on the next boot. This removes the former redundant leading `CHECKPOINT` while preserving customized schedules. A default schedule whose burst profiles were stripped (a pre-v0.1.121 PUT that omitted `compute_profile` cleared them) is also re-stamped on the next boot; to keep a deliberately cleared profile, change any step field so the schedule no longer matches the default shape. Any edited schedule no longer matches and is never touched. Wiping the row and restarting is the only other way back to the default. `PUT` body: ```json { "cron": "0 3 * * *", "timezone": "UTC", "enabled": true, "steps": [ { "operation": "checkpoint" }, { "operation": "compact", "schema": "main", "table": "orders" }, { "operation": "expire_snapshots", "older_than_days": 30 }, { "operation": "cleanup_old_files", "older_than_days": 30 } ], "confirm_destructive": true, "compute_profile": "lakehouse-large" } ``` Behaviour: - **Upsert by reserved name.** Replaces the existing `ducklake-maintenance` pipeline if it exists, or creates it if not. An archived row is revived. - **Collision guard.** A pipeline that already exists with the reserved name but was not written by this endpoint (i.e. its `description` lacks the `[managed:maintenance-schedule]` tag) returns `409`; rename or delete it before re-PUTting the schedule. - **Cadence floor.** Schedules that fire more often than once per day are rejected — maintenance ops can scan the whole lake, so a sub-daily cadence is almost always a misconfiguration. Run ad-hoc maintenance via `POST /lakehouse/maintenance/runs` if a one-off shorter cycle is needed. The general per-pipeline 1-minute floor still applies to other pipelines. - **Defaults.** Omit `steps` entirely and the endpoint installs the canonical list: `flush_inlined_data`, `expire_snapshots(older_than_days=30, dry_run=false)`, whole-lake `compact` (`merge_adjacent_files`), whole-lake `rewrite(delete_threshold=0.95)`, `cleanup_old_files(older_than_days=30, dry_run=false)`, `delete_orphaned_files(older_than_days=30, dry_run=false)`, and `vacuum_catalog` (a plain `VACUUM (ANALYZE)` of the catalog Postgres). These are the operations DuckLake bundles into `CHECKPOINT`, expressed as individual steps so each has its own retry boundary, output, and settings. Destructive steps run live on purpose — a dry-run schedule previews-but-never-reclaims, which silently leaks storage. The `confirm_destructive` acknowledgment applies only to an explicit `steps` list that sets `dry_run=false` on a destructive op; requesting the defaults doesn't re-prompt. - **Burst profile.** `compute_profile` applies to the schedule as a whole. A profile name routes each step to that burst tier, except `vacuum_catalog` — that step VACUUMs the catalog Postgres in-pod, and a burst sandbox has no Postgres credentials. If the field is absent, `null`, or empty, the stored profile stays: a cron-only PUT does not change burst routing. Only the explicit value `"default"` clears the profile, and all steps then run in the job-runner pod. The default schedule runs its heavy steps on `lakehouse-large`. - **Step shape.** Each `steps[i]` is a [`maintenance` step](#-no-anchor-) config (`operation` + the same per-op fields the ad-hoc `/runs` endpoint accepts: `schema`, `table`, `older_than_days`, `delete_threshold`, `dry_run`). The step is validated through the same `validate_maintenance_config` rule used by the `AutomationStep` model. - **`enabled: false`** keeps the row + definition around but clears `next_fire_at` so the scheduler skips it. Re-enable by PUTting again with `enabled: true`. The resulting pipeline is a regular `automation_pipelines` row — runs, logs, and history all show up under the same `/api/v1/automations/` endpoints. The convenience is in the auto-naming, upsert semantics, and the maintenance-specific cron + confirmation rules. **UI.** Settings → Maintenance ships a "Scheduled maintenance" card that calls the endpoints above: cron + timezone fields, three preset chips (daily 03:00 UTC, weekly Sun 02:00 UTC, monthly 1st 02:00 UTC), an enabled checkbox, a read-only summary of the current step list, and the human-readable cadence next to the cron input. Editing the step list (or toggling `dry_run=false` on a destructive op) still requires the PUT endpoint. ## Current limits - Steps execute in declared order; no jump targets, DAG, or fanout. A step may be skipped by a [`when`](#step-guards-when) guard, but the order is fixed. Concurrency is per-run (see [Concurrency, lanes, and cancelling runs](#concurrency-lanes-and-cancelling-runs)); steps within one run are always sequential. - Python steps run in the shared job-runner pod unless they set a non-default `compute_profile`; memory-heavy workloads should use a burst profile. Concurrent in-pod python steps share the pod's CPU/memory limits — size `resources.jobRunner.resources` with `jobRunner.maxConcurrentRuns`. - Mid-step cancellation covers `python` steps (in-pod and burst-sandbox). Other step types cancel at the next between-steps checkpoint. ## Slack setup Create a Kubernetes Secret in the deployment namespace and expose it to `job-runner` via Helm values: ```bash kubectl create secret generic definite-automation-secrets \ -n definite \ --from-literal=slack-webhook-url="$SLACK_WEBHOOK_URL" ``` ```yaml jobRunner: extraEnv: - name: SLACK_WEBHOOK_URL valueFrom: secretKeyRef: name: definite-automation-secrets key: slack-webhook-url ``` Do not commit actual Slack webhook URLs. --- # Staleness Checks A staleness check is a small scheduled [automation](/docs/automations) that watches the tables you care about and tells you when data stops updating. It exists because of a failure mode that per-run alerts can't see: every upstream feed keeps succeeding, but the transform that builds your analytics tables stops running — its schedule was removed during an edit, its spill disk filled up, someone paused it — and every downstream table silently freezes. Nothing "failed", so nothing alerted. A staleness check watches the *data* instead of the runs: if `max(updated_at)` on a table you care about stops advancing, you hear about it. Because it's an ordinary automation you own, everything is yours to tune: which tables, which timestamp column, how stale is too stale, how often to check, and whether an alert means a failed run in your Inbox, a Slack message, or an email. > **The simple case has a built-in.** If all you want is "warn when this > table hasn't loaded in N hours", set an SLA on the table in the Catalog > (the SLA editor sits under each table's freshness pills) — breaches > surface in the Inbox as `sla_breach` alerts with no automation needed. Reach for the recipes below when you > want a custom timestamp column, a cross-table comparison, your own alert > text, Slack/email delivery per check, or a different schedule per table. ## Variation 1 — raise to alert (recommended default) One `python` step. It checks each table with a single SQL comparison and **fails the run** when anything is stale. A failed run is already a first-class event: it shows up as a pipeline-failure alert in the Inbox, and — if you've configured Settings → Notifications — goes out by webhook and/or email. You write no alerting code at all. ```python from definite_lakehouse import query CHECKS = { # "schema.table": ("timestamp column", max age in hours) "analytics.orders": ("updated_at", 2), "analytics.revenue_daily": ("day", 26), } stale = [] for table, (col, hours) in CHECKS.items(): fresh = query( f"SELECT max({col}) >= now() - INTERVAL {hours} HOUR AS fresh FROM {table}" ).to_pylist()[0]["fresh"] if not fresh: stale.append(f"{table}: no new {col} in {hours}h") if stale: raise SystemExit("STALE DATA: " + "; ".join(stale)) print("all fresh") ``` The freshness comparison runs inside SQL (`max(col) >= now() - INTERVAL n HOUR`), which sidesteps timezone handling in Python entirely. An empty table yields `NULL`, which is not true — so a table with no rows counts as stale, which is what you want. As a full pipeline definition (hourly): ```json { "steps": [ { "id": "check", "type": "python", "config": { "attach_lake": true, "script": "from definite_lakehouse import query\n\nCHECKS = {\n \"analytics.orders\": (\"updated_at\", 2),\n \"analytics.revenue_daily\": (\"day\", 26),\n}\n\nstale = []\nfor table, (col, hours) in CHECKS.items():\n fresh = query(\n f\"SELECT max({col}) >= now() - INTERVAL {hours} HOUR AS fresh FROM {table}\"\n ).to_pylist()[0][\"fresh\"]\n if not fresh:\n stale.append(f\"{table}: no new {col} in {hours}h\")\n\nif stale:\n raise SystemExit(\"STALE DATA: \" + \"; \".join(stale))\nprint(\"all fresh\")\n" } } ] } ``` ```bash definite run automation create \ --name staleness-check \ --definition "$(cat staleness-check.json)" \ --cron "0 * * * *" \ --format json # run it once right now to verify (id from the create output) definite run automation run ``` The `SystemExit` message becomes the run's error, so the Inbox alert (and any notification email) reads exactly what you wrote: `STALE DATA: analytics.orders: no new updated_at in 2h`. For longer scripts, prefer the [stored-script workflow](/docs/automations#stored-script-recommended). ## Variation 2 — a report to Slack or email, only when stale Sometimes a failed run is the wrong shape — you want the check itself to stay green and instead receive a *report*, and only when there is something to say. Split it into a probe step that prints a report **only when something is stale**, plus a delivery step guarded by [`when`](/docs/automations#step-guards-when): if the probe printed nothing, `output_truthy:stdout` is false and the delivery step is skipped. The probe: ```python from definite_lakehouse import query CHECKS = { "analytics.orders": ("updated_at", 2), "analytics.revenue_daily": ("day", 26), } lines = [] for table, (col, hours) in CHECKS.items(): row = query( f"SELECT max({col}) AS last, " f"max({col}) >= now() - INTERVAL {hours} HOUR AS fresh FROM {table}" ).to_pylist()[0] if not row["fresh"]: lines.append(f"- {table}: last {col} = {row['last']} (threshold {hours}h)") if lines: print("Stale tables:\n" + "\n".join(lines)) ``` Then deliver to Slack (via a stored `slack_webhook` [integration](/docs/integrations)), to email, or both — each step templates the probe's stdout straight into the message: ```json { "steps": [ { "id": "check", "type": "python", "config": { "attach_lake": true, "script": "" } }, { "id": "slack", "type": "slack_webhook", "when": { "step": "check", "expr": "output_truthy:stdout" }, "config": { "integration": "slack-alerts", "text": ":warning: {{ steps.check.stdout }}" } }, { "id": "email", "type": "send_email", "when": { "step": "check", "expr": "output_truthy:stdout" }, "config": { "to": ["data-team@example.com"], "subject": "Stale data detected", "text_body": "{{ steps.check.stdout }}\nSent by the staleness-check automation." } } ] } ``` When everything is fresh the run succeeds with both delivery steps `skipped` — no noise anywhere. Keep whichever delivery step you want, or both. `send_email` requires the deployment's [email delivery](/docs/config#email) to be configured; `slack_webhook` needs a `slack_webhook` integration (see [Slack setup](/docs/automations#slack-setup)) or a `webhook_url`. Which variation to pick: **Variation 1** if you already route pipeline-failure notifications (one step, zero config, the Inbox is the record). **Variation 2** if stale data should page a Slack channel or a distribution list directly, or you don't want red runs for a data-quality condition. ## Configuration **How often to check** — the pipeline's `cron_schedule` (standard 5-field cron, minimum every minute) and optional `cron_timezone`: | Goal | `cron_schedule` | `cron_timezone` | |---|---|---| | Every hour | `0 * * * *` | — | | Every 15 minutes | `*/15 * * * *` | — | | Daily at 06:30 New York time | `30 6 * * *` | `America/New_York` | | Weekday mornings only | `0 7 * * 1-5` | `America/New_York` | Set them at create time (`--cron`, `--cron-timezone`) or later with `definite run automation update --cron "..."`. **Which tables, and how stale is too stale** — rows in the `CHECKS` dict: the timestamp column and a per-table max age. Set each threshold to **2–3× the feed's expected cadence** (hourly loads → 2–3h threshold; a daily table → 26h) so one slow run doesn't produce a false alarm. A date-grain column like `day` needs the daily-scale threshold even if the job runs hourly. **Custom timestamp columns** — anything SQL can evaluate works as the freshness probe, not just a `TIMESTAMP` column: ```sql -- epoch milliseconds SELECT to_timestamp(max(updated_ms) / 1000) >= now() - INTERVAL 2 HOUR AS fresh FROM ... -- ingestion timestamp written by your loader SELECT max(_loaded_at) >= now() - INTERVAL 2 HOUR AS fresh FROM ... ``` **Mart vs. raw feed** — the sharpest check when raw ingestion and transforms are separate pipelines: raw feeds can keep landing while the transform that builds the mart has stopped. Compare the two directly instead of using a fixed age: ```sql SELECT (SELECT max(updated_at) FROM analytics.orders) >= (SELECT max(updated_at) FROM raw.orders) - INTERVAL 1 HOUR AS fresh ``` This alerts precisely when the mart stops keeping up with its source, regardless of how often either one loads. ## Setting it up with Fi You don't have to write any of this by hand — ask Fi: > Set up a staleness check: alert if analytics.orders has no new updated_at > for 2 hours or revenue_daily hasn't updated in 26 hours. Check hourly and > post to our alerts Slack channel. Fi will build the pipeline, create the Slack integration through a secure form if one doesn't exist, and run the check once to verify it. ## Notes - The check itself is a scheduled pipeline — if someone disables *it*, it goes silent too. For belt-and-braces, add a daily heartbeat variant (an unconditional `slack_webhook` step reporting "checked N tables, all fresh") so silence itself becomes a signal. - Alert emails for Variation 1 require email notifications to be enabled in Settings → Notifications (pipeline failures are `error` severity, so the default severity threshold delivers them once the rule is on). In-app Inbox alerts need no setup. - The `python` step runs with `attach_lake: true` and the preinstalled `definite_lakehouse` client — see the [environment contract](/docs/automations#environment-contract) for exactly what the script can reach. --- # Transformations Transformation projects let users manage a folder of SQL models, persist the model graph on the server, inspect lineage, and execute the models through the existing automation runner. This is intentionally dbt-inspired, not dbt-compatible. There is no Jinja, package manager, dbt manifest support, tests, or dbt data snapshots. Models can materialize as a table, a view, or incrementally (dbt-style `materialized: incremental`; see below). A Definite "run SQL snapshot" means the exact SQL statements captured for one transformation run; it is not a dbt snapshot model. ## Project layout ```text transformations/ staging/ stg_orders.sql marts/ orders.sql ``` Each `.sql` file is one model. The model name defaults to the file stem. ```sql -- @definite: -- schema_name: marts -- materialized: table -- compute_profile: large -- description: Clean order facts for reporting. select * from {{ ref("stg_orders") }} ``` Supported header fields: | Field | Meaning | |---|---| | `name` | Override the model name. Defaults to the SQL file stem. | | `schema_name` | Destination schema. Defaults to the project default schema. | | `relation_name` | Destination table or view name. Defaults to the model name. | | `materialized` | `table`, `view`, or `incremental`. Defaults to `table`. | | `description` | Human-readable model description. | | `depends_on` | Explicit model dependencies when SQL parsing is not enough. | | `compute_profile` | Optional compute profile override for this model. The project default is used when omitted. | | `incremental_strategy` | `delete_insert` (default) or `insert_overwrite`. Incremental models only. `merge` is planned, not yet supported. | | `unique_key` | Replace-by-key column(s) for `delete_insert`. A scalar or a list. | | `partition_key` | Partition expression for `insert_overwrite` (e.g. `date_trunc('day', created_at)`). | | `watermark` | Column of the model **output** used as the incremental high-water mark. | | `lookback` | Optional re-scan window behind the high-water mark, e.g. `6 hours`. Requires `watermark`. | | `delta_keys_sql` | Optional `delete_insert`-only SELECT that returns the changed keys (column order must match `unique_key`). Mutually exclusive with `watermark`. | The tiny `{{ ref("model_name") }}` helper is supported for project-internal dependencies. It is not a general Jinja renderer. ## Incremental models Large fact models should not be rebuilt from scratch on every run. With `materialized: incremental` the engine compiles a delta plan instead of `CREATE OR REPLACE TABLE`: ```sql -- @definite: -- schema_name: analytics -- materialized: incremental -- incremental_strategy: delete_insert -- unique_key: [participantid] -- watermark: updated_at -- lookback: 6 hours select * from {{ ref("stg_participants") }} ``` Two strategies are supported in v1: - **`delete_insert`** (default): stage the rows whose `watermark` is newer than the target's current maximum (minus the optional `lookback`) in a session temp table, delete the matching `unique_key` rows from the target, and insert the staged rows. This is replace-by-key — late updates inside the lookback window converge with no duplicates. - **`insert_overwrite`**: stage the **distinct partitions** (`partition_key`) that contain new/changed rows by the same watermark window, delete those whole partitions from the target, and re-insert them from the model output. Use this when changed rows must replace whole days/months, e.g. late status flips on old days. Advanced: when the rows to rebuild are keyed by something the model output's watermark cannot see (fan-out joins), provide `delta_keys_sql` — a single SELECT returning the changed keys, with columns in `unique_key` order. The engine deletes those keys and re-inserts the model output rows that match them. With `delta_keys_sql` *you* own delta detection; the first run of such a model should be a `--full-refresh` (see below) so the target starts complete. Semantics worth knowing: - **First run is pure SQL**: an empty (or just-created) target makes the high-water mark `NULL`, so the very first incremental run loads everything. Note the delta path stages the full model output in a temp table on that first run — for very large first builds, prefer an initial run with `--full-refresh`. - **Materialization flips converge**: incremental models materialize a table. Flipping `table` → `incremental` adopts the existing table without a rebuild; `view` → `incremental` drops the stale view first. - **Schema changes need a full refresh**: incremental runs `INSERT` into the existing target, so a model that adds/renames output columns fails until a `full_refresh` run rebuilds the table (`on_schema_change` handling is future work). ### Full refresh runs Every incremental model also compiles a full-rebuild variant (the exact `CREATE OR REPLACE TABLE` a `materialized: table` model would run). A run queued with `full_refresh: true` executes those variants instead of the incremental plans — non-incremental steps are unaffected, and the stored pipeline is untouched (scheduled runs stay incremental): ```bash definite transform run core-models --full-refresh ``` or `POST /api/v1/transformations/projects/{id}/runs` with `{"full_refresh": true}`. A weekly scheduled-off-hours full-refresh run is the recommended backstop for hourly incrementals: `CREATE OR REPLACE TABLE` rewrites the table compactly, which also clears the DuckLake delete files that key-scoped `DELETE`s accumulate (compaction and correctness backstop in one). ## CLI workflow ```bash # Create a starter project. definite transform init transformations # Parse the local project, infer edges, and show the execution plan. definite transform plan transformations # Persist the graph and create/update the linked automation pipeline. definite transform apply transformations --name core-models --compute-profile large # List persisted projects. definite transform list # Inspect the persisted project, models, edges, and execution order. definite transform get core-models --format json # List immutable applied versions for a project. definite transform versions core-models --format json # Inspect a historical version; add --include-ast only for parser debugging. definite transform get core-models --version 3 --format json definite transform get core-models --version 3 --include-ast --format json # Show source/output lineage, optionally filtered to one project or table. definite transform lineage --project core-models --format json definite transform lineage --source-table orders --format json # Queue a run through the linked automation pipeline. definite transform run core-models --format json # Rebuild incremental models from scratch for this one run. definite transform run core-models --full-refresh --format json ``` `apply` sends the manifest to `/api/v1/transformations/projects/{slug}/manifest`. The API stores the project, models, and edges in Postgres, then compiles the models into ordered automation `sql` steps. The linked automation owns schedule, execution, logs, retries, and sharing. `apply` treats pipeline state as preserve-unless-specified. Without `--cron`, the stored cron and timezone are untouched, so re-applying model changes cannot silently stop scheduled runs; `--cron` sets the schedule (`--cron-timezone` optionally changes the timezone, otherwise the stored one is kept) and `--clear-cron` explicitly removes it. The enabled flag works the same way: apply leaves a paused pipeline paused unless `--enable` or `--disabled` is passed. Table output ends with a `schedule:` line stating the resulting schedule and whether it was set, preserved, or cleared; JSON/CSV consumers should read `data.project.automation_pipeline.cron_schedule` instead. Preservation is enforced by the API server — applying against a server older than this release still clears an unspecified schedule. The same preserve-unless-specified rule covers the rest of the project's settable state. Without `--compute-profile`, the project's stored profile is kept (`--compute-profile default` resets it explicitly). Without `--description`, the stored description is kept; `--description ""` clears it. A pipeline renamed on the automations page keeps its custom name permanently — a project rename only updates pipelines still carrying the derived `Transforms: …` name. Note that `--name` defaults to the local directory name, so applying from a renamed directory renames the project. Two caveats: `--default-schema` (default `main`) is resolved into headerless models by the CLI at build time, so changing it re-points where those models materialize — the apply response carries a `default_schema_changed` warning when this happens; and visibility grants are seeded only when the apply creates the pipeline, so sharing changes made in the product are never re-asserted by a re-apply. `plan` warns when a model reads a table in a schema the project writes to (the default schema or any model's `schema_name`) that no model in the project produces — typically a stale leftover table or a missing model that would otherwise fail mid-run. The warning lists each table with the models that read it; in `--format json` it is carried as a `warnings` array, and in `--format csv` it goes to stderr so stdout stays machine-parseable. It is a warning, not an error: reads from a shared schema that another project populates can be intentional. `apply` reruns the same check server-side with DuckDB's parser and returns it as `warnings` in the response, persisted with the version's manifest. Use `--format json` when handing results to another tool, to Fi, or to an external review workflow. The JSON payload preserves project ids, linked automation ids, version ids, run ids, lineage edges, source refs, parser status, compute-profile choices, AST summaries, and exact run SQL snapshots when those fields are returned by the deployed API. The version and lineage CLI commands require a deployment API that exposes the matching version/lineage endpoints. Older API builds can still plan, apply, get, list, and run transformation projects, but may not return version history, source lineage, or full AST payloads. ## Versioning and run snapshots A transformation project has a current definition and may have multiple applied versions over time. Treat each applied version as the reviewable definition that was current at the moment of `apply`: model SQL, model metadata, dependency edges, compute-profile routing, parsed source lineage, and parser metadata all belong to that version. When a run is queued, the automation layer snapshots the exact definition it will execute into the automation run record, along with a definition hash. For a transformation-generated pipeline, that definition contains the ordered `sql` steps: the fully compiled `CREATE OR REPLACE TABLE` or `CREATE OR REPLACE VIEW` statement for each model, plus the `compute_profile` each step will use. Debug past runs from this run SQL snapshot, not from whatever the latest local files or latest project version say now. When the definition carries `transformation_project_id` and `transformation_version_id`, those ids identify which transformation definition produced the run. This distinction matters: - **Editable source** is the SQL model text a user should modify in a project folder or source editor. - **Applied version SQL** is the server-side definition saved by an apply. - **Run SQL snapshot** is the immutable SQL that a specific run attempted. If a model is edited after a failed run, the latest project SQL may no longer match the SQL that failed. Use the run SQL snapshot for incident review, audit, and exact reproduction. ## Lineage Transformation lineage has two layers: - **Model lineage** is project-internal: `depends_on`, `ref()`, and inferred model-to-model edges such as `stg_orders -> orders`. - **Source lineage** is external: lakehouse source tables that a model reads, such as `raw.orders -> stg_orders`. Source lineage is parsed server-side at apply time with DuckDB's own parser (`json_serialize_sql`) — the same engine that runs the SQL, so the lineage is authoritative. Each source ref records the raw reference, resolved source schema and table, reference kind, and whether the reference matched another internal model. If DuckDB cannot serialize a model's SQL (a non-`SELECT` body, or syntax it rejects), the server falls back to a token-scan and marks the model `degraded`; those refs are lower confidence. Dynamic table names or unusual table functions may still produce partial lineage or a degraded parse. Use explicit `depends_on` for model-to-model edges that the parser could miss. Source lineage is for graphing and impact analysis; table-level query permissions are still enforced by the query execution path. The UI should make the distinction visible. Source tables and transformation models are different node types, and a run detail should be able to show lineage for the version and SQL snapshot that actually ran. ## AST summary and full AST DuckDB's parser produces both a compact AST summary and, when needed, the full serialized AST for the DuckDB dialect. The AST summary is the default product surface. It includes stable facts such as parser name/version/dialect (`duckdb` / the DuckDB library version / `duckdb`), parse status, statement count, referenced tables (with the internal/external flag), CTE names, fallback mode, and any parse error. The summary is small enough for lists, model drawers, lineage graph sidebars, and Fi context. The full AST is a debugging aid. It can be large, parser-version-specific, and awkward to read. Use this when a historical version needs full parser detail: ```bash definite transform get --version --include-ast --format json ``` UI flows should lazy-load full AST only when a user asks to inspect parser details, and Fi should summarize relevant nodes instead of pasting the whole object into chat. ## Server graph The server persists: - one transformation project row; - one model row per SQL file in the current graph; - one edge row per project-internal dependency; - a linked automation pipeline containing the compiled execution steps; - automation run definition snapshots and hashes for exact run reproduction; - version, run-snapshot, source-lineage, and AST metadata where enabled by the deployed API version. The graph can be read with: ```bash definite transform get core-models --format json ``` or via: ```text GET /api/v1/transformations/projects/{id_or_slug} ``` ## UI concepts The editor-only `/transformations` page uses the same server graph and run records as the CLI. The page is organized around: - **Project filters**: text search plus status, source schema/table, and output schema/table filters. - **Projects list**: project name, slug, model count, edge count, last run, and source/output hints. - **Project detail**: models, model dependency edges, selected-model SQL, source/output table refs, versions, and linked automation metadata. - **Actions**: refresh, queue a transformation run, open the linked automation, and open the latest automation run. Exact run SQL snapshots and full AST payloads are detail/debug payloads. They should stay out of default lists and load only when a user explicitly opens the relevant run, version, or parser-debug view. ## Where transform SQL executes & sizing the runner Transform projects compile to one automation `sql` step per model. The API pod never executes transform models — it parses, plans, and serves interactive queries. The job runner orchestrates the model steps, and the SQL execution surface depends on the compiled `compute_profile` values: - **Default profile**: the step executes on the job-runner pod's embedded DuckDB via `AutomationExecutor.execute_sql` and `lakehouse.query`. - **Uniform non-default profile**: if every compiled SQL step in the transform run declares the same non-default profile (the normal project-level `compute_profile` case), the runner leases one `BurstSqlSession` for the whole run. Every model statement runs through that warm burst sandbox's persistent `/sql-session` worker, so the DuckDB connection and lake attach are reused across the DAG. - **Mixed profiles**: per-model overrides that produce different profiles keep the existing per-step burst path. Each profile-bound step leases, runs one statement, and releases its own sandbox. Everything below is about the default in-runner path. For a uniform profile-bound DAG, size the selected compute profile instead; the job-runner pod remains the orchestrator and does not carry the heavy DuckDB plan. ### What bounds a heavy model DuckDB executes each compiled `CREATE OR REPLACE TABLE` with a memory budget of ~40% of the job-runner container's memory limit and threads equal to the CPU limit (rounded up). Both are handed down through the pod environment and can be overridden for the job-runner alone. Hash joins / sorts / large aggregates that exceed the budget spill to the pod's `/scratch` volume. These Helm values decide whether a heavy model completes: | Knob | Default | What it bounds | |---|---|---| | `resources.jobRunner.resources.limits` | `1` CPU / `3Gi` memory | DuckDB's memory budget (~40% of the limit) and thread count | | `jobRunner.duckdb.memoryFraction` | empty: inherits `lakehouse.duckdb.memoryFraction` (`0.4`) | Fraction of runner memory available to each in-pod DuckDB engine | | `jobRunner.duckdb.threads` | empty: derives from the runner CPU limit | Runner DuckDB worker threads; fewer threads trade speed for per-operator memory headroom | | `jobRunner.spill.size` (falls back to `lakehouse.spill.size`) | `50Gi` | The scratch PVC heavy operators spill into | | `jobRunner.spill.maxTempDirectorySize` | derived: ~90% of the effective `spill.size` | Hard cap on one connection's spill; an explicit value wins | The spill values are per-component: `jobRunner.spill.*` overrides the shared `lakehouse.spill.*` for the runner alone, so the runner can carry several times the API pod's spill without resizing both. When `maxTempDirectorySize` is left empty the chart derives it from the scratch PVC size (floor of 90%, as a binary GiB quantity), so the cap can no longer drift past the volume it bounds. Two defaults keep large writes in these limits: - DuckDB `preserve_insertion_order` is off by default on the job-runner engine (`jobRunner.duckdb.preserveInsertionOrder`), on the `definite_lakehouse` SDK engines for `attach_lake` python steps, burst sandboxes, and connector loaders, and on the fi-sandbox burst SQL runner (the last three through `lakehouse.duckdb.preserveInsertionOrder`). Ordered `INSERT`/CTAS buffers cannot spill, and the memory budget does not count them. The api pod's query engine is the one exception: it keeps the DuckDB default (`true`) and has no configuration value. To get the DuckDB default on the other engines, set the applicable value to `true`, or use `SET preserve_insertion_order = true` in a step. When the setting is off, `CREATE TABLE ... AS SELECT ... ORDER BY` sorts the query stream but does not sort the stored table — parallel insert sinks can write blocks out of sequence. A read that must have an order must use `ORDER BY`. - `attach_lake` python steps get the DuckDB limits of their container from the `DUCKDB_*` variables (memory fraction and bytes, threads, and spill-to-disk settings). The steps do not calculate their own limits. The one DuckDB limit setting that the job-runner does not forward to each step is the absolute `DUCKDB_MEMORY_LIMIT` value: that value is a memory budget for the entire engine, and each step would get the full value again if it were forwarded. To give one step an exact budget, put `DUCKDB_MEMORY_LIMIT` in the `config.env` block of that step; the `config.env` block can override each of the other values too (see `helm/values.yaml`). ### Worked example (real 100M+-row migration) A 41-model DAG over 134M / 92M / 36M-row source tables: - **Chart defaults** (3Gi runner, 50Gi scratch, 45GB temp cap): OOM'd mid-DAG, hours in — model 9/40 on one attempt, 18/40 on another (`could not allocate block` at 28.7GiB). - **Completed config** — 41/41 models in 131 minutes: ```yaml resources: jobRunner: replicas: 1 resources: requests: { cpu: "2", memory: 8Gi } limits: { cpu: "8", memory: 48Gi } jobRunner: duckdb: # Runner-only: does not change API queries or Fi sandboxes. memoryFraction: "0.4" # Fewer threads than CPUs: each concurrent operator pipeline holds # its own working set, so 4 threads at 48Gi left each join more # memory than 8 did. threads: 4 spill: size: 250Gi # derived max_temp_directory_size: 225GiB ``` The heaviest step — a 42M x 134M x 92M three-way join — ran 103.7 minutes pinned at 47.8Gi of the 48Gi limit while fully spilling. At this scale the spill volume is doing real work; the defaults could never absorb it. Rules of thumb from that run: - Budget runner memory against the largest single join, not the DAG as a whole — models execute serially through the automation. - If a model OOMs before `/scratch` fills, raise the runner memory limit. If it dies on spill exhaustion (an error naming `max_temp_directory_size`, or `No space left on device` under `/scratch`), raise `jobRunner.spill.size` — the temp cap follows automatically unless you pinned it. - Threads default to the CPU limit. Lowering `jobRunner.duckdb.threads` trades speed for per-operator memory headroom and is often the cheapest fix for a single giant join. `jobRunner.duckdb.memoryFraction` similarly scopes a different memory fraction to the runner without changing API or Fi limits. For new large DAGs, prefer a project-level non-default `compute_profile` so the whole SQL run uses one sized, warm burst sandbox. The runner sizing knobs above remain the supported controls for default-profile runs and deployments that intentionally keep transform SQL in-process. ## Current limits - The runner still executes models as a linear topological order through Automations; DAG-native parallel execution is not implemented. - Dependency inference is intentionally conservative. Use `ref()` or `depends_on` for reliable project-internal edges. - Source lineage and AST summaries are parser-derived and best-effort. Dynamic SQL or unsupported syntax may produce partial lineage or a parse error. - Full AST output is for debugging, not a stable public data model. - Versioning captures server-side transformation definitions. Use git or another source-control workflow for branching, code review, and local author history. - Incremental v1 supports `delete_insert` and `insert_overwrite`. `merge` and automatic `on_schema_change` handling are planned follow-ups; an output schema change today requires a `--full-refresh` run. - There is no dbt compatibility layer. --- # Autonomous Agents An **agent** is a monitor. When it runs it: 1. **Probes** — runs a query (SQL or Python) against the lakehouse. 2. **Decides** — hands the probe result, plus its memory of recent runs, to an LLM that returns a structured judgment: should we act, and why. 3. **Acts** — if the LLM says act (and a cooldown allows it), it fires an action. Canonical example: *"sales up 20% week-over-week → notify / buy more inventory."* The probe computes the number; the LLM judges whether that warrants action; the action posts to Slack, hits a webhook, runs SQL, or hands off to a Fi agent. ```text agent definition → trigger (cron / event / manual) → probe → LLM decision → (cooldown) → action ``` Agents are **not** [automations](/docs/automations): an automation runs an ordered list of steps blindly, with no branching. An agent is a single conditional — probe, judge, maybe act. The two share the job-runner poll loop and the cron helpers and nothing else. ## Enabling agents Agents are **off by default**. Enabling them lets the job-runner make outbound LLM calls, so air-gapped clusters should leave them off. ```yaml # config.yaml agents: enabled: true ``` This maps to `AGENTS_ENABLED` on the API and job-runner. When disabled, agent *reads* still work but create / run are rejected with a 403. ## Letting Fi write the agent The fastest way to create an agent is to ask Fi. The definition is just JSON to `POST /api/v1/agents`, and `definite run agent create` is a command Fi has in its sandbox — so *"Fi, watch my sales table and ping #ops if revenue jumps 20% week-over-week"* is enough; Fi composes the probe, instructions, and action and creates the agent. The hand-written definition below is the manual path. ## Agent definition ```json { "name": "Sales surge watcher", "probe": { "type": "sql", "sql": "SELECT this.t AS this_week, last.t AS last_week FROM (SELECT sum(amount) t FROM analytics.sales WHERE order_date >= current_date - 7) this, (SELECT sum(amount) t FROM analytics.sales WHERE order_date >= current_date - 14 AND order_date < current_date - 7) last" }, "decision_instructions": "Act if this week's sales are more than 20% above last week's.", "mode": "simple", "action_config": { "action_type": "slack_webhook", "integration": "slack-ops" }, "cron_schedule": "0 9 * * 1", "cron_timezone": "America/New_York", "cooldown_seconds": 604800 } ``` | Field | Notes | |---|---| | `probe` | The condition — a `sql` or `python` object (see below). | | `decision_integration` | **Optional.** id-or-name of a stored `anthropic` / `openai` integration. Omit it to use the deployment LLM. | | `decision_model` | **Optional** when there is no integration (defaults to the deployment `LLM_MODEL`); **required** when `decision_integration` is set. | | `decision_instructions` | The operator's judgment criteria — the LLM system prompt. | | `decision_history_limit` | How many prior runs to feed the LLM (default 10). | | `mode` | `simple` or `fi`. | | `action_config` | Mode-specific (see Actions). | | `state` | **Optional.** Seed for the durable scratchpad (e.g. an initial watermark). | | `cron_schedule` | **Optional.** 5-field cron. | | `event_trigger` | **Optional.** Fire on an automation event (see Triggers). | | `cooldown_seconds` | Suppress the action when it last fired less than this long ago. `0` disables. | An agent may have a `cron_schedule`, an `event_trigger`, both, or neither (manual-only) — they are independent. ## Probes ### `sql` ```json { "type": "sql", "sql": "SELECT sum(amount) AS total FROM analytics.sales" } ``` Runs against the lakehouse. May be an aggregate. The result set (capped at 200 rows) becomes `probe_result`. SQL probes are stateless. ### `python` ```json { "type": "python", "script_name": "sales_probe", "requirements": ["pandas"] } ``` A Python probe runs through the same machinery as an automation `python` step (`uv run`, ephemeral venv, `requirements`, `integrations`, baked `definite_lakehouse` SDK). Specify the body with exactly one of `script` (inline), `script_id`, or `script_name`. A Python probe is **stateful**: it is handed the agent's durable memory and run history, and returns its result — and an optional new watermark — via the SDK: ```python from definite_lakehouse import agent_input, emit_probe, query ctx = agent_input() # {state, history, agent_id, run_id} last = ctx["state"].get("last_total", 0) total = query("SELECT sum(amount) AS t FROM analytics.sales").to_pylist()[0]["t"] emit_probe( result={"total": total, "previous_total": last}, # fed to the LLM state={"last_total": total}, # watermark for next run ) ``` `emit_probe()` must be called exactly once; the `result` object is the `probe_result`, and `state` (when given) merges into the agent's durable memory. ## The decision The probe result, the durable memory, and the recent run history go to an LLM, which is forced to call a single `submit_decision` tool returning `{should_act, reasoning, action_args, memo}`. The response is always structured JSON — there is no prose to parse. **Which LLM?** By default the agent uses the **deployment LLM** — the same `llm:` provider/key configured in `config.yaml` that Fi uses. Supported for the default path: `anthropic` and `litellm` (the in-cluster proxy). Set `decision_integration` (+ `decision_model`) to override per-agent, or when the deployment uses a provider the default path can't reach (`bedrock`, `vertex`, `azureOpenai` without litellm). ## Memory An agent has two layers of memory, both shown to the LLM each run: - **Episodic — the `agent_runs` log.** One immutable row per run with the probe result, decision, action result, and any error. The last `decision_history_limit` rows (including **failed** runs) are fed to the LLM, so it can see "last run errored", "last run posted this to Slack", and judge trends. - **Durable — the `agents.state` scratchpad.** A JSONB blob that persists across runs. A Python probe reads and rewrites it (watermarks); the decision LLM writes a `memo` into it — *"a note to your future self"* — which is shown back on the next run. This is how an agent remembers "I already alerted on the May spike" without re-deriving it. ## Action modes ### `simple` One predefined action, with arguments the LLM supplies in `action_args`: | `action_type` | What it does | `action_config` | |---|---|---| | `slack_webhook` | Posts to Slack. LLM supplies `action_args.text`. | `integration` (a stored `slack_webhook`), or `webhook_url` / `webhook_url_env`. | | `webhook` | POSTs to an HTTP endpoint; body is the LLM's `action_args`. | `integration` (a stored `generic_webhook`), or a static `webhook_url`. | | `sql` | Runs a SQL statement (e.g. write a row). LLM supplies `action_args.sql`, or set a static `action_config.sql`. | optional `sql`, `max_output_rows`. | ### `fi` Hands the situation to a Fi agent run that reasons and acts with its full toolset. Requires `fi.enabled`. `action_config.prompt_template` is the base prompt; the decision reasoning and probe result are appended. ## Cooldown `cooldown_seconds` is the hard guard against re-firing the same alert. After an action fires, `last_acted_at` is stamped; any action within `cooldown_seconds` of it is **suppressed** — the run still succeeds, `decision.suppressed_by_cooldown` is `true`, no action runs. Checked at execution time, so manual runs respect it too. The LLM also sees recent history and its own memo as a soft secondary guard. ## Triggers An agent fires on any of: - **Cron** — `cron_schedule` (5-field, min interval once per minute) + `cron_timezone`. The job-runner scheduler tick enqueues overdue agents. - **Event** — `event_trigger`, fired when an automation run succeeds: - `{"type": "automation", "automation_id": ""}` — when that pipeline succeeds. - `{"type": "table", "table": "main.orders"}` — when any succeeded automation run had a `pg_sync` step that landed rows in that table. Use this for event-driven runs after new rows arrive. - **Manual** — `POST /api/v1/agents/{id}/runs` or `definite run agent run`. Event-triggered runs go through the same cooldown gate. ## CLI ```bash definite run agent create --name "Sales surge watcher" \ --definition agent.json \ --cron "0 9 * * 1" --cron-timezone America/New_York \ --cooldown-seconds 604800 definite run agent run definite run agent status # probe_result / decision / action_result definite run agent list definite run agent runs # history ``` ## API ```text GET /api/v1/agents POST /api/v1/agents GET /api/v1/agents/{agent_id} PATCH /api/v1/agents/{agent_id} DELETE /api/v1/agents/{agent_id} POST /api/v1/agents/{agent_id}/runs GET /api/v1/agents/{agent_id}/runs POST /api/v1/agents/{agent_id}/trigger-schedule GET /api/v1/agent-runs/{run_id} ``` Same bearer-token auth as the rest of the API. Create / run require `agents.enabled`. `trigger-schedule` (advance `next_fire_at` by one tick for testing) requires admin. ## Cost notes - `simple` mode: one bounded LLM decision call per run (`max_tokens` ~1024, history capped by `decision_history_limit`). Cost scales with trigger frequency — pair a frequent cron/event trigger with a cooldown. - `fi` mode: the decision call **plus** a full Fi agent run, but the Fi run only happens when `should_act` is true and the cooldown has passed. ## Current limits - One probe and one action per agent — no multi-step branching. - The probe runs with full lakehouse privileges (operator-authored, like an automation `sql` / `python` step). Don't expose agent creation to untrusted users. - No missed-run replay — an agent that falls more than an hour behind its cron skips the backlog. - Durable `state` is persisted whenever the probe succeeds; a probe should be idempotent (it may re-run if a later stage fails). --- # Embeddings & Vector Search Vector search over DuckLake columns: embed a text column once, then rank its rows against a search query by cosine similarity — all on DuckDB, no separate vector database and no GPU node pool. ## Why this shape Embedding work splits cleanly into two workloads of very different weight, and the design follows that split: | Workload | Where it runs | Why | |---|---|---| | **Query embedding** — one short string per search | In-process in the **API pod** | A few ms of CPU; a network hop to a separate service would dominate it | | **Column embedding** — a whole DuckLake column | A **job-runner run** (transient) | Bursty, CPU-heavy; belongs in a unit of work that spins up and ends | So there is **no standalone embedding pod**. The API embeds queries itself; batch column embedding is enqueued as an ordinary `python` automation step. The model runs on **CPU**. Embedding models are ~100–350M params — the default `BAAI/bge-small-en-v1.5` is 384-dim and ~130 MB on disk. fastembed (ONNX runtime, no PyTorch) is used so the image grows by ~hundreds of MB rather than ~2 GB. ## Configuration ```yaml # helm/values.yaml embeddings: model: "BAAI/bge-small-en-v1.5" # any fastembed-supported model ``` The model name is read by the API (query embedding) and baked into the batch step (column embedding) so the two always agree. The API pod's memory limit is `3Gi` to hold the loaded model; a larger model needs a further bump. The model is fetched from HuggingFace **on first use**. Air-gapped installs must pre-seed the fastembed cache (mount it, or bake it into the image) — the first search otherwise fails with a `503 embedding model unavailable`. ## Storage model The batch step writes a table with three columns: - the source **id** column (unchanged name + type) - the source **text** column - `embedding` — the vector as a JSON-array `VARCHAR` `embedding` is a string, not a native `FLOAT[]`, because the lakehouse write SDK maps list/array Arrow types to `VARCHAR`. Search casts it back with `CAST(embedding AS FLOAT[])` and ranks with the core `list_cosine_similarity` function — a **brute-force scan**, no `vss` extension and no HNSW index. That is correct and fast up to a few hundred thousand rows. Past that, materialize a native-typed table and add an HNSW index. ## API ### Embed a column (batch) ``` POST /api/v1/embeddings/columns { "schema": "main", "table": "documents", "id_column": "id", "text_column": "body", "dest_schema": "main", // optional; defaults to source schema "dest_table": "documents_emb", // optional; defaults to
__embeddings "batch_size": 256 // optional } ``` Enqueues an ad-hoc job-runner run (a one-step `python` pipeline) and returns the `run` plus the `destination` table. Poll the run via `GET /api/v1/automations/runs/{run_id}`. ### Search ``` POST /api/v1/embeddings/search { "schema": "main", "table": "documents_emb", // the embedded table "id_column": "id", "text_column": "body", "query": "some dog I need to find", "limit": 10 } ``` Embeds `query` in-process and returns rows of `(id, text, similarity)`, best match first. ### Misc ``` GET /api/v1/embeddings/model -> { "model": "BAAI/bge-small-en-v1.5" } ``` ## Limitations (first cut) - The batch step loads the whole source column into the job-runner process before embedding. Fine for moderate columns; very large columns need a larger job-runner Job or a chunked rewrite. - Brute-force search only — no ANN index (see *Storage model*). - Re-embedding replaces the destination table wholesale; there is no incremental "embed only new rows" mode yet. --- # Data Apps Data apps are React dashboards that Definite builds into a single self-contained HTML file and serves from the on-prem deployment at `/apps/`. They are useful when you want a richer, purpose-built analytical app than a saved SQL query or table preview. The normal lifecycle is: ```text scaffold source -> edit app.json and React -> npm run build -> upload -> open /apps/ ``` The compiled HTML, manifest, and editable source snapshot are stored in Postgres. The source snapshot is required for new uploads so a human, Fi, or an MCP client can fetch the app later, edit it, rebuild it against the current runtime, and restore prior versions when needed. ## Quick start Create a starter project, replace the sample SQL and React, build it, then upload it: ```bash definite run app scaffold revenue-explorer cd revenue-explorer # Edit app.json and src/App.tsx. npm run build definite run app upload revenue-explorer . --validate ``` Open the app at: ```text https:///apps/revenue-explorer ``` Useful lifecycle commands: ```bash definite run app list definite run app get revenue-explorer definite run app get revenue-explorer --source definite run app rebuild revenue-explorer --validate definite run app delete revenue-explorer ``` Uploads are create-only by default. If the slug already exists, inspect it first with `definite run app get ` and use `--force` only when you mean to replace that app. Replacements keep the prior HTML and source in the app's version history. Source fetched with `app get --source` includes a hidden local revision marker. An update sends that revision back, so a checkout cannot silently overwrite a newer edit. If the upload returns `data_app_source_conflict`, fetch the app into a new directory and reapply your intended change to the current source. Do not retry the stale checkout. `--validate` checks each manifest resource before publishing the candidate. A failed resource check leaves the current app unchanged. This validation does not execute browser-side `useSqlQuery`, mount React, or initialize charts, so a successful response still reports `verification.render_verified=false`. Open the live app and confirm the modified views separately. ## Manifest Every app has an `app.json` manifest. On-prem manifests use `version: 2` and SQL-backed resources: ```json { "version": 2, "name": "Revenue Explorer", "entry": "src/main.tsx", "resources": { "orders": { "kind": "dataset", "source": { "type": "sql", "sql": "SELECT * FROM marts.orders" } } } } ``` Supported resource shapes: | Field | Meaning | |---|---| | `kind` | `dataset` or `json` | | `source.type` | Must be `sql` | | `source.sql` | SQL run by the API against the lakehouse | SQL should reference on-prem lakehouse objects directly, such as `marts.orders`. `LAKE.SCHEMA.` prefixes are not valid in on-prem manifests. ## Runtime data flow The app runs in the browser, but the browser never receives lakehouse credentials. The bundled runtime calls: ```text POST /api/v1/data-apps//query ``` with a named `resource_key`. The API checks the caller's app permission, runs the resource SQL, and returns Arrow IPC bytes. The browser-side runtime loads those bytes into DuckDB-WASM, so components can use `useDataset` and `useSqlQuery` for local filtering, grouping, and chart preparation. Do not load an export-sized or hidden-tab resource at mount. Keep the hook unconditional, but gate the request until the data is actually needed: ```tsx const detail = useDataset("detail_rows", { enabled: activeTab === "detail", }); ``` `enabled: false` is idle rather than loading and performs no API request. For large source tables, push the current structured filters into the server query instead of fetching the unfiltered table and filtering only in DuckDB-WASM: ```tsx const orders = useDataset("orders", { enabled: Boolean(tenantId), filters: tenantId ? [{ column: "tenant_id", operator: "equals", value: tenantId }] : [], }); ``` Filter operators are `equals`, `not_equals`, `in`, `gte`, and `lte`. Range operators are available for `number` columns and strict ISO `date` values (`YYYY-MM-DD`). Date columns use calendar-day semantics: the projected value is cast to `DATE`, so an `lte` bound includes the full end date even when the resource returns timestamps. The column and value type are checked against the resource's `filterable` declaration, and every predicate is compiled server-side before DuckDB materializes the result. Home and Apps cards use a preview query route backed by the app's last successful resource snapshots. Opening the full app runs the live resource queries. ## Resource result limits Live and embedded data-app resources use the workspace client-side query limits. The defaults are 200,000 rows and 100 MiB of Arrow IPC. An operator can lower either value in **Settings → General → Client-side query limits**; the data-app byte limit always has a hard 100 MiB ceiling even if another query surface is configured higher. The API consumes DuckDB record batches incrementally and stops before accepting an Arrow file larger than the byte limit. A result over either limit returns HTTP 413 with a structured `data_app_query_result_too_large` detail containing the limit kind, configured limit, observed size, row count, and accepted serialized bytes. Narrow the resource SQL or move an export-sized result to an on-demand export flow instead of loading it as a dashboard dataset. Cold resource queries also have bounded server-side admission. Identical concurrent cache misses share one materialization, the 60-second server cache is bounded by both entries and bytes, and completed Arrow responses retain their admission reservation until the API has handed the body to the client. Admins can inspect current reservations, cache bytes, cumulative delivered response bytes, and row/byte cap rejections at `GET /api/v1/admin/data-apps/materialization-metrics`. ## On-demand CSV exports Use the queued export path when a user needs more detail than should be loaded into the browser: ```tsx import { exportResource } from "@definite/runtime"; const result = await exportResource("orders", { filters: [ { column: "tenant_id", operator: "equals", value: tenantId }, { column: "created_on", operator: "gte", value: dateRange.from }, { column: "created_on", operator: "lte", value: dateRange.to }, ], }); window.location.assign(result.downloadUrl); ``` `exportResource` enqueues the resource query on the job runner's backfill lane, polls it, and returns a short-lived signed object-storage URL. DuckDB writes the CSV directly to object storage; the API never holds the result rows. The same `filterable` and `required_filters` rules as interactive resource queries are enforced before enqueue. Exports are capped at 500,000 rows and a 1 GiB CSV file. If the row cap is reached, `result.truncated` is true. A file over the byte cap is deleted and the export fails. This API is available to signed-in in-product apps; preview cards and external embeds cannot start exports. ## Cache TTL Resource results are cached in the browser's IndexedDB for 24 hours by default. The cache is partitioned by resource definition, serving surface, credential, and effective filters. It retains at most 64 entries / 64 MiB and does not persist any one entry over 32 MiB; oldest entries are evicted first. Tune the TTL in `app.json` only when the app needs fresher or longer-lived client-side data: ```json { "version": 2, "name": "Hourly Revenue", "cache_ttl_hours": 1, "resources": { "orders": { "kind": "dataset", "cache_ttl_hours": 0.25, "source": { "type": "sql", "sql": "SELECT * FROM marts.orders" } } } } ``` Top-level `cache_ttl_hours` sets the default for every resource. A per-resource value overrides it for that resource. Values must be positive numbers and can be fractional. This is the in-browser cache. The external embed path also has server-side backpressure and cache behavior, covered in [Data app embedding](/docs/data-app-embedding). ## Compute profiles For heavier dashboard queries, add a top-level `compute_profile`: ```json { "version": 2, "name": "Heavy Dashboard", "compute_profile": "large", "resources": { "orders": { "kind": "dataset", "source": { "type": "sql", "sql": "SELECT * FROM marts.orders" } } } } ``` The profile name must exist in the deployment's `compute_profiles` registry. Non-default profiles route SQL resources through the Fi sandbox burst path, so interactive dashboards may need a warm pool to avoid first-load latency. See [Compute Profiles](/docs/compute-profiles#data-apps). ## Embedding Inside Definite, users open apps from Home, Apps, or `/apps/`. To put the same app in another website, create an external embed. Embeds use revocable `emb_` credentials, optional short-lived `emv_` view tokens, allowed-host framing rules, and optional row/column scoping. See [Data app embedding](/docs/data-app-embedding) for iframe setup, token minting, scoped filters, and capacity notes. Each resource that accepts runtime or embed row filters must declare the filterable columns: ```json { "resources": { "orders": { "kind": "dataset", "source": { "type": "sql", "sql": "SELECT * FROM marts.orders" }, "filterable": [ { "column": "tenant_id", "type": "number" }, { "column": "region", "type": "string" }, { "column": "created_on", "type": "date" } ] } } } ``` Scoped embed queries fail closed when a resource does not declare a required filterable column. For resources that must never execute unfiltered, add `required_filters`. This is enforced for authenticated app queries, external embeds, and exports: ```json { "resources": { "orders": { "kind": "dataset", "source": { "type": "sql", "sql": "SELECT * FROM marts.orders" }, "filterable": [ { "column": "tenant_id", "type": "number" }, { "column": "region", "type": "string" } ], "required_filters": ["tenant_id"] } } } ``` Every required column must also be declared in `filterable`. A missing required column returns a structured HTTP 400 with code `data_app_required_filter_missing`. The camel-case cloud field `requiredFilters` is a different contract and is rejected during on-prem build and upload; migrate it explicitly to `filterable` plus `required_filters`. ## Source, rebuilds, and versions Every current upload includes editable source files. You can download them: ```bash definite run app get revenue-explorer --source ``` After editing, rebuild locally with `npm run build` and upload with `--force`, or ask Definite to rebuild the stored source against the deployment's current data-app runtime: ```bash definite run app rebuild revenue-explorer --validate ``` The app detail page and API expose runtime metadata so stale apps can be found after a runtime/template change. Admins can also bulk rebuild stored-source apps through the admin API. ## Permissions Creating a data app requires an editor or admin session. Viewing the app, loading its HTML, and running its resources require view access to that app. Replacing, renaming, rebuilding, changing its compute profile, or deleting it requires edit access to the app. New apps are initialized with the deployment's default content visibility, then use the same content sharing model as other Definite objects. ## Authoring with Fi or MCP Fi and external MCP clients can build normal data apps. The MCP server exposes `scaffold_data_app`, `save_data_app`, `validate_data_app`, `query_data_app_resource`, `list_data_apps`, and `get_data_app`. Apps created this way use the same source snapshot, version history, permissions, and runtime as CLI-created apps. See [MCP Server](/docs/mcp#building-a-data-app-end-to-end) for the tool flow. ## Troubleshooting | Symptom | What to check | |---|---| | Upload returns a slug conflict | Use `definite run app get ` to inspect the existing app, then pick a new slug or upload with `--force` only for an intentional replacement. | | Upload says `source_files is required` | Upload a project directory, not just a loose `index.html`; the directory must include editable source such as `app.json` and `src/`. | | Upload returns `data_app_source_conflict` | Another editor published after this source was fetched. Fetch into a new directory and reapply the intended edit; do not retry the stale checkout. | | App opens but a chart errors | Resource validation does not execute browser-side SQL or charts. Open the app, inspect the surfaced runtime error, and fix the named component or `useSqlQuery`; use `--validate` separately for manifest-resource SQL. | | App still shows old data | Check `cache_ttl_hours`, then reload after the browser cache expires or upload a manifest with a shorter TTL. | | App is marked stale | Rebuild it from stored source so it picks up the current runtime and mirrored library URLs. | | Embedded app fails with scoped filters | Make sure every queried resource declares every filtered column in `filterable`. | | Resource query returns HTTP 413 | The resource exceeded the workspace row limit or the 100 MiB data-app Arrow ceiling. Narrow the SQL; do not eagerly load export-sized data into a dashboard resource. | ## Related docs - [CLI Reference](/docs/cli#definite-run-app) - [API Reference](/docs/api#data-apps) - [Data app embedding](/docs/data-app-embedding) - [Compute Profiles](/docs/compute-profiles#data-apps) - [MCP Server](/docs/mcp#building-a-data-app-end-to-end) --- # Data App Embedding A **data app** is a React app compiled to a single HTML file and stored in Postgres (`definite.data_apps`). Inside the Definite UI you open it from the Apps list. **External embedding** lets you drop that same app into a page on your own website — a customer dashboard, an internal wiki, a partner portal — by pasting an ` ``` Paste it into the HTML of the page where the app should appear. The `t` query parameter carries the embed token — keep the snippet as issued. When the iframe loads, the API serves the app's compiled HTML directly from the Definite origin and injects a small bootstrap script ahead of the app's own module script. That script sets three globals the app reads to talk back to the API: - `window.__DEFINITE_API_BASE` — the API base path (default `/api/v1`) - `window.__DEFINITE_APP_SLUG` — the app's slug - `window.__DEFINITE_TOKEN` — the embed token > This external-embed path serves the app HTML **directly from the Definite > origin**. It is deliberately different from the in-UI preview, which renders > the app from a `blob:` URL inside the Definite app. The embed path needs a > real origin so the browser can apply the framing and header policy below. ## Data scoping By default an embed shows every row the app's SQL returns. **Data scoping** lets you narrow that down — so a customer sees only their own rows, or each signed-in end user sees only theirs — without forking the app or writing a per-tenant query. ### The filter model A **filter** is a single row-level condition: ```json { "column": "tenant_id", "operator": "equals", "value": 42 } ``` - `column` — the column to filter on. It must be declared `filterable` in the app manifest (see below). - `operator` — one of `equals`, `not_equals`, `in`, `gte`, or `lte`. - `value` — a scalar for `equals` / `not_equals` / `gte` / `lte`; a non-empty list for `in`. Multiple filters are **ANDed** together. There is no `OR`, no comparison operator beyond the typed `gte` / `lte` bounds, and no free-text SQL — the model is deliberately small so every filter is easy to reason about and safe to compile. Range operators are available only for `number` and `date` columns. ### Declaring `filterable` columns A resource can only be filtered on columns it explicitly opts in. Add a `filterable` array to the resource in the app manifest, listing each column and its type (`string`, `number`, `boolean`, or `date`): ```json { "version": 2, "resources": { "orders": { "kind": "dataset", "source": { "type": "sql", "sql": "SELECT * FROM orders" }, "filterable": [ { "column": "tenant_id", "type": "number" }, { "column": "region", "type": "string" }, { "column": "is_paid", "type": "boolean" }, { "column": "created_on", "type": "date" } ] } } } ``` A resource with no `filterable` array cannot be safely queried by a scoped embed. When an embed or view token has filters, every resource the app queries must declare every filtered column in its own `filterable` list. If it does not, the query fails closed instead of running unfiltered. The declared `type` is used to validate filter values up front: a `number` column rejects a non-numeric value, a `boolean` column rejects anything that isn't a real boolean. Date values must use the strict `YYYY-MM-DD` form. ### Fixed-filter embeds When you create an embed in the UI you can attach a fixed set of filters to it. Every viewer of that embed sees the same scoped data — useful when one embed belongs to one customer. On the **Embed** tab, after entering the name and allowed hosts, add one or more filters (column, operator, value). The filters are stored on the embed and applied to every query the embed token authorizes; they cannot be changed by the page hosting the iframe. ### Per-end-user minted tokens When a single embed serves many end users — each of whom should see only their own rows — your backend mints a **short-lived per-user token** from the durable embed token. Call: ``` POST /api/v1/data-apps/{slug}/embed/token ``` from your server (never the browser), authorized by the `emb_` embed token, with the filters for the user you're rendering the page for: ```bash curl -X POST https://definite.your-company.com/api/v1/data-apps/revenue-explorer/embed/token \ -H "Authorization: Bearer emb_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \ -H "Content-Type: application/json" \ -d '{ "filters": [ { "column": "tenant_id", "operator": "equals", "value": 42 } ] }' ``` The response carries a short-lived `emv_` token. Hand that token to the iframe (in place of the `emb_` token) — it expires in minutes, so mint a fresh one per page render and never embed the durable `emb_` token in a public page. **A minted token can only narrow.** The effective filters for an `emv_` token are the parent embed's fixed filters **AND** the filters supplied at mint time — never a replacement. A view cannot widen access beyond what its parent embed already allows; passing a filter on a column the embed already constrains can only further restrict the rows, never reveal more. ### Security note Filter values are never concatenated raw into SQL. Each value is compiled to a **safe SQL literal** — strings are single-quoted with every inner quote doubled, numbers are validated as numeric, booleans render as `TRUE`/`FALSE` — so a hostile value like `'); DROP TABLE users;--` stays fully contained inside one quoted literal and cannot break out. Columns are **allowlisted** to the manifest's `filterable` set, so a filter can never reference a column the app author didn't expose. A scoped query also fails if the specific resource being queried does not declare every filtered column. The scoped query the lakehouse runs is the resource SQL wrapped as: ```sql SELECT * FROM ( ) AS _embed_scoped WHERE ``` ## Endpoints | Method & path | Purpose | |---|---| | `POST /api/v1/data-apps/{slug}/embeds` | Create a named embed for an app | | `GET /api/v1/data-apps/{slug}/embeds` | List an app's embeds | | `DELETE /api/v1/data-apps/{slug}/embeds/{embed_id}` | Revoke an embed | | `GET /api/v1/data-apps/{slug}/embed?t=` | Public — serve the embeddable HTML | | `POST /api/v1/data-apps/{slug}/embed/token` | Mint a short-lived per-end-user (`emv_`) token from an embed token | | `POST /api/v1/data-apps/{slug}/query` | Read-only query, authorized by the embed or minted token | The first three are management endpoints for editors/admins who have edit access to the app. `GET .../embeds` returns metadata only; full tokens and iframe snippets are redacted after creation. The rest are the runtime path the iframe, the app inside it, and your token-minting backend use. ## Security model ### Allowed hosts and `frame-ancestors` Each embed carries an `allowed_hosts` list. The public embed response sets a `Content-Security-Policy` header whose `frame-ancestors` directive is built from that list: - **Empty list** → `frame-ancestors *`. Any site may frame the app. Convenient for testing; not recommended for production. - **Non-empty list** → the hosts space-joined, e.g. `frame-ancestors https://app.example.com *.example.com`. Only those origins may frame the app; every other site gets a blank frame. Accepted host forms: `*`, a hostname (`example.com`, `app.example.com`), a wildcard subdomain (`*.example.com`), an optional scheme (`https://example.com`), and an optional port (`example.com:8443`). Entries containing whitespace, `;`, `,`, quotes, backticks, or newlines are rejected so a bad value cannot break out of the CSP header. ### Response headers The public `GET .../embed` response is locked down: | Header | Value | |---|---| | `Content-Security-Policy` | `frame-ancestors ` | | `Referrer-Policy` | `no-referrer` | | `Cache-Control` | `private, no-store` | | `X-Content-Type-Options` | `nosniff` | ### Token scope The embed token authorizes exactly one thing beyond loading the HTML: **read-only** `POST /api/v1/data-apps/{slug}/query` for the **one app** the embed belongs to. It cannot query other apps, cannot write, and cannot reach any other API surface. It is not a user session. Durable and view tokens are stored hashed in the Definite application database. The plaintext token is only available to the creator response or the mint-token response, so treat that response like a secret and store it in your own secret manager if your backend needs to mint `emv_` tokens later. ## Capacity and backpressure at embed scale Embedded apps run their resource queries on the deployment's shared lakehouse engine — the same engine serving syncs, transformations, and in-UI queries. Admission to that engine is bounded: when a query can't get a slot within `lakehouse.maxConcurrencyWaitSeconds`, `POST .../query` fast-fails with **HTTP 503 + `Retry-After`** instead of queueing unboundedly. A 503 here means *transient backpressure*, not a broken query — the bundled app runtime retries it automatically (up to 3 attempts, honoring `Retry-After`, capped at 10s per wait) before surfacing an error. Brief overlaps between a transform window and dashboard traffic self-heal; **persistent** errors under embed load mean the deployment needs more capacity. Custom clients that call `/query` directly should implement the same retry-on-503 behavior. Each response is also bounded by the workspace client-side row and byte limits (200,000 rows and 100 MiB by default), with a hard 100 MiB data-app Arrow ceiling. An over-limit resource returns HTTP 413 with structured `data_app_query_result_too_large` detail. This is not transient backpressure: clients should not retry the same query unchanged. Apply narrower scoped filters or redesign the app so export-sized data is requested on demand. The runtime is compiled into each app's HTML bundle, so apps built before the retry shipped keep their old behavior until rebuilt (`POST /api/v1/data-apps/{slug}/rebuild`, or re-save the app from source). App metadata includes the runtime version/fingerprint recorded at build time and `runtime_stale` when it differs from the deployment's current template. Use `GET /api/v1/data-apps?stale=true` to list stale apps, or have an admin call `POST /api/v1/admin/data-apps/rebuild-all` to rebuild every app with stored source files against the current runtime. Apps without stored source are reported as skipped and must be re-uploaded from source. Migration or port tooling should target the deployment's current server-side template runtime (`DATA_APP_TEMPLATE_DIR`, `/opt/data-apps-template` by default) instead of copying a local `runtime/` snapshot that can drift behind the installed deployment. Several server-side effects soften the load before sizing matters: - Query results are cached for ~60 s keyed by `(app, resource, filters)`, so N viewers of the same embed with the same scoping share one lakehouse query per resource per minute. Per-end-user minted tokens with *distinct* filters each miss that cache. - Concurrent misses for the same cache key share one in-flight materialization. The server cache is capped at 128 entries and 128 MiB, and expired entries are evicted during lookup. - Only cache misses consume lakehouse slots; an embed page-load fires one `/query` per resource, concurrently. - Data-app response delivery has a separate memory semaphore. Requests wait up to `api.dataApp.deliveryAdmissionWaitSeconds` (60 s by default) behind that bounded queue before returning a retryable 503. The wait is asynchronous, so queued resources do not occupy FastAPI worker threads. This is distinct from the lakehouse admission wait below. This server-side embed cache is separate from the in-UI browser cache. Data apps opened inside Definite cache resource payloads in IndexedDB for 24 hours by default; app authors can set top-level `cache_ttl_hours` in `app.json`, or a per-resource `resources..cache_ttl_hours`, to tune that browser TTL. External embeds do not use that browser IndexedDB cache. ### Sizing the lakehouse for embed traffic The knobs live under `lakehouse:` in the Helm values (defaults in parentheses): | Knob | Default | What it bounds | |---|---|---| | `lakehouse.readerPoolSize` | 4 | Pooled DuckDB reader connections — the real read-parallelism ceiling | | `lakehouse.maxConcurrency` | 8 | Outer admission bound on in-flight lakehouse ops | | `lakehouse.maxConcurrencyWaitSeconds` | 5 | How long an over-limit query waits for a slot before the 503 | | `lakehouse.busyRetryAfterSeconds` | 2 | The `Retry-After` value advertised on that 503 | | `api.dataApp.deliveryMaxConcurrency` | 2 | In-flight Arrow responses retained through ASGI delivery | | `api.dataApp.deliveryAdmissionWaitSeconds` | 60 | How long a board resource waits for a delivery-memory slot before a 503 | Rules of thumb: - Estimate peak *concurrent cache-missing* queries: roughly `(dashboards opened per minute) × (resources per app)` for fixed-filter embeds, higher when per-end-user filters defeat the result cache. - A handful of concurrently open dashboards fits the defaults. For ~10+ production embeds with steady viewer traffic, raise `readerPoolSize` to 6–8 and `maxConcurrency` proportionally (it should cover the reader pool plus a writer permit; the client enforces that floor automatically). - Keep `maxConcurrency` well under the API's worker threadpool size (~40). **Prerequisite — catalog Postgres `max_connections`.** Each pooled reader holds one direct connection to the DuckLake catalog Postgres for its lifetime (plus the writer, sync workers, the app-DB pool, and any worker-tier pods on a shared instance). The default budget is sized for a small catalog tier (`max_connections=50`): 4 readers is safe there, but raising the pool without raising `max_connections` trades 503s for hard `too many clients` 500s. Bump the catalog tier first (e.g. Cloud SQL `db-custom-1-3840` → `max_connections=150` gives headroom for 8 readers), then raise the knobs. The comments above each knob in `helm/values.yaml` carry the full connection budget. Per-class admission (interactive embed traffic vs background transform/sync work) is not implemented today: all lakehouse work shares one admission bound, so a heavy transform window can briefly consume every slot. The retry path above is what absorbs that overlap. ## Revoking an embed On the **Embed** tab, delete the embed (or call `DELETE /api/v1/data-apps/{slug}/embeds/{embed_id}`). Revocation is immediate and per-credential — other embeds for the same app keep working. After revocation: - New iframe loads fail: `GET .../embed?t=` no longer returns the app. - The revoked token can no longer authorize `/query`, so an already-loaded iframe stops being able to fetch data and shows whatever error state the app renders for a failed query. - Already-rendered pixels in a live iframe are not magically erased, but the app is dead the moment it next calls the API. To force every viewer off immediately, revoke the embed; to also blank the frame, take the app down or rotate to a fresh embed. Revoking an embed never deletes or changes the underlying app. --- # Drive Drive is a light, object-store-backed file store. Users drag files — a large Parquet export, a CSV, an Excel sheet — into the **Drive** page; the bytes are staged in the deployment's existing object-store bucket, and any Parquet/CSV/JSON file can be loaded into a lakehouse table with one click. It is the UI counterpart to the headless `definite run load` CLI flow. ## Storage layout Drive needs **no new bucket and no new credentials**. The deployment already has one object-store bucket with the lakehouse's data files; Drive adds one sibling prefix: | Prefix | Contents | |---|---| | `lake/` | DuckLake's own Parquet data files | | `lake/_staging/` | Files staged by `definite run load` by default | | `drive/` | **Drive uploads** — `drive/{file_id}/{filename}` | All three prefixes are covered by the same object-store credentials (`GCS_HMAC_KEY_ID`/`GCS_HMAC_SECRET`, `S3_ACCESS_KEY_ID`/`S3_SECRET_ACCESS_KEY` or S3 IRSA through the AWS credential chain, or `AZURE_STORAGE_ACCOUNT`/`AZURE_STORAGE_KEY`) that the API and job-runner pods already use. If `jobRunner.staging.uri` is explicitly moved outside the lakehouse prefix, grant that custom staging prefix to the same object-store identity as well. On Azure the store's "bucket" is the account host, so these are prefixes **inside the configured container** (`/lake/`, `/drive/`, and so on). ## Bucket CORS — required Drive uploads go **directly from the browser to object storage** via presigned `PUT` URLs, so multi-GB files never pass through the API pod. A browser cross-origin `PUT` requires the bucket to have a CORS policy that allows `GET` and `PUT` from the deployment's web origin. GCS example (`cors.json`, applied with `gcloud storage buckets update gs://YOUR_BUCKET --cors-file=cors.json`): ```json [ { "origin": ["https://your-deployment.example.com"], "method": ["GET", "PUT"], "responseHeader": ["Content-Type"], "maxAgeSeconds": 3600 } ] ``` The equivalent S3 CORS rule allows the same `AllowedOrigins` / `AllowedMethods` (`GET`, `PUT`) and `AllowedHeaders` (`Content-Type`). ### Azure Blob Azure uploads use an account-key SAS `PUT` to the blob endpoint, and that `PUT` carries an `x-ms-blob-type` header, so the storage account's CORS rules must allow that header in addition to `GET`/`PUT`. Set CORS on the storage account (Portal: **Settings > Resource sharing (CORS) > Blob service**, or the CLI): ```bash az storage cors add \ --services b \ --methods GET PUT \ --origins https://your-deployment.example.com \ --allowed-headers 'x-ms-blob-type,content-type,content-length' \ --exposed-headers '*' \ --max-age 3600 \ --account-name YOUR_ACCOUNT --account-key "$AZURE_STORAGE_KEY" ``` **Private-endpoint / VNet-restricted accounts.** The browser (not the API pod) connects straight to `https://.blob.core.windows.net`, so that endpoint has to be reachable and DNS-resolvable *from the end user's browser*. A storage account locked behind a private endpoint only answers inside the VNet, so end users must reach it over that same private network (corporate network, VPN, or ExpressRoute) with the `privatelink.blob.core.windows.net` private DNS zone in effect. If browsers cannot resolve or reach the blob endpoint, Drive uploads fail even with correct CORS. This is the same browser-to-storage requirement S3 and GCS have; Azure private endpoints just make it explicit. Without a CORS rule, browser uploads fail with a CORS error; the headless `definite run load` flow is unaffected (the CLI is not a browser). ## Lifecycle - Uploads are **persistent** by default — they stay until explicitly deleted. - An upload can be marked **temporary** with a TTL of 1–30 days. Expired files are swept (object + metadata row) the next time the file list is fetched. - Deleting a file removes both the object and the `drive_files` row. ## API All endpoints are under `/api/v1/drive`. Reads require any authenticated user; uploads, loads, and deletes require the `editor` role. Drive files are **workspace-shared** — every user sees every file. | Method + path | Purpose | |---|---| | `POST /presign` | Mint a presigned `PUT` URL; creates a `pending` row. | | `POST /files/{id}/complete` | Confirm the upload finished; flips the row to `ready`. | | `GET /files` | List all `ready` files (also sweeps expired ones). | | `GET /files/{id}/download-url` | Short-lived presigned `GET` URL. | | `POST /files/{id}/load` | Load the file into a lakehouse table. | | `DELETE /files/{id}` | Delete the object and its row. | ## Row actions Each file row has a three-dot (⋮) menu: - **Ask Fi** — opens a fresh Fi conversation pre-seeded with the file's path, so you can ask the agent to analyze it. - **Load into lakehouse** — wrap the file in a table (Parquet/CSV/JSON only). - **Copy path** — copy the file's `gs://…`/`s3://…` object path to the clipboard. Paste it to Fi, or into a `read_csv()` / `read_parquet()` query. - **Download** — open a short-lived signed URL. - **Delete** — remove the object and its row. ## Working with Fi The Fi agent can read Drive files directly. It has no object-store credentials of its own and does not need them: its `definite_sql_query` tool runs through the lakehouse, whose DuckDB session holds the bucket-wide credentials. The access path Fi reaches for depends on the file type: | File type | How Fi reads it | |---|---| | Tabular (Parquet/CSV/JSON) | `SELECT * FROM read_parquet('gs://…/drive/…/sales.parquet')` (or `read_csv_auto` / `read_json_auto`) | | Text (`.md`, `.txt`, `.log`, `.sql`, `.yaml`, source code…) | `SELECT content FROM read_text('gs://…/drive/…/notes.md')` | | Binary / arbitrary (`.xlsx`, `.pdf`, images, `.zip`…) | `definite run drive get ` into the sandbox, then process with bash + Python | Fi's system prompt has a Drive section that points it at each path. Nothing needs to be granted to the Fi sandbox itself. ## CLI: `definite run drive get` Download a Drive file by its `gs://`/`s3://` path or by its bare file id: ```bash # Path form — destination defaults to the filename in the path. definite run drive get gs://acme-lake/drive/946aacbb-…/notes.md # Bare id form — destination is required. definite run drive get 946aacbb-ea0a-4776-b854-a5e654d2b6d8 ./notes.md # Stream to stdout (no envelope on stdout — info goes to stderr): definite run drive get gs://…/drive/…/data.csv - ``` Use `--force` to overwrite an existing destination file. This is how Fi pulls binary files (xlsx, pdf, images) into its sandbox so they can be processed locally; humans use it the same way. ## Limitations (v1) - Flat filenames only — no nested folders. - Single presigned `PUT`, so uploads cap at 5 GB on S3 and roughly 5,000 MiB on Azure Blob (GCS is higher); multipart / block upload is a follow-up. Same limitation as `definite run load`. - Only Parquet, CSV, and JSON can be loaded into the lakehouse; other file types are stored but not loadable. - Azure Blob uploads need the storage account's CORS rules to allow the `x-ms-blob-type` header and the blob endpoint to be reachable from end-user browsers (see [Bucket CORS](#bucket-cors--required)). --- # MCP Server Definite On-Prem exposes a [Model Context Protocol](https://modelcontextprotocol.io) server so external AI clients — Claude Cowork, Claude Desktop, claude.ai, the MCP Inspector — can query the deployment directly. The server is mounted at **`/mcp`** on the same host as the API and web UI (e.g. `https://your-deployment.example.com/mcp`). ## Connecting Pick one setup path before you start. | Option | Use it when | Credential handling | |---|---|---| | Option A - OAuth connector | You are connecting from Claude Cowork, Claude Desktop, or claude.ai and want Claude to handle the token exchange. | Claude opens Definite's MCP OAuth consent page and stores the returned session token. | | Option B - static bearer token | You are connecting from Claude Code, scripts, MCP Inspector, or any client that accepts an `Authorization` header. | You provide a Definite session token or `def_` API token yourself. | > **Deployment URL.** In the examples below, `` means the full > deployment hostname, not a path segment. If your web UI is > `https://analytics.example.com`, the MCP URL is > `https://analytics.example.com/mcp`. The server authenticates every request with a bearer token. There are two ways to obtain one. ### Option A - OAuth connector (Claude Cowork, Claude Desktop, claude.ai) The deployment runs a small OAuth 2.1 authorization server, so it can be added as a **custom connector** with no manual token handling. 1. In claude.ai or Claude Desktop, open **Customize > Connectors**. 2. Click the **+** button next to Connectors, then select **Add custom connector**. 3. Name the connector, enter `https:///mcp`, and add it. 4. Claude registers itself, then opens a Definite sign-in page in the browser. 5. Sign in with your Definite email + password and approve the request. 6. Claude is returned an access token automatically and the connector is live. The token Claude receives is a normal Definite session (14-day lifetime). When it expires, reconnect the connector to sign in again. This flow uses Definite's current MCP OAuth consent page, which verifies local Definite email/password credentials. If password sign-in is disabled on your deployment, use a `def_` API token for Option B. #### How it works The flow is standard OAuth 2.1 authorization-code with PKCE - no client secret. | Step | Endpoint | |---|---| | Discovery (resource) | `GET /.well-known/oauth-protected-resource` | | Discovery (AS) | `GET /.well-known/oauth-authorization-server` | | Dynamic client registration (RFC 7591) | `POST /api/v1/mcp-oauth/register` | | Authorization + consent | `GET/POST /api/v1/mcp-oauth/authorize` | | Token exchange | `POST /api/v1/mcp-oauth/token` | An unauthenticated request to `/mcp` returns `401` with a `WWW-Authenticate` header pointing at the protected-resource metadata, which is how OAuth-aware clients discover the rest. The access token is an opaque Definite session token - the same credential the REST API and CLI use - not a JWT. The deployment does not run a JWKS endpoint or manage signing keys. ### Option B - static bearer token (Claude Code, scripts, MCP Inspector) Clients that accept a pre-supplied header can skip OAuth entirely. For a short-lived session token, use the CLI login path: 1. Install the `definite` CLI; see the [CLI reference](/docs/cli). 2. Sign in to your deployment with [`definite login`](/docs/cli#definite-login). Use the deployment host, without `/mcp`: ```bash definite login ``` 3. Copy the token from `~/.definite/credentials.json`: ```bash jq -r '.token' ~/.definite/credentials.json ``` `definite login` uses local Definite email/password auth. On SSO-only deployments, create a long-lived `def_` API token in **Settings > API tokens** instead; the MCP server accepts either session tokens or API tokens as bearer credentials. An **unscoped** `def_` token (or a session token) can call every MCP tool, as before. A **scoped** token may only call the tools its scopes cover — the same [scope taxonomy as the REST API](/docs/api#scopes): `run_sql_query` needs `query:read`, `run_automation` needs `pipelines:run`, `save_data_app` needs `docs:write`, and so on. A tool called without the required scope returns a clear "missing required scope" error. Session tokens expire after 14 days. Re-run `definite login ` and update the MCP client when the token expires. Add the server to Claude Code with the HTTP transport: ```bash claude mcp add --transport http definite https:///mcp \ --header "Authorization: Bearer " ``` For Claude Desktop's config file, the `mcp-remote` bridge does the same: ```json { "mcpServers": { "definite": { "command": "npx", "args": [ "-y", "mcp-remote", "https:///mcp", "--header", "Authorization:Bearer " ] } } } ``` ### Approving Claude Code access After adding a server, start a new Claude Code session in the project directory where that server should load. If you use a project-scoped `.mcp.json`, run Claude Code from that project root so it reads the right file. Claude Code asks before using project-scoped `.mcp.json` servers. Until you approve one, `claude mcp list` and `claude mcp get ` show it as `Pending approval` and Claude Code will not connect to it. Start `claude` interactively from the project directory to review and approve it. If your `.mcp.json` contains an `Authorization` header with a live token, add `.mcp.json` to that project's `.gitignore`, or use Claude Code's default local scope so the secret is stored in your user config instead of the repository. ### Verify the connection List the configured servers: ```bash claude mcp list claude mcp get definite ``` The URL should be your on-prem deployment, such as `https://analytics.example.com/mcp`. If the configured host is not your deployment host, update the MCP server URL before testing. In Claude, ask it to use the `definite` MCP server and call `list_integrations`. A successful response lists integration ids, names, types, and public config without returning secrets. ## Tools A caller sees only what its authenticated user is permitted to see. | Tool | Purpose | |---|---| | `run_sql_query` | Run a SQL query against the lakehouse | | `list_integrations` | List integrations (no secrets) | | `get_integration` | Get one integration by id or name (no secrets) | | `list_automations` | List automation pipelines | | `run_automation` | Trigger an automation pipeline run | | `cancel_automation_run` | Cancel a queued or running automation run | | `discover` | Start an analytical question by searching ontology and semantic metadata together | | `list_semantic_models` | List semantic models with grain | | `describe_semantic_model` | Full definition of one semantic model | | `search_semantic` | Search semantic models / metrics / dimensions | | `search_ontology` | Search the top-level ontology of business concepts and their linked objects | | `describe_ontology_object` | Full definition of one ontology business concept and its soft links | | `resolve_ontology` | Bind one short or ambiguous token (a code, categorical value, or metric word) to a single governed concept and its column/measure | | `run_semantic_query` | Run a semantic query (named dimensions + measures, grouped rows) | | `run_cli` | Run an allowlisted `definite` CLI command, authenticated as the caller | | `write_workspace_file` | Write a text file into the caller's private CLI workspace | | `read_workspace_file` | Read a file from the caller's CLI workspace | | `list_workspace_files` | List the caller's CLI workspace files | | `scaffold_data_app` | Starter template source (editable files + authoring notes) | | `save_data_app` | Create a data app from source; `mode="update"` intentionally edits an existing app | | `validate_data_app` | Dry-run every SQL resource in an app's manifest | | `query_data_app_resource` | Run one app resource, return JSON rows | | `list_data_apps` | List data apps | | `get_data_app` | One app's record + manifest (+ source on request) | ### Resolve before you discover `discover` is the right entry point for an open-ended question ("what do we have about revenue?"). When the user instead names a specific code, categorical value, or short ambiguous word (`HI`, `XXL`, `missed`), call `resolve_ontology` first: it walks the ontology's typed edges on the server and returns one binding (`{resolved, binding, value, confidence, alternatives, candidates}`) rather than candidate prose to interpret. Pass the surrounding question text as `context` so homonyms land on the right concept. A `confidence` of `ambiguous` means the tie was genuine: show the `alternatives` and ask, rather than guessing. The same capability is available to Fi as `definite_resolve` and on the command line as `definite ontology resolve [--context ]`. ### Building a data app end-to-end An MCP client can author a data app without node or npm on its side — the build (tsc + eslint + esbuild) runs inside the deployment, using the same template and toolchain as `definite run app rebuild`: 1. `scaffold_data_app` — returns the starter template's editable files (`app.json` manifest + `src/` React components) and the authoring notes. 2. Edit the manifest's `resources..source.sql` and the components, then `save_data_app` with the changed files. The default `mode="create"` is create-only: an existing slug returns `{ok: false, stage: "slug_conflict"}` so the client can pick a new slug. Use `mode="update"` only when the user intentionally wants to modify that existing app; update mode merges files over the app's stored source. A failed build returns `{ok: false, error: }` to fix and resubmit; a successful save returns the app record, its `/apps/` URL, and a per-resource SQL validation report. Validation runs before publish, so a failed candidate leaves the current app unchanged. Concurrent source changes return `stage="source_conflict"` instead of overwriting newer work. The report does not mount the browser runtime; `verification.render_verified` remains false until a user opens and confirms the modified views. Optional browser-cache tuning lives in the same manifest: top-level `cache_ttl_hours` sets the default IndexedDB TTL for every resource, and `resources..cache_ttl_hours` overrides one resource. Omit both for the 24-hour default. 3. `query_data_app_resource` — spot-check the rows feeding each chart; `validate_data_app` — re-run the SQL dry-run any time. Apps created this way are normal data apps: they appear on Home/Apps (with snapshot previews after their first run), are shareable, and can be edited later by Fi, the CLI, or another MCP session (`get_data_app` with `include_source=true`). Intentional updates record a prior source/HTML version that can be viewed or restored from the app detail page. ### CLI passthrough (`run_cli`) The long tail of platform operations — automation/script/agent CRUD, semantic and ontology writes, transformation projects, file loads, permission grants — ships as `definite` CLI subcommands. `run_cli` executes the CLI binary baked into the api image, so MCP clients get all of it without a bespoke tool per operation. - **Discoverability.** Calling `run_cli` with no `args` returns `definite --help`; every subcommand accepts `--help` too. Output defaults to JSON. - **Same identity, same permissions.** The subprocess is pinned to this deployment's own API and authenticated with the caller's bearer token — every CLI call round-trips through the same permission checks as the REST API. The `--api-url` / `--token` flags are rejected. - **Allowlisted.** Only `run`, `semantic`, `ontology`, `transform`, and `version` are accepted (the same set the CLI itself permits inside a Fi sandbox). Deploy/ops commands (`init`, `upgrade`, `admin`, ...) and the interactive `run fi` are blocked. - **A private workspace per caller.** The CLI runs inside a scratch directory scoped to the calling token. File-taking commands (`semantic save -f`, `run automation create `, `transform apply `) read files placed there with `write_workspace_file`; outputs (`semantic pull`, `run app scaffold`) are read back with `read_workspace_file` / `list_workspace_files`. The workspace is ephemeral — a pod restart clears it. - **Bounded.** Calls time out (120s default), output is truncated past 64 KiB stdout / 16 KiB stderr, and concurrent calls are capped so the CLI cannot starve the API. ## Security notes - **PKCE is mandatory.** `code_challenge_method` must be `S256`; the `plain` method and PKCE-less requests are rejected. - **Redirect URIs are allowlisted per client.** A client may only be sent to a `redirect_uri` it registered, and only `https` (or `http` loopback for local dev tools) URIs may be registered. `/authorize` never redirects the browser to an unverified URI — failures render a plain error page instead. - **Authorization codes are single-use** and expire in ~90 seconds. They are stored only as SHA-256 hashes. - **The consent page shows the requesting client name and the redirect host** so the signing-in user can see where the grant is going. - Tokens issued via OAuth are ordinary sessions: revoke one by deleting its `definite.sessions` row, or let it expire. - Static bearer tokens in MCP client config are live credentials. Do not commit them to source control. --- # Semantic Layer The semantic layer is Definite's record of what your data **means** — the business names, measures, and join graph that sit between raw lakehouse tables and the people (and agents) asking questions of them. It is a thin, lakehouse-native store: seven tables in a `semantic` schema, served by an HTTP API, an in-app Catalog editor, and the `definite semantic` CLI. There is no separate metric service to run, no extra database to operate, and no MDL DSL to learn. A model is YAML you author in your repo; what the runtime reads is the rows in the lake. ## The data model | Table | What it holds | |---|---| | `semantic.models` | One row per model — a relation plus the metadata about it (label, grain, owner). | | `semantic.dimensions` | Groupable / filterable attributes. SQL expression + label + synonyms. | | `semantic.measures` | Aggregate expressions, calculated measures, or `mode`/`column` shorthand with synonyms, format hints, certified flag. | | `semantic.relationships` | Join edges between models — `left_model`, `right_model`, `left_key`, `right_key`. | | `semantic.context` | AI / governance entries attached to a target (`measure:orders.gross_revenue`, `github_issues`, …). Carries glossary text, preferred-for / avoid notes, example questions. | | `semantic.ontology_objects` | Higher-level business concepts such as customer, order, product, revenue, or return. (Physically lives in the `semantic` schema, but is owned by the ontology layer — see [ontology.md](/docs/ontology).) | | `semantic.ontology_links` | Soft typed links from ontology objects back to semantic models, dimensions, measures, relationships, lakehouse tables, and columns. (Physically lives in the `semantic` schema, but is owned by the ontology layer — see [ontology.md](/docs/ontology).) | A whole **model bundle** — model + its dimensions, measures, relationships, and the context entries that target any of them — is the unit you author. The `PUT /api/v1/semantic/models/{name}` route writes a bundle as one transaction (replace-semantics: a dimension you remove from the file is dropped from the table). ## Authoring surface Three ways in, one source of truth: - **YAML + CLI** — `definite semantic save -f model.yaml` or `definite semantic apply semantic/` to push a whole directory in CI. The recommended workflow: keep `semantic/*.yaml` in your repo, review changes in PRs, let CI apply. - **Catalog UI** — the **Catalog** page in the Definite UI has a model editor: create / edit / delete dimensions and measures with a form. Good for ad-hoc exploration. Edits write straight to the tables, so an edit made in the UI does **not** propagate back to your YAML — see [Drift](#drift) below. - **HTTP API** — `PUT`, `PATCH`, `DELETE`, `GET` against `/api/v1/semantic/*`. The CLI and the UI are both thin clients of this surface. ## HTTP API All endpoints require a bearer token (the same session token the CLI uses). | Method | Path | What it does | |---|---|---| | `GET` | `/api/v1/semantic/models` | List every model. | | `GET` | `/api/v1/semantic/models/{name}` | One model bundled with its dimensions, measures, relationships, and context. | | `PUT` | `/api/v1/semantic/models/{name}` | Atomic save — body is a `ModelSpec` (replace-semantics). | | `PATCH` | `/api/v1/semantic/models/{name}` | Patch one child object in place. Body: `{kind, keys, patch}`. | | `DELETE` | `/api/v1/semantic/models/{name}` | Drop the model and all of its children. | | `POST` | `/api/v1/semantic/context` | Add (or replace) one context entry — `{target, context_type, content}`. | | `GET` | `/api/v1/semantic/search?q=...` | Token-aware ranked search across models / dimensions / measures. | | `GET` | `/api/v1/discovery/search?q=...` | Search ontology and semantic metadata together; returns bounded per-layer results, partial errors, and next actions. | For an analytical question, start with unified discovery rather than choosing one layer yourself. A successful request searches both layers; an empty result set is a discovery miss, not proof that the underlying lakehouse data is absent. If one layer fails, the response preserves results from the other and sets `partial: true`. Only failure of both layers returns `503`. ## The CLI Semantic commands are thin wrappers over the API. Same auth and `--api-url` flags as `definite run` — explicit `--token`, then `DEFINITE_TOKEN`, then the session saved by `definite login`. | Command | What it does | |---|---| | `definite discover ` | Search ontology and semantic metadata together before querying data. | | `definite semantic list` | List every model (name, label, relation). | | `definite semantic get ` | Show one model. Default output is YAML — pipe to a file to round-trip. | | `definite semantic save -f ` | Create or replace one model from a YAML file. Atomic. | | `definite semantic apply ` | Save every `*.yaml` in `` — the GitOps sync. | | `definite semantic pull ` | Dump a live model back to `.yaml` (or `-o path.yaml`). | | `definite semantic delete ` | Drop the model and all of its children. `--yes` to skip the prompt. | | `definite semantic search ` | Rank models / dimensions / measures by normalized query terms across name, label, synonym, and description. | Add `--format json` on any subcommand to get machine output (Fi runs do this automatically when stdout is not a TTY). ### Examples ```bash # List every model definite semantic list # Apply every YAML file in semantic/ — what CI runs on merge definite semantic apply semantic/ # Edit a model with the Catalog UI, then re-capture it back into your repo definite semantic pull orders -o semantic/orders.yaml # Find every measure with a "revenue" synonym or label definite semantic search revenue # Recommended first step for an analytical question (quotes are optional) definite discover monthly visitors by brand # Drop a model non-interactively definite semantic delete legacy_orders --yes ``` Search is case-insensitive and token-aware: a query such as `monthly visitors` can match terms distributed across a label, description, and synonyms, while exact names and phrases rank first. Longer exploratory queries return partial matches ordered by the number and quality of matched terms. Search and list read the current semantic catalog on every call, so a newly saved model is available immediately; there is no background learning or refresh delay. ## YAML format One file, one model. The body is the API's `ModelSpec` shape; an optional top-level `context:` list is fanned out to `POST /context` by `save` so a single file applies the whole thing. ```yaml name: github_issues label: GitHub Issues relation: github.issues description: Issues synced from the GitHub repo. metadata: grain: one row per issue owner: data-team dimensions: - name: state label: State expression: state metadata: synonyms: [status] - name: created_month label: Created Month expression: "date_trunc('month', created_at::timestamp)" metadata: is_time: true measures: - name: issue_count label: Issue Count expression: count(*) metadata: certified: true synonyms: [issues, tickets, bugs] - name: open_issue_count label: Open Issues mode: count column: id filter: "state = 'open'" - name: open_rate label: Open Rate expression: "measure(open_issue_count) * 1.0 / nullif(measure(issue_count), 0)" relationships: [] context: - target: measure:github_issues.issue_count context_type: ai_usage content: preferred_for: [counting issues] avoid: - "select * from github.issues" example_questions: - How many open issues are there? ``` A ready-to-apply copy of this file lives at `examples/semantic/github_issues.yaml` in the repo. **Field reference.** `name` is required and is the model's stable identifier (it is what `apply` keys on). `relation` is the lakehouse table the model is over (`schema.table`). `metadata` is a free-form JSON map — by convention `grain`, `owner`, and per-dimension/measure `synonyms`, `is_time`, `certified`, `format` are honoured by the UI and Fi. **Measures.** A measure can be authored directly with `expression`, or with the shorthand fields `mode`, `column`, and optional `filter`. `expression` wins if both forms are present. Supported modes are `count`, `sum`, `avg`, `min`, `max`, and `count_distinct`; every mode requires `column`. Use `expression: count(*)` for whole-table counts. **Reference warnings.** On save, `relation` is resolved against the lake's `information_schema` and every compiled measure `column` against that relation. Anything that does not resolve comes back in the save response's `warnings` list rather than failing the write, so you can author a model ahead of the pipeline that lands its table. A `relation` in a schema that does not exist yet has severity `unresolved`; a relation missing from a schema that does exist, or a column missing from a relation that does, is `missing`. Both `relation` and `column` are spliced into the compiled SQL verbatim, so values that hold SQL rather than a name (a subquery relation, `column: "*"`, a `CASE` expression) are skipped instead of guessed at. See [ontology.md](/docs/ontology) for the same mechanism on link targets. ```yaml measures: - name: revenue mode: sum column: amount - name: active_users mode: count_distinct column: user_id filter: "deleted = 0" ``` **Calculated measures.** A measure `expression` may reference another measure on the same model with `measure(name)`. The compiler expands each referenced measure's aggregate inline before generating the final SELECT. Cycles, unknown measure names, malformed `measure(...)` calls, and expansion chains deeper than 10 levels are rejected at compile time with a 400 error. ```yaml measures: - name: clicks mode: sum column: click_count - name: blocks mode: sum column: block_count - name: block_rate expression: "measure(blocks) * 1.0 / nullif(measure(clicks), 0)" ``` **Context targets** address a specific thing: - `` — the model itself (e.g. `github_issues`). - `measure:.` — a measure (e.g. `measure:github_issues.issue_count`). - `dimension:.` — a dimension. `context_type` is a string you pick (`glossary`, `ai_usage`, `ownership`, …). Anything stored under `content` is JSON — Fi reads `synonyms`, `preferred_for`, `avoid`, and `example_questions` to ground its answers. ## Ontology The ontology — the top-level layer of business concepts (`customer`, `revenue`, `company`, …) that link via soft typed references down to semantic objects, raw tables/columns, scripts, docs, or nothing at all — now has its own surface. See [ontology.md](/docs/ontology) for its API, CLI, and YAML format. ## Drift The CLI keeps the YAML files in **your** git; the lakehouse keeps the rows. That split is dbt-shaped: files are the authoring source, the warehouse holds the applied state. A consequence: the **Catalog UI edits the tables directly**. If someone tweaks a measure in the UI and you re-run `definite semantic apply semantic/`, the file wins and the UI edit is overwritten. Pick a discipline: - Treat UI edits as exploratory; keep `apply` (from files, in CI) authoritative. - Or keep prod edits file-only and use `pull` to escape-hatch a UI change back into its file before applying. `pull` is the round-trip lever — re-capture a model that has drifted, diff it, and commit. ## Read paths The same `semantic.*` tables back several read surfaces: - **Catalog UI** — list / view / edit models. - **Fi** — the agent starts analytical questions with unified `discover`, then follows likely concepts/models with describe and semantic-query tools. The targeted `search_ontology` and `search_semantic` MCP tools remain available for follow-up clients (see [MCP Server](/docs/mcp)). - **Custom SQL** — the tables are first-class in the lakehouse, so `select * from semantic.measures where ...` works from any SQL surface. All three are reading the same rows. There is no second source of truth at runtime. ## Running queries The semantic layer stores models — to actually count issues, the engine compiles a JSON query naming dimensions and measures into SQL and runs it through the same lakehouse + RLS + audit-log path as raw SQL. ### The JSON shape ```json { "model": "github_issues", "measures": ["issue_count", "open_issues"], "dimensions": ["state", "created_month"], "filters": [ {"dimension": "state", "operator": "in", "values": ["open", "closed"]}, {"dimension": "created_month", "operator": "gte", "values": ["2026-01-01"]} ], "order": [{"field": "created_month", "direction": "desc"}], "limit": 1000, "offset": 0 } ``` A bare identifier (`state`, `issue_count`) refers to a field on the FROM model. A dotted identifier (`repos.repo_name`) refers to a field on a foreign model — the engine auto-joins by walking the model's `relationships` (one-hop only in v1). **Filter operators:** `equals`, `not_equals`, `in`, `not_in`, `gt`, `gte`, `lt`, `lte`, `contains`, `is_null`, `is_not_null`. Filters target dimensions only; HAVING-style measure filters are deferred. **Order:** field is a bare or dotted name (need not appear in `dimensions` / `measures`). Direction is `asc` (default) or `desc`. **Defaults & limits:** `limit` defaults to 10000; hard ceiling is 100000. `offset` defaults to 0. At least one of `dimensions` or `measures` is required; if there are measures, a `GROUP BY` over every dimension is generated; if there are only dimensions, the SELECT is `DISTINCT`. ### Endpoints | Method | Path | Returns | |---|---|---| | `POST` | `/api/v1/semantic/query` | `{columns, rows, row_count, sql}` | | `POST` | `/api/v1/semantic/query/compile` | `{sql}` — no execution, no audit row | ### CLI ```bash # Inline form definite semantic query --model github_issues \ -m issue_count -m open_issues \ -d state -d created_month \ --where 'state in open,closed' \ --where 'created_month gte 2026-01-01' \ --limit 100 # JSON file form definite semantic query -f examples/semantic/queries/issue_count_by_state.json # Compile only (no execution) — print the SQL the engine would have run definite semantic query -f q.json --compile ``` `--format json|table|csv` works for query just like for `definite run query`. Tables default for a TTY, JSON otherwise. ### Errors | HTTP | When | |---|---| | 400 | unknown dimension or measure on the model | | 400 | invalid model YAML/API shape (unknown field, duplicate name, missing relation, invalid measure mode) | | 400 | calculated-measure reference cycle, unknown reference, malformed `measure(...)`, or expansion depth over 10 | | 400 | filter targets a measure (filters must target dimensions) | | 400 | unsupported filter operator | | 400 | ambiguous join (multiple relationships connect two models) | | 400 | unreachable join (no relationship from FROM model to foreign model) | | 400 | limit exceeds 100000 | | 404 | model not found | | 403 | data-access denial — the caller has no grant on the underlying relation | RLS is enforced on the compiled SQL: a user without a grant on `github.issues` cannot run a `model: github_issues` query even though the model name is "their" semantic concept. Admins bypass. ### Limitations (v1) - One-hop joins only. Chains across three or more models will fail with "no relationship from X to Z". - A relationship's `left_key` / `right_key` must reference dimensions whose `expression` is a plain column name — compound expressions on join keys are rejected at compile time. - Cross-model queries do not rewrite authored expressions to alias-qualify column references. If two joined tables share a column name and a dimension's `expression` is the bare name, DuckDB will error on the ambiguity; fix by qualifying the column in the dimension itself. - Calculated measures can reference measures on the same model only. Cross-model calculated measures need explicit SQL today. - Measure-on-measure (HAVING) filters are not supported. --- # Ontology The ontology layer is the **top** of Definite's meaning stack — the layer above the [semantic layer](/docs/semantic). It is where you name the business concepts your organization talks about — `customer`, `revenue`, `return`, even a plain business term like `company` — independent of how (or whether) they are modeled in the lakehouse. A concept points outward through **soft, typed links** to whatever backs it: - a semantic object (model / dimension / measure / relationship), - a raw lakehouse table or column, - a python / transformation script, - an external doc or URL, - or **nothing at all** — a standalone concept is first-class. Links are *soft references*: the save path **enforces** each target's shape but only **warns** about its existence, so you can author ontology before the underlying models, scripts, or tables exist. A target that does not resolve against the catalog comes back in the save response's `warnings` list; the object saves either way. The two storage tables (`semantic.ontology_objects` and `semantic.ontology_links`) physically live in the `semantic` schema, but they are owned by the ontology layer. ## HTTP API All endpoints require a bearer token (the same session token the CLI uses). | Method | Path | What it does | |---|---|---| | `GET` | `/api/v1/ontology` | List every concept. Add `?q=` for token-aware ranked search across names, aliases, guidance, metadata, and linked targets. Returns `{objects:[…]}`. | | `GET` | `/api/v1/discovery/search?q=...` | Recommended analytical entry point: search ontology and semantic metadata together. | | `POST` | `/api/v1/ontology/resolve` | Bind one surface token to a single concept. Body `{term, context?}`; returns `{term, resolved, binding, value, confidence, alternatives, candidates}`. `confidence` is `high` / `medium` / `ambiguous` / `none`. | | `GET` | `/api/v1/ontology/{name}` | One concept bundled with its links. `{object}`. | | `PUT` | `/api/v1/ontology/{name}` | Atomic save — body is an `OntologyObjectSpec` (replace-semantics: a link you drop from the body is removed). `{object}`. | | `DELETE` | `/api/v1/ontology/{name}` | Drop one concept and all of its links. `204`. | ## The CLI Ontology commands are thin wrappers over the API. Same auth and `--api-url` flags as `definite run` — explicit `--token`, then `DEFINITE_TOKEN`, then the session saved by `definite login`. | Command | What it does | |---|---| | `definite discover ` | Search ontology and semantic metadata together before querying data. | | `definite ontology list` | List every concept (name, kind, label). | | `definite ontology search ` | Find concepts by name, alias, guidance, or linked target. | | `definite ontology resolve ` | Bind one code, value, or short word to a single concept. `--context ""` breaks homonym ties; a genuine tie prints every candidate instead of guessing. | | `definite ontology get ` | Show one concept as YAML — pipe to a file to round-trip. | | `definite ontology save -f ` | Create or replace one concept from a YAML file. Atomic. | | `definite ontology delete ` | Drop one concept and all of its links. `--yes` to skip the prompt. | Add `--format json` on any subcommand to get machine output (Fi runs do this automatically when stdout is not a TTY). ## YAML format One file, one concept. The body is the API's `OntologyObjectSpec` shape. A `revenue` metric concept linked to a semantic measure, a source column, and a default time dimension: ```yaml name: revenue kind: metric_concept label: Revenue aliases: [sales, gmv, gross revenue] description: Realized sales from order items. guidance: preferred_for: [sales reporting, revenue trends] avoid: [products.retail_price as realized revenue] links: - relation_type: measured_by target: measure:thelook_order_items.total_revenue - relation_type: source_column target: column:thelook.order_items.sale_price - relation_type: default_time target: dimension:thelook_order_items.created_date ``` ### Standalone concepts A concept needs no lakehouse backing. A pure business term — something everyone in the company says, but that nothing in the warehouse models yet — is a legal, first-class concept with an empty `links` list: ```yaml name: company kind: entity label: Company aliases: [account, organization, org] description: A business we sell to or partner with. links: [] ``` Zero-link concepts are **never rejected**. They let you capture the shared vocabulary first and wire up the links — to semantic objects, tables, scripts, or docs — later, as the data catches up to the language. ## Supported target forms `target` is a soft typed reference. Shape is enforced; the linked object does not have to exist when you save. `table:` / `column:` targets are resolved against the lake's `information_schema`, and `model:` / `dimension:` / `measure:` / `relationship:` targets against the `semantic.*` tables. Anything that does not resolve is reported in the save response's `warnings` list, each entry carrying a `severity`: | severity | meaning | |---|---| | `unresolved` | the target's **parent** does not exist yet — a model nobody has authored, a schema that has not landed. Expected while the data catches up to the language; always advisory. | | `missing` | the parent **does** exist and the target is not in it — a dropped column, a table named against the wrong schema. This is a real error and is what a future enforcement mode rejects. | Note that on-prem runs `USE LAKE`, so targets are schema-qualified only: a `LAKE.`-prefixed target is a shape error and is rejected outright. - `ontology:` - `model:` - `dimension:.` - `measure:.` - `relationship:.` - `table:.
` - `column:.
.` - `script:` — a python / transformation reference (e.g. `script:transforms/revenue.py`) - `doc:` — an external definition (a doc id or path) - `url:` — an external URL ## Unified Fi discovery flow For every analytical question, Fi starts with one unified discovery call that searches ontology concepts and semantic models/measures/dimensions. It reads both result sets, describes likely concepts and models, and follows linked semantic definitions before falling back to raw tables. A concept that links to a `measure:` or `dimension:` routes the agent straight to a certified definition; a standalone concept tells the agent the term is real but not yet modeled. Empty discovery is not evidence that the lakehouse lacks the data. ---