fix: Fix regression in instructions_utils placeholder matching

Co-authored-by: Bo Yang <ybo@google.com>
PiperOrigin-RevId: 934602575
This commit is contained in:
Bo Yang
2026-06-18 16:23:16 -07:00
committed by Copybara-Service
parent 20ba01c2ca
commit 9ecbaed5d6
2 changed files with 20 additions and 9 deletions
+10 -5
View File
@@ -181,24 +181,29 @@ async def inject_session_state(
if leading_count == trailing_count:
n = leading_count
is_valid = _is_valid_path(full_path) or full_path.startswith('artifact.')
if n % 2 == 0:
# Even: Escaped, no evaluation
half_n = n // 2
return '{' * half_n + full_path + '}' * half_n
if is_valid:
half_n = n // 2
return '{' * half_n + full_path + '}' * half_n
else:
return raw_match
else:
# Odd: Evaluate and wrap
if not _is_valid_path(full_path) and not full_path.startswith('artifact.'):
if not is_valid:
return raw_match
evaluated_value = await _evaluate_path(full_path)
wrap_braces = (n - 1) // 2
return '{' * wrap_braces + evaluated_value + '}' * wrap_braces
else:
# Asymmetric: fallback to old behavior (treat as N=1 if valid path)
if not _is_valid_path(full_path) and not full_path.startswith('artifact.'):
if not _is_valid_path(full_path) and not full_path.startswith(
'artifact.'
):
return raw_match
return await _evaluate_path(full_path)
return await _async_sub(r'{+[^{}]*}+', _replace_match, template)
@@ -516,14 +516,19 @@ async def test_inject_session_state_with_invalid_nested_path_returns_original():
@pytest.mark.asyncio
async def test_inject_session_state_escaped_braces():
instruction_template = "This is a literal {{placeholder}} and this is {value}."
instruction_template = (
"This is a literal {{placeholder}} and this is {value}."
)
invocation_context = await _create_test_readonly_context(
state={"value": "real_value"}
)
populated_instruction = await instructions_utils.inject_session_state(
instruction_template, invocation_context
)
assert populated_instruction == "This is a literal {placeholder} and this is real_value."
assert (
populated_instruction
== "This is a literal {placeholder} and this is real_value."
)
@pytest.mark.asyncio
@@ -556,7 +561,9 @@ async def test_inject_session_state_quadruple_braces():
populated_instruction = await instructions_utils.inject_session_state(
instruction_template, invocation_context
)
assert populated_instruction == "This is literal double braces: {{placeholder}}."
assert (
populated_instruction == "This is literal double braces: {{placeholder}}."
)
@pytest.mark.asyncio
@@ -581,4 +588,3 @@ async def test_inject_session_state_asymmetric_braces_right():
instruction_template, invocation_context
)
assert populated_instruction == "Asymmetric right: real_value."