Skip to content

fix(inventory): preserve ledger chain continuity for legacy stock precision - #1248

Merged
khaira777 merged 3 commits into
mainfrom
fm/remediate-f6-inventory-precision
Oct 21, 2026
Merged

khaira777 merged 3 commits into
mainfrom
fm/remediate-f6-inventory-precision

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Closes #1217

Problem & Root Cause

In main/services/inventory.ts, adjustInventoryStockPool clipped stock_after to 14 decimal places via:

const targetPrecision = Math.max(
  INVENTORY_QUANTITY_PRECISION,
  Math.min(14, getDecimalPlaces(stockBefore)),
);

and updated the database using SQLite ROUND(COALESCE(stock_quantity, 0) + ?, ?), followed by computing:

const effectiveQuantityDelta = Number((stockAfter - stockBefore).toFixed(targetPrecision));

When legacy stock quantities had 15 or 16 decimal places (such as 0.123456789012345), applying an adjustment (e.g. +0.01) rounded stock_after to 0.13345678901235 and set effectiveQuantityDelta to 0.01000000000001. This created a floating-point discrepancy of 4.996e-15 against the true IEEE-754 sum, exceeding the ledger's machine-epsilon tolerance (Math.max(1e-9, Math.max(1, ...) * Number.EPSILON * 16) = 2.220e-15). As a result, validateInventoryLedgerRows in main/db.ts failed with:
Inventory movement history contains a broken stock chain

Solution & Minimal Fix

  • Standard Stock (<= 8 decimals): Preserves ROUND(..., 8) in SQLite and .toFixed(8) in JavaScript so ordinary fractional stock calculations never accumulate floating-point residue.
  • Legacy High-Precision Stock (> 8 decimals): Removes premature 14-decimal truncation. For legacy IEEE-754 stock values (including 12, 15, and 16 decimals), stock values are updated directly via SQLite parameter binding without ROUND(), and effectiveQuantityDelta is computed as stockAfter - stockBefore. This guarantees stockBefore + effectiveQuantityDelta == stockAfter within <= 1 ULP, preserving ledger chain continuity across sequential adjustments and backup/restore cycles.

Additional Regression Coverage Added

  1. Cloud Live Orders & Table Chunk Boundaries (>400 IDs): Added Test 7 in tests/cloud-live-orders-batching.test.ts testing 450 orders across 450 distinct tables and add-on rows across the CHUNK_SIZE = 400 boundary, verifying complete decoration without data loss.
  2. Imported Order FTS Search After Partial Import: Added Test 3e in tests/database-tools-api.test.ts verifying that partial imports (POST /api/db/import with orders and customers) synchronize orders_fts, making newly imported orders immediately searchable by order number, customer name, and customer phone digits via GET /api/orders?search=....
  3. Populated Historical v114 Backup Restore: Added Scenario 5 in tests/inventory-legacy-precision-backup.test.ts creating a populated schema v114 database (orders, items, bills, payments, inventory movements), taking a backup snapshot, restoring into a clean v115 database, verifying clean migration upgrade, PRAGMA integrity check, and inventory ledger validation.

Reproduction & Verification

  • Red Repro: Captured in /Users/gurkiratkhaira/tools/firstmate/data/remediate-f6-inventory-precision/repro-red.txt reproducing failure on unfixed main (Inventory movement history contains a broken stock chain: expected stock 0.13345678901235 vs calculated 0.13345678901234502 (diff: 4.996003610813204e-15 > tolerance: 2.220446049250313e-15)).
  • Green Verification: Captured in /Users/gurkiratkhaira/tools/firstmate/data/remediate-f6-inventory-precision/repro-green.txt passing all scenarios.

Verification Commands & Results

  • npm run test:inventory-legacy-precision-backup - Passed (Scenarios 1-5 green)
  • npm run test:cloud-live-orders-batching - Passed (7/7 tests passed)
  • npm run test:database-tools-api - Passed (150/150 tests passed)
  • npm run test:inventory-ledger - Passed (82/82 + 60/60 tests passed)
  • npm run test:addon-inventory-db - Passed
  • npm run test:addon-inventory-api - Passed
  • npm run test:backup - Passed
  • npm run test:script-coverage - Passed (245 reachable test scripts, 302 test files covered)
  • npx oxfmt --check - Passed (0 formatting errors across all modified/added files)
  • npm run lint & npm run lint:budget - Passed (0 errors, 998/1000 backend warning budget)
  • npm run build - Passed (clean TypeScript compilation to dist/)

Invariant Checks

  • Database Migrations: None (schema remains at version 115).
  • Permissions: Unchanged.
  • API Payloads: Unchanged.
  • Financial Calculations: Unchanged (preserves ledger chain continuity for legacy >8-decimal stock movements).
  • Telemetry Behavior: Unchanged.

…cision (#1217)

Remediate legacy inventory precision defect F6 (#1217) in main/services/inventory.ts so 12-, 15-, and 16-decimal IEEE-754 stock values maintain machine-epsilon ledger chain continuity across stock adjustments and backup/restore round-trips.

- Compute stockAfter and effectiveQuantityDelta without premature 14-decimal clipping when legacy precision > 8 decimals, while preserving 8-decimal rounding for normal operations.
- Add regression tests in tests/inventory-legacy-precision-backup.test.ts covering 12-, 15-, and 16-decimal stock adjustments across product, variant, and add-on pools, backup/restore round-trips, and populated historical schema v114 restore.
- Add regression test in tests/cloud-live-orders-batching.test.ts covering live-order and table chunk boundaries with >400 orders and >400 tables.
- Add regression test in tests/database-tools-api.test.ts covering order and customer FTS search index rebuild following partial data import.
@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration
  • Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c3b85e42-e79a-4a76-b330-5d046a3c4b0e

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@khaira777 khaira777 changed the title fix(inventory): preserve ledger chain continuity for legacy stock precision (#1217) fix(inventory): preserve ledger chain continuity for legacy stock precision Oct 20, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptile review

@greptile-apps

greptile-apps Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change reaches stock adjustments across the inventory workflow.

The runtime change appears sound, but the new comments must meet the repository’s explicit rule before merging.

Findings

  1. P2 Future migrations break this test ▶
  2. P2 Precision loss can pass unnoticed ▶
  3. P2 Comments exceed repository limits ▶

Summary

The inventory change keeps legacy stock digits when adjusting quantities, while retaining eight-decimal rounding for ordinary stock.

  • Inventory adjustments keep legacy high-precision stock linked to its ledger.
  • Cloud order coverage checks decoration beyond 400 records.
  • Import tests check that new orders appear in search.

Review was based on source inspection. Tests, lint, and builds were not run.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A["Read stockBefore and normalize quantityDelta"] --> B{"More than 8 decimal places?"}
  B -->|Yes| C["Add without ROUND"]
  B -->|No| D["Add with ROUND to 8 places"]
  C --> E["Record stockAfter - stockBefore"]
  D --> F["Record difference rounded to 8 places"]
  E --> G["Save inventory movement"]
  F --> G
Loading

Reviews (1) · Last reviewed commit: "fix(inventory): preserve ledger chain co..." · Reviewed by Greptile

khaira777 and others added 2 commits October 20, 2026 17:22
…tions, and package.json

- Replace verbose header and inline issue tags in tests/inventory-legacy-precision-backup.test.ts with concise comments per AGENTS.md rules.
- Strengthen precision assertions across product, variant, and add-on pools by verifying exact IEEE-754 values on returned results, stock tables, and inventory movements.
- Verify restored stock quantities and movements match exact pre-backup values after backup/restore round-trip.
- Read expectedSchemaVersion dynamically from getCurrentSchemaVersion() before restore in historical v114 fixture.
- Chain test:inventory-legacy-precision-backup onto test:inventory-ledger in package.json and revert line 54 to prevent merge conflicts.
@khaira777
khaira777 merged commit b83fd11 into main Oct 21, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/remediate-f6-inventory-precision branch October 21, 2026 02:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(inventory): preserve ledger chain continuity when adjusting legacy stock with high decimal precision

1 participant