ds_common_placeholder_py_lib.context ==================================== .. py:module:: ds_common_placeholder_py_lib.context .. autoapi-nested-parse:: **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 ------- .. autoapisummary:: ds_common_placeholder_py_lib.context.Provider ds_common_placeholder_py_lib.context.Context Functions --------- .. autoapisummary:: ds_common_placeholder_py_lib.context.mask_written_secrets ds_common_placeholder_py_lib.context.secret_forms Module Contents --------------- .. py:function:: 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 ``@{…}``. .. py:function:: secret_forms(secret: str) -> set[str] 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``). .. py:class:: Provider Bases: :py:obj:`Protocol` Supplies the values of one namespace. .. py:method:: get(path: tuple[str, ...]) -> Any Return the value at *path*, or raise ``MissingValue``. .. py:class:: 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 = ()) 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`. :param tenant_id: The run's tenant. ``get_secret`` keys must name it. :param 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. :param functions: The service's own functions, by name, added to the built-in ones (see :meth:`from_values`). :param verbatim: Paths in the context whose values are taken as written (see :meth:`from_values`). :param 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``. :raises TypeError: If a namespace is none of those, or *verbatim* or *sql* is a single string or holds something that is not a path. .. py:attribute:: providers :type: dict[str, Provider] .. py:method:: 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 :classmethod: 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")``. :param values: ``tenant_id`` plus namespace name to its values (or a :class:`Provider`). :param functions: Function name to a callable. A built-in name is refused. :param 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. :param 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``. :raises TypeError: If *verbatim* or *sql* is a single string, or holds something that is not a path. .. py:property:: tenant_id :type: str it is the boundary ``get_secret`` checks keys against. :type: The run's tenant. Fixed for the life of the context .. py:method:: set(name: str, value: Any, *, verbatim: ds_common_placeholder_py_lib.resolve.Paths = (), sql: ds_common_placeholder_py_lib.resolve.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"]]) :param name: Namespace name (``[A-Za-z_][A-Za-z0-9_]*``). :param value: A JSON value, a function returning the current one, or a :class:`Provider`. :param verbatim: Paths inside this namespace taken as written. :param sql: Paths inside this namespace that are SQL text. :raises ValueError: If *name* is not a namespace name, or a path is not one. :raises 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. .. py:method:: resolve(path: ds_common_placeholder_py_lib.resolve.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"]) :param 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). :param 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: verbatim values as written, SQL values as SQL. Not *strict*, a template (above). :rtype: 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``). :raises TypeError: If *path* is neither a string nor a list of keys. :raises ValueError: If *path* is not a path. .. py:method:: scrub(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. :param text: A message, log line, or serialized payload. :returns: *text* without any secret this context resolved.