# Quickstart ## Install ```bash uv add ds-common-placeholder-py-lib ``` Python 3.12 or later. Dependencies: `ds-vault-py-sdk` for secrets and `tzdata`, so IANA time zones work on slim images without system zone data. For `get_secret`, set `VAULT_DATABASE_URL` and give the process AWS credentials that can use the vault's KMS key, as the dispatchers have today. A service that never resolves secrets needs neither. ## A complete example A definition with placeholders, resolved the way a service does: the context holds the definition's parts and everything they read, and the service resolves each part by its path. It runs as it is: `fake_vault` stands in for ds-vault. ```python from ds_common_placeholder_py_lib import Context, PlaceholderError, validate from ds_common_placeholder_py_lib.testing import fake_vault definition = { "settings": { "variables": {"year": "@{get_start_date_last_month, Europe/Oslo, run.logical_at}"}, "dataset": { "company": "@{lookup, owner.settings.company_key}", "from": "@{lookup, variables.year}", "label": "job @{lookup, run.job_id} for @{lookup, owner.settings.company_key}", "password": "@{get_secret, /ds/vault/ds_vault/t1/c1/prod}", }, "transform": {"sql": "SELECT * FROM accounts WHERE company = @{lookup, owner.settings.company_key}"}, } } assert validate(definition) == [] # 1. at save time settings = definition["settings"] ctx = Context.from_values( # 2. when the run starts { "tenant_id": "t1", "run": {"job_id": "j1", "logical_at": "2026-05-03T01:30:00Z"}, "owner": {"settings": {"company_key": "643b"}}, "variables": settings["variables"], # parts of the definition, "dataset": settings["dataset"], # resolved when read "transform": settings["transform"], }, verbatim=["owner"], # data, never parsed sql=["transform.sql"], # SQL text: values become SQL literals ) with fake_vault({"/ds/vault/ds_vault/t1/c1/prod": b"pw"}): # stands in for ds-vault try: dataset = ctx.resolve("dataset") # 4. right before use sql = ctx.resolve("transform.sql") except PlaceholderError as err: raise SystemExit(f"failed: {err}") print(dataset) # {'company': '643b', 'from': '2026-04-01', 'label': 'job j1 for 643b', 'password': 'pw'} print(sql) # SELECT * FROM accounts WHERE company = '643b' print(ctx.scrub(f"login failed with password {dataset['password']}")) # 5. # login failed with password *** ``` The numbers in the comments are the steps below. ## The steps Every service that resolves placeholders does the same things. ### 1. Check the definition ```python from ds_common_placeholder_py_lib import validate errors = validate(definition) # the whole definition for error in errors: print(error.code, error.path, error.placeholder) ``` Call `validate` only on `standard` definitions. A workflow without `settings.placeholder_dialect: "standard"` is `legacy` and is not valid `standard`; pipelines are always `standard`. A clone holds only `get_secret` calls, which its dispatcher resolves. `validate` needs no runtime data. It checks syntax and the dialect: unknown functions, argument counts, and literal arguments such as a timezone. Namespaces are open, so it does not check them. It also rejects any `@{` in `id`, `name`, `type`, and `version` outside `settings` (see [protected fields](concepts.md#protected-fields)). It returns every problem in document order; an empty list means valid. Everything that depends on runtime data (missing values, secrets, SQL literal positions) is checked when the value is resolved. Variable names and formats are the frontend's concern. ### 2. Build one context per run A {py:class}`~ds_common_placeholder_py_lib.context.Context` is one self-contained object: the parts of the definition a run resolves and every value their placeholders read, for one run of a computing block (a pipeline stage execution, a whole workflow run, or one job a dispatcher sends). What a placeholder needs and the context lacks fails; providing it is the service's job. Build it when the run starts and drop it when the run ends. Never share one between runs or retries. Pass each namespace as any JSON value: an object or array, or a plain string, number, or boolean (`"region": "NO"`, read as `@{lookup, region}`): ```python from ds_common_placeholder_py_lib import Context ctx = Context.from_values({ "tenant_id": request["tenant_id"], # required: the run's tenant "run": run_facts, # from the request "owner": owner_record, # read from ds-config }) ``` `tenant_id` is required. It is a namespace like the others, read as `@{lookup, tenant_id}`, but fixed: always taken as written, and it cannot change later (`get_secret` keys must name it). Only the namespaces you pass exist in the context. See [Using it in a service](services.md) for what each computing block passes. Values in the context may hold placeholders: each is resolved when it is read, so one part can use another. Pass the definition's parts and its declared variables as they are written. Tell the context what the values are, by path from its root: `verbatim` for data, taken as written; `sql` for SQL text, whose values become SQL literals: ```python ctx = Context.from_values( { "tenant_id": request["tenant_id"], "run": run_facts, "owner": owner_record, "variables": request["payload"]["variables"], # may hold placeholders "transform": request["context"]["transform"], # a part of the definition }, verbatim=["run", "owner"], sql=["transform.sql_query"], ) ctx.resolve("variables.start") # one value, resolved ctx.resolve() # the whole context, resolved ``` A value read again while it is being resolved fails with `cycle`. Outside `verbatim`, write a literal `@{` in a value with {py:func}`escape `. ### 3. Add to the context as the run goes The context is not read-only. While the run goes on, the engine adds or replaces namespaces with {py:meth}`Context.set `. A workflow, before each task, sets the task executing now and the outputs of the tasks done so far: ```python outputs = {} # {task_id: {"output": …}} ctx.set("tasks", outputs) for index, task in enumerate(job["tasks"]): # job is in the context as "job" ctx.set("execution", {"id": task["id"], "name": task["name"], "attempt_no": 1}) settings = ctx.resolve(["job", "tasks", index, "settings"]) outputs[task["id"]] = {"output": run(task, settings)} ``` - `set` keeps a **reference** to the value, not a copy: later changes to that object are seen by the next resolve. Values `resolve` returns are copies, so callers never change the engine's objects through them. - The `verbatim` and `sql` paths given when the context was built apply to a namespace added later too; `set(name, value, verbatim=[...], sql=[...])` adds paths inside that namespace. - A value can be any JSON value (objects and arrays may hold DataFrames, such as task outputs), a function returning the current one (called only when a placeholder needs that namespace), or a provider. A digit in a path indexes an array: `ctx.set("payload", [{"account_id": 7}])`, then `@{lookup, payload.0.account_id}`. - Call `set` between resolves, not while another thread is resolving with the same context. ### 4. Resolve each part right before using it ```python from ds_common_placeholder_py_lib import PlaceholderError try: settings = ctx.resolve("dataset.settings") # one part, by path sql = ctx.resolve("transform.sql_query") # a sql path: SQL literals except PlaceholderError as err: fail_execution(code=err.code.value, message=str(err)) ``` `resolve` returns a new value and leaves the context unchanged. The error message names the placeholder and where it is in the context (`err.path`, such as `/dataset/settings/from`), never a resolved value, so it can go into a failure event as it is. A value that is data, such as a script's code, is passed through as written with `verbatim` (see [verbatim fields](concepts.md#verbatim-fields)): ```python ctx.set( "task", {"timeout": "@{lookup, variables.timeout}", "source": {"content": 'def main(**kwargs):\n return kwargs["s"].startswith("@{")'}}, verbatim=["source.content"], ) settings = ctx.resolve("task") # {"timeout": 30, "source": {"content": 'def main(**kwargs):\n return kwargs["s"].startswith("@{")'}} ``` ### 5. Scrub everything that leaves the process ```python logger.error(ctx.scrub(str(exc))) ``` `scrub` removes every secret this context has read, in plain and JSON-escaped form. ## Placeholders by example Each input below is a value in this context (put it under any path, then `ctx.resolve` that path), resolved against the rest of it: ```python ctx = Context.from_values({ "tenant_id": "t1", "run": {"job_id": "j1", "logical_at": "2026-05-03T01:30:00Z"}, "owner": {"settings": {"company_key": "643b", "company_no": 1234, "tz": "Europe/Oslo", "host": "db.internal", "tags": ["a", "b"], "secrets": {"client_key": "/ds/vault/ds_vault/t1/c1/prod"}}}, "variables": {"fiscal_year": 2026}, "tasks": {"read": {"output": {"row_count": 42, "rows": [{"id": 7}]}}}, "execution": {"name": "load", "attempt_no": 2}, }) ``` **Reading values.** A placeholder that is the whole string keeps the value's JSON type; inside text it becomes text. | Input | Result | | --- | --- | | `"@{lookup, owner.settings.company_key}"` | `"643b"` | | `"@{lookup, owner.settings.company_no}"` | `1234` (a number) | | `"company-@{lookup, owner.settings.company_no}"` | `"company-1234"` | | `"@{lookup, owner.settings.tags}"` | `["a", "b"]` | | `"@{lookup, variables.fiscal_year}"` | `2026` | | `"@{lookup, tasks.read.output.row_count}"` | `42` (an earlier task's output) | | `"@{lookup, tasks.read.output.rows.0.id}"` | `7` (a digit indexes an array) | | `"@{lookup, run.job_id}/@{lookup, execution.name}#@{lookup, execution.attempt_no}"` | `"j1/load#2"` | **Functions.** A date function computes from the time it is given (here `run.logical_at`, the time the run is for); without one, from the current time. | Input | Result | | --- | --- | | `"@{get_start_date_last_month, Europe/Oslo, run.logical_at}"` | `"2026-04-01"` | | `"@{get_end_date_last_month, owner.settings.tz, run.logical_at}"` | `"2026-04-30"` (an argument can be a reference) | | `"@{get_last_month_period, NO, Europe/Oslo, run.logical_at}"` | `"April 2026"` | | `"@{str_join, owner.settings.company_key, '-', variables.fiscal_year}"` | `"643b-2026"` | | `"@{coalesce, owner.settings.region, NO}"` | `"NO"`: the owner has no region, so the default | | `"@{coalesce, owner.settings.file, 'report.csv'}"` | `"report.csv"`: quote a default with a dot | **Secrets and `@`.** | Input | Result | | --- | --- | | `"@{get_secret, owner.settings.secrets.client_key}"` | the vault value, e.g. `"pw"` | | `"postgresql://app:@{get_secret, owner.settings.secrets.client_key}@@{lookup, owner.settings.host}/db"` | `"postgresql://app:pw@db.internal/db"`: an `@` before a placeholder is just text | | `"@{'@{not a placeholder}'}"` | `"@{not a placeholder}"`: a quoted text is how to write `@{` | **SQL.** At a `sql` path, each value becomes a SQL literal: ```python ctx.set("query", {"text": "SELECT * FROM accounts WHERE company = @{lookup, owner.settings.company_key} AND year = @{lookup, variables.fiscal_year}"}, sql=["text"]) ctx.resolve("query.text") # SELECT * FROM accounts WHERE company = '643b' AND year = 2026 ``` **What fails.** Every failure is a `PlaceholderError`; its message never contains a resolved value. | Input | Error | | --- | --- | | `"@{lookup, owner.settings.missing}"` | `missing_value`: no such path (also `null` or blank). There is no default unless you write `coalesce` | | `"x-@{lookup, owner.settings.tags}"` | `type`: an array cannot be embedded in text | | `"@{lookup, env.HOME}"` | `unknown_namespace`: the context has no `env` | | `"@{nope}"` | `unknown_function` | | `"@{lookup, owner.settings.x"` | `syntax`: unclosed placeholder | | `"@{get_secret, /ds/vault/ds_vault/t2/c1/prod}"` | `secret_scope`: another tenant's key, refused before the vault is read | | SQL `… WHERE a = '@{lookup, owner.settings.company_key}'` | `sql_position`: a placeholder inside SQL quotes | | SQL `SELECT @{get_secret, …}` | `sql_secret`: secrets never go into SQL | Every code and rule: [Concepts](concepts.md), [Functions](functions.md), [Error codes](errors.md). ## When the worker cannot reach the vault The vault is only reachable inside the VPC. If the service that runs the job is outside it, its dispatcher reads the secrets, and resolves what it can, before handing the job over: ```python # dispatcher (in the VPC) ctx = Context.from_values({"tenant_id": tenant_id, "job": job}) job = ctx.resolve("job", strict=False) # each @{get_secret, …} becomes @{secret, ''} send(job) # worker (outside the VPC) ctx = Context.from_values({"tenant_id": tenant_id, "run": run, "job": job}) settings = ctx.resolve("job.settings") # steps 2-5 as usual ``` What the job looks like at each step, with the vault value `pw`: ```python job = { "password": "@{get_secret, /ds/vault/ds_vault/t1/c1/prod}", "url": "postgresql://app:@{get_secret, /ds/vault/ds_vault/t1/c1/prod}@db/@{lookup, run.job_id}", } dispatcher = Context.from_values({"tenant_id": "t1", "job": job}) template = dispatcher.resolve("job", strict=False) # {"password": "@{secret, 'pw'}", # "url": "postgresql://app:@{secret, 'pw'}@db/@{lookup, run.job_id}"} worker = Context.from_values({"tenant_id": "t1", "run": {"job_id": "j1"}, "job": template}) worker.resolve("job") # {"password": "pw", "url": "postgresql://app:pw@db/j1"} ``` - A placeholder the dispatcher cannot resolve yet (`@{lookup, run.job_id}` above: it has no `run`) is left as written for the worker. One it can resolve, such as a time function with no `at`, is resolved at dispatch. Resolving the result gives what one `resolve` of the original would give. - `@{secret, '…'}` carries the value and marks it as a secret, so the worker needs nothing else: once it resolves the value, its `scrub` and SQL check know it. Any context's `scrub` masks `@{secret, '…'}` itself, so the job can be logged before that. A `'` in the value is doubled. - The secrets travel in plaintext with the job. Details and trade-offs: [workers without vault access](secrets.md#workers-without-vault-access). ## Runnable examples The repository's `examples/` folder has one script per block. Each starts with a real definition (from the pipeline-per-ERP proof of concept, ds-workflow-manager and ds-clone-dispatcher, or modelled on the end-to-end-tested Xledger workflow) and resolves it the way the owning service does: | Script | Block | | --- | --- | | `01_pipeline.py` | One pipeline for many owners, one job per owner: stage dispatchers resolve bronze settings and secrets and silver SQL (DuckDB); gold takes no placeholders | | `02_workflow.py` | A workflow from the dispatcher to the workflow manager: `resolve(strict=False)`, verbatim Python code, DataFrame outputs read by path and by table functions | | `03_clone.py` | A Datalake → Azure Table clone: the clone dispatcher reads its secrets and sends them as `@{secret, '…'}`, the service resolves, tenant check | ```bash uv run python examples/01_pipeline.py ```