Caio Theodoro Caio Theodoro
← Blog · Nov 2026 · 9 min read

Malha: Priced, Not Passed — What Accounting Agents Actually Lose (and Win) in a SPED Audit

An accounting agent that misses R$40,000 of unrecorded revenue and one that flags 53 phantoms are both wrong in a binary eval. I built malha — a SPED-native audit environment with scanned documents, a fail-closed Trust Ledger, and Lei 8.218/1991 statutory fine pricing — and measured when hybrid VLM agents decisively beat both deterministic SPED rules and Tesseract OCR regex.

ML Agent Systems

Part of the malha project

This project measures what an accounting agent is worth in reais, not in pass rate. malha generates a synthetic Brazilian company's complete fiscal year — NF-e XMLs, double-entry journal, trial balances, rendered scanned source documents (DANFEs, receipts, delivery canhotos), and the statutory ECD and EFD-Contribuições filings — injects defects from a frozen 19-class taxonomy, re-derives every downstream artifact so the books stay internally consistent, and prices an agent's audit in the statutory fines the law actually charges (Lei 8.218/1991, art. 12).

The core finding is architectural, not ideological: standalone agents lose to deterministic rules, but a deterministic-first hybrid agent with a SQL index, fail-closed Trust Ledger, and pixel-level vision beats both deterministic SPED rules (malha_rules) and Tesseract OCR regex (ocr_rules) decisively — priced in BRL.

  • Measured (v2.1, locked test pool 501–530****): 30 worlds × 3 episodes × 3 physical scan-noise regimes (clean, mild_scan, noisy_scan), 1,759 Gate-4 scored episodes, paired 10,000-resample bootstrap over worlds
  • H1 separated everywhere: agent_v2_vlm+glm-flash cuts neutral expected loss from R$15,719 (malha_rules) to R$5,699 on clean (+10,020 BRL [+5,106, +15,755]), holding across all 3 noise levels and all 6 enforcement/rework sensitivity profiles
  • H3 separated under real scan noise: ocr_rules degrades +77.4% from clean (6,241 BRL) to noisy_scan (11,070 BRL), while pixel-vision glm-5.3-flash degrades only +5.0% (5,699 → 5,986 BRL), beating ocr_rules by +5,084 BRL [+1,476, +9,531] overall and +2,532 BRL [+9, +6,150] on the 4 scan-substantive classes alone
  • Same-model causal vision ablation: holding glm-5.3-flash weights, prompt, SQL index, and Trust Ledger 100% identical on noisy_scan, attaching scan PNG pixels doubles recall on both OCR-degraded classes (scan_value_alteration 28% → 56%, scan_ineligible_credit_desc 22% → 44%) and separates on the scan slice (+2,163 BRL [+157, +5,465])
  • 8B trainability negative: SFT on verified traces yields format-perfect, judgment-absent policies (0/30 model-origin findings), and unshaped terminal-reward GRPO stalls at zero within-group reward variance
  • Preprint (v2.1): doi.org/10.5281/zenodo.24589622

Why binary scoring lies in accounting

An auditor who misses R$40,000 of unrecorded revenue and an auditor who flags 53 phantom defects are both wrong in a binary benchmark. In practice they cost different money, in opposite directions: a miss is priced by the tax code times the probability the Receita Federal audits you, and a phantom is priced in professional hours spent chasing nothing.

Mainstream agent benchmarks — OSWorld, WorkArena, WebArena, $\tau$-bench, Terminal-Bench — score tasks as passed or failed. Even newer accounting benchmarks (FinBalance, APEX-Accounting, CAB) target internal books rather than government-specified regulatory filings, and none prices errors in statutory currency. The deployment question for an accounting agent isn't whether it can pass a task; it's what it costs to let one run against the deterministic validator and OCR pipeline you already have.

The v2 architecture: deterministic-first, fail-closed, multimodal

Every world is a seed-deterministic fiscal year for a synthetic lucro real company: NF-e XMLs, double-entry postings, monthly trial balances, ECD (26 covered records), EFD-Contribuições (33 covered records), and rendered PNG scans across three seeded degradation levels (clean, mild_scan, noisy_scan) with real Portuguese Tesseract OCR caches. CNPJs pass check-digit validation and are drawn from the reserved 99.xxx.xxx synthetic base.

Three design decisions separate v2 from naive tool-calling loops:

  1. Mandatory deterministic pre-pass outside the agent's budget. Running malha_rules (L1 layout, L2 invariants, L3 cross-filing rules) before turn 1 locks structural catches into the Trust Ledger so the agent spends 100% of its 25-call budget on book-side judgment, physical scans, and open warnings (sequence_gap).
  2. Read-only SQLite index + fail-closed hash-chained Trust Ledger. Every sql_query, read_document, and inspect_scan mints a cryptographic receipt (rcpt_NNNN). flag_finding fails closed if its citations are not backed by receipts observed in the episode.
  3. Real physical scan layer (4 scan-substantive classes). scan_personal_expense (leisure items on a travel receipt behind a corporate journal description), scan_cutoff_delivery (January delivery stamp on a December NF-e), scan_value_alteration (DANFE total contradicting consistent books + XML), and scan_ineligible_credit_desc (non-creditable item description behind a creditable CFOP). In agent_v2_vlm, calling inspect_scan attaches the actual PNG image directly to the model alongside Tesseract OCR spans.

Expected loss is cents-exact decimal BRL under Lei 8.218/1991 art. 12:

  • Presentation (art. 12, I): 0.5% × receita_bruta
  • Operation (art. 12, II): min(5% × vl_doc, 1% × receita_bruta)
  • Substantive: P(autuação) × (1 + 0.75) × vl_doc (principal + 75% multa de ofício)
  • False positive: R$250.00 rework cost per unmatched finding (also stress-tested at R$1,500)

Every headline is evaluated across the full 3 × 2 sensitivity grid (P(autuação) ∈ {0.05, 0.15, 0.40} × c_fp ∈ {R$250, R$1,500}).

The headline numbers: H1 and H3 both separate decisively

On the locked 30-world test pool (seeds 501–530, k = 3 episodes per cell = 270 episodes per 3-noise arm, neutral enforcement P = 0.15, R$250/FP), after fixing three v2.0 harness bugs caught by code audit (D033: adjudicate_warning schema mismatch, SQL schema_text column names, and wiring PNG pixels into inspect_scan):

Arm clean (BRL) mild_scan (BRL) noisy_scan (BRL) Clean → Noisy degradation
flag_everything 43,836 43,836 43,836 0.0%
file_as_is 39,086 39,086 39,086 0.0%
malha_rules (SPED floor) 15,719 15,719 15,719 0.0% (scan-blind)
ocr_rules (Tesseract regex floor) 6,241 7,991 11,070 +77.4%
agent_v2_fixed+deepseek-flash (text-only) 7,387 9,107 8,714 +18.0%
agent_v2_fixed+glm-flash (text-only ablation) — — 7,733 —
agent_v2_vlm+glm-flash (pixel vision) 5,699 6,447 5,986 +5.0%
Mean expected loss on noisy_scan under neutral enforcement (BRL/world, lower is better)
Complete 30 worlds × 3 episodes on noisy_scan (neutral profile, P=0.15, R$250/FP). From results/v2/analysis.json (1,759 scored episodes).
Paired bootstrap contrasts (BRL/world; positive = second arm better, 95% CI, n=30 worlds)
ΔEL (BRL/world, 10,000 paired world resamples)
Positive values favor the agent / pixel-vision arm. H1 separates across all noise levels; H3 and the same-model pixel-vision ablation separate decisively on noisy_scan.

Two results carry the study:

  1. H1 separates decisively across every noise and enforcement regime. Both agent_v2_fixed+deepseek-flash (+8,332 BRL [+4,116, +13,235] on clean) and agent_v2_vlm+glm-flash (+10,020 BRL [+5,106, +15,755] on clean) cut expected loss by more than half relative to malha_rules, holding across all 6 sensitivity profiles (conservative/neutral/aggressive × R$250/R$1,500). They unlock every book-side judgment class where deterministic rules are 0% by construction (cutoff_violation up to 44%, expense_personal_mixed 78–89%, transitoria_parking 33%, pis_cofins_ineligible_credit 25%, sequence_gap 92–100%).
  2. H3 separates monotonically under scan noise — and the same-model ablation proves pixels cause the gain. On clean scans, 20 lines of regex over perfect OCR (ocr_rules, R$6,241) nearly match the VLM (R$5,699; +542 [−2,492, +3,559]). As physical scan noise rises, ocr_rules degrades +77.4% to R$11,070 while pixel-vision vlm+glm-flash degrades only +5.0% to R$5,986 — separating decisively at +5,084 BRL [+1,476, +9,531] overall and +2,532 BRL [+9, +6,150] on the 4 scan-substantive classes alone.

The same-model causal vision ablation

To rule out model-family confounds, I ran glm-5.3-flash on the exact same 30 noisy_scan worlds with identical prompt, SQL index, and Trust Ledger — toggling only whether inspect_scan attaches the scan PNG pixels:

Defect class (noisy_scan) ocr_rules (Tesseract regex) fixed+glm-flash (text-only OCR) vlm+glm-flash (pixel vision)
scan_value_alteration 33% (2/6) 28% (5/18) 56% (10/18) — 2.0×
scan_ineligible_credit_desc 0% (0/3) 22% (2/9) 44% (4/9) — 2.0×
scan_personal_expense 100% (3/3) 67% (6/9) 78% (7/9)
scan_cutoff_delivery 100% (5/5) 100% (15/15) 100% (15/15)
Mean world loss (overall) 11,070 BRL 7,733 BRL 5,986 BRL

Turning pixels on doubles recall on both OCR-degraded classes and separates decisively on the 4-class scan slice (+2,163 BRL [+157, +5,465]).

What still fails: 8B imitation and unshaped RL

Frontier VLM capability does not trivially distill to an 8B model. Across both v1 (80 curated frontier traces on Kaggle T4) and v2 (154 verified expert traces on Apple Silicon MLX), 4-bit LoRA SFT on Qwen3-8B converges cleanly on training loss (0.059 in v2) yet emits zero model-origin findings across all 30 locked test worlds — format-perfect tool calls, judgment completely absent. Subsequent Stage-2 GRPO smoke runs under unshaped terminal reward from both SFT and base initialisations hit reward_std = 0.0 on every group, leaving zero gradient to start. Programmatic ledger-shaped warm-up GRPO (V2_PLAN.md §5.3) is implemented and ready in scripts/modal_v2.py and training/mlx_grpo.py.

Operational takeaways for accounting agents

  1. Never replace deterministic validation with an agent that merely has it as a tool. Run the rules engine unconditionally outside the agent's budget, lock its findings into a fail-closed Trust Ledger, and spend the model's budget strictly on substantive judgment and physical documents.
  2. Never stop at text-only OCR when physical documents degrade. Regex over clean OCR is a strong floor (R$6.2k), but collapses +77.4% under realistic scan noise; giving a VLM direct pixel access on inspect_scan cuts degradation to +5.0% and doubles recall on garbled fields.
  3. Audit your own evaluation harness before trusting a negative result. Fixing three silent v2.0 harness bugs (D033: adjudicate_warning schema mismatch, SQL schema_text column names, and text-only inspect_scan) cut expected loss by 46% on identical worlds and flipped H1 and H3 from inconclusive to decisively separated.
  4. Price both error directions in statutory currency. Accuracy hides the asymmetry between a missed R$40,000 tax exposure and a R$250 false-positive rework bill.

Everything — paper, code, frozen pre-registrations (prereg-v1, prereg-v2), 33-entry decision log, 1,759 scored v2/v2.1 episodes, and traces — is public: