"""
**File:** ``context.py``
**Region:** ``ds-common-placeholder-py-lib``
Description
-----------
The per-run resolution context (contract §10) and the providers that supply
namespace values.
"""
from __future__ import annotations
import json
import math
import re
from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Protocol
from .errors import ErrorCode, MissingValue, PlaceholderError
from .functions.tables import _is_frame, json_value
from .grammar import _NAMESPACE, BLANK
if TYPE_CHECKING:
from .resolve import Path, Paths
# A secret as resolve(strict=False) writes it, also inside JSON or a Python repr,
# where its quote may appear as \' (q is the quote as it appears; '' inside).
_WRITTEN_SECRET = re.compile(
r"@\{[ \t\r\n]*secret[ \t\r\n]*,[ \t\r\n]*(?P<q>\\*')(?:(?P=q)(?P=q)|(?!(?P=q)).)*(?P=q)[ \t\r\n]*\}",
re.DOTALL,
)
# One cut off before its end (a truncated log line): mask to the end.
_WRITTEN_SECRET_CUT = re.compile(r"@\{[ \t\r\n]*secret[ \t\r\n]*,[ \t\r\n]*\\*'(?!\*\*\*).*\Z", re.DOTALL)
# A placeholder whose text holds a value that may be a secret: a quoted text,
# or a secret written by resolve(strict=False).
_HIDDEN = re.compile("@\\{[ \t\r\n]*(?:['\"]|secret[ \t\r\n]*,)")
[docs]
def mask_written_secrets(text: str) -> str:
"""*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 ``@{…}``."""
if _HIDDEN.match(text):
return "@{…}"
text = _WRITTEN_SECRET.sub("@{secret, '***'}", text)
return _WRITTEN_SECRET_CUT.sub("@{secret, '***", text)
[docs]
class Provider(Protocol):
"""Supplies the values of one namespace."""
[docs]
def get(self, path: tuple[str, ...]) -> Any:
"""Return the value at *path*, or raise ``MissingValue``."""
class _DictProvider:
"""Walks nested objects, arrays, and DataFrames. It keeps a reference to
*data*, not a copy, so values the service keeps adding to (the run's task
outputs) are read live.
Every namespace is read the same way: an all-digit segment indexes an
array, ``NaN`` is read as ``None``, and a pandas ``DataFrame`` is read as
ds-workflow-manager reads it: ``<column>`` is the first row's value,
``rows`` its rows as objects, ``rows.<n>`` the row at position *n*.
Args:
data: The namespace's values, or a function returning them, called on
every lookup so the value is always the current one.
"""
def __init__(self, data: Any) -> None:
self._data = data
def get(self, path: tuple[str, ...]) -> Any:
"""Return the value at *path*.
Raises:
MissingValue: If any segment is absent.
"""
value: Any = self._data() if callable(self._data) else self._data
if value is None:
if path:
raise MissingValue
return None # null: read as no value, like a null inside an object
if _is_frame(value):
raise TypeError("a namespace cannot be a DataFrame: put it under a key, such as tasks.<id>.output")
if not isinstance(value, Mapping | list):
if path:
raise MissingValue # a string, number, or boolean has nothing under it
return _nan_to_none(value)
from_frame = False
for segment in path:
from_frame = from_frame or _is_frame(value) or isinstance(value, _FrameRows)
value = _step(value, segment)
if isinstance(value, _FrameRows):
return value.records() # already plain JSON
return value if from_frame and not isinstance(value, Mapping | list) else _nan_to_none(value)
class _FrameRows:
"""A DataFrame's ``rows``, read one row at a time."""
def __init__(self, frame: Any) -> None:
names = [str(column) for column in frame.columns]
if len(set(names)) != len(names):
raise PlaceholderError(ErrorCode.ARGUMENT, "the table's column names are not unique")
self.frame = frame
def row(self, position: int) -> dict[str, Any]:
# A one-row frame, not iloc[n]: a row Series would make ints floats.
return self._plain(self.frame.iloc[position : position + 1].to_dict(orient="records"))[0]
def records(self) -> list[dict[str, Any]]:
return self._plain(self.frame.to_dict(orient="records"))
@staticmethod
def _plain(records: list[Mapping[Any, Any]]) -> list[dict[str, Any]]:
return [{str(key): json_value(item) for key, item in record.items()} for record in records]
def _step(value: Any, segment: str) -> Any:
"""One segment of a path into *value*.
Raises:
MissingValue: If there is nothing at *segment*.
PlaceholderError: ``argument`` for a frame whose column names repeat.
"""
if isinstance(value, Mapping):
if segment in value:
return value[segment]
elif isinstance(value, list):
if _index(segment) < len(value):
return value[int(segment)]
elif isinstance(value, _FrameRows):
if _index(segment) < len(value.frame.index):
return value.row(int(segment))
elif _is_frame(value):
if segment == "rows":
return _FrameRows(value)
names = [str(column) for column in value.columns]
if len(set(names)) != len(names):
raise PlaceholderError(ErrorCode.ARGUMENT, "the table's column names are not unique")
if segment in names and len(value.index):
return json_value(value[value.columns[names.index(segment)]].iloc[0])
raise MissingValue
def _nan_to_none(value: Any) -> Any:
if isinstance(value, float) and math.isnan(value):
return None
if isinstance(value, Mapping):
return {key: _nan_to_none(item) for key, item in value.items()}
if isinstance(value, list):
return [_nan_to_none(item) for item in value]
return value
def _index(segment: str) -> int:
"""An all-ASCII-digit segment as an int; anything else (or too long to be
a real index) as a position past any list."""
if segment.isascii() and segment.isdigit() and len(segment) <= 18:
return int(segment)
return 1 << 62
def _provider(name: str, value: Any) -> Provider:
if value is None or isinstance(value, Mapping | list | str | int | float):
return _DictProvider(value) # any JSON value (bool is an int)
if _is_frame(value) and any(cls.__module__.startswith("pandas") for cls in type(value).__mro__):
raise TypeError(f"namespace {name!r} cannot be a DataFrame: put it under a key, such as tasks.<id>.output")
if callable(getattr(value, "get", None)):
return value # type: ignore[no-any-return]
if callable(value):
# A function returning the namespace's current value, called
# each time the namespace is read (lazy, always current).
return _DictProvider(value)
raise TypeError(f"namespace {name!r} needs a JSON value, a function returning one, or a provider")
_TENANT = "/tenant_id"
"""The pointer of the ``tenant_id`` namespace: always taken as written."""
def _pointers(paths: Paths, *, under: str = "", sql: bool = False) -> frozenset[str]:
"""The JSON Pointers of *paths*, each under the pointer *under*.
Raises:
ValueError: If a path is not one, or is a *sql* path at or under
``tenant_id`` (the tenant is data, never SQL).
TypeError: As :func:`~ds_common_placeholder_py_lib.resolve.verbatim_pointers`.
"""
from .resolve import verbatim_pointers # noqa: PLC0415
found = frozenset(under + path for path in verbatim_pointers(paths))
if sql and any(path == _TENANT or path.startswith(_TENANT + "/") for path in found):
raise ValueError("tenant_id is taken as written: it cannot be a sql path")
return found
[docs]
class Context:
"""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
:meth:`from_values`.
Args:
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
:class:`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 :meth:`from_values`).
verbatim: Paths in the context whose values are taken as written
(see :meth:`from_values`).
sql: Paths in the context whose values are SQL text (see
:meth:`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.
"""
def __init__(
self,
*,
tenant_id: str,
providers: Mapping[str, Any],
functions: Mapping[str, Callable[..., Any]] | None = None,
verbatim: Paths = (),
sql: Paths = (),
) -> None:
if (
not isinstance(tenant_id, str)
or not tenant_id.isprintable()
or tenant_id != tenant_id.strip()
or not tenant_id
or "/" in tenant_id
or tenant_id in {".", ".."}
):
raise ValueError("tenant_id must be a non-empty path segment")
self._tenant_id = tenant_id
# Paths given when the context is built, and per namespace with set.
self._paths: dict[str, tuple[frozenset[str], frozenset[str]]] = {
"": (_pointers(verbatim) | {_TENANT}, _pointers(sql, sql=True))
}
self._verbatim: frozenset[str] = frozenset()
self._sql: frozenset[str] = frozenset()
self._join_paths()
if "tenant_id" in providers:
raise ValueError("tenant_id is the context's tenant: pass it as tenant_id, not as a provider")
# The tenant is a namespace like any other, read with @{lookup, tenant_id}.
self.providers: dict[str, Provider] = {"tenant_id": _DictProvider(tenant_id)}
self.providers.update({name: _provider(name, value) for name, value in providers.items()})
from .functions import FUNCTIONS, service_function # noqa: PLC0415
self._functions = dict(FUNCTIONS)
self._functions.update({name: service_function(name, fn) for name, fn in (functions or {}).items()})
self._secrets: set[str] = set()
self._secret_reads = 0 # counts every secret read, known or not
[docs]
@classmethod
def from_values(
cls,
values: Mapping[str, Any],
*,
functions: Mapping[str, Callable[..., Any]] | None = None,
verbatim: Paths = (),
sql: Paths = (),
) -> Context:
"""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:
.. code-block:: python
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 :meth:`set`. A value read
again while it is being resolved fails with ``cycle``. Outside
*verbatim*, write a literal ``@{`` with :func:`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:
.. code-block:: python
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")``.
Args:
values: ``tenant_id`` plus namespace name to its values (or a
:class:`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.
"""
namespaces = dict(values)
tenant_id = namespaces.pop("tenant_id", None)
if tenant_id is None:
raise ValueError("values must include tenant_id")
return cls(tenant_id=tenant_id, providers=namespaces, functions=functions, verbatim=verbatim, sql=sql)
@property
def tenant_id(self) -> str:
"""The run's tenant. Fixed for the life of the context: it is the
boundary ``get_secret`` checks keys against."""
return self._tenant_id
[docs]
def set(self, name: str, value: Any, *, verbatim: Paths = (), sql: Paths = ()) -> None:
"""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
:meth:`resolve` are copies, so callers never change the engine's
objects through them.
.. code-block:: python
ctx.set("execution", {"id": task_id, "attempt_no": 1})
ctx.set("job", job, verbatim=[["tasks", 0, "settings", "source", "content"]])
Args:
name: Namespace name (``[A-Za-z_][A-Za-z0-9_]*``).
value: A JSON value, a function returning the current one, or a
:class:`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.
"""
if name == "tenant_id":
raise ValueError("tenant_id is fixed: it is the context's tenant and cannot be set")
if not isinstance(name, str) or not _NAMESPACE.fullmatch(name):
raise ValueError(f"not a namespace name: {name!r}")
prefix = "/" + name # a namespace name needs no escaping
paths = (_pointers(verbatim, under=prefix), _pointers(sql, under=prefix, sql=True))
self.providers[name] = _provider(name, value)
self._paths[name] = paths
self._join_paths()
[docs]
def resolve(self, path: Path | None = None, *, strict: bool = True) -> Any:
"""Resolve the value at *path* in the context, or the whole context.
.. code-block:: python
ctx.resolve() # {"tenant_id": …, "run": {…}, "dataset": {…}}
ctx.resolve("dataset.settings") # one part
ctx.resolve(["tasks", task_id, "settings"])
Args:
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 :class:`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:
.. code-block:: python
# 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:
A new value with every placeholder replaced: verbatim values as
written, SQL values as SQL. Not *strict*, a template (above).
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.
"""
from .resolve import _Resolver, path_keys # noqa: PLC0415
keys = None if path is None else path_keys(path)
with self._scrubbed_errors():
resolver = _Resolver(self)
return resolver.whole(strict=strict) if keys is None else resolver.at(keys, strict=strict)
def _join_paths(self) -> None:
self._verbatim = frozenset().union(*(verbatim for verbatim, _ in self._paths.values()))
self._sql = frozenset().union(*(sql for _, sql in self._paths.values()))
[docs]
def scrub(self, text: str) -> str:
"""Replace every secret this context has read, in plain and
JSON-escaped form, with ``***``. A secret written by
:meth:`resolve` with ``strict=False``, ``@{secret, '…'}``, is masked by its form,
even before this context has resolved it.
Args:
text: A message, log line, or serialized payload.
Returns:
*text* without any secret this context resolved.
"""
text = _WRITTEN_SECRET.sub("@{secret, '***'}", text)
text = _WRITTEN_SECRET_CUT.sub("@{secret, '***", text)
forms: set[str] = set()
for secret in self._secrets:
forms.update(secret_forms(secret))
for form in sorted(forms, key=len, reverse=True):
if form:
text = text.replace(form, "***")
return text
@contextmanager
def _scrubbed_errors(self) -> Iterator[None]:
"""A placeholder's text can hold a secret (``resolve(strict=False)`` writes
secrets as ``@{secret, '…'}``): never show such a placeholder or a
quoted text, which this context may not have resolved yet, and scrub
any other before the error leaves."""
try:
yield
except PlaceholderError as err:
text = err._placeholder
hidden = text is not None and _HIDDEN.match(text) is not None
if text is not None:
err.placeholder = "@{…}" if hidden else self.scrub(text)
if err.reference is not None:
# Written in the same placeholder: hidden or scrubbed with it.
err.reference = None if hidden else self.scrub(err.reference)
raise
def _record_secret(self, value: str) -> None:
self._secret_reads += 1
if value.strip(BLANK):
self._secrets.add(value)