<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Nexo Ledgerbox Engineering]]></title><description><![CDATA[Nexo Ledgerbox Engineering]]></description><link>https://nexoledgerbox.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6b0a611afb27fd05b61cdd54/4137011e-18e6-4b63-ad9b-a41d806206ce.png</url><title>Nexo Ledgerbox Engineering</title><link>https://nexoledgerbox.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 21:21:29 GMT</lastBuildDate><atom:link href="https://nexoledgerbox.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Why Pure LLM Extraction Failed for Bank Statement PDFs — Building a $0.00-Discrepancy, RAM-Only Engine in Node 24]]></title><description><![CDATA[How we replaced pure-LLM bank statement extraction with (x, y) coordinate bucketing, integer-cents math checks, and RAM-only zero retention.]]></description><link>https://nexoledgerbox.hashnode.dev/bank-statement-pdf-parsing-math-verification-node-24</link><guid isPermaLink="true">https://nexoledgerbox.hashnode.dev/bank-statement-pdf-parsing-math-verification-node-24</guid><category><![CDATA[webdev]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[node]]></category><category><![CDATA[SaaS]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[pdf]]></category><dc:creator><![CDATA[ArcVey]]></dc:creator><pubDate>Sat, 28 Nov 2026 05:18:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0a611afb27fd05b61cdd54/ff2bae06-104f-470a-a0c0-7fa4c4885ffc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every AI wrapper demo makes PDF-to-Excel conversion look solved: upload a bank statement, send it to a vision or text model with <code>"Return JSON"</code>, and render a table.</p>
<p>When I built <strong><a href="https://nexoledgerbox.com/?utm_source=devto">Nexo Ledgerbox</a></strong> for freelance bookkeepers, landlords, and small-business owners, that naive pipeline broke on week one. Not because LLMs can't read text, but because <strong>accounting has zero tolerance for "mostly right."</strong></p>
<p>Three failure modes showed up immediately in real multi-page statements:</p>
<ol>
<li><strong>Silent $0.01 hallucinations and sign flips:</strong> A model turns a <code>-42.19</code> fee into <code>42.19</code>, drops a negative sign on a credit memo, or misreads one <code>8</code> as <code>3</code>. Everything looks clean in CSV until reconciliation fails by $0.05 at 11 PM during tax season.</li>
<li><strong>Latency and token waste on digital PDFs:</strong> A standard 6-to-20 page bank statement already contains crisp vector text coordinates—plus 2–3 pages of fine-print legal disclosures (<code>"What To Do If You Think You Find A Mistake"</code>). Sending all of that through a multimodal LLM costs money and seconds for zero accuracy gain.</li>
<li><strong>Privacy deal-breakers:</strong> Bookkeepers and SMB owners understandably refuse to upload raw corporate bank PDFs into tools that park files in S3 buckets, dump payloads into logs, or auto-record browser sessions.</li>
</ol>
<p>Here is the engineering architecture we ended up building in Node 24 + TypeScript to solve all three: deterministic <code>(x, y)</code> coordinate parsing, two-stage integer-cents math verification, and strict RAM-only zero data retention.</p>
<hr />
<h2>1. Hybrid Routing: Deterministic <code>(x, y)</code> Coordinate Bucketing Before Touching an LLM</h2>
<p>Before invoking any language model, every uploaded PDF passes through an in-memory preflight router (<code>pdfRouter.ts</code>) powered by <code>pdfjs-dist</code>.</p>
<p>Instead of flattening <code>page.getTextContent()</code> into a dumb string—which scrambles multi-column bank tables into unreadable word soup—we bucket each text span by its rounded PDF <code>y</code> coordinate and sort left-to-right by <code>x</code>:</p>
<pre><code class="language-ts">// app/src/statement/pdfRouter.ts
async function extractPageLayoutText(
  doc: Awaited&lt;ReturnType&lt;typeof pdfjsLib.getDocument&gt;['promise']&gt;,
  pageNumber: number
): Promise&lt;PdfPageText&gt; {
  const page = await doc.getPage(pageNumber);
  const content = await page.getTextContent();

  // Group spans into visual rows by rounded Y coordinate so table columns stay aligned.
  const rowMap = new Map&lt;number, PdfLayoutItem[]&gt;();

  for (const rawItem of content.items) {
    const item = rawItem as PdfTextItemLike;
    const text = item.str?.trim();
    if (!text) continue;

    const transform = item.transform ?? [1, 0, 0, 1, 0, 0];
    const x = Math.round((transform[4] ?? 0) * 10) / 10;
    const y = Math.round((transform[5] ?? 0) / 3) * 3;

    const bucket = rowMap.get(y) ?? [];
    bucket.push({ x, text });
    rowMap.set(y, bucket);
  }

  // Sort rows top-to-bottom (higher Y first in PDF coordinates) and left-to-right.
  const sortedY = Array.from(rowMap.keys()).sort((a, b) =&gt; b - a);
  const rows: PdfLayoutRow[] = sortedY.map((y) =&gt; {
    const items = rowMap.get(y) ?? [];
    items.sort((a, b) =&gt; a.x - b.x);
    return {
      y,
      items,
      lineText: items.map((entry) =&gt; entry.text).join('  '),
    };
  });

  const joined = rows.map((r) =&gt; r.lineText).join('\n');
  const nonWhitespaceCount = joined.replace(/\s+/g, '').length;
  const isNoisePage = detectNoiseDisclosurePage(joined);

  return { pageNumber, text: joined, charCount: nonWhitespaceCount, rows, isNoisePage };
}
</code></pre>
<p>Two small details made a massive difference here:</p>
<ul>
<li><strong>Noise-page filtering (<code>detectNoiseDisclosurePage</code>):</strong> If a page lacks transaction dates and formatted money amounts, and matches standard boilerplate headings (<code>Account Reconciliation Form</code>, <code>In Case of Errors or Questions About Your Electronic Transfers</code>), it is tagged <code>isNoisePage</code> and excluded from prompt payloads.</li>
<li><strong>Deterministic fast-path routing:</strong> If <code>averageCharsPerPage &gt;= 120</code> and the document matches <code>/\d+[.,]\d{2}/</code>, it goes to our text route—where our deterministic local table parser handles standard digital bank statements first. Scanned PDFs and mobile receipt photos (<code>PNG</code>/<code>JPG</code>/<code>WEBP</code>) skip text extraction and route directly to vision.</li>
</ul>
<p>On our internal 6-page sample statement benchmark (47 transactions), the deterministic coordinate parser finishes in <strong>~87ms</strong> at <strong>$0 API token cost</strong>, while still passing through the exact same normalization and math audit pipeline as vision outputs.</p>
<hr />
<h2>2. Two-Stage Integer-Cents Math Verification (Without Cascade False Positives)</h2>
<p>Even deterministic parsers hit weird bank exports, and OCR/vision extraction will eventually misread a digit on a crumpled receipt or blurry scan. The real question isn't <em>"can we hit 100% OCR perfection forever?"</em>—it's <strong>"can the system mathematically prove whether every cent adds up, and pinpoint the exact broken row when it doesn't?"</strong></p>
<p>First rule: <strong>never do ledger arithmetic in IEEE-754 floats.</strong> In JavaScript, <code>0.1 + 0.2 === 0.30000000000000004</code> is funny in tweets and fatal in accounting exports. Every opening balance, debit, credit, running balance, and closing balance is converted to integer cents (<code>toCents</code>) before verification runs (<code>app/src/statement/mathVerifier.ts</code>):</p>
<pre><code class="language-ts">// app/src/statement/mathVerifier.ts
export function verifyStatement(statement: ParsedStatement): VerificationResult {
  const openingCents = toCents(statement.opening_balance);
  const closingCents = toCents(statement.closing_balance);

  let totalCreditsCents = 0;
  let totalDebitsCents = 0;

  const hasRunningBalance = statement.transactions.some(
    (tx) =&gt; typeof tx.running_balance === 'number'
  );

  const rowDiscrepancies: RowDiscrepancy[] = [];
  let runningCents = openingCents;

  statement.transactions.forEach((tx, index) =&gt; {
    const creditCents = toCents(tx.credit);
    const debitCents = toCents(tx.debit);

    totalCreditsCents += creditCents;
    totalDebitsCents += debitCents;

    const expectedCents = runningCents + creditCents - debitCents;

    if (typeof tx.running_balance === 'number') {
      const actualCents = toCents(tx.running_balance);
      const diffCents = actualCents - expectedCents;

      if (diffCents !== 0) {
        rowDiscrepancies.push({
          rowIndex: index,
          expectedRunningBalance: fromCents(expectedCents),
          actualRunningBalance: fromCents(actualCents),
          discrepancy: fromCents(diffCents),
          reason: `Row ${index + 1} (${tx.date} ${tx.description}): expected balance ${formatCurrencyValue(fromCents(expectedCents))}, got ${formatCurrencyValue(fromCents(actualCents))}.`,
        });
      }

      // Reset baseline to actual running balance so a single OCR typo
      // does not cascade across every subsequent row.
      runningCents = actualCents;
    } else {
      runningCents = expectedCents;
    }
  });

  const computedClosingCents = openingCents + totalCreditsCents - totalDebitsCents;
  const summaryDiffCents = closingCents - computedClosingCents;

  const isVerified = rowDiscrepancies.length === 0 &amp;&amp; summaryDiffCents === 0;
  // ...
}
</code></pre>
<p>Notice that critical line inside the loop:</p>
<pre><code class="language-ts">runningCents = actualCents;
</code></pre>
<p>In our earliest prototype, we carried <code>expectedCents</code> forward instead of resetting <code>runningCents = actualCents</code>. The result? <strong>A single misread debit on row #4 caused false discrepancy alerts on rows #5 through #47</strong>, overwhelming the user with 44 red flags for 1 typo. Resetting the running baseline to the printed <code>actualCents</code> isolates each error to the exact row where it happened.</p>
<p>When <code>verifyStatement()</code> catches row discrepancies on a multi-step extraction, the pipeline triggers a targeted <strong><code>healDiscrepantRows()</code></strong> pass aimed only at those flagged rows. Any leftover mismatch stays highlighted inline in the workspace (<code>Exp $X.XX</code>), letting the user fix one cell and watch the badge flip to <strong><code>Math Verified ($0.00 discrepancy)</code></strong> before exporting to <code>.xlsx</code>, <code>.csv</code>, QuickBooks CSV, or Xero CSV.</p>
<p><img src="https://cdn.hashnode.com/uploads/covers/6b0a611afb27fd05b61cdd54/8191f378-6337-4d56-bcf6-9aa9632d3c5d.png" alt="06-gallery-workspace" /></p>
<blockquote>
<p><em>Caption: Nexo Ledgerbox workspace showing inline row-level math verification, discrepancy highlighting, and multi-format accounting exports.</em></p>
</blockquote>
<hr />
<h2>3. True RAM-Only Zero Data Retention (and 3 Subtle Gotchas)</h2>
<p>"We delete your files after 24 hours" is marketing fluff. If a PDF never touches disk, there is nothing to delete—and nothing left behind to breach.</p>
<p>Every upload in Nexo Ledgerbox enters via <code>multer.memoryStorage()</code>, stays in a Node <code>Buffer</code>, and is scrubbed inside <code>finally</code> (<code>app/src/statement/operations.ts</code>). While building that guarantee end-to-end, we hit <strong>three real gotchas</strong> that almost quietly broke it.</p>
<p><img src="https://cdn.hashnode.com/uploads/covers/6b0a611afb27fd05b61cdd54/4628d132-a34d-4627-8950-36b81155de48.png" alt="05-poster-zero-retention" /></p>
<blockquote>
<p><em>Caption: End-to-end Zero Data Retention pipeline: RAM-only ingress, stdio vision rendering, explicit buffer zeroing, and sanitized telemetry.</em></p>
</blockquote>
<h3>Gotcha A: <code>pdfjs-dist</code> detaching your <code>ArrayBuffer</code> (breaking downstream scrubbing)</h3>
<p>If you hand <code>pdfBuffer</code> directly to <code>pdfjsLib.getDocument()</code>, worker/stream internals can transfer or detach the underlying <code>ArrayBuffer</code>—causing downstream vision retries or <code>buffer.fill(0)</code> cleanup to operate on a zero-length detached view.</p>
<p>The fix in <code>pdfRouter.ts</code> is copying into an isolated <code>Uint8Array</code> before calling <code>getDocument</code>, while keeping the original <code>input.buffer</code> intact for the <code>finally</code> scrub in <code>operations.ts</code>:</p>
<pre><code class="language-ts">// app/src/statement/pdfRouter.ts
const data = Uint8Array.from(pdfBuffer);

const loadingTask = pdfjsLib.getDocument({
  data,
  password: password || undefined,
  useWorkerFetch: false,
  isEvalSupported: false,
  useSystemFonts: true,
  verbosity: 0,
});
</code></pre>
<pre><code class="language-ts">// app/src/statement/operations.ts
} finally {
  // Strict Zero Data Retention: overwrite raw uploaded bytes in RAM immediately.
  if (input.buffer.buffer.byteLength &gt; 0) {
    input.buffer.fill(0);
  }
}
</code></pre>
<p>Our SQLite <code>conversion_audits</code> telemetry only stores anonymized counters (<code>page_count</code>, <code>route</code>, <code>model_used</code>, <code>verification_status</code>, <code>duration_ms</code>)—never filenames, transaction descriptions, or account numbers (<code>retained_bytes = 0</code>).</p>
<h3>Gotcha B: Rendering scanned PDFs to PNG without writing to <code>/tmp</code></h3>
<p>Many Node PDF-to-image wrappers shell out to <code>pdftoppm</code> or <code>ghostscript</code> using temporary files on <code>/tmp</code>. Even if you <code>fs.unlink()</code> afterward, temp files hit disk I/O and risk leftovers on crash or <code>SIGKILL</code>.</p>
<p>Instead, <code>app/src/statement/pdfImageRenderer.ts</code> spawns Python 3 + PyMuPDF (<code>fitz</code>) and streams the PDF bytes directly over <code>stdin</code> and receives base64 PNGs back over <code>stdout</code>—zero temp files created:</p>
<pre><code class="language-ts">// app/src/statement/pdfImageRenderer.ts
const PYTHON_RENDER_SCRIPT = `
import sys, json, base64, os
import fitz

pdf_bytes = sys.stdin.buffer.read()
dpi = int(os.environ.get("NEXO_RENDER_DPI", "160"))
max_pages = int(os.environ.get("NEXO_RENDER_MAX_PAGES", "12"))
password = os.environ.get("NEXO_PDF_PASSWORD", "")

doc = fitz.open(stream=pdf_bytes, filetype="pdf")
if doc.needs_pass and password:
    doc.authenticate(password)

pages_out = []
count = min(len(doc), max_pages)
for idx in range(count):
    page = doc.load_page(idx)
    pix = page.get_pixmap(dpi=dpi, alpha=False)
    png_bytes = pix.tobytes("png")
    pages_out.append({
        "pageNumber": idx + 1,
        "base64Png": base64.b64encode(png_bytes).decode("ascii"),
        "width": pix.width,
        "height": pix.height
    })

doc.close()
sys.stdout.write(json.dumps(pages_out))
`;
</code></pre>
<h3>Gotcha C: Frontend analytics SDKs quietly capturing financial DOM text</h3>
<p>Even if your backend is strictly RAM-only, dropping a default PostHog / FullStory / Clarity snippet onto the frontend with <strong>Session Replay</strong> and <strong>Autocapture</strong> enabled will happily ship every bank transaction rendered in your React preview table to third-party servers.</p>
<p>We had to explicitly lock down our client analytics initialization (<code>app/src/analytics/posthog.ts</code>):</p>
<pre><code class="language-ts">// app/src/analytics/posthog.ts
// Enforce Zero Data Retention on the client: never record screens or auto-capture DOM text from statement previews.
posthog.init(key, {
  api_host: host || DEFAULT_POSTHOG_HOST,
  capture_pageview: false,
  capture_pageleave: true,
  disable_session_recording: true,
  autocapture: false,
  person_profiles: 'identified_only',
});
</code></pre>
<hr />
<h2>4. A Boring, Resilient Stack on a Single 2GB VPS</h2>
<p>To keep latency low and operational surface tiny, Nexo Ledgerbox runs on a single 2GB Ubuntu VPS without managed Postgres, Redis, or queues:</p>
<ul>
<li><strong>Runtime &amp; Storage:</strong> Node 24's built-in <code>node:sqlite</code> in WAL mode stores user accounts, credit ledgers, payment idempotency records, encrypted runtime settings, and daily health stats—backed up nightly via <code>sqlite3 .backup</code> cron.</li>
<li><strong>Public Edge Isolation for Admin:</strong> Rather than relying solely on password strength for <code>/admin</code> or <code>/api/admin/*</code>, Caddy returns a hard <code>404</code> on the public internet, while the app container binds strictly to <code>127.0.0.1:3001</code> so admin operations only happen over an SSH tunnel.</li>
</ul>
<p>One quick <strong>Caddy + Docker gotcha</strong> worth saving you an hour on:</p>
<p>In <code>Caddyfile</code>, a bare <code>respond @blocked_admin 404</code> can lose directive ordering against a <code>handle { reverse_proxy ... }</code> block. Wrapping the block inside its own mutually exclusive <code>handle</code> solves it cleanly:</p>
<pre><code class="language-caddyfile"># infra/Caddyfile
@blocked_admin {
  path /admin /admin/* /api/admin /api/admin/*
}
handle @blocked_admin {
  respond 404
}

handle {
  reverse_proxy {$APP_UPSTREAM}
}
</code></pre>
<p>And if you single-file bind-mount <code>./Caddyfile:/etc/caddy/Caddyfile</code> in Docker Compose and overwrite the host file atomically (like extracting a <code>tar</code> archive), <code>caddy reload</code> inside the container keeps reading the old inode. Running <code>docker compose up -d --force-recreate caddy</code> ensures the new inode is mounted.</p>
<hr />
<h2>Wrapping Up</h2>
<p>If you want to see the two-stage math verification and inline discrepancy editing in action without signing up, open <strong><a href="https://nexoledgerbox.com/?utm_source=devto">Nexo Ledgerbox</a></strong> and click <strong>Load Demo</strong> right on the workspace. If you want to stress-test it against a nasty multi-page digital or scanned statement, a free account gives you 5 pages/month with zero file retention.</p>
<p>I'd love to hear from anyone else who has built document/PDF pipelines in Node or Python: <strong>what is the weirdest bank statement layout or PDF encoding bug that broke your parser?</strong></p>
]]></content:encoded></item></channel></rss>