@davoodmehraban89 / Aram-1 / commits / 9fba3c6
Fork 0

feat(notes): safe formula grammar + note engine (Phase 3)

- domain/formula: hand-written tokenizer + recursive-descent parser -> whitelisted AST, exact Decimal evaluation; NO eval/exec (P-05); unknown tokens/functions fail closed; division-by-zero rejected; mypy --strict clean - services/note_engine: evaluate disclosure rows from latest ledger import; acct/ row/note/sum/abs functions; earlier-row + cross-note references with cycle detection; per-row referenced accounts for drill-down - statement_api: note-row create (formula validated on create), list, evaluate - ADR-020 formula grammar (mandatory pre-code ADR) Tests: 22 formula parse/eval/safety cases (injection rejected), note engine account/subtotal/cross-note/circular/forward-ref/unknown-account, API create+ evaluate+invalid-formula rejection. 250 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 10:00 UTC 9fba3c69aee253f7598a2e00b9a2b00631201b7a
6 files changed +697
backend/src/aram_backend/domain/formula.py new
+213
@@ -0,0 +1,213 @@
1 +"""Safe note formula grammar (Phase 3, ADR-020, P-05: no eval/exec).
2 +
3 +A hand-written tokenizer + recursive-descent parser produces a whitelisted AST
4 +that is evaluated with exact Decimal. Unknown tokens/functions fail closed.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +import re
10 +from collections.abc import Callable
11 +from dataclasses import dataclass
12 +from decimal import Decimal, DivisionByZero, InvalidOperation
13 +
14 +_ZERO = Decimal(0)
15 +
16 +
17 +class FormulaError(ValueError):
18 + """Raised when a formula cannot be parsed or evaluated safely."""
19 +
20 +
21 +# --------------------------------------------------------------------------- AST
22 +@dataclass(frozen=True)
23 +class Num:
24 + value: Decimal
25 +
26 +
27 +@dataclass(frozen=True)
28 +class Str:
29 + value: str
30 +
31 +
32 +@dataclass(frozen=True)
33 +class Unary:
34 + op: str
35 + operand: object
36 +
37 +
38 +@dataclass(frozen=True)
39 +class Binary:
40 + op: str
41 + left: object
42 + right: object
43 +
44 +
45 +@dataclass(frozen=True)
46 +class Call:
47 + name: str
48 + args: tuple[object, ...]
49 +
50 +
51 +# ------------------------------------------------------------------- tokenizer
52 +_TOKEN_RE = re.compile(
53 + r"""
54 + (?P<NUMBER>\d+(?:\.\d+)?)
55 + | (?P<STRING>"[^"]*")
56 + | (?P<IDENT>[A-Za-z_][A-Za-z_0-9]*)
57 + | (?P<OP>[+\-*/(),])
58 + | (?P<WS>\s+)
59 + """,
60 + re.VERBOSE,
61 +)
62 +
63 +
64 +def _tokenize(text: str) -> list[tuple[str, str]]:
65 + tokens: list[tuple[str, str]] = []
66 + pos = 0
67 + while pos < len(text):
68 + match = _TOKEN_RE.match(text, pos)
69 + if match is None:
70 + raise FormulaError(f"illegal character at position {pos}: {text[pos]!r}")
71 + kind = match.lastgroup
72 + value = match.group()
73 + pos = match.end()
74 + if kind == "WS":
75 + continue
76 + assert kind is not None
77 + tokens.append((kind, value))
78 + return tokens
79 +
80 +
81 +# ---------------------------------------------------------------------- parser
82 +class _Parser:
83 + def __init__(self, tokens: list[tuple[str, str]]) -> None:
84 + self._tokens = tokens
85 + self._pos = 0
86 +
87 + def _peek(self) -> tuple[str, str] | None:
88 + return self._tokens[self._pos] if self._pos < len(self._tokens) else None
89 +
90 + def _next(self) -> tuple[str, str]:
91 + token = self._peek()
92 + if token is None:
93 + raise FormulaError("unexpected end of formula")
94 + self._pos += 1
95 + return token
96 +
97 + def _peek_value(self) -> str | None:
98 + token = self._peek()
99 + return token[1] if token is not None else None
100 +
101 + def parse(self) -> object:
102 + node = self._expr()
103 + if self._peek() is not None:
104 + raise FormulaError(f"unexpected token {self._peek_value()!r}")
105 + return node
106 +
107 + def _expr(self) -> object:
108 + node = self._term()
109 + while self._peek_value() in ("+", "-"):
110 + op = self._next()[1]
111 + node = Binary(op, node, self._term())
112 + return node
113 +
114 + def _term(self) -> object:
115 + node = self._factor()
116 + while self._peek_value() in ("*", "/"):
117 + op = self._next()[1]
118 + node = Binary(op, node, self._factor())
119 + return node
120 +
121 + def _factor(self) -> object:
122 + token = self._peek()
123 + if token is None:
124 + raise FormulaError("unexpected end of formula")
125 + kind, value = token
126 + if value in ("+", "-"):
127 + self._next()
128 + return Unary(value, self._factor())
129 + if value == "(":
130 + self._next()
131 + node = self._expr()
132 + if self._next()[1] != ")":
133 + raise FormulaError("expected ')'")
134 + return node
135 + if kind == "NUMBER":
136 + self._next()
137 + return Num(Decimal(value))
138 + if kind == "STRING":
139 + self._next()
140 + return Str(value[1:-1])
141 + if kind == "IDENT":
142 + self._next()
143 + if self._peek_value() != "(":
144 + raise FormulaError(f"unknown name {value!r}; only function calls are allowed")
145 + self._next() # consume '('
146 + args: list[object] = []
147 + if self._peek_value() not in (None, ")"):
148 + args.append(self._expr())
149 + while self._peek_value() == ",":
150 + self._next()
151 + args.append(self._expr())
152 + if self._next()[1] != ")":
153 + raise FormulaError("expected ')' after arguments")
154 + return Call(value, tuple(args))
155 + raise FormulaError(f"unexpected token {value!r}")
156 +
157 +
158 +def parse_formula(text: str) -> object:
159 + if not text or not text.strip():
160 + raise FormulaError("formula is empty")
161 + return _Parser(_tokenize(text)).parse()
162 +
163 +
164 +# -------------------------------------------------------------------- evaluator
165 +Resolver = Callable[[str, tuple[object, ...]], Decimal]
166 +
167 +
168 +def evaluate(node: object, resolver: Resolver) -> Decimal:
169 + if isinstance(node, Num):
170 + return node.value
171 + if isinstance(node, Unary):
172 + operand = evaluate(node.operand, resolver)
173 + return -operand if node.op == "-" else operand
174 + if isinstance(node, Binary):
175 + left = evaluate(node.left, resolver)
176 + right = evaluate(node.right, resolver)
177 + if node.op == "+":
178 + return left + right
179 + if node.op == "-":
180 + return left - right
181 + if node.op == "*":
182 + return left * right
183 + if node.op == "/":
184 + if right == _ZERO:
185 + raise FormulaError("division by zero")
186 + try:
187 + return left / right
188 + except (DivisionByZero, InvalidOperation) as exc:
189 + raise FormulaError("division is not exact") from exc
190 + raise FormulaError(f"unknown operator {node.op!r}")
191 + if isinstance(node, Call):
192 + args = tuple(
193 + arg.value if isinstance(arg, Str) else evaluate(arg, resolver) for arg in node.args
194 + )
195 + return resolver(node.name, args)
196 + raise FormulaError(f"unsupported node {type(node).__name__}")
197 +
198 +
199 +def eval_formula(text: str, resolver: Resolver) -> Decimal:
200 + return evaluate(parse_formula(text), resolver)
201 +
202 +
203 +__all__ = [
204 + "FormulaError",
205 + "parse_formula",
206 + "evaluate",
207 + "eval_formula",
208 + "Num",
209 + "Str",
210 + "Unary",
211 + "Binary",
212 + "Call",
213 +]
backend/src/aram_backend/services/note_engine.py new
+168
@@ -0,0 +1,168 @@
1 +"""Note engine (Phase 3, ADR-020): evaluate disclosure-row formulas safely.
2 +
3 +Computes note row values on demand from the latest ledger import using the safe
4 +formula grammar (no eval). Rows may reference earlier rows and other notes; cross
5 +note references are cycle-detected. Each row reports the accounts it references
6 +for drill-down.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from decimal import Decimal
12 +
13 +from sqlalchemy import func, select
14 +from sqlalchemy.orm import Session
15 +
16 +from aram_backend.domain.formula import Call, FormulaError, eval_formula, parse_formula
17 +from aram_backend.models import LedgerBalance, NoteDefinition
18 +
19 +_ZERO = Decimal(0)
20 +_FIELDS = {"opening", "debit", "credit", "closing"}
21 +
22 +
23 +class NoteEngineError(ValueError):
24 + """Raised when a note cannot be evaluated."""
25 +
26 +
27 +def _balances(session: Session, year_id: int) -> dict[str, LedgerBalance]:
28 + version = session.scalar(
29 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
30 + )
31 + if version is None:
32 + return {}
33 + rows = session.scalars(
34 + select(LedgerBalance).where(
35 + LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
36 + )
37 + ).all()
38 + return {b.account_full_code: b for b in rows}
39 +
40 +
41 +def _referenced_accounts(node: object) -> set[str]:
42 + found: set[str] = set()
43 + if isinstance(node, Call):
44 + if node.name == "acct" and node.args and hasattr(node.args[0], "value"):
45 + found.add(node.args[0].value)
46 + for arg in node.args:
47 + found |= _referenced_accounts(arg)
48 + elif hasattr(node, "left"):
49 + found |= _referenced_accounts(node.left) | _referenced_accounts(node.right)
50 + elif hasattr(node, "operand"):
51 + found |= _referenced_accounts(node.operand)
52 + return found
53 +
54 +
55 +def evaluate_note(
56 + session: Session,
57 + note_id: int,
58 + *,
59 + _stack: tuple[int, ...] = (),
60 + _cache: dict[int, dict] | None = None,
61 +) -> dict:
62 + if _cache is not None and note_id in _cache:
63 + return _cache[note_id]
64 + if note_id in _stack:
65 + raise NoteEngineError(f"circular note reference involving note {note_id}")
66 + note = session.get(NoteDefinition, note_id)
67 + if note is None:
68 + raise NoteEngineError(f"note {note_id} does not exist")
69 +
70 + balances = _balances(session, note.year_id)
71 + rows = sorted(note.rows, key=lambda r: r.row_order)
72 + values: dict[int, Decimal] = {}
73 + stack = _stack + (note_id,)
74 + cache = _cache if _cache is not None else {}
75 +
76 + def _other_note_row(note_number: str, row_order: int) -> Decimal:
77 + other = session.scalar(
78 + select(NoteDefinition)
79 + .where(
80 + NoteDefinition.year_id == note.year_id, NoteDefinition.note_number == note_number
81 + )
82 + .order_by(NoteDefinition.version.desc())
83 + .limit(1)
84 + )
85 + if other is None:
86 + raise FormulaError(f"note '{note_number}' not found")
87 + result = evaluate_note(session, other.id, _stack=stack, _cache=cache)
88 + for row in result["rows"]:
89 + if row["row_order"] == row_order:
90 + return Decimal(row["value"])
91 + raise FormulaError(f"note '{note_number}' has no row {row_order}")
92 +
93 + def resolver(name: str, args: tuple) -> Decimal:
94 + if name == "acct":
95 + if not args or not isinstance(args[0], str):
96 + raise FormulaError("acct() requires an account code string")
97 + field = args[1] if len(args) > 1 else "closing"
98 + if field not in _FIELDS:
99 + raise FormulaError(f"unknown account field '{field}'")
100 + balance = balances.get(args[0])
101 + if balance is None:
102 + raise FormulaError(f"account '{args[0]}' not found in the latest import")
103 + return getattr(balance, field)
104 + if name == "row":
105 + if not args:
106 + raise FormulaError("row() requires a row order")
107 + order = int(args[0])
108 + if order not in values:
109 + raise FormulaError(f"row {order} is not an earlier computed row")
110 + return values[order]
111 + if name == "note":
112 + if len(args) < 2 or not isinstance(args[0], str):
113 + raise FormulaError("note() requires a note number and row order")
114 + return _other_note_row(args[0], int(args[1]))
115 + if name == "sum":
116 + return sum((Decimal(a) for a in args), _ZERO)
117 + if name == "abs":
118 + if len(args) != 1:
119 + raise FormulaError("abs() requires one argument")
120 + return abs(Decimal(args[0]))
121 + raise FormulaError(f"unknown function '{name}'")
122 +
123 + out_rows = []
124 + for row in rows:
125 + referenced: set[str] = set()
126 + if row.formula_logic:
127 + try:
128 + ast = parse_formula(row.formula_logic)
129 + referenced = _referenced_accounts(ast)
130 + value = eval_formula(row.formula_logic, resolver)
131 + except FormulaError as exc:
132 + raise NoteEngineError(
133 + f"note {note.note_number} row {row.row_order}: {exc}"
134 + ) from exc
135 + else:
136 + value = _ZERO
137 + values[row.row_order] = value
138 + out_rows.append(
139 + {
140 + "row_order": row.row_order,
141 + "label": row.label,
142 + "formula": row.formula_logic,
143 + "value": str(value),
144 + "accounts_referenced": sorted(referenced),
145 + }
146 + )
147 +
148 + result = {
149 + "note_id": note.id,
150 + "note_number": note.note_number,
151 + "title": note.title,
152 + "rows": out_rows,
153 + }
154 + cache[note_id] = result
155 + return result
156 +
157 +
158 +def evaluate_year_notes(session: Session, year_id: int) -> list[dict]:
159 + notes = session.scalars(
160 + select(NoteDefinition)
161 + .where(NoteDefinition.year_id == year_id)
162 + .order_by(NoteDefinition.note_number)
163 + ).all()
164 + cache: dict[int, dict] = {}
165 + return [evaluate_note(session, note.id, _cache=cache) for note in notes]
166 +
167 +
168 +__all__ = ["evaluate_note", "evaluate_year_notes", "NoteEngineError"]
backend/src/aram_backend/statement_api.py
+58
@@ -25,6 +25,7 @@ from aram_backend.models import (
25 LedgerBalance,
26 MappingRule,
27 NoteDefinition,
28 + NoteRow,
29 StatementLine,
30 )
31 from aram_backend.services.approval import ApprovalError, approve_year
@@ -39,6 +40,7 @@ from aram_backend.services.mapping_workflow import (
40 carry_forward_mappings,
41 unknown_accounts,
42 )
43 +from aram_backend.services.note_engine import NoteEngineError, evaluate_note
44 from aram_backend.services.source_store import SourceStore, SourceStoreError
45 from aram_backend.services.statement_build import (
46 SECTION_LABELS_FA,
@@ -363,3 +365,59 @@ def approve(year_id: int, body: ApproveIn, session: Session = Depends(get_sessio
365 }
366 session.commit()
367 return {"approved": True, "status": "Approved"}
368 +
369 +
370 +# ----------------------------------------------------------- Phase 3: note engine
371 +class NoteRowIn(BaseModel):
372 + row_order: int = Field(ge=0)
373 + label: str = Field(min_length=1, max_length=512)
374 + formula_logic: str | None = Field(default=None, max_length=2000)
375 +
376 +
377 +@router.post("/years/{year_id}/notes/{note_id}/rows")
378 +def create_note_row(
379 + year_id: int, note_id: int, body: NoteRowIn, session: Session = Depends(get_session)
380 +) -> dict:
381 + _year_or_404(session, year_id)
382 + note = session.get(NoteDefinition, note_id)
383 + if note is None or note.year_id != year_id:
384 + raise HTTPException(status_code=404, detail="note not found in this year")
385 + if body.formula_logic:
386 + from aram_backend.domain.formula import FormulaError, parse_formula
387 +
388 + try:
389 + parse_formula(body.formula_logic)
390 + except FormulaError as exc:
391 + raise HTTPException(status_code=422, detail=f"invalid formula: {exc}") from exc
392 + row = NoteRow(
393 + note_id=note_id,
394 + row_order=body.row_order,
395 + label=body.label,
396 + formula_logic=body.formula_logic,
397 + )
398 + session.add(row)
399 + session.commit()
400 + return {"row_id": row.id, "row_order": row.row_order}
401 +
402 +
403 +@router.get("/notes/{note_id}/rows")
404 +def list_note_rows(note_id: int, session: Session = Depends(get_session)) -> dict:
405 + note = session.get(NoteDefinition, note_id)
406 + if note is None:
407 + raise HTTPException(status_code=404, detail="note not found")
408 + rows = sorted(note.rows, key=lambda r: r.row_order)
409 + return {
410 + "note_id": note.id,
411 + "rows": [
412 + {"row_order": r.row_order, "label": r.label, "formula_logic": r.formula_logic}
413 + for r in rows
414 + ],
415 + }
416 +
417 +
418 +@router.get("/notes/{note_id}/evaluate")
419 +def evaluate_note_endpoint(note_id: int, session: Session = Depends(get_session)) -> dict:
420 + try:
421 + return evaluate_note(session, note_id)
422 + except NoteEngineError as exc:
423 + raise HTTPException(status_code=422, detail=str(exc)) from exc
backend/tests/test_formula.py new
+78
@@ -0,0 +1,78 @@
1 +"""Phase 3: safe formula grammar (ADR-020) — parsing, evaluation, and safety."""
2 +
3 +from __future__ import annotations
4 +
5 +from decimal import Decimal
6 +
7 +import pytest
8 +
9 +from aram_backend.domain.formula import FormulaError, eval_formula
10 +
11 +
12 +def _resolver(name, args):
13 + if name == "acct":
14 + return Decimal(100)
15 + if name == "sum":
16 + return sum((Decimal(a) for a in args), Decimal(0))
17 + if name == "abs":
18 + return abs(Decimal(args[0]))
19 + if name == "row":
20 + return Decimal(int(args[0])) * 10
21 + raise FormulaError(f"unknown function {name}")
22 +
23 +
24 +@pytest.mark.parametrize(
25 + ("formula", "expected"),
26 + [
27 + ("1 + 2 * 3", Decimal(7)),
28 + ("(1 + 2) * 3", Decimal(9)),
29 + ("-5 + 3", Decimal(-2)),
30 + ("1.5 + 2.5", Decimal(4)),
31 + ("10 / 2", Decimal(5)),
32 + ("sum(1, 2, 3)", Decimal(6)),
33 + ("abs(-5)", Decimal(5)),
34 + ('acct("148348")', Decimal(100)),
35 + ("row(3)", Decimal(30)),
36 + ('sum(acct("148348"), 5)', Decimal(105)),
37 + ],
38 +)
39 +def test_evaluates(formula, expected):
40 + assert eval_formula(formula, _resolver) == expected
41 +
42 +
43 +@pytest.mark.parametrize(
44 + "formula",
45 + [
46 + "",
47 + " ",
48 + "1 @ 2",
49 + "foo",
50 + "1 +",
51 + "(1 + 2",
52 + "1 / 0",
53 + "__import__('os')",
54 + 'acct("x"); import os',
55 + "1 .. 2",
56 + ],
57 +)
58 +def test_rejects_unsafe_or_invalid(formula):
59 + with pytest.raises(FormulaError):
60 + eval_formula(formula, _resolver)
61 +
62 +
63 +def test_unknown_function_fails_closed():
64 + with pytest.raises(FormulaError):
65 + eval_formula('evil("x")', _resolver)
66 +
67 +
68 +def test_string_literal_passed_to_resolver():
69 + seen = {}
70 +
71 + def resolver(name, args):
72 + seen["name"] = name
73 + seen["args"] = args
74 + return Decimal(0)
75 +
76 + eval_formula('acct("148348", "debit")', resolver)
77 + assert seen["name"] == "acct"
78 + assert seen["args"] == ("148348", "debit")
backend/tests/test_note_engine.py new
+124
@@ -0,0 +1,124 @@
1 +"""Phase 3 acceptance: note engine evaluates formulas against real balances."""
2 +
3 +from __future__ import annotations
4 +
5 +import pytest
6 +
7 +from aram_backend.models import NoteRow
8 +from aram_backend.services.note_engine import NoteEngineError, evaluate_note, evaluate_year_notes
9 +from test_statement_build import _balance, _note, _setup
10 +
11 +
12 +def _row(session, note, order, label, formula):
13 + r = NoteRow(note_id=note.id, row_order=order, label=label, formula_logic=formula)
14 + session.add(r)
15 + session.flush()
16 + return r
17 +
18 +
19 +def _seed(session):
20 + year, source = _setup(session)
21 + _balance(session, year, source, "148348", 100, 3)
22 + _balance(session, year, source, "241001", -60, 4)
23 + session.flush()
24 + return year
25 +
26 +
27 +class TestNoteEngine:
28 + def test_rows_with_account_and_subtotal(self, session):
29 + year = _seed(session)
30 + note = _note(session, year, "6", "نقد", "BS", "Assets")
31 + _row(session, note, 0, "حساب نقد", 'acct("148348")')
32 + _row(session, note, 1, "پرداختنی", 'acct("241001")')
33 + _row(session, note, 2, "جمع", "sum(row(0), row(1))")
34 + session.flush()
35 + result = evaluate_note(session, note.id)
36 + values = [r["value"] for r in result["rows"]]
37 + assert values == ["100", "-60", "40"]
38 + assert result["rows"][0]["accounts_referenced"] == ["148348"]
39 +
40 + def test_cross_note_reference(self, session):
41 + year = _seed(session)
42 + n6 = _note(session, year, "6", "نقد", "BS", "Assets")
43 + _row(session, n6, 0, "نقد", 'acct("148348")')
44 + n7 = _note(session, year, "7", "مشتق", "BS", "Assets")
45 + _row(session, n7, 0, "مشتق", 'note("6", 0) + 5')
46 + session.flush()
47 + result = evaluate_note(session, n7.id)
48 + assert result["rows"][0]["value"] == "105"
49 +
50 + def test_circular_reference_detected(self, session):
51 + year = _seed(session)
52 + n6 = _note(session, year, "6", "الف", "BS", "Assets")
53 + _row(session, n6, 0, "a", 'note("7", 0)')
54 + n7 = _note(session, year, "7", "ب", "BS", "Assets")
55 + _row(session, n7, 0, "b", 'note("6", 0)')
56 + session.flush()
57 + with pytest.raises(NoteEngineError, match="circular"):
58 + evaluate_note(session, n6.id)
59 +
60 + def test_forward_row_reference_rejected(self, session):
61 + year = _seed(session)
62 + note = _note(session, year, "6", "نقد", "BS", "Assets")
63 + _row(session, note, 0, "bad", "row(1)")
64 + _row(session, note, 1, "x", 'acct("148348")')
65 + session.flush()
66 + with pytest.raises(NoteEngineError):
67 + evaluate_note(session, note.id)
68 +
69 + def test_unknown_account_rejected(self, session):
70 + year = _seed(session)
71 + note = _note(session, year, "6", "نقد", "BS", "Assets")
72 + _row(session, note, 0, "bad", 'acct("999999")')
73 + session.flush()
74 + with pytest.raises(NoteEngineError):
75 + evaluate_note(session, note.id)
76 +
77 + def test_evaluate_year_notes(self, session):
78 + year = _seed(session)
79 + note = _note(session, year, "6", "نقد", "BS", "Assets")
80 + _row(session, note, 0, "نقد", 'acct("148348")')
81 + session.flush()
82 + results = evaluate_year_notes(session, year.id)
83 + assert len(results) == 1
84 + assert results[0]["rows"][0]["value"] == "100"
85 +
86 +
87 +class TestNoteEngineApi:
88 + def test_create_rows_and_evaluate(self, api_client):
89 + c = api_client
90 + year_id = c.post(
91 + "/api/v1/companies", json={"code": "N3", "name": "x", "year": 1404}
92 + ).json()["year_id"]
93 + csv = (
94 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
95 + "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
96 + ).encode()
97 + c.post(f"/api/v1/years/{year_id}/ledger", files={"file": ("l.csv", csv, "text/csv")})
98 + note_id = c.post(
99 + f"/api/v1/years/{year_id}/notes",
100 + json={"note_number": "6", "title": "نقد", "statement": "BS", "section": "Assets"},
101 + ).json()["note_id"]
102 + r = c.post(
103 + f"/api/v1/years/{year_id}/notes/{note_id}/rows",
104 + json={"row_order": 0, "label": "نقد", "formula_logic": 'acct("148348")'},
105 + )
106 + assert r.status_code == 200, r.text
107 + r = c.get(f"/api/v1/notes/{note_id}/evaluate")
108 + assert r.status_code == 200, r.text
109 + assert r.json()["rows"][0]["value"] == "100"
110 +
111 + def test_invalid_formula_rejected_on_create(self, api_client):
112 + c = api_client
113 + year_id = c.post(
114 + "/api/v1/companies", json={"code": "N4", "name": "x", "year": 1404}
115 + ).json()["year_id"]
116 + note_id = c.post(
117 + f"/api/v1/years/{year_id}/notes",
118 + json={"note_number": "6", "title": "نقد", "statement": "BS", "section": "Assets"},
119 + ).json()["note_id"]
120 + r = c.post(
121 + f"/api/v1/years/{year_id}/notes/{note_id}/rows",
122 + json={"row_order": 0, "label": "bad", "formula_logic": "__import__('os')"},
123 + )
124 + assert r.status_code == 422
docs/adr/ADR-020-formula-grammar.md new
+56
@@ -0,0 +1,56 @@
1 +# ADR-020 — Safe note formula grammar (Phase 3)
2 +
3 +- Status: Accepted (Phase 3)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 3, P-05 (no eval of formulas), §7
6 +
7 +## Context
8 +
9 +Disclosure notes contain computed rows (subtotals, sums, derived figures). The
10 +booklet forbids `eval`/`exec` of user formulas. We need a small, deterministic,
11 +safe expression language that can reference account balances and other note rows.
12 +
13 +## Decision
14 +
15 +A restricted grammar parsed by a hand-written tokenizer + recursive-descent parser
16 +into a whitelisted AST, evaluated with exact `Decimal`. **No `eval`, `exec`,
17 +attribute access, imports, or arbitrary names.** Any unknown token/function fails
18 +closed with `FormulaError`.
19 +
20 +### Grammar (EBNF)
21 +
22 +```
23 +expr := term (('+' | '-') term)*
24 +term := factor (('*' | '/') factor)*
25 +factor := NUMBER | STRING | '(' expr ')' | ('-' | '+') factor | call
26 +call := IDENT '(' [expr (',' expr)*] ')'
27 +```
28 +
29 +### Allowed functions
30 +
31 +| Call | Meaning |
32 +|---|---|
33 +| `acct("code")` | closing balance of account (debit-positive, ADR-013) |
34 +| `acct("code", "opening"\|"debit"\|"credit"\|"closing")` | selected field |
35 +| `row(n)` | value of row `n` in the current note (must be earlier row) |
36 +| `note("6", n)` | value of row `n` in note `6` |
37 +| `sum(a, b, ...)` | exact sum |
38 +| `abs(x)` | absolute value |
39 +
40 +- Numbers are exact decimals; strings are double-quoted account/note codes.
41 +- Division by zero raises `FormulaError` (never silently coerced).
42 +- Evaluation order follows `row_order`; a row may only reference earlier rows in
43 + the same note. Cross-note references are resolved with cycle detection.
44 +
45 +## Consequences
46 +
47 +- Formulas are safe by construction (whitelist AST, no code execution).
48 +- Values are reproducible: same balances + formula ⇒ same result.
49 +- The note engine computes values on demand from the latest ledger import; the
50 + formula text is the single source of truth (no invented stored figures).
51 +
52 +## Rejected alternatives
53 +
54 +- Python `eval` with a restricted namespace: still executes arbitrary code and is
55 + explicitly forbidden (P-05).
56 +- A full spreadsheet engine: unnecessary scope and a larger attack surface.