Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions ccflow/plugins/omegaconf_resolvers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import re
import sys
from datetime import date, datetime, time
from importlib.resources import files
from pathlib import Path
from socket import gethostname
from subprocess import check_output
Expand Down Expand Up @@ -92,6 +93,46 @@ def dict_from_tuples_resolver(tuples: list[list]) -> dict:
return result


_ABSENT = object()


def _select_for_ref(key: str, root: DictConfig):
"""Return the value at the absolute config key `key`, raising if its parent is absent or a value is mandatory."""
if key.startswith("."):
raise ValueError(f"'{key}' is a relative config key; refer to it by its absolute key")
parent = key.rpartition(".")[0]
if parent and OmegaConf.select(root, parent, default=_ABSENT, throw_on_missing=True) is _ABSENT:
raise KeyError(f"'{key}' refers to '{parent}', which the config does not contain")
return OmegaConf.select(root, key, throw_on_missing=True)


def ref_resolver(key: str, *, _root_: DictConfig) -> str | None:
"""Return the registry path of `key` (dots become slashes), or None when the config holds no value at `key`."""
return None if _select_for_ref(key, _root_) is None else "/" + key.replace(".", "/")


def refs_resolver(key: str, *, _root_: DictConfig) -> dict[str, str]:
"""Return the registry path of each non-null entry of the mapping at `key`, by entry name."""
mapping = _select_for_ref(key, _root_)
if mapping is None:
return {}
if not isinstance(mapping, DictConfig):
raise TypeError(f"'{key}' holds a {type(mapping).__name__}, not a mapping")
path = "/" + key.replace(".", "/")
return {str(name): f"{path}/{name}" for name, value in mapping.items() if value is not None}


def read_text_resolver(path: str, resource: str | None = None) -> str:
"""Return the text of the file at `path`, or of `resource` inside the installed package `path`.

Text containing "${" is rejected, as it would be resolved as an interpolation when the config is instantiated.
"""
text = (files(path) / resource if resource else Path(path)).read_text(encoding="utf-8")
if "${" in text:
raise ValueError(f"read_text does not accept text containing '${{': {resource or path}")
return text


# Register a resolver to return the current date in a specified timezone. If none, uses local time
register_omegaconf_resolver("today_at_tz", today_resolver)

Expand Down Expand Up @@ -139,6 +180,15 @@ def dict_from_tuples_resolver(tuples: list[list]) -> dict:
# Register a resolver to run a command and return the value
register_omegaconf_resolver("cmd", lambda cmd: check_output([cmd], shell=True).decode("utf-8").rstrip("\n"))

# Refer to the registered model at a config key, or null when the key is null or absent
register_omegaconf_resolver("cc.ref", ref_resolver)

# Refer to each registered model in a mapping by name, leaving out null entries
register_omegaconf_resolver("cc.refs", refs_resolver)

# Read the text of a file, or of a resource inside an installed package
register_omegaconf_resolver("cc.read_text", read_text_resolver)

# Register a resolver to format a date/datetime object or config into a formatted string
register_omegaconf_resolver("strftime", date_resolver)

Expand Down
135 changes: 135 additions & 0 deletions ccflow/tests/plugins/test_omegaconf_resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,25 @@
from socket import gethostname
from unittest.mock import patch

import pytest
from omegaconf import OmegaConf
from omegaconf.errors import InterpolationResolutionError

import ccflow
from ccflow import BaseModel, ModelRegistry
from ccflow.plugins.omegaconf_resolvers import register_omegaconf_resolver


class Leaf(BaseModel):
x: int = 0


class Node(BaseModel):
one: Leaf | None = None
off: Leaf | None = None
many: dict[str, Leaf] | None = None


def test_today_resolver():
conf = OmegaConf.create({"date": "${today_at_tz:America/New_York}"})
assert isinstance(conf["date"], date)
Expand Down Expand Up @@ -100,6 +114,127 @@ def test_cmd_resolver():
assert conf["out"] == "foo"


def test_ref():
conf = OmegaConf.create(
{"a": {"b": 1, "c": None}, "c": None, "out": "${cc.ref:a}", "nested": "${cc.ref:a.b}", "null": "${cc.ref:c}", "absent": "${cc.ref:d}"}
)
assert conf["out"] == "/a"
assert conf["nested"] == "/a/b"
assert conf["null"] is None
assert conf["absent"] is None
conf = OmegaConf.create(
{"a": {"c": None}, "nested_null": "${cc.ref:a.c}", "nested_absent": "${cc.ref:a.d}", "null_parent": "${cc.ref:c.d}", "c": None}
)
assert conf["nested_null"] is None
assert conf["nested_absent"] is None
assert conf["null_parent"] is None


@pytest.mark.parametrize(
("value", "match"),
[
({"leaves": {"a": 1}, "out": "${cc.ref:leavs.a}"}, "does not contain"),
({"a": "???", "out": "${cc.ref:a}"}, "Missing mandatory value"),
({"a": "???", "out": "${cc.ref:a.b}"}, "Missing mandatory value"),
({"a": {"b": 1}, "out": "${cc.ref:.a}"}, "relative config key"),
],
ids=["absent_parent", "missing", "missing_parent", "relative"],
)
def test_ref_rejects(value, match):
with pytest.raises(InterpolationResolutionError, match=match):
OmegaConf.create(value)["out"]


def test_refs():
conf = OmegaConf.create(
{"a": {"b": {"x": 1, "y": None, "z": 2}, 1: {"x": 1}}, "out": "${cc.refs:a.b}", "absent": "${cc.refs:c}", "ints": "${cc.refs:a}"}
)
assert conf["out"] == {"x": "/a/b/x", "z": "/a/b/z"}
assert conf["absent"] == {}
assert conf["ints"] == {"b": "/a/b", "1": "/a/1"}


@pytest.mark.parametrize(
("value", "match"),
[
({"a": [1, 2], "out": "${cc.refs:a}"}, "holds a ListConfig, not a mapping"),
({"a": 1, "out": "${cc.refs:a}"}, "holds a int, not a mapping"),
({"a": "???", "out": "${cc.refs:a}"}, "Missing mandatory value"),
({"a": {}, "out": "${cc.refs:b.c}"}, "does not contain"),
],
ids=["list", "scalar", "missing", "absent_parent"],
)
def test_refs_rejects(value, match):
with pytest.raises(InterpolationResolutionError, match=match):
OmegaConf.create(value)["out"]


def test_new_resolvers_are_only_registered_with_the_prefix():
for name in ("ref", "refs", "read_text"):
assert OmegaConf.has_resolver(f"cc.{name}")
assert not OmegaConf.has_resolver(name)


def test_read_text(tmp_path):
(tmp_path / "prompt.md").write_text("# Prompt\n")
conf = OmegaConf.create({"out": f"${{cc.read_text:{tmp_path / 'prompt.md'}}}"})
assert conf["out"] == "# Prompt\n"

resource = "config/function/scale.yaml"
conf = OmegaConf.create({"out": f"${{cc.read_text:ccflow.examples.calculator,{resource}}}"})
assert conf["out"] == (Path(ccflow.__file__).parent / "examples" / "calculator" / resource).read_text()


def test_read_text_rejects_interpolation(tmp_path):
(tmp_path / "prompt.md").write_text("${cc.cmd:echo executed}")
conf = OmegaConf.create({"out": f"${{cc.read_text:{tmp_path / 'prompt.md'}}}"})
with pytest.raises(InterpolationResolutionError, match="does not accept text containing"):
conf["out"]


def test_ref_and_refs_share_registered_models():
leaf = {"_target_": f"{__name__}.Leaf"}
conf = OmegaConf.create(
{
"leaves": {"a": {**leaf, "x": 1}, "b": {**leaf, "x": 2}, "c": None},
"nothing": None,
"node": {"_target_": f"{__name__}.Node", "one": "${cc.ref:leaves.a}", "off": "${cc.ref:nothing}", "many": "${cc.refs:leaves}"},
}
)
registry = ModelRegistry(name="test").load_config(conf)
node = registry["node"]
assert node.one is registry["leaves/a"]
assert node.off is None
assert list(node.many) == ["a", "b"]
assert all(model is registry[f"leaves/{name}"] for name, model in node.many.items())


def test_ref_and_refs_share_models_in_a_lazy_registry():
leaf = {"_target_": f"{__name__}.Leaf"}
conf = OmegaConf.create(
{
"lazy": {
"_target_": "ccflow.base.LazyRegistry",
"_recursive_": False,
"leaves": {"a": {**leaf, "x": 1}, "b": {**leaf, "x": 2}},
"node": {"_target_": f"{__name__}.Node", "one": "${cc.ref:lazy.leaves.a}", "many": "${cc.refs:lazy.leaves}"},
}
}
)
registry = ModelRegistry(name="test").load_config(conf)
node = registry["lazy/node"]
assert node.one is registry["lazy/leaves/a"]
assert all(model is registry[f"lazy/leaves/{name}"] for name, model in node.many.items())


def test_ref_relative_to_a_config_key_raises(tmp_path):
leaf = {"_target_": f"{__name__}.Leaf"}
path = tmp_path / "config.yaml"
OmegaConf.save({"sub": {"leaves": {"a": leaf}, "node": {"_target_": f"{__name__}.Node", "one": "${cc.ref:leaves.a}"}}}, path)
with pytest.raises(InterpolationResolutionError, match="does not contain"):
ModelRegistry(name="test").load_config_from_path(path, config_key="sub")


def test_date():
expected = "2025-06-01"

Expand Down
10 changes: 10 additions & 0 deletions docs/wiki/reference/Core-Types.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ Models expose their placement in the registry:
- `get_registered_names()` — list of path strings.
- `get_registry_dependencies()` — the registered models this model depends on, found recursively.

### Configuration resolvers

Importing `ccflow.plugins` registers OmegaConf resolvers for use in configs. Most are registered under their own name and with a `cc.` prefix; `ref`, `refs` and `read_text` are registered only with the prefix. Among them:

- `${cc.ref:KEY}` — the registry path of the config node at `KEY` (`/KEY`, with dots as slashes), or null when that node is null or absent. It raises if `KEY` is relative, if its parent is absent (as with a typo), or if a value on the way is mandatory (`???`). Use it to refer to a registered model by name, sharing the instance as `/KEY` does, while letting a config switch an optional model off by setting it to null. `${KEY}` would instead copy the model's configuration.
- `${cc.refs:KEY}` — a mapping from each name in the mapping at `KEY` to its registry path (`/KEY/name`), leaving out null entries, or an empty mapping when `KEY` is null or absent. It raises in the same cases as `ref`, and if the value at `KEY` is not a mapping. Use it for a field holding the models that a config group selected.
- `${cc.read_text:PATH}` or `${cc.read_text:PACKAGE,RESOURCE}` — the text of a file, or of a resource inside an installed package. A relative `PATH` is resolved from the current working directory, not from the config file. Quote a `PATH` that contains a comma (`${cc.read_text:'a,b.md'}`), or it is read as `PACKAGE,RESOURCE`. Use it to keep long text, such as a prompt, in its own file while making it part of the configuration. Text containing `${` is rejected, as it would otherwise be resolved as an interpolation when the config is instantiated. The text reaches its field as a literal string would, so read untrusted files only into fields that do not evaluate their contents.

`ref` and `refs` build registry paths from config keys, so they assume the whole config is loaded into the registry (no `config_key`). `KEY` is a dotted path of mapping keys; list indexes are not supported.

## `ContextBase`

Base class for contexts — the runtime parameters that templatize a workflow. A `ContextBase` is a `BaseModel` and also a `ResultBase` (so a context can be produced as a step's result). Contexts are **frozen** (immutable) and hashable by default, so they can serve as cache keys. See [Contexts and Results](Contexts-and-Results) for the built-in context types.
Expand Down
Loading