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
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
### Fixed

- **A regex a user writes that Python cannot compile is refused, not a traceback.** `re.compile` raises `OverflowError` for a repeat count that does not fit (`a{999999999999}`) and `RecursionError` for groups nested too deep, not the `re.error` the `process_metrics` and contract loaders caught. Those patterns now refuse as bad input (exit 2, `Error: ...`) instead of crashing: a `process_metrics` counter in the repo manifest and a `trace consistency --contract` pattern.
- **A regex a user writes that Python cannot compile is refused, not a traceback.** `re.compile` raises `OverflowError` for a repeat count that does not fit (`a{999999999999}`) and `RecursionError` for groups nested too deep, not the `re.error` the `process_metrics` and contract loaders caught. A `trace consistency --contract` pattern that triggers either error is refused with exit 2 and `Error: ...`. If a `process_metrics` counter in a repo manifest triggers either error, `eval check` and `repo run` report a manifest error with `✗` and exit 1.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix before merge (blocking): The changelog says eval check exits 1 with ✗ for a bad process_metrics regex, but eval check --schema-only exits 2 with Error:.

I tested this suggestion: it fixes the problem, and the tests still pass.

Suggested change
- **A regex a user writes that Python cannot compile is refused, not a traceback.** `re.compile` raises `OverflowError` for a repeat count that does not fit (`a{999999999999}`) and `RecursionError` for groups nested too deep, not the `re.error` the `process_metrics` and contract loaders caught. A `trace consistency --contract` pattern that triggers either error is refused with exit 2 and `Error: ...`. If a `process_metrics` counter in a repo manifest triggers either error, `eval check` and `repo run` report a manifest error with `✗` and exit 1.
- **A regex a user writes that Python cannot compile is refused, not a traceback.** `re.compile` raises `OverflowError` for a repeat count that does not fit (`a{999999999999}`) and `RecursionError` for groups nested too deep, not the `re.error` the `process_metrics` and contract loaders caught. A `trace consistency --contract` pattern that triggers either error is refused with exit 2 and `Error: ...`. If a `process_metrics` counter in a repo manifest triggers either error, `eval check` and `repo run` exit 1 and print `✗` with the manifest error; `eval check --schema-only` exits 2 with `Error: ...`.
Details

I put a{999999999999} in process_metrics of a manifest and ran eval check --schema-only. It printed Error: ... process_metrics/bazel: not a valid regex: the repetition number is too large and exited 2. The plain eval check and repo run do print ✗ and exit 1, as the sentence says, so the sentence should name the --schema-only case too.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!--
Copyright (C) 2026 Intel Corporation
SPDX-License-Identifier: Apache-2.0
-->

### Fixed

- **A list of regexes in a `trace consistency --contract` action is checked one element at a time.** The list was joined with `|`, each element wrapped in `(?:...)`, and only the joined pattern was compiled, so `["a)|(?:b"]` was accepted (it joins to two groups) though `a)|(?:b` is not a regex. Each element is now compiled on its own, and a bad one is refused by name as `bad regex`. A list whose elements are each a regex compiles to the same pattern as before. The behaviour change: a list in which one element refers to a group of another (`["(a)", "\1"]`, `["(?P<x>a)", "(?P=x)"]`) is now refused, since that element is not a regex on its own; it was accepted before. The same holds for a list whose elements are each invalid alone but join to a valid pattern (`["(a", "b)"]`): it is now refused.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix before merge (blocking): The changelog says a list whose elements are each a regex compiles as before, but ["(?i)pytest", "tox"] is refused.

I tested this suggestion: it fixes the problem, and the tests still pass.

Suggested change
- **A list of regexes in a `trace consistency --contract` action is checked one element at a time.** The list was joined with `|`, each element wrapped in `(?:...)`, and only the joined pattern was compiled, so `["a)|(?:b"]` was accepted (it joins to two groups) though `a)|(?:b` is not a regex. Each element is now compiled on its own, and a bad one is refused by name as `bad regex`. A list whose elements are each a regex compiles to the same pattern as before. The behaviour change: a list in which one element refers to a group of another (`["(a)", "\1"]`, `["(?P<x>a)", "(?P=x)"]`) is now refused, since that element is not a regex on its own; it was accepted before. The same holds for a list whose elements are each invalid alone but join to a valid pattern (`["(a", "b)"]`): it is now refused.
- **A list of regexes in a `trace consistency --contract` action is checked one element at a time.** The list was joined with `|`, each element wrapped in `(?:...)`, and only the joined pattern was compiled, so `["a)|(?:b"]` was accepted (it joins to two groups) though `a)|(?:b` is not a regex. Each element is now compiled on its own, and a bad one is refused by name as `bad regex`. A list compiles to the same pattern as before only when the joined pattern is also valid: `["(?i)pytest", "tox"]` is refused with `bad regex`, since `(?i)` then no longer starts the expression. The behaviour change: a list in which one element refers to a group of another (`["(a)", "\1"]`, `["(?P<x>a)", "(?P=x)"]`) is now refused, since that element is not a regex on its own; it was accepted before. The same holds for a list whose elements are each invalid alone but join to a valid pattern (`["(a", "b)"]`): it is now refused.
Details

Each element of ["(?i)pytest", "tox"] compiles alone, but joined the flag is no longer at the start, so the contract refuses it with bad regex (global flags not at the start of the expression ...). Main refuses it the same way, so this change does not cause it, but the sentence promises more than the code does.

13 changes: 11 additions & 2 deletions dokimi/dokimi/context/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,18 @@ def _names(value: Any, where: str) -> tuple[str, ...]:

def _pattern(value: Any, where: str) -> str:
"""A regex, or a list of them as one alternation; anything else (a number, a mapping) is refused,
so that `[pytest, tox]` is not read as the character class `['pytest', 'tox']`."""
so that `[pytest, tox]` is not read as the character class `['pytest', 'tox']`. Each element must be a regex
on its own: joined, `a)|(?:b` would compile as two groups and pass. So a list element cannot refer to a group
of another element (`["(a)", "\\1"]`), though the joined pattern compiled before."""
if isinstance(value, list) and value:
return "|".join(f"(?:{p})" for p in _names(value, where))
parts = []
for p in _names(value, where):
try:
compile_user_regex(p)
except ValueError as exc:
raise ValueError(f"{where}: element {p!r}: bad regex ({exc})") from exc
parts.append(f"(?:{p})")
return "|".join(parts)
if isinstance(value, str):
return value
raise ValueError(f"{where} wants a regex or a list of regexes, got {value!r}")
Expand Down
11 changes: 11 additions & 0 deletions dokimi/tests/test_context_consistency.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,17 @@ def test_a_pattern_that_is_not_a_regex_is_refused(value):
parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []})


@pytest.mark.parametrize("value", [
["a)|(?:b"], [r"\bpytest\b", "a)|(?:b"], ["(", "x"],
["(a)", "\\1"], ["(?P<x>a)", "(?P=x)"], # each joins to a pattern that compiled before; alone, neither element does
])
def test_each_element_of_a_list_pattern_must_be_a_valid_regex_on_its_own(value):
"""Joined with `|` and each wrapped in `(?:...)`, `a)|(?:b` compiles; it is not a regex on its own. The
backreference cases are refused on the same rule: `\\1` alone is not a regex."""
with pytest.raises(ValueError, match="bad regex"):
parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []})


@pytest.mark.parametrize("value", ["a{999999999999}", "(" * 2000 + ")" * 2000])
def test_a_regex_that_overflows_or_nests_too_deep_is_refused(value):
"""re.compile raises OverflowError or RecursionError for these; the contract refuses them as bad input."""
Expand Down
Loading