fix: add operator arity validation to lint + enrich LLM prompt with exact arities to prevent 'Invalid number of inputs' errors"
Browse files
alpha_factory/deterministic/lint.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
"""
|
| 2 |
-
Static Lint
|
| 3 |
-
Now
|
| 4 |
-
No LLM. Pure Python. Catches 100% of mechanical failures.
|
| 5 |
"""
|
| 6 |
import re
|
| 7 |
from pathlib import Path
|
|
@@ -9,27 +8,40 @@ from ..schemas import LintResult
|
|
| 9 |
from ..data.brain_fields import FIELD_INDEX
|
| 10 |
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
def _load_operators(path: Path = Path("data/operators.csv")) -> set[str]:
|
| 13 |
-
"""Load valid operator names from operators.csv
|
| 14 |
if not path.exists():
|
| 15 |
-
|
| 16 |
-
return {
|
| 17 |
-
"abs", "bucket", "correlation", "covariance", "equal", "filter",
|
| 18 |
-
"fraction", "greater", "group_count", "group_max", "group_mean",
|
| 19 |
-
"group_median", "group_min", "group_neutralize", "group_rank",
|
| 20 |
-
"group_sum", "group_zscore", "if_else", "indneutralize", "less",
|
| 21 |
-
"log", "market_neutralize", "mask", "max", "min", "pasteurize",
|
| 22 |
-
"power", "quantile", "rank", "regression_neut", "relu", "sigmoid",
|
| 23 |
-
"sign", "sqrt", "tail", "tanh", "trade_when", "truncate",
|
| 24 |
-
"ts_argmax", "ts_argmin", "ts_av_diff", "ts_backfill",
|
| 25 |
-
"ts_correlation", "ts_covariance", "ts_decay_exp_window",
|
| 26 |
-
"ts_decay_linear", "ts_delay", "ts_delta", "ts_entropy",
|
| 27 |
-
"ts_hump", "ts_kurtosis", "ts_max", "ts_mean", "ts_min",
|
| 28 |
-
"ts_moment", "ts_product", "ts_rank", "ts_regression",
|
| 29 |
-
"ts_scale", "ts_skewness", "ts_std", "ts_step", "ts_sum",
|
| 30 |
-
"ts_zscore", "vec_avg", "vec_count", "vec_norm", "vec_sum",
|
| 31 |
-
"winsorize", "zscore",
|
| 32 |
-
}
|
| 33 |
ops = set()
|
| 34 |
with open(path) as f:
|
| 35 |
for line in f:
|
|
@@ -41,7 +53,6 @@ def _load_operators(path: Path = Path("data/operators.csv")) -> set[str]:
|
|
| 41 |
|
| 42 |
ALLOWED_OPS: set[str] | None = None
|
| 43 |
|
| 44 |
-
# Look-ahead deny patterns
|
| 45 |
LOOKAHEAD_PATTERNS = [
|
| 46 |
r"ts_delay\([^,]+,\s*-\d",
|
| 47 |
r"\bfuture_",
|
|
@@ -49,16 +60,29 @@ LOOKAHEAD_PATTERNS = [
|
|
| 49 |
r"ts_backfill\([^,]+,\s*\d{3,}",
|
| 50 |
]
|
| 51 |
|
| 52 |
-
# Unit-safety wrappers
|
| 53 |
UNIT_SAFE_WRAPPERS = {"zscore", "rank", "quantile", "group_zscore", "group_rank", "group_neutralize", "indneutralize"}
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
"
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
def lint(expression: str, operators_path: Path = Path("data/operators.csv")) -> LintResult:
|
|
@@ -75,20 +99,17 @@ def lint(expression: str, operators_path: Path = Path("data/operators.csv")) ->
|
|
| 75 |
errors.append("Expression is empty or trivially short")
|
| 76 |
return LintResult(passed=False, errors=errors, warnings=warnings)
|
| 77 |
|
| 78 |
-
# CHECK 2: Operator validity
|
| 79 |
found_ops = re.findall(r"\b([a-z_]+)\s*\(", expression.lower())
|
| 80 |
-
invalid_ops = []
|
| 81 |
for op in found_ops:
|
| 82 |
if op not in ALLOWED_OPS and op not in {"if", "and", "or", "not"}:
|
| 83 |
-
|
| 84 |
-
if invalid_ops:
|
| 85 |
-
errors.append(f"Unknown operators (not in 71-op catalog): {invalid_ops}")
|
| 86 |
|
| 87 |
# CHECK 3: Look-ahead detection
|
| 88 |
for pattern in LOOKAHEAD_PATTERNS:
|
| 89 |
match = re.search(pattern, expression, re.IGNORECASE)
|
| 90 |
if match:
|
| 91 |
-
errors.append(f"Look-ahead detected: '{match.group()}'
|
| 92 |
|
| 93 |
# CHECK 4: Balanced parentheses
|
| 94 |
depth = 0
|
|
@@ -103,7 +124,20 @@ def lint(expression: str, operators_path: Path = Path("data/operators.csv")) ->
|
|
| 103 |
if depth > 0:
|
| 104 |
errors.append(f"Unbalanced parentheses: {depth} unclosed '('")
|
| 105 |
|
| 106 |
-
# CHECK 5:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
additive_parts = re.split(r"\s*\+\s*", expression.strip())
|
| 108 |
if len(additive_parts) > 1:
|
| 109 |
for part in additive_parts:
|
|
@@ -112,45 +146,36 @@ def lint(expression: str, operators_path: Path = Path("data/operators.csv")) ->
|
|
| 112 |
if first_func:
|
| 113 |
func_name = first_func.group(1)
|
| 114 |
if func_name not in UNIT_SAFE_WRAPPERS:
|
| 115 |
-
warnings.append(
|
| 116 |
-
f"Additive operand not unit-safe: '{part_clean[:60]}...' — wrap in zscore/rank"
|
| 117 |
-
)
|
| 118 |
|
| 119 |
-
# CHECK
|
| 120 |
-
# Extract potential field references (words that aren't operators and aren't numbers)
|
| 121 |
all_words = re.findall(r"\b([a-z][a-z0-9_]+)\b", expression.lower())
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
field = FIELD_INDEX[fid]
|
| 128 |
-
if field.coverage < 0.60:
|
| 129 |
-
warnings.append(f"Field '{fid}' has low coverage ({field.coverage:.0%}) — use ts_backfill({fid}, 30)")
|
| 130 |
-
|
| 131 |
-
# CHECK 7: Decay sanity
|
| 132 |
decay_match = re.search(r"ts_decay_linear\([^,]+,\s*(\d+)", expression)
|
| 133 |
if decay_match and int(decay_match.group(1)) > 20:
|
| 134 |
warnings.append(f"Decay of {decay_match.group(1)} days is high — typical range 3-15")
|
| 135 |
|
| 136 |
-
# CHECK
|
| 137 |
for match in re.finditer(r"ts_\w+\([^,]+,\s*(\d+)", expression):
|
| 138 |
window = int(match.group(1))
|
| 139 |
if window > 252:
|
| 140 |
-
warnings.append(f"Window of {window} days > 1 year — may reduce coverage
|
| 141 |
|
| 142 |
-
# CHECK
|
| 143 |
empty_args = re.findall(r"\b[a-z_]+\(\s*,", expression.lower())
|
| 144 |
if empty_args:
|
| 145 |
errors.append(f"Empty first argument detected: {empty_args}")
|
| 146 |
-
|
| 147 |
empty_func = re.findall(r"\b[a-z_]+\(\s*\)", expression.lower())
|
| 148 |
if empty_func:
|
| 149 |
errors.append(f"Function called with no arguments: {empty_func}")
|
| 150 |
|
| 151 |
-
# CHECK
|
| 152 |
if "ts_decay_linear" not in expression.lower():
|
| 153 |
-
warnings.append("No ts_decay_linear found — turnover may exceed 70%
|
| 154 |
|
| 155 |
return LintResult(
|
| 156 |
passed=len(errors) == 0,
|
|
@@ -160,12 +185,10 @@ def lint(expression: str, operators_path: Path = Path("data/operators.csv")) ->
|
|
| 160 |
|
| 161 |
|
| 162 |
def quick_dedup_hash(expression: str, neutralization: str, decay: int) -> str:
|
| 163 |
-
"""Generate a deterministic hash for dedup against factor store."""
|
| 164 |
import hashlib
|
| 165 |
key = f"{expression.strip()}|{neutralization}|{decay}"
|
| 166 |
return hashlib.sha256(key.encode()).hexdigest()[:16]
|
| 167 |
|
| 168 |
|
| 169 |
def validate_field_exists(field_id: str) -> bool:
|
| 170 |
-
"""Check if a field ID exists in the canonical registry."""
|
| 171 |
return field_id in FIELD_INDEX
|
|
|
|
| 1 |
"""
|
| 2 |
+
Static Lint v3 — Layer 2: Deterministic pre-flight checks.
|
| 3 |
+
Now validates operator ARITY (argument count) to catch 'Invalid number of inputs' errors.
|
|
|
|
| 4 |
"""
|
| 5 |
import re
|
| 6 |
from pathlib import Path
|
|
|
|
| 8 |
from ..data.brain_fields import FIELD_INDEX
|
| 9 |
|
| 10 |
|
| 11 |
+
# Operator → required number of arguments (minimum)
|
| 12 |
+
OPERATOR_ARITY: dict[str, int] = {
|
| 13 |
+
# 1-argument operators
|
| 14 |
+
"rank": 1, "zscore": 1, "quantile": 1, "abs": 1, "log": 1,
|
| 15 |
+
"sign": 1, "sqrt": 1, "sigmoid": 1, "tanh": 1, "relu": 1,
|
| 16 |
+
"pasteurize": 1, "truncate": 1, "fraction": 1,
|
| 17 |
+
"vec_avg": 1, "vec_sum": 1, "vec_norm": 1, "vec_count": 1,
|
| 18 |
+
# 2-argument operators
|
| 19 |
+
"ts_mean": 2, "ts_std": 2, "ts_sum": 2, "ts_min": 2, "ts_max": 2,
|
| 20 |
+
"ts_rank": 2, "ts_zscore": 2, "ts_delta": 2, "ts_delay": 2,
|
| 21 |
+
"ts_decay_linear": 2, "ts_argmax": 2, "ts_argmin": 2,
|
| 22 |
+
"ts_skewness": 2, "ts_kurtosis": 2, "ts_entropy": 2,
|
| 23 |
+
"ts_product": 2, "ts_moment": 2, "ts_av_diff": 2,
|
| 24 |
+
"ts_hump": 2, "ts_scale": 2, "ts_step": 2,
|
| 25 |
+
"ts_decay_exp_window": 2, "ts_backfill": 2,
|
| 26 |
+
"group_neutralize": 2, "group_rank": 2, "group_zscore": 2,
|
| 27 |
+
"group_mean": 2, "group_sum": 2, "group_median": 2,
|
| 28 |
+
"group_max": 2, "group_min": 2, "group_count": 2,
|
| 29 |
+
"indneutralize": 2, "market_neutralize": 2,
|
| 30 |
+
"power": 2, "max": 2, "min": 2, "winsorize": 2,
|
| 31 |
+
"less": 2, "greater": 2, "equal": 2,
|
| 32 |
+
"bucket": 2, "tail": 2, "mask": 2, "filter": 2,
|
| 33 |
+
# 3-argument operators
|
| 34 |
+
"ts_correlation": 3, "ts_covariance": 3,
|
| 35 |
+
"if_else": 3, "trade_when": 3,
|
| 36 |
+
# Variable (3+)
|
| 37 |
+
"ts_regression": 3,
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
def _load_operators(path: Path = Path("data/operators.csv")) -> set[str]:
|
| 42 |
+
"""Load valid operator names from operators.csv."""
|
| 43 |
if not path.exists():
|
| 44 |
+
return set(OPERATOR_ARITY.keys())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
ops = set()
|
| 46 |
with open(path) as f:
|
| 47 |
for line in f:
|
|
|
|
| 53 |
|
| 54 |
ALLOWED_OPS: set[str] | None = None
|
| 55 |
|
|
|
|
| 56 |
LOOKAHEAD_PATTERNS = [
|
| 57 |
r"ts_delay\([^,]+,\s*-\d",
|
| 58 |
r"\bfuture_",
|
|
|
|
| 60 |
r"ts_backfill\([^,]+,\s*\d{3,}",
|
| 61 |
]
|
| 62 |
|
|
|
|
| 63 |
UNIT_SAFE_WRAPPERS = {"zscore", "rank", "quantile", "group_zscore", "group_rank", "group_neutralize", "indneutralize"}
|
| 64 |
|
| 65 |
+
|
| 66 |
+
def _count_args(expression: str, start_pos: int) -> int:
|
| 67 |
+
"""Count arguments of a function call starting at the opening paren."""
|
| 68 |
+
depth = 0
|
| 69 |
+
arg_count = 1 # At least 1 if there's any content
|
| 70 |
+
i = start_pos
|
| 71 |
+
has_content = False
|
| 72 |
+
while i < len(expression):
|
| 73 |
+
ch = expression[i]
|
| 74 |
+
if ch == '(':
|
| 75 |
+
depth += 1
|
| 76 |
+
elif ch == ')':
|
| 77 |
+
depth -= 1
|
| 78 |
+
if depth == 0:
|
| 79 |
+
return arg_count if has_content else 0
|
| 80 |
+
elif ch == ',' and depth == 1:
|
| 81 |
+
arg_count += 1
|
| 82 |
+
elif ch not in ' \t\n' and depth == 1:
|
| 83 |
+
has_content = True
|
| 84 |
+
i += 1
|
| 85 |
+
return arg_count if has_content else 0
|
| 86 |
|
| 87 |
|
| 88 |
def lint(expression: str, operators_path: Path = Path("data/operators.csv")) -> LintResult:
|
|
|
|
| 99 |
errors.append("Expression is empty or trivially short")
|
| 100 |
return LintResult(passed=False, errors=errors, warnings=warnings)
|
| 101 |
|
| 102 |
+
# CHECK 2: Operator validity
|
| 103 |
found_ops = re.findall(r"\b([a-z_]+)\s*\(", expression.lower())
|
|
|
|
| 104 |
for op in found_ops:
|
| 105 |
if op not in ALLOWED_OPS and op not in {"if", "and", "or", "not"}:
|
| 106 |
+
errors.append(f"Unknown operator: '{op}' — not in 71-op catalog")
|
|
|
|
|
|
|
| 107 |
|
| 108 |
# CHECK 3: Look-ahead detection
|
| 109 |
for pattern in LOOKAHEAD_PATTERNS:
|
| 110 |
match = re.search(pattern, expression, re.IGNORECASE)
|
| 111 |
if match:
|
| 112 |
+
errors.append(f"Look-ahead detected: '{match.group()}'")
|
| 113 |
|
| 114 |
# CHECK 4: Balanced parentheses
|
| 115 |
depth = 0
|
|
|
|
| 124 |
if depth > 0:
|
| 125 |
errors.append(f"Unbalanced parentheses: {depth} unclosed '('")
|
| 126 |
|
| 127 |
+
# CHECK 5: Operator ARITY validation (catches "Invalid number of inputs")
|
| 128 |
+
for match in re.finditer(r"\b([a-z_]+)\s*\(", expression.lower()):
|
| 129 |
+
op_name = match.group(1)
|
| 130 |
+
if op_name in OPERATOR_ARITY:
|
| 131 |
+
expected_min = OPERATOR_ARITY[op_name]
|
| 132 |
+
paren_start = match.end() - 1 # position of '('
|
| 133 |
+
actual_args = _count_args(expression.lower(), paren_start)
|
| 134 |
+
if actual_args < expected_min:
|
| 135 |
+
errors.append(
|
| 136 |
+
f"Arity error: '{op_name}' requires {expected_min} args, got {actual_args}. "
|
| 137 |
+
f"Example: {op_name}(field, days)" if expected_min == 2 else f"Example: {op_name}(x, y, z)"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# CHECK 6: Unit-safety for additive expressions
|
| 141 |
additive_parts = re.split(r"\s*\+\s*", expression.strip())
|
| 142 |
if len(additive_parts) > 1:
|
| 143 |
for part in additive_parts:
|
|
|
|
| 146 |
if first_func:
|
| 147 |
func_name = first_func.group(1)
|
| 148 |
if func_name not in UNIT_SAFE_WRAPPERS:
|
| 149 |
+
warnings.append(f"Additive operand not unit-safe: '{part_clean[:60]}...' — wrap in zscore/rank")
|
|
|
|
|
|
|
| 150 |
|
| 151 |
+
# CHECK 7: Field coverage validation
|
|
|
|
| 152 |
all_words = re.findall(r"\b([a-z][a-z0-9_]+)\b", expression.lower())
|
| 153 |
+
for fid in all_words:
|
| 154 |
+
if fid in FIELD_INDEX and FIELD_INDEX[fid].coverage < 0.60:
|
| 155 |
+
warnings.append(f"Field '{fid}' has low coverage ({FIELD_INDEX[fid].coverage:.0%}) — use ts_backfill({fid}, 30)")
|
| 156 |
+
|
| 157 |
+
# CHECK 8: Decay sanity
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
decay_match = re.search(r"ts_decay_linear\([^,]+,\s*(\d+)", expression)
|
| 159 |
if decay_match and int(decay_match.group(1)) > 20:
|
| 160 |
warnings.append(f"Decay of {decay_match.group(1)} days is high — typical range 3-15")
|
| 161 |
|
| 162 |
+
# CHECK 9: Very long lookback
|
| 163 |
for match in re.finditer(r"ts_\w+\([^,]+,\s*(\d+)", expression):
|
| 164 |
window = int(match.group(1))
|
| 165 |
if window > 252:
|
| 166 |
+
warnings.append(f"Window of {window} days > 1 year — may reduce coverage")
|
| 167 |
|
| 168 |
+
# CHECK 10: Empty arguments
|
| 169 |
empty_args = re.findall(r"\b[a-z_]+\(\s*,", expression.lower())
|
| 170 |
if empty_args:
|
| 171 |
errors.append(f"Empty first argument detected: {empty_args}")
|
|
|
|
| 172 |
empty_func = re.findall(r"\b[a-z_]+\(\s*\)", expression.lower())
|
| 173 |
if empty_func:
|
| 174 |
errors.append(f"Function called with no arguments: {empty_func}")
|
| 175 |
|
| 176 |
+
# CHECK 11: Turnover guard
|
| 177 |
if "ts_decay_linear" not in expression.lower():
|
| 178 |
+
warnings.append("No ts_decay_linear found — turnover may exceed 70%")
|
| 179 |
|
| 180 |
return LintResult(
|
| 181 |
passed=len(errors) == 0,
|
|
|
|
| 185 |
|
| 186 |
|
| 187 |
def quick_dedup_hash(expression: str, neutralization: str, decay: int) -> str:
|
|
|
|
| 188 |
import hashlib
|
| 189 |
key = f"{expression.strip()}|{neutralization}|{decay}"
|
| 190 |
return hashlib.sha256(key.encode()).hexdigest()[:16]
|
| 191 |
|
| 192 |
|
| 193 |
def validate_field_exists(field_id: str) -> bool:
|
|
|
|
| 194 |
return field_id in FIELD_INDEX
|