Setting the file. One moment.
Test Delta Reference Schema · LLM To Bedrock · aws/agent-toolkit-for-aws · Skills Docs
ContentsBack to the top of the page 81
Creating Amazon Aurora Db Cluster With Instances
104
Routing Traffic With Route53 And CloudFront
Resilience Program Design
Creating API Gateway Stage
def test_documented_responses_image_blocks_set_detail
— line 186
This file
Number 30.26
Position 26 of 35
Type Python
Size 9 KB
Lines 193 scripts/ test_delta_reference_schema.py
Python · 193 lines · 9 KB
import
re
16 from pathlib import Path
17
18 REFS = Path( __file__ ).resolve().parent.parent / "references/helpers/behavior-delta-detection/references"
19 SCHEMA = Path( __file__ ).resolve().parent / "schemas/analysis.json"
20
21 # Matches both the bullet form (`- `resolution_kind`: `impl_path``) and prose
22 # mentions (`... `resolution_kind: impl_path`. Apply ...`), with the value inside
23 # or outside the backticks.
24 PATTERN = re.compile( r "resolution_kind` ? \s * : \s * ` ? ([ a-z_ ] + ) ` ? " )
25
26
27 def allowed_kinds () -> set[ str ]:
28 schema = json.loads( SCHEMA .read_text())
29
30 found: list[list[ str ]] = []
31
32 def walk (node):
33 if isinstance (node, dict ):
34 if node.get( "enum" ) and "resolution_kind" not in found:
35 pass
36 for key, value in node.items():
37 if key == "resolution_kind" and isinstance (value, dict ) and "enum" in value:
38 found.append(value[ "enum" ])
39 walk(value)
40 elif isinstance (node, list ):
41 for item in node:
42 walk(item)
43
44 walk(schema)
45 assert found, "analysis.json no longer declares a resolution_kind enum"
46 return set (found[ 0 ])
47
48
49 def test_every_reference_resolution_kind_is_in_the_schema ():
50 allowed = allowed_kinds()
51 offenders = []
52 for ref in sorted ( REFS .glob( "*.md" )):
53 for lineno, line in enumerate (ref.read_text().splitlines(), 1 ):
54 for value in PATTERN .findall(line):
55 if value not in allowed:
56 offenders.append( f " { ref.name } : { lineno } -> { value !r} " )
57 assert not offenders, (
58 "delta references instruct the analyzer to emit resolution_kind values that "
59 f "analysis.json rejects (allowed: { sorted (allowed) } ): \n " + " \n " .join(offenders))
60
61
62 def test_pattern_catches_both_declaration_forms ():
63 # Guards the guard: if PATTERN stops matching either form, the test above
64 # silently passes on a broken reference.
65 assert PATTERN .findall( "- `resolution_kind`: `impl_path`" ) == [ "impl_path" ]
66 assert PATTERN .findall( "always `user_visible: false`, `resolution_kind: mechanical`." ) == [ "mechanical" ]
67
68
69 # --- Same guard, applied to the evaluator's documented control states ----------
70 # The evaluator writes `{ blocked: { reason, detail } }` and then validates against
71 # eval.json. A reason documented in the prompt but absent from the schema means a
72 # real failure mode (404, IAM denial, missing deps) cannot be represented at all,
73 # so the phase enters the retry path with no valid outcome file.
74
75 AGENTS = Path( __file__ ).resolve().parent.parent.parent.parent / "agents"
76 EVAL_SCHEMA = Path( __file__ ).resolve().parent / "schemas/eval.json"
77 REASON_PATTERN = re.compile( r "reason: \s * ' ([ a-z_ ] + ) '" )
78
79
80 def _eval_enums () -> tuple[set[ str ], set[ str ]]:
81 schema = json.loads( EVAL_SCHEMA .read_text())
82 blocked, partial = set (), set ()
83 for branch in schema.get( "oneOf" , []):
84 props = branch.get( "properties" , {})
85 if "blocked" in props:
86 blocked = set (props[ "blocked" ][ "properties" ][ "reason" ][ "enum" ])
87 if "partial" in props:
88 partial = set (props[ "partial" ][ "properties" ][ "reason" ][ "enum" ])
89 assert blocked, "eval.json no longer declares a blocked.reason enum"
90 return blocked, partial
91
92
93 def test_evaluator_control_state_reasons_are_representable ():
94 blocked, partial = _eval_enums()
95 allowed = blocked | partial
96 prompt = ( AGENTS / "llm2bedrock-prompt-evaluator.md" ).read_text()
97 offenders = []
98 for lineno, line in enumerate (prompt.splitlines(), 1 ):
99 for value in REASON_PATTERN .findall(line):
100 if value not in allowed:
101 offenders.append( f "llm2bedrock-prompt-evaluator.md: { lineno } -> { value !r} " )
102 assert not offenders, (
103 "the evaluator documents control-state reasons that eval.json rejects "
104 f "(blocked: { sorted (blocked) } , partial: { sorted (partial) } ): \n " + " \n " .join(offenders))
105
106
107 # --- Guard: the evaluator must not hand-assemble Responses image payloads -------
108 # Both mistakes below pass the §9.5a smoke test (it hardcodes a known-good jpeg)
109 # and fail only on golden cases, so a static check is the cheapest place to catch
110 # a regression in prompt text that no unit test can reach.
111
112 def test_evaluator_does_not_document_a_bare_responses_content_list ():
113 prompt = ( AGENTS / "llm2bedrock-prompt-evaluator.md" ).read_text()
114 offenders = []
115 for lineno, line in enumerate (prompt.splitlines(), 1 ):
116 if "input_image" not in line and "input_text" not in line:
117 continue
118 # Any line showing a Responses content block must either be inside a
119 # role/content wrapper or be delegating to the helper.
120 if '"role"' in line or "'role'" in line:
121 continue
122 if "responses_message" in line:
123 continue
124 # The §9.5a snippet wraps across lines; allow the inner block lines there.
125 offenders.append((lineno, line.strip()[: 90 ]))
126 # Lines inside the multi-line §9.5a wrapper are legitimate; assert every
127 # offender sits within 3 lines of a role wrapper.
128 lines = prompt.splitlines()
129 real = []
130 for lineno, text in offenders:
131 window = " \n " .join(lines[ max ( 0 , lineno - 4 ):lineno])
132 # Any message-item role is a valid wrapper: `user` for prompts, `developer`
133 # for a system prompt on the Responses API.
134 if not re.search( r '"role": \s * " ( user | developer | system | assistant ) "' , window):
135 real.append( f "line { lineno } : { text } " )
136 assert not real, (
137 "Responses image content documented without a user-message wrapper "
138 "(input takes [{'role':'user','content':[...]}], not a bare block list): \n "
139 + " \n " .join(real))
140
141
142 def test_evaluator_never_templates_an_extension_into_a_mime_type ():
143 # `image/<ext>` yields the invalid `image/jpg` for a .jpg case.
144 prompt = ( AGENTS / "llm2bedrock-prompt-evaluator.md" ).read_text()
145 bad = [ f "line { n } : { l.strip()[: 90 ] } "
146 for n, l in enumerate (prompt.splitlines(), 1 )
147 if "image/<ext>" in l or "'format': <ext>" in l or '"format": <ext>' in l]
148 assert not bad, (
149 "extension templated directly into a wire format; use image_input helpers "
150 "(.jpg -> jpeg / image/jpeg): \n " + " \n " .join(bad))
151
152
153 # --- Guard: golden-case field names, derived from the canonical record ----------
154 # The evaluator reads golden cases by key. A key that does not exist in the record
155 # the log-ingestor writes raises KeyError before any API call, which no unit test
156 # reaches because the loop lives in prompt text.
157
158 def _canonical_case_fields () -> set[ str ]:
159 """Field names from the canonical prompts.jsonl record in the log-ingestor prompt."""
160 text = ( AGENTS / "llm2bedrock-log-ingestor.md" ).read_text()
161 marker = "Write each entry as one JSON object per line"
162 start = text.index(marker)
163 block = text[text.index( "```json" , start) + len ( "```json" ):]
164 block = block[:block.index( "```" )]
165 record = json.loads(block)
166 assert "user_prompt" in record, "canonical record shape changed — revisit this guard"
167 return set (record)
168
169
170 def test_evaluator_reads_only_canonical_golden_case_fields ():
171 fields = _canonical_case_fields()
172 prompt = ( AGENTS / "llm2bedrock-prompt-evaluator.md" ).read_text()
173 # Subscripts on the per-case variables used in the §8 / §10 loops.
174 subscript = re.compile( r " \b(?: case | prompt | entry ) \[ [ \" ' ]([ a-z_ ] + )[ \" ' ] \] " )
175 getter = re.compile( r " \b(?: case | prompt | entry ) \. get \( [ \" ' ]([ a-z_ ] + )[ \" ' ] " )
176 offenders = []
177 for lineno, line in enumerate (prompt.splitlines(), 1 ):
178 for key in subscript.findall(line) + getter.findall(line):
179 if key not in fields:
180 offenders.append( f "llm2bedrock-prompt-evaluator.md: { lineno } -> { key !r} " )
181 assert not offenders, (
182 "evaluator reads golden-case fields absent from the canonical record "
183 f "(fields: { sorted (fields) } ): \n " + " \n " .join(offenders))
184
185
186 def test_documented_responses_image_blocks_set_detail ():
187 # Mirrors the helper-level test, for the image blocks written inline in prompts.
188 prompt = ( AGENTS / "llm2bedrock-prompt-evaluator.md" ).read_text()
189 bad = [ f "line { n } : { l.strip()[: 90 ] } "
190 for n, l in enumerate (prompt.splitlines(), 1 )
191 if '"type": "input_image"' in l and '"detail"' not in l]
192 assert not bad, (
193 "inline input_image block without the SDK-required `detail` field: \n " + " \n " .join(bad))