Using it in a service

The package knows the standard dialect, not the computing blocks. The service that owns a definition decides what it can use, simply by what it puts in the context.

The package

The service

Syntax and dialect checks (validate)

Which parts of its definition take placeholders, and which paths it resolves

Resolution, value typing, missing values

What the context holds: the parts of its definition and every value they read

Data taken as written (verbatim)

Which paths are data

SQL literals (sql paths)

Which paths are SQL text

get_secret: tenant check, ds-vault read, base64

Vault configuration (VAULT_DATABASE_URL, AWS credentials)

Scrubbing

Calling scrub on what leaves the process

Building the context

from ds_common_placeholder_py_lib import Context

ctx = Context.from_values(
    {
        "tenant_id": tenant_id,                  # required, from the request envelope
        "run": run_facts,                        # one JSON object per namespace
        "owner": owner,
        "variables": declared_variables,         # as written: may hold placeholders
        "transform": definition_part,            # the part of the definition to resolve
    },
    verbatim=["run", "owner"],                   # data: taken as written
    sql=["transform.sql_query"],                 # SQL text: values become SQL literals
)
settings = ctx.resolve("transform.settings")     # one part, by path
everything = ctx.resolve()                       # or the whole context

The context is self-contained: it holds the parts of the definition the service resolves and every value their placeholders read. A value may hold placeholders; it is resolved when it is read, so one part of the context can use another. The service tells the context what its values are, by path: verbatim for data, taken as written and never parsed; sql for SQL text. A value read again while it is being resolved fails with cycle.

Only the namespaces you pass exist. @{lookup, owner.x} in a context without owner fails with unknown_namespace, so leaving a namespace out is how a service keeps it away from a part of its definition.

A field the request does not carry should stay absent, not be filled with a default: a placeholder that needs it then fails with missing_value, as the contract requires (§9.1).

Variables

To the package, variables is an ordinary namespace. Pass a definition’s declared variables (settings.variables) as they are written; a placeholder in one is resolved when it is read, like any value in the context:

ctx = Context.from_values({..., "variables": definition["settings"]["variables"]})
  • A variable is resolved each time it is read, with the context as it is then: it can read another variable, execution, or tasks. A broken one fails only the part that reads it.

  • A function of the current time or a get_secret in a variable is evaluated at each read. To fix a value for the whole run, resolve the variables once and pass the result as data: Context.from_values({..., "variables": resolved}, verbatim=["variables"]).

  • Resolve with the run’s context, so it knows the secrets they read: scrub masks them, and a SQL path refuses any value that contains one.

  • Overrides arrive escaped with escape (@{ as @{'@{'}); resolving turns them back into literal @{.

How the computing blocks use it

These rules come from the contract (§9). They live in each block’s service, not in this package. The repository’s examples/ show each one as runnable code.

Pipeline (stage dispatchers)

In a pipeline the stage dispatcher resolves everything in its stage’s part of the definition and starts the worker with final values. The worker (bronze, silver, gold service) has no placeholders, no context, and no library: it takes the values as they are and changes nothing. The dispatcher starts the worker right away, so a value resolved at dispatch is the value the worker would have computed.

One job runs for one owner. The router validates the definition (syntax only, with validate) and forwards the owner record, context.owner with its settings, on every stage request; it never resolves. Each dispatcher builds one context per stage request:

ctx = Context.from_values(
    {
        "tenant_id": tenant_id,
        "run": run,                                 # from the request
        "variables": payload["variables"],          # resolved when read
        **request["context"],                       # the job's one owner, and the stage's part
    },
    verbatim=["owner"],                             # the owner record is data
    sql=["transform.sql_query"],                    # silver's query
)
settings = ctx.resolve("dataset.settings")          # bronze
query = ctx.resolve("transform.sql_query")          # silver

Part

Resolved by

Namespaces

Path

settings.variables

every stage dispatcher, when a part reads one

what the context has

read through the parts below

bronze.dataset.settings, bronze.dataset.linked_service.settings

bronze dispatcher

owner, variables, run, execution

dataset.settings, dataset.linked_service.settings

silver.transform.sql_query

silver dispatcher

owner, variables, run

transform.sql_query, a sql path

other silver.transform keys

silver dispatcher

owner, variables, run

transform.<key>

gold, and the rest

nobody: no placeholders

reject any @{

  • A variable is resolved when a part reads it, with the job’s context, so a variable may read the owner.

  • A part that takes no placeholders (gold) is checked, not passed through: validate({"gold": part}, protected={"gold"}) reports any @{ in it, quoted or malformed, as protected_field.

  • The worker’s launch payload carries resolved values, secrets included as plain text. Send it to the worker only; never log it, publish it in an event, or store it (see lifecycle rules). The worker cannot scrub: it must not log its request values or credentials, and must not copy request fields into its completion event (a worker that echoes every key it does not read would publish them). Send the worker only what it reads. The dispatcher scrubs every failure it publishes with its context.

  • The owner record is data: the dispatcher lists owner in verbatim. An owner setting holding the text "@{get_secret, …}" comes out as that text through @{lookup, owner.settings.x}, not as the secret. Store the vault key in the owner ("settings": {"secrets": {"token": "/ds/vault/…"}}) and read it in the definition: @{get_secret, owner.settings.secrets.token}.

  • A failure fails the request (one owner). Map the error code to the stage’s failure: whether the owner’s data or the definition is at fault decides who fixes it. Tell them apart with the error’s reference and namespaces (who is at fault), as owner_failure() in examples/01_pipeline.py does.

  • Date functions compute from the time they are given. Pass run.logical_at (@{get_start_date_last_month, UTC, run.logical_at}), the same for every stage and retry; without it they use the dispatch time, as get_iso_timestamp_now does.

The stage request maps onto namespace values like this (§9.1):

Value

From the stage request

run.trigger_type, triggered_at, logical_at, load_mode

payload.run (no other key from there)

run.job_id, run.pipeline_id

payload.job_id, payload.pipeline_id

tenant_id (the context’s tenant), run.tenant_id

envelope tenant_id

execution.id, name, attempt_no

payload.stage_id, stage_name, attempt_no (bronze)

execution.started_at

the dispatcher’s clock, when it starts the worker

variables

payload.variables (declared values with overrides merged and escaped), as written

owner

context.owner: id (equal to the envelope owner_id), name, type, settings

examples/01_pipeline.py has this mapping as a stage_context() function, the bronze and silver dispatchers’ resolution around it, the check that gold takes no placeholders, and how a failure is published with its fault.

Workflow (workflow manager)

A definition opts in with settings.placeholder_dialect: "standard".

The context is a runtime idea: it exists only while something runs. The workflow manager builds one context per workflow run, when the run starts, adds to it as the run goes, and drops it when the run ends.

Namespace

Holds

Added

run

The run’s facts: job_id, tenant_id, triggered_at, logical_at, …

When the run starts

variables

The definition’s declared variables, as written

When the run starts

tasks

The run’s outputs so far (below)

With ctx.set when each task starts

execution

The task executing now: id, name, attempt_no, started_at

With ctx.set when each task starts

ctx.set(name, value) adds a namespace or replaces it. The context keeps a reference to the value, not a copy, so later changes to that object are seen by the next resolve:

class WorkflowRun:
    def __init__(self, definition, tenant_id, run_facts):
        self.outputs = {}                                 # {task_id: {"output": …, "status": …}}
        # code_paths(definition): the tasks' code fields, e.g. [["tasks", 0, "settings", "source", "content"]]
        self.context = Context.from_values(
            {"tenant_id": tenant_id, "job": definition, "run": run_facts,
             "variables": definition["settings"]["variables"], "tasks": self.outputs},
            verbatim=["run", "execution", "tasks", *(["job", *path] for path in code_paths(definition))],
        )

    def run_task(self, index, task, attempt_no=1):
        self.context.set("execution", {"id": task["id"], "name": task["name"],
                                       "attempt_no": attempt_no, "started_at": now_iso()})
        resolved = {key: self.context.resolve(["job", "tasks", index, key])
                    for key in ("settings", "dataset") if key in task}
        self.outputs[task["id"]] = {"output": run(task, resolved), "status": "success"}
  • A namespace can be any JSON value (an object, array, string, number, boolean, or null), or a function returning its current value, called each time the namespace is read, for state the engine keeps elsewhere: ctx.set("run", lambda: workflow_run.info).

  • tenant_id cannot change after the context is built; it is read as @{lookup, tenant_id} and always taken as written.

  • Call set between resolves, not while another thread is resolving with the same context.

  • A function is only called when its namespace is used. One that returns None (no task running yet) makes the namespace’s values missing.

  • verbatim paths are set when the context is built and apply to namespaces added later with set: execution and tasks above are listed before they exist.

  • A variable is resolved each time a task reads it, so it sees the current run, execution, and tasks.

  • scrub with the run’s context knows every secret the run read.

  • One execution per context means tasks run one at a time. With parallel branches, task B would read task A’s execution and nothing detects it: give each running task its own context over the same run state, or set execution to a function reading a per-task value (for example a contextvars.ContextVar).

  • The context reads the run’s state each time a placeholder needs it, so change the state between resolves, not during one, and add each task’s output in one assignment. Then every placeholder in one resolve sees the same state.

The workflow manager resolves each task just before it runs, with its code fields as verbatim. examples/02_workflow.py runs a workflow from the dispatcher (resolve(strict=False)) to the worker, offline.

Task outputs during a run

A workflow run keeps producing results: each task’s output becomes available to the tasks after it (§4.3). Keep the run’s outputs in one dict, {task_id: {"output": …}}, and add each task’s output when it succeeds. The context reads that dict live, so a task sees every output written before it started.

  • A task that has not finished, or has no successful output, gives missing_value to the task that references it.

  • A resolved value is a copy, so changing it does not change the stored output.

  • Variables cannot read task outputs: they are resolved before any task runs (§6).

  • Store each output in one assignment (outputs[task_id] = {"output": result}) and never change it afterwards (§10.2). Tasks running in parallel then never see a half-written output.

  • Everything under outputs[task_id] is readable by definitions (@{lookup, tasks.<id>.…}). The keys are the manager’s to choose: output for the success content, and, for example, error, status, metadata, and result beside it. A key that is not set is simply absent, and reading it is missing_value. Whatever is stored there, error text included, can be read by any later task’s definition and so can end up in its settings or logs: keep secrets out of it, and scrub what you log.

An output too big to keep in memory, such as an exported file, stays out of the context: put a reference in the output, and let placeholders read it:

outputs[task["id"]] = {"output": {"artifact_uri": "s3://…/export.parquet", "row_count": 1_000_000}}
# @{lookup, tasks.<task_id>.output.artifact_uri}

An output can be JSON or a pandas DataFrame, stored as it is: no conversion. A DataFrame is read the way the manager’s $. paths read it: @{lookup, tasks.fetch.output.account_id} is the first row’s value, @{lookup, tasks.fetch.output.rows.1.account_id} the second row’s (by position), and @{lookup, tasks.fetch.output.rows} all rows as objects. NaN, NaT, pd.NA, and infinite numbers are read as null, and null, an empty table, or a row out of range is a missing value. The table functions take the frame itself: @{get_column_as_list, account_id, tasks.fetch.output}.

Task ids can be used as they are: a path segment allows - and :, so both @{lookup, tasks.7819bdd0-654e-45d2-b710-aa86b5c13d74.output.row_count} (the task’s UUID id) and @{lookup, tasks.READ::POSTGRESQL.output.row_count} (its name) work. Prefer the id: it is stable, while a name can be renamed. The workflow manager decides which one it keys outputs by; examples/02_workflow.py uses the id.

Clone (clone dispatcher)

ds-clone-service cannot reach the vault. The clone dispatcher, which can, reads every get_secret in the job before sending it, for every clone, and the service resolves the job with its own context, as the workflow manager does:

ctx = Context.from_values({"tenant_id": job_tenant_id, "clone": clone})   # the envelope's tenant
job_context = ctx.resolve("clone", strict=False)                           # secrets as @{secret, '…'}
  • Nothing else in a clone is a placeholder, so no validate and no other namespaces are needed; a malformed @{ still fails with syntax.

  • The tenant check, errors, and scrubbing work as for the workflow dispatcher (see workers without vault access).

  • Resolve once, before the job is hashed, so each secret is read once per dispatch. examples/03_clone.py shows it.

Dispatchers, routers, ds-config

Routers and ds-config never resolve placeholders (§7, §10), so they never reach the vault. ds-config calls validate when a definition is saved.

A pipeline stage dispatcher resolves its stage’s part of the definition and sends final values (above). Any other dispatcher resolves nothing, with one exception: when the worker it starts cannot reach the vault, it puts the job in its context and calls ctx.resolve("job", strict=False) once and sends the result: it reads the secrets, resolves what it can (a time function with no at is resolved at dispatch) and leaves the rest for the worker. See workers without vault access.

Lifecycle rules

A context belongs to one run of a computing block: a pipeline stage execution, a whole workflow run, or a dispatch (one job). Every such run, including a retry or a redelivered request, must:

  • build a new context when it starts, and never reuse one from another run;

  • resolve nothing before it starts. Routers never resolve. A pipeline stage dispatcher resolves its stage’s part for the worker it starts; any other dispatcher only reads secrets, with resolve(strict=False), for a worker that cannot reach the vault;

  • keep the context and every resolved value in memory, and drop them when it ends. Resolved values never go into events, job or stage rows, the runtime store, logs, or checkpoints. The one exception is what a dispatcher sends to the worker it starts: a pipeline stage’s resolved part, or the job after resolve(strict=False). It goes to that worker only.

Within a workflow run, the tasks share the run’s context and the context reads the changing state (execution, tasks, run) lazily, as described above. Variables are resolved when read.