rsnarsna commited on
Commit
4df4f1d
·
1 Parent(s): 5ab51f1

feat(validation): implement Phase 5 Step 5.4 semantic & parameter constraint validation (GAP-05, GAP-06, GAP-11)

Browse files
lambdas/validate_handler.py CHANGED
@@ -509,6 +509,11 @@ def validate_workflow_protocol_logic(
509
  import keyword
510
  from collections import deque, defaultdict
511
  from language_core.node_schema import default_registry
 
 
 
 
 
512
 
513
  STD_LIBS = {
514
  "math", "json", "sys", "os", "re", "time", "datetime", "random",
@@ -1013,35 +1018,69 @@ def validate_workflow_protocol_logic(
1013
  except ValueError:
1014
  pass
1015
 
1016
- # Identifier validation (Variables, functions, classes)
1017
- for id_field in ("var_name", "func_name", "fn_name", "class_name"):
1018
- val = combined_params.get(id_field)
1019
- if val is not None and str(val).strip():
1020
- ident = str(val).strip()
1021
- err_code = "FUNC-E001" if "func" in id_field else ("OOP-E001" if "class" in id_field else "COMP-E101")
1022
- if not re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", ident):
1023
- add_diag(
1024
- "error",
1025
- "Node Validation",
1026
- err_code,
1027
- f"Invalid Python identifier '{ident}' on node '{label}' ({nid}).",
1028
- 2,
1029
- node_id=nid,
1030
- port_id=id_field,
1031
- fix="Use letters, numbers, and underscores (cannot start with a digit)."
1032
- )
1033
- elif keyword.iskeyword(ident):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034
  add_diag(
1035
  "error",
1036
  "Node Validation",
1037
- err_code,
1038
- f"Reserved Keyword Conflict: '{ident}' on node '{label}' ({nid}) is a reserved Python keyword.",
1039
  2,
1040
  node_id=nid,
1041
- port_id=id_field,
1042
- fix="Choose a non-reserved identifier name (e.g. 'my_var', 'result')."
1043
  )
1044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1045
  # Expression AST verification
1046
  if "condition" in combined_params or "if" in ntype.lower():
1047
  cond = str(combined_params.get("condition") or "True")
 
509
  import keyword
510
  from collections import deque, defaultdict
511
  from language_core.node_schema import default_registry
512
+ from language_core.parameter_validator import (
513
+ is_non_finite_number,
514
+ validate_parameter_value,
515
+ validate_python_identifier,
516
+ )
517
 
518
  STD_LIBS = {
519
  "math", "json", "sys", "os", "re", "time", "datetime", "random",
 
1018
  except ValueError:
1019
  pass
1020
 
1021
+ # ─── NON-FINITE NUMERIC VALUES CHECK (GAP-11) ─────────────────
1022
+ for pk, pv in combined_params.items():
1023
+ found_nf, tok_nf = is_non_finite_number(pv)
1024
+ if found_nf:
1025
+ add_diag(
1026
+ "error",
1027
+ "Node Validation",
1028
+ "VAL-PARAM-NON-FINITE",
1029
+ f"Non-Finite Number Error: Parameter '{pk}' on node '{label}' ({nid}) contains non-finite numeric value '{tok_nf}' (NaN or Infinity). Only finite numeric values are permitted.",
1030
+ 2,
1031
+ node_id=nid,
1032
+ port_id=pk,
1033
+ fix=f"Replace '{tok_nf}' with a valid finite number."
1034
+ )
1035
+
1036
+ # ─── SCHEMA-DRIVEN PARAMETER CONSTRAINTS VALIDATION (GAP-05) ──
1037
+ validated_param_ids = set()
1038
+ node_schema = default_registry.get(ntype)
1039
+ if node_schema and node_schema.parameters:
1040
+ for param in node_schema.parameters:
1041
+ validated_param_ids.add(param.id)
1042
+ if param.id in combined_params:
1043
+ pval = combined_params[param.id]
1044
+ elif param.id in custom:
1045
+ pval = custom[param.id]
1046
+ elif f"param_{param.id}" in combined_params:
1047
+ pval = combined_params[f"param_{param.id}"]
1048
+ else:
1049
+ pval = param.default
1050
+
1051
+ p_valid, p_code, p_msg, p_fix = validate_parameter_value(
1052
+ param, pval, node_label=label, node_id=nid
1053
+ )
1054
+ if not p_valid:
1055
  add_diag(
1056
  "error",
1057
  "Node Validation",
1058
+ p_code or "VAL-PARAM-CONSTRAINT",
1059
+ p_msg or f"Parameter '{param.name}' violates declared schema constraint.",
1060
  2,
1061
  node_id=nid,
1062
+ port_id=param.id,
1063
+ fix=p_fix
1064
  )
1065
 
1066
+ # ─── PYTHON IDENTIFIER VALIDATION (GAP-06) ────────────────────
1067
+ for id_field in ("var_name", "variable_name", "func_name", "fn_name", "function_name", "class_name", "loop_var", "iter_var", "target_var"):
1068
+ if id_field in combined_params and id_field not in validated_param_ids:
1069
+ val = combined_params[id_field]
1070
+ if val is not None:
1071
+ id_valid, id_code, id_msg, id_fix = validate_python_identifier(val, field_id=id_field)
1072
+ if not id_valid:
1073
+ add_diag(
1074
+ "error",
1075
+ "Node Validation",
1076
+ id_code or "COMP-E101",
1077
+ f"{id_msg} on node '{label}' ({nid}).",
1078
+ 2,
1079
+ node_id=nid,
1080
+ port_id=id_field,
1081
+ fix=id_fix
1082
+ )
1083
+
1084
  # Expression AST verification
1085
  if "condition" in combined_params or "if" in ntype.lower():
1086
  cond = str(combined_params.get("condition") or "True")
language_core/node_schema.py CHANGED
@@ -112,9 +112,17 @@ def check_type_compatibility(value: Any, expected_type: str) -> bool:
112
  if expected == "none":
113
  return False
114
  if expected == "int":
115
- return isinstance(value, int) and not isinstance(value, bool)
 
 
 
 
116
  if expected in ("float", "number"):
117
- return isinstance(value, (int, float)) and not isinstance(value, bool)
 
 
 
 
118
  if expected == "str":
119
  return isinstance(value, str)
120
  if expected == "bool":
@@ -219,6 +227,7 @@ class ParameterDefinition(BaseModel):
219
  max_value: Optional[float] = Field(default=None, description="Upper bound for numeric parameters")
220
  required: bool = Field(default=True, description="Whether parameter is mandatory")
221
  step: Optional[float] = Field(default=None, description="Increment step for numeric parameters")
 
222
  regex: Optional[str] = Field(default=None, description="Regex pattern for string parameters")
223
  enum_values: Optional[List[Any]] = Field(default=None, description="Allowed raw choices for enum parameters")
224
  widget: Optional[str] = Field(default=None, description="UI control widget override")
@@ -541,19 +550,19 @@ class NodeSchemaRegistry:
541
  if parameters:
542
  params.update(parameters)
543
 
 
 
 
 
 
 
 
 
544
  for p in schema.parameters:
545
  val = params.get(p.id)
546
- if p.required and val is None:
547
- raise ValueError(f"Mandatory parameter '{p.id}' is missing for node '{node_type}'.")
548
- if p.type == ParameterType.SELECT and p.options:
549
- valid_opts = [opt.value for opt in p.options]
550
- if val not in valid_opts:
551
- raise ValueError(f"Value '{val}' for parameter '{p.id}' not permitted. Allowed: {valid_opts}")
552
- if p.type == ParameterType.NUMBER and isinstance(val, (int, float)):
553
- if p.min_value is not None and val < p.min_value:
554
- raise ValueError(f"Value {val} for parameter '{p.id}' is below minimum bound {p.min_value}.")
555
- if p.max_value is not None and val > p.max_value:
556
- raise ValueError(f"Value {val} for parameter '{p.id}' exceeds maximum bound {p.max_value}.")
557
 
558
  # 2. Validate input ports presence and type compatibility
559
  validated_inputs: Dict[str, Any] = {}
 
112
  if expected == "none":
113
  return False
114
  if expected == "int":
115
+ if isinstance(value, bool):
116
+ return False
117
+ if isinstance(value, float):
118
+ return False
119
+ return isinstance(value, int)
120
  if expected in ("float", "number"):
121
+ if isinstance(value, bool):
122
+ return False
123
+ if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
124
+ return False
125
+ return isinstance(value, (int, float))
126
  if expected == "str":
127
  return isinstance(value, str)
128
  if expected == "bool":
 
227
  max_value: Optional[float] = Field(default=None, description="Upper bound for numeric parameters")
228
  required: bool = Field(default=True, description="Whether parameter is mandatory")
229
  step: Optional[float] = Field(default=None, description="Increment step for numeric parameters")
230
+ precision: Optional[int] = Field(default=None, description="Maximum decimal precision for numeric parameters")
231
  regex: Optional[str] = Field(default=None, description="Regex pattern for string parameters")
232
  enum_values: Optional[List[Any]] = Field(default=None, description="Allowed raw choices for enum parameters")
233
  widget: Optional[str] = Field(default=None, description="UI control widget override")
 
550
  if parameters:
551
  params.update(parameters)
552
 
553
+ from language_core.parameter_validator import validate_parameter_value, is_non_finite_number
554
+
555
+ # Reject non-finite input socket values
556
+ for inp_k, inp_v in inputs.items():
557
+ has_nf, tok_nf = is_non_finite_number(inp_v)
558
+ if has_nf:
559
+ raise ValueError(f"Input port '{inp_k}' on node '{node_type}' contains non-finite number '{tok_nf}'.")
560
+
561
  for p in schema.parameters:
562
  val = params.get(p.id)
563
+ p_valid, p_code, p_msg, p_fix = validate_parameter_value(p, val, node_label=schema.label, node_id=node_type)
564
+ if not p_valid:
565
+ raise ValueError(f"Parameter validation failed on '{p.id}' of '{node_type}': {p_msg}")
 
 
 
 
 
 
 
 
566
 
567
  # 2. Validate input ports presence and type compatibility
568
  validated_inputs: Dict[str, Any] = {}
language_core/parameter_validator.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ALLI Parameter and Constraint Validation Engine - Phase 5 Step 5.4.
3
+ Enforces schema-driven parameter constraints, Python identifier rules, and non-finite number rejection.
4
+ Provides 100% parity with Next.js frontend validation and UI drawer controls.
5
+ """
6
+
7
+ import math
8
+ import re
9
+ import json
10
+ import keyword
11
+ from typing import Any, Tuple, Optional, Dict, List, Set, Union
12
+ from language_core.node_schema import ParameterDefinition, ParameterType, ParameterOption
13
+
14
+
15
+ NON_FINITE_STRINGS = {
16
+ "nan", "+nan", "-nan",
17
+ "inf", "+inf", "-inf",
18
+ "infinity", "+infinity", "-infinity"
19
+ }
20
+
21
+
22
+ def is_non_finite_number(val: Any) -> Tuple[bool, Optional[str]]:
23
+ """
24
+ Recursively inspects val to detect non-finite numbers (NaN, Inf, -Inf).
25
+ Returns (True, token_str) if non-finite number is found, otherwise (False, None).
26
+ Covers primitives, strings, and nested containers (lists, tuples, sets, dicts).
27
+ """
28
+ if val is None or isinstance(val, bool):
29
+ return False, None
30
+
31
+ if isinstance(val, float):
32
+ if math.isnan(val):
33
+ return True, "NaN"
34
+ if math.isinf(val):
35
+ return True, "-Infinity" if val < 0 else "Infinity"
36
+ return False, None
37
+
38
+ if isinstance(val, str):
39
+ s = val.strip().lower()
40
+ if s in NON_FINITE_STRINGS:
41
+ return True, val.strip()
42
+ return False, None
43
+
44
+ if isinstance(val, (list, tuple, set)):
45
+ for item in val:
46
+ found, token = is_non_finite_number(item)
47
+ if found:
48
+ return True, token
49
+ return False, None
50
+
51
+ if isinstance(val, dict):
52
+ for k, v in val.items():
53
+ found_k, token_k = is_non_finite_number(k)
54
+ if found_k:
55
+ return True, token_k
56
+ found_v, token_v = is_non_finite_number(v)
57
+ if found_v:
58
+ return True, token_v
59
+ return False, None
60
+
61
+ return False, None
62
+
63
+
64
+ def validate_python_identifier(name: Any, field_id: str = "var_name") -> Tuple[bool, Optional[str], Optional[str], Optional[str]]:
65
+ """
66
+ Validates identifier according to Python 3 language rules.
67
+ - Rejects empty, whitespace-only, leading or trailing whitespace.
68
+ - Rejects reserved Python keywords (35 keywords in Python 3).
69
+ - Enforces valid identifier format: starts with letter or underscore, alphanumeric + underscore.
70
+ - Supports Unicode identifier characters per PEP 3131 (via str.isidentifier()).
71
+ - Returns (is_valid, error_code, error_message, fix_suggestion).
72
+ """
73
+ err_code = (
74
+ "FUNC-E001" if ("func" in field_id or "fn" in field_id)
75
+ else ("OOP-E001" if "class" in field_id else "COMP-E101")
76
+ )
77
+
78
+ if name is None or (isinstance(name, str) and not name.strip()):
79
+ return (
80
+ False,
81
+ err_code,
82
+ "Identifier name cannot be empty.",
83
+ "Provide a valid Python identifier like 'x' or 'my_var'."
84
+ )
85
+
86
+ s = str(name)
87
+ if s != s.strip():
88
+ return (
89
+ False,
90
+ err_code,
91
+ f"Identifier '{s}' contains leading or trailing whitespace.",
92
+ "Remove leading and trailing spaces from the identifier name."
93
+ )
94
+
95
+ if keyword.iskeyword(s):
96
+ return (
97
+ False,
98
+ err_code,
99
+ f"Reserved Keyword Conflict: '{s}' is a reserved Python keyword and cannot be used as an identifier.",
100
+ f"Choose a non-reserved identifier name (e.g. 'my_{s}')."
101
+ )
102
+
103
+ if not s.isidentifier():
104
+ return (
105
+ False,
106
+ err_code,
107
+ f"Invalid Python identifier '{s}'. Identifiers must begin with a letter or underscore and contain only alphanumeric characters or underscores without spaces or punctuation.",
108
+ "Use letters, numbers, and underscores (cannot start with a digit or contain spaces/punctuation)."
109
+ )
110
+
111
+ return True, None, None, None
112
+
113
+
114
+ def validate_parameter_value(
115
+ param: ParameterDefinition,
116
+ val: Any,
117
+ node_label: str = "Node",
118
+ node_id: str = "node"
119
+ ) -> Tuple[bool, Optional[str], Optional[str], Optional[str]]:
120
+ """
121
+ Validates a parameter value against declared constraints in ParameterDefinition:
122
+ - Non-finite check (VAL-PARAM-NON-FINITE)
123
+ - Required parameter check (VAL-PARAM-CONSTRAINT)
124
+ - Python identifier check (COMP-E101, FUNC-E001, OOP-E001)
125
+ - Numeric bounds (min_value, max_value) (VAL-PARAM-CONSTRAINT)
126
+ - Step increment (step) (VAL-PARAM-CONSTRAINT)
127
+ - Decimal precision (precision) (VAL-PARAM-CONSTRAINT)
128
+ - Select options & enum_values membership (VAL-PARAM-CONSTRAINT)
129
+ - Safe regular expression pattern check (VAL-PARAM-CONSTRAINT)
130
+ - Structured JSON list/dict check (VAL-PARAM-CONSTRAINT)
131
+ Returns (is_valid, error_code, error_message, fix_suggestion).
132
+ """
133
+ # 1. Non-finite check (GAP-11)
134
+ found_nf, token_nf = is_non_finite_number(val)
135
+ if found_nf:
136
+ return (
137
+ False,
138
+ "VAL-PARAM-NON-FINITE",
139
+ f"Non-Finite Number Error: Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) contains non-finite value '{token_nf}' (NaN or Infinity). Only finite numeric values are permitted.",
140
+ f"Replace '{token_nf}' with a valid finite number."
141
+ )
142
+
143
+ # 2. Missing & Required check
144
+ is_none = val is None
145
+ is_empty_str = isinstance(val, str) and val.strip() == ""
146
+
147
+ # Note: 0, 0.0, False, [], {} are NOT missing; they are valid values according to their types
148
+ if is_none:
149
+ if param.required:
150
+ return (
151
+ False,
152
+ "VAL-PARAM-CONSTRAINT",
153
+ f"Required Parameter Missing: Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) is required but has no value.",
154
+ f"Provide a value for '{param.name}' in the configuration drawer."
155
+ )
156
+ return True, None, None, None
157
+
158
+ # Determine numeric classification
159
+ is_int_param = param.type in (ParameterType.NUMBER, "number", "int", "integer")
160
+ is_numeric_param = (
161
+ is_int_param
162
+ or param.type in ("float", "slider")
163
+ or getattr(param, "widget", None) in ("number", "slider")
164
+ or param.min_value is not None
165
+ or param.max_value is not None
166
+ or getattr(param, "step", None) is not None
167
+ or getattr(param, "precision", None) is not None
168
+ )
169
+
170
+ if is_numeric_param:
171
+ if is_empty_str:
172
+ if param.required:
173
+ return (
174
+ False,
175
+ "VAL-PARAM-CONSTRAINT",
176
+ f"Required Parameter Missing: Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) requires a numeric value.",
177
+ f"Provide a valid finite number for '{param.name}'."
178
+ )
179
+ return True, None, None, None
180
+
181
+ if not is_numeric_param and is_empty_str:
182
+ if param.required:
183
+ # Check if regex or identifier or select applies
184
+ is_ident = getattr(param, "is_identifier", False) or param.id in ("var_name", "variable_name", "func_name", "fn_name", "class_name", "loop_var")
185
+ if is_ident:
186
+ return (
187
+ False,
188
+ "COMP-E101",
189
+ f"Required Identifier Missing: Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) cannot be empty.",
190
+ "Provide a valid Python identifier."
191
+ )
192
+ # If plain string parameter with no regex, empty string is valid representation
193
+ if getattr(param, "regex", None):
194
+ try:
195
+ pat = re.compile(param.regex)
196
+ if not pat.search(""):
197
+ return (
198
+ False,
199
+ "VAL-PARAM-CONSTRAINT",
200
+ f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) cannot be empty (must match pattern '{param.regex}').",
201
+ f"Provide a value matching pattern '{param.regex}'."
202
+ )
203
+ except re.error:
204
+ pass
205
+ else:
206
+ return True, None, None, None
207
+
208
+ # 3. Python Identifier check (GAP-06)
209
+ is_identifier = (
210
+ getattr(param, "is_identifier", False) is True
211
+ or param.id in (
212
+ "var_name", "variable_name", "func_name", "fn_name", "function_name",
213
+ "class_name", "loop_var", "iter_var", "target_var"
214
+ )
215
+ )
216
+ if is_identifier:
217
+ is_valid_id, id_code, id_msg, id_fix = validate_python_identifier(val, field_id=param.id)
218
+ if not is_valid_id:
219
+ return False, id_code, f"{id_msg} on parameter '{param.name}' ({param.id}) of node '{node_label}' ({node_id}).", id_fix
220
+
221
+ # 4. Numeric Constraints (bounds, integer check, safe integer, step, precision)
222
+ if is_numeric_param and not is_empty_str:
223
+ if isinstance(val, (int, float)) and not isinstance(val, bool):
224
+ num = float(val)
225
+ elif isinstance(val, str) and val.strip() != "":
226
+ try:
227
+ num = float(val.strip())
228
+ except ValueError:
229
+ return (
230
+ False,
231
+ "VAL-PARAM-CONSTRAINT",
232
+ f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a valid number, received '{val}'.",
233
+ "Provide a valid finite number."
234
+ )
235
+ else:
236
+ return (
237
+ False,
238
+ "VAL-PARAM-CONSTRAINT",
239
+ f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a numeric value.",
240
+ "Provide a valid finite number."
241
+ )
242
+
243
+ # Check integer constraint
244
+ if param.type in ("int", "integer") or (getattr(param, "widget", None) == "number" and isinstance(param.default, int) and not isinstance(param.default, bool)):
245
+ if not num.is_integer():
246
+ return (
247
+ False,
248
+ "VAL-PARAM-CONSTRAINT",
249
+ f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be an integer, received {num}.",
250
+ "Provide a whole integer value."
251
+ )
252
+ if abs(num) > 9007199254740991:
253
+ return (
254
+ False,
255
+ "VAL-PARAM-CONSTRAINT",
256
+ f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) exceeds safe integer limits.",
257
+ "Provide an integer within [-9007199254740991, 9007199254740991]."
258
+ )
259
+
260
+ # min_value
261
+ if param.min_value is not None and num < param.min_value:
262
+ return (
263
+ False,
264
+ "VAL-PARAM-CONSTRAINT",
265
+ f"Parameter Constraint Error: Parameter '{param.name}' value {num} on node '{node_label}' ({node_id}) is below minimum allowed value {param.min_value}.",
266
+ f"Provide a value greater than or equal to {param.min_value}."
267
+ )
268
+
269
+ # max_value
270
+ if param.max_value is not None and num > param.max_value:
271
+ return (
272
+ False,
273
+ "VAL-PARAM-CONSTRAINT",
274
+ f"Parameter Constraint Error: Parameter '{param.name}' value {num} on node '{node_label}' ({node_id}) exceeds maximum allowed value {param.max_value}.",
275
+ f"Provide a value less than or equal to {param.max_value}."
276
+ )
277
+
278
+ # step
279
+ if getattr(param, "step", None) is not None and param.step > 0:
280
+ base = param.min_value if param.min_value is not None else 0.0
281
+ diff = abs(num - base)
282
+ rem = diff % param.step
283
+ eps = 1e-6
284
+ if rem > eps and abs(rem - param.step) > eps:
285
+ return (
286
+ False,
287
+ "VAL-PARAM-CONSTRAINT",
288
+ f"Parameter Constraint Error: Parameter '{param.name}' value {num} on node '{node_label}' ({node_id}) must be an increment of step {param.step}.",
289
+ f"Adjust value to be an increment of step {param.step}."
290
+ )
291
+
292
+ # precision
293
+ param_prec = getattr(param, "precision", None)
294
+ if param_prec is not None and param_prec >= 0:
295
+ str_repr = str(val).strip()
296
+ if "." in str_repr:
297
+ decimals = len(str_repr.split(".")[1])
298
+ if decimals > param_prec:
299
+ return (
300
+ False,
301
+ "VAL-PARAM-CONSTRAINT",
302
+ f"Parameter Constraint Error: Parameter '{param.name}' value on node '{node_label}' ({node_id}) exceeds maximum precision of {param_prec} decimal place(s).",
303
+ f"Round or format value to at most {param_prec} decimal place(s)."
304
+ )
305
+
306
+ # 5. Select Options & enum_values Membership
307
+ allowed_opts: List[Any] = []
308
+ if param.options:
309
+ for opt in param.options:
310
+ v = opt.value if hasattr(opt, "value") else (opt.get("value") if isinstance(opt, dict) else opt)
311
+ allowed_opts.append(v)
312
+ if getattr(param, "enum_values", None):
313
+ for ev in param.enum_values:
314
+ if ev not in allowed_opts:
315
+ allowed_opts.append(ev)
316
+
317
+ if allowed_opts:
318
+ matches = any(opt == val or str(opt) == str(val) for opt in allowed_opts)
319
+ if not matches:
320
+ choices_str = ", ".join(repr(o) for o in allowed_opts)
321
+ return (
322
+ False,
323
+ "VAL-PARAM-CONSTRAINT",
324
+ f"Parameter Constraint Error: Parameter '{param.name}' value '{val}' on node '{node_label}' ({node_id}) is not one of the allowed options: [{choices_str}].",
325
+ f"Select one of the allowed options: [{choices_str}]."
326
+ )
327
+
328
+ # 6. Regex Pattern Check
329
+ if getattr(param, "regex", None) and isinstance(val, str):
330
+ try:
331
+ pat = re.compile(param.regex)
332
+ if not pat.search(val):
333
+ return (
334
+ False,
335
+ "VAL-PARAM-CONSTRAINT",
336
+ f"Parameter Constraint Error: Parameter '{param.name}' value '{val}' on node '{node_label}' ({node_id}) does not match required pattern '{param.regex}'.",
337
+ f"Provide a value matching pattern '{param.regex}'."
338
+ )
339
+ except re.error as e:
340
+ # Handle malformed schema regex gracefully without crashing validation
341
+ pass
342
+
343
+ # 7. Structured JSON (list, dict) Check
344
+ if param.type in ("list", "dict") or getattr(param, "widget", None) == "json":
345
+ if isinstance(val, str) and val.strip():
346
+ try:
347
+ parsed = json.loads(val.strip())
348
+ if param.type == "list" and not isinstance(parsed, list):
349
+ return (
350
+ False,
351
+ "VAL-PARAM-CONSTRAINT",
352
+ f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a valid JSON list (e.g. [1, 2, 3]).",
353
+ "Provide a valid JSON list."
354
+ )
355
+ if param.type == "dict" and not isinstance(parsed, dict):
356
+ return (
357
+ False,
358
+ "VAL-PARAM-CONSTRAINT",
359
+ f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a valid JSON dictionary (e.g. {{\"key\": \"val\"}}).",
360
+ "Provide a valid JSON dictionary."
361
+ )
362
+ except Exception as e:
363
+ return (
364
+ False,
365
+ "VAL-PARAM-CONSTRAINT",
366
+ f"Invalid JSON for parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}): {e}",
367
+ "Provide valid JSON syntax."
368
+ )
369
+ elif isinstance(val, (list, dict)):
370
+ if param.type == "list" and not isinstance(val, list):
371
+ return (
372
+ False,
373
+ "VAL-PARAM-CONSTRAINT",
374
+ f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a list.",
375
+ "Provide a list."
376
+ )
377
+ if param.type == "dict" and not isinstance(val, dict):
378
+ return (
379
+ False,
380
+ "VAL-PARAM-CONSTRAINT",
381
+ f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a dictionary.",
382
+ "Provide a dictionary."
383
+ )
384
+
385
+ return True, None, None, None
tests/test_workflow_validation.py CHANGED
@@ -382,6 +382,198 @@ def test_step5_2_preserving_falsy_configured_values():
382
  assert any(d["code"] == "VAL-REQUIRED-INPUT-MISSING" for d in res_empty_str["diagnostics"])
383
 
384
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
  def run_tests():
386
  print("=" * 75)
387
  print("ALLI PHASE 3.9 & 5.2: WORKFLOW-LEVEL VALIDATION TEST SUITE")
@@ -410,8 +602,16 @@ def run_tests():
410
  print(" PASS: test_step5_2_empty_and_malformed_node_ids")
411
  test_step5_2_preserving_falsy_configured_values()
412
  print(" PASS: test_step5_2_preserving_falsy_configured_values")
 
 
 
 
 
 
 
 
413
  print("\n" + "=" * 75)
414
- print("ALL 12 TEST SUITES PASSED WITH ZERO FAILURES!")
415
  print("=" * 75)
416
 
417
 
 
382
  assert any(d["code"] == "VAL-REQUIRED-INPUT-MISSING" for d in res_empty_str["diagnostics"])
383
 
384
 
385
+
386
+
387
+ # ---------------------------------------------------------------------------
388
+ # 13. Step 5.4: Non-Finite Numeric Values Rejection (GAP-11)
389
+ # ---------------------------------------------------------------------------
390
+ def test_step5_4_non_finite_numeric_rejection():
391
+ import math
392
+
393
+ # 1. Direct NaN float
394
+ nan_graph = {
395
+ "nodes": [
396
+ {"id": "n_nan", "node_type": "math.sqrt", "data": {"label": "Sqrt NaN", "customData": {"x": float("nan")}}}
397
+ ],
398
+ "edges": []
399
+ }
400
+ res_nan = validate_workflow_protocol_logic(nan_graph)
401
+ assert not res_nan["valid"], "Graph with NaN must be invalid"
402
+ assert not res_nan["can_execute"], "Graph with NaN cannot execute"
403
+ assert any(d["code"] == "VAL-PARAM-NON-FINITE" for d in res_nan["diagnostics"])
404
+
405
+ # 2. Positive and negative infinity
406
+ inf_graph = {
407
+ "nodes": [
408
+ {"id": "n_inf", "node_type": "math.sqrt", "data": {"label": "Sqrt Inf", "customData": {"x": float("inf")}}}
409
+ ],
410
+ "edges": []
411
+ }
412
+ res_inf = validate_workflow_protocol_logic(inf_graph)
413
+ assert not res_inf["valid"]
414
+ assert any(d["code"] == "VAL-PARAM-NON-FINITE" for d in res_inf["diagnostics"])
415
+
416
+ # 3. String representation 'infinity' and 'nan'
417
+ str_inf_graph = {
418
+ "nodes": [
419
+ {"id": "n_str_inf", "node_type": "math.sqrt", "data": {"label": "Sqrt Str Inf", "customData": {"x": "Infinity"}}}
420
+ ],
421
+ "edges": []
422
+ }
423
+ res_str_inf = validate_workflow_protocol_logic(str_inf_graph)
424
+ assert not res_str_inf["valid"]
425
+ assert any(d["code"] == "VAL-PARAM-NON-FINITE" for d in res_str_inf["diagnostics"])
426
+
427
+ # 4. Nested in list
428
+ nested_list_graph = {
429
+ "nodes": [
430
+ {"id": "n_list", "node_type": "io.print", "data": {"label": "Print Nested", "customData": {"value": [1.0, float("nan"), 3.0]}}}
431
+ ],
432
+ "edges": []
433
+ }
434
+ res_nested = validate_workflow_protocol_logic(nested_list_graph)
435
+ assert not res_nested["valid"]
436
+ assert any(d["code"] == "VAL-PARAM-NON-FINITE" for d in res_nested["diagnostics"])
437
+
438
+ # 5. Nested in dictionary
439
+ nested_dict_graph = {
440
+ "nodes": [
441
+ {"id": "n_dict", "node_type": "io.print", "data": {"label": "Print Dict", "customData": {"value": {"metric": float("-inf")}}}}
442
+ ],
443
+ "edges": []
444
+ }
445
+ res_dict = validate_workflow_protocol_logic(nested_dict_graph)
446
+ assert not res_dict["valid"]
447
+ assert any(d["code"] == "VAL-PARAM-NON-FINITE" for d in res_dict["diagnostics"])
448
+
449
+
450
+ # ---------------------------------------------------------------------------
451
+ # 14. Step 5.4: Schema Parameter Constraints (GAP-05)
452
+ # ---------------------------------------------------------------------------
453
+ def test_step5_4_schema_parameter_constraints():
454
+ # 1. Bounds check (precision below minimum 0 or above maximum 10 on math.sqrt)
455
+ # math.sqrt precision parameter has min_value=0, max_value=10
456
+ sqrt_bound_err = {
457
+ "nodes": [
458
+ {"id": "sqrt_1", "node_type": "math.sqrt", "data": {"label": "Sqrt", "customData": {"x": 16.0, "precision": -1}}}
459
+ ],
460
+ "edges": []
461
+ }
462
+ res_bound = validate_workflow_protocol_logic(sqrt_bound_err)
463
+ assert not res_bound["valid"]
464
+ assert any(d["code"] == "VAL-PARAM-CONSTRAINT" for d in res_bound["diagnostics"])
465
+ assert any("below minimum allowed value" in d["message"] for d in res_bound["diagnostics"])
466
+
467
+ # 2. Select option membership check (e.g. invalid rounding mode on math.sqrt)
468
+ sqrt_select_err = {
469
+ "nodes": [
470
+ {"id": "sqrt_2", "node_type": "math.sqrt", "data": {"label": "Sqrt", "customData": {"x": 16.0, "rounding": "invalid_rounding_mode"}}}
471
+ ],
472
+ "edges": []
473
+ }
474
+ res_select = validate_workflow_protocol_logic(sqrt_select_err)
475
+ assert not res_select["valid"]
476
+ assert any(d["code"] == "VAL-PARAM-CONSTRAINT" for d in res_select["diagnostics"])
477
+ assert any("not one of the allowed options" in d["message"] for d in res_select["diagnostics"])
478
+
479
+ # 3. Valid parameters within constraints
480
+ sqrt_valid = {
481
+ "nodes": [
482
+ {"id": "sqrt_3", "node_type": "math.sqrt", "data": {"label": "Sqrt", "customData": {"x": 16.0, "rounding": "round", "precision": 2}}}
483
+ ],
484
+ "edges": []
485
+ }
486
+ res_valid = validate_workflow_protocol_logic(sqrt_valid)
487
+ assert res_valid["valid"], f"Valid config failed: {res_valid['diagnostics']}"
488
+ assert not any(d["code"] == "VAL-PARAM-CONSTRAINT" for d in res_valid["diagnostics"])
489
+
490
+
491
+ # ---------------------------------------------------------------------------
492
+ # 15. Step 5.4: Python Identifier Validation (GAP-06)
493
+ # ---------------------------------------------------------------------------
494
+ def test_step5_4_python_identifier_validation():
495
+ # 1. Valid identifier
496
+ valid_var_graph = {
497
+ "nodes": [
498
+ {"id": "var_1", "node_type": "constant.int", "data": {"label": "Int Node", "customData": {"var_name": "my_valid_var_1", "value": 42}}}
499
+ ],
500
+ "edges": []
501
+ }
502
+ res_valid = validate_workflow_protocol_logic(valid_var_graph)
503
+ assert res_valid["valid"]
504
+
505
+ # 2. Reserved Python keyword
506
+ for kw in ["def", "class", "for", "while", "import", "return", "pass"]:
507
+ kw_graph = {
508
+ "nodes": [
509
+ {"id": f"var_{kw}", "node_type": "constant.int", "data": {"label": "Keyword", "customData": {"var_name": kw, "value": 10}}}
510
+ ],
511
+ "edges": []
512
+ }
513
+ res_kw = validate_workflow_protocol_logic(kw_graph)
514
+ assert not res_kw["valid"]
515
+ assert any(d["code"] in ("COMP-E101", "FUNC-E001", "OOP-E001") for d in res_kw["diagnostics"])
516
+
517
+ # 3. Invalid identifier with space or hyphen
518
+ invalid_chars_graph = {
519
+ "nodes": [
520
+ {"id": "var_bad", "node_type": "constant.int", "data": {"label": "Bad Var", "customData": {"var_name": "var with space", "value": 10}}}
521
+ ],
522
+ "edges": []
523
+ }
524
+ res_bad = validate_workflow_protocol_logic(invalid_chars_graph)
525
+ assert not res_bad["valid"]
526
+ assert any(d["code"] == "COMP-E101" for d in res_bad["diagnostics"])
527
+
528
+ # 4. Starting with digit
529
+ digit_graph = {
530
+ "nodes": [
531
+ {"id": "var_digit", "node_type": "constant.int", "data": {"label": "Digit", "customData": {"var_name": "123var", "value": 10}}}
532
+ ],
533
+ "edges": []
534
+ }
535
+ res_digit = validate_workflow_protocol_logic(digit_graph)
536
+ assert not res_digit["valid"]
537
+ assert any(d["code"] == "COMP-E101" for d in res_digit["diagnostics"])
538
+
539
+ # 5. Ordinary display labels are NOT restricted by Python identifier rules
540
+ label_graph = {
541
+ "nodes": [
542
+ {"id": "sqrt_label", "node_type": "math.sqrt", "data": {"label": "My Square Root & Calculations (v1)", "customData": {"x": 25.0}}}
543
+ ],
544
+ "edges": []
545
+ }
546
+ res_label = validate_workflow_protocol_logic(label_graph)
547
+ assert res_label["valid"], f"Ordinary label should not be restricted: {res_label['diagnostics']}"
548
+
549
+
550
+ # ---------------------------------------------------------------------------
551
+ # 16. Step 5.4: Execution Preflight Blocking
552
+ # ---------------------------------------------------------------------------
553
+ def test_step5_4_execution_preflight_blocking():
554
+ from language_core.execution_planner import build_execution_plan
555
+ from language_core.workflow_executor import execute_workflow_graph
556
+
557
+ # Non-finite number workflow
558
+ nan_workflow = {
559
+ "name": "NaN Preflight Test",
560
+ "nodes": [
561
+ {"id": "n_nan", "node_type": "math.sqrt", "data": {"label": "Sqrt", "customData": {"x": float("nan")}}}
562
+ ],
563
+ "edges": []
564
+ }
565
+
566
+ # 1. Execution planner MUST reject and return can_execute: False
567
+ plan = build_execution_plan(nan_workflow)
568
+ assert not plan["valid"], "Execution planner must mark invalid"
569
+ assert not plan["can_execute"], "Execution planner must block execution"
570
+ assert any(err["code"] == "VAL-PARAM-NON-FINITE" for err in plan["validation_errors"])
571
+
572
+ # 2. Workflow executor MUST block execution before subprocess/docker
573
+ exec_res = execute_workflow_graph(nan_workflow)
574
+ assert exec_res["status"] == "failed"
575
+ assert exec_res["node_results"]["n_nan"]["status"] == "failed"
576
+ assert exec_res["node_results"]["n_nan"]["error_semantics"]["code"] == "VAL-PARAM-NON-FINITE"
577
  def run_tests():
578
  print("=" * 75)
579
  print("ALLI PHASE 3.9 & 5.2: WORKFLOW-LEVEL VALIDATION TEST SUITE")
 
602
  print(" PASS: test_step5_2_empty_and_malformed_node_ids")
603
  test_step5_2_preserving_falsy_configured_values()
604
  print(" PASS: test_step5_2_preserving_falsy_configured_values")
605
+ test_step5_4_non_finite_numeric_rejection()
606
+ print(" PASS: test_step5_4_non_finite_numeric_rejection")
607
+ test_step5_4_schema_parameter_constraints()
608
+ print(" PASS: test_step5_4_schema_parameter_constraints")
609
+ test_step5_4_python_identifier_validation()
610
+ print(" PASS: test_step5_4_python_identifier_validation")
611
+ test_step5_4_execution_preflight_blocking()
612
+ print(" PASS: test_step5_4_execution_preflight_blocking")
613
  print("\n" + "=" * 75)
614
+ print("ALL 16 TEST SUITES PASSED WITH ZERO FAILURES!")
615
  print("=" * 75)
616
 
617