ds_common_placeholder_py_lib.context

File: context.py Region: ds-common-placeholder-py-lib

Description

The per-run resolution context (contract §10) and the providers that supply namespace values.

Classes

Provider

Supplies the values of one namespace.

Context

Everything one run of a computing block needs: one self-contained

Functions

mask_written_secrets(text) → str

text with every secret written by resolve(strict=False),

secret_forms(secret) → set[str]

How a secret can appear in text: as it is, quoted as

Module Contents

ds_common_placeholder_py_lib.context.mask_written_secrets(text: str) → str[source]

text with every secret written by resolve(strict=False), @{secret, '…'}, masked, also one cut off at the end. A placeholder that starts with a quoted text or a written secret is shown as @{…}.

ds_common_placeholder_py_lib.context.secret_forms(secret: str) → set[str][source]

How a secret can appear in text: as it is, quoted as resolve(strict=False) writes it, JSON-escaped (as json.dumps and dataframe_to_json_array write it), and as Python’s repr writes it (an error message that quotes the value with !r).

class ds_common_placeholder_py_lib.context.Provider[source]

Bases: Protocol

Supplies the values of one namespace.

get(path: tuple[str, ...]) → Any[source]

Return the value at path, or raise MissingValue.

class ds_common_placeholder_py_lib.context.Context(*, tenant_id: str, providers: collections.abc.Mapping[str, Any], functions: collections.abc.Mapping[str, collections.abc.Callable[..., Any]] | None = None, verbatim: ds_common_placeholder_py_lib.resolve.Paths = (), sql: ds_common_placeholder_py_lib.resolve.Paths = ())[source]

Everything one run of a computing block needs: one self-contained object holding every value its placeholders read. Build one when the run starts and drop it when the run ends (contract §10). Most callers use from_values().

Parameters:
  • tenant_id – The run’s tenant. get_secret keys must name it.

  • providers – Namespace name to a JSON value (an object, array, string, number, boolean, or null), a function returning the current one (called each time the namespace is read), or a Provider. An object with a get method is treated as a Provider even if it is also callable.

  • functions – The service’s own functions, by name, added to the built-in ones (see from_values()).

  • verbatim – Paths in the context whose values are taken as written (see from_values()).

  • sql – Paths in the context whose values are SQL text (see from_values()).

Raises:
  • ValueError – If tenant_id is not a non-empty path segment, or a verbatim or sql path is not a path or is tenant_id.

  • TypeError – If a namespace is none of those, or verbatim or sql is a single string or holds something that is not a path.

providers: dict[str, Provider]
classmethod from_values(values: collections.abc.Mapping[str, Any], *, functions: collections.abc.Mapping[str, collections.abc.Callable[..., Any]] | None = None, verbatim: ds_common_placeholder_py_lib.resolve.Paths = (), sql: ds_common_placeholder_py_lib.resolve.Paths = ()) → Context[source]

Build a context from one JSON object: tenant_id and one value per namespace, any JSON value ("region": "NO" is read as @{lookup, region}; null has no value).

The context is self-contained: it holds every value its placeholders read, and a value may read another (dataset.from reading variables.start). A value is resolved each time it is read; what a placeholder needs and the context lacks fails with unknown_namespace or missing_value. Resolve the whole context or one part of it by path:

ctx = Context.from_values(
    {
        "tenant_id": "t1",                 # required; the run's tenant
        "run": {"logical_at": "2026-05-03T01:30:00Z"},
        "owner": {"settings": {"company_key": "643b"}},
        "variables": {"start": "@{get_start_date_last_month, UTC, run.logical_at}"},
        "dataset": {"from": "@{variables.start}", "company": "@{owner.settings.company_key}"},
        "transform": {"sql_query": "SELECT * FROM t WHERE c = @{owner.settings.company_key}"},
    },
    verbatim=["run", "owner"],             # data: taken as written
    sql=["transform.sql_query"],           # SQL text: each placeholder a SQL literal
)
ctx.resolve("dataset")    # {"from": "2026-04-01", "company": "643b"}
ctx.resolve()             # the whole context, resolved

Only the namespaces in values exist. tenant_id is one of them, read as @{lookup, tenant_id} or ctx.resolve("tenant_id"); it is always taken as written and cannot be replaced with set(). A value read again while it is being resolved fails with cycle. Outside verbatim, write a literal @{ with escape().

Values are read when they are resolved, not when the context is built. A namespace can be a function returning its current JSON object; it is called each time the namespace is read, so the context is built once and always sees the latest state:

ctx = Context.from_values({
    "tenant_id": tenant_id,
    "run": lambda: workflow_run.info,
    "execution": lambda: workflow_run.current_task,
    "tasks": lambda: workflow_run.outputs,
}, verbatim=["run", "execution", "tasks"])

A service adds its own functions with functions. Each is called with the arguments’ values, positionally, and its signature sets how many it takes. A reference argument is passed as the provider holds it (a DataFrame stays one); null or blank as None: @{get_rate, NOK, EUR} calls get_rate("NOK", "EUR").

Parameters:
  • values – tenant_id plus namespace name to its values (or a Provider).

  • functions – Function name to a callable. A built-in name is refused.

  • verbatim – Paths in the context whose values are data, taken as written and never parsed (task outputs, an owner record, a script’s code). Each is a dotted string from the context’s root (tasks, job.tasks.0.settings.'a.b') or a list of keys (["job", "tasks", 0, "settings"]; use that for keys that come from data). Everything under a path is taken as written. A path that is not in the context is ignored.

  • sql – Paths in the context whose values are SQL text: each placeholder in it becomes a SQL literal (quoted and escaped), a placeholder where no literal can stand fails with sql_position, and a secret with sql_secret. A SQL path that is not listed is resolved as plain text, so list every one.

Returns:

A new context.

Raises:
  • ValueError – If tenant_id is missing or not a non-empty path segment, a function name is not one or is a built-in one, or a verbatim or sql path is not a path, or a sql path names tenant_id.

  • TypeError – If verbatim or sql is a single string, or holds something that is not a path.

property tenant_id: str

it is the boundary get_secret checks keys against.

Type:

The run’s tenant. Fixed for the life of the context

set(name: str, value: Any, *, verbatim: ds_common_placeholder_py_lib.resolve.Paths = (), sql: ds_common_placeholder_py_lib.resolve.Paths = ()) → None[source]

Add a namespace, or replace one, while the run goes on.

The paths given when the context was built apply to it too. verbatim and sql add paths inside this namespace, from its root; they are replaced with it by the next set of the same name. To take a whole namespace as written, name it in the context’s verbatim when the context is built (verbatim=["tasks"]).

The context keeps a reference to value, not a copy: later changes to that object are seen by the next resolve. Values returned by resolve() are copies, so callers never change the engine’s objects through them.

ctx.set("execution", {"id": task_id, "attempt_no": 1})
ctx.set("job", job, verbatim=[["tasks", 0, "settings", "source", "content"]])
Parameters:
  • name – Namespace name ([A-Za-z_][A-Za-z0-9_]*).

  • value – A JSON value, a function returning the current one, or a Provider.

  • verbatim – Paths inside this namespace taken as written.

  • sql – Paths inside this namespace that are SQL text.

Raises:
  • ValueError – If name is not a namespace name, or a path is not one.

  • TypeError – If value is none of the accepted kinds, or a path argument is a single string or holds something that is not a path.

resolve(path: ds_common_placeholder_py_lib.resolve.Path | None = None, *, strict: bool = True) → Any[source]

Resolve the value at path in the context, or the whole context.

ctx.resolve()                          # {"tenant_id": …, "run": {…}, "dataset": {…}}
ctx.resolve("dataset.settings")        # one part
ctx.resolve(["tasks", task_id, "settings"])
Parameters:
  • path – A dotted string (dataset.settings, tasks.0.settings.'a.b') or a list of keys, from the context’s root; its first key is a namespace (tenant_id included). Left out, the whole context: every namespace, tenant_id first (a Provider is read with the empty path).

  • strict –

    False to keep, as written, every placeholder this context cannot resolve yet: one reading a namespace or a value it does not have (unknown_namespace, missing_value). For a dispatcher that resolves what it can (secrets, run facts) and hands the rest to a worker:

    # dispatcher: no task outputs yet
    job = ctx.resolve("job", strict=False)
    # worker: the rest, as each task runs
    ctx.resolve(["job", "tasks", i, "settings"])
    

    The result is then a template for a later resolve. A resolved value holding @ or { is written as a quoted text, @{'…'}, so the later resolve reads it back exactly and nothing in it can start a placeholder; one holding a secret this context read as @{secret, '…'}, so the later context records it (its scrub masks it, SQL refuses it). A sql path is kept as written (a SQL literal cannot be escaped). Every other error still raises, a failing provider too: a later resolve would not fix it. coalesce skips an argument with no value here as always, so it can settle on a later argument before the later context has the value.

Returns:

verbatim values as written, SQL values as SQL. Not strict, a template (above).

Return type:

A new value with every placeholder replaced

Raises:
  • PlaceholderError – On the first placeholder that cannot be resolved (not strict: one failing for any other reason than a missing namespace or value); unknown_namespace or missing_value if there is nothing at path. Its path is a JSON Pointer into the context (/dataset/settings/from).

  • TypeError – If path is neither a string nor a list of keys.

  • ValueError – If path is not a path.

scrub(text: str) → str[source]

Replace every secret this context has read, in plain and JSON-escaped form, with ***. A secret written by resolve() with strict=False, @{secret, '…'}, is masked by its form, even before this context has resolved it.

Parameters:

text – A message, log line, or serialized payload.

Returns:

text without any secret this context resolved.