A wallet opened between reconciliation cuts gets flagged: zero-fill or skip the missing snapshot?
When I worked on a wallet service, wallets opened between cuts were wrongly flagged because they had no previous snapshot; the fix was coalesce. The SQL below uses made-up data to reproduce that kind of mismatch, with the original query left out. A missing snapshot leaves NULL on the right of the LEFT JOIN, so adding the interval’s movements still comes out NULL. For this data, the operator and currency totals then show a mismatch; using coalesce to replace NULL with 0 in both terms puts the status back to ok.
The per-wallet check in this PostgreSQL 16.15 example also misses a discrepancy when NULL is left alone, and finds it after filling with 0. Whether filling is justified depends on why the snapshot is missing; the assumptions are set out below.
The calculation
The example groups reconciliation results by cut and (operator, currency) pair, reporting ok or mismatch. It first calculates each wallet’s expected balance as follows:
expected = balance at previous cut + sum of ledger movements in (previous cut, this cut]
actual = balance at this cut
Expected and actual are summed per operator and currency, then compared. Offsetting discrepancies can leave totals equal even when individual wallets do not balance.
The test data has three wallets, all under op-a in TWD. Cut 1 is at 00:00 on 9 November 2026, and cut 2 is at 01:00. w1 already existed and has two movements in the window; w2 already existed and has none; w3 was opened at 00:30, so it has no snapshot at cut 1.
CREATE TABLE cuts (id int PRIMARY KEY, cut_at timestamptz NOT NULL);
CREATE TABLE wallets (id text PRIMARY KEY, operator text NOT NULL, currency text NOT NULL, created_at timestamptz NOT NULL);
CREATE TABLE balance_snapshots (cut_id int REFERENCES cuts, wallet_id text REFERENCES wallets, balance numeric NOT NULL, PRIMARY KEY (cut_id, wallet_id));
CREATE TABLE ledger (wallet_id text REFERENCES wallets, amount numeric NOT NULL, created_at timestamptz NOT NULL);
INSERT INTO cuts VALUES (1, '2026-11-09 00:00+08'), (2, '2026-11-09 01:00+08');
INSERT INTO wallets VALUES
('w1', 'op-a', 'TWD', '2026-11-01 12:00+08'), -- existed before the cut, has transactions in the window
('w2', 'op-a', 'TWD', '2026-11-01 12:00+08'), -- existed before the cut, no transactions in the window
('w3', 'op-a', 'TWD', '2026-11-09 00:30+08'); -- opened between the two cuts
INSERT INTO balance_snapshots VALUES
(1, 'w1', 100), (1, 'w2', 50),
(2, 'w1', 120), (2, 'w2', 50), (2, 'w3', 180);
INSERT INTO ledger VALUES
('w1', -30, '2026-11-09 00:10+08'), ('w1', 50, '2026-11-09 00:40+08'),
('w3', 200, '2026-11-09 00:31+08'), ('w3', -20, '2026-11-09 00:45+08');
Under the assumptions in the example, every wallet balances: w1 is 100 - 30 + 50 = 120, w2 stays at 50, and w3 starts at 0 and ends at 200 - 20 = 180.
Adding them up: balances correct, status mismatch
The first version joins the previous snapshot and movement totals with LEFT JOIN:
-- Version 1: add the previous snapshot and the window's movements as they are
WITH delta AS (
SELECT l.wallet_id, sum(l.amount) AS amount
FROM ledger l
WHERE l.created_at > (SELECT cut_at FROM cuts WHERE id = 1)
AND l.created_at <= (SELECT cut_at FROM cuts WHERE id = 2)
GROUP BY l.wallet_id
), per_wallet AS (
SELECT w.operator, w.currency, w.id,
prev.balance + d.amount AS expected,
cur.balance AS actual
FROM wallets w
JOIN balance_snapshots cur ON cur.wallet_id = w.id AND cur.cut_id = 2
LEFT JOIN balance_snapshots prev ON prev.wallet_id = w.id AND prev.cut_id = 1
LEFT JOIN delta d ON d.wallet_id = w.id
)
SELECT operator, currency, sum(expected) AS expected, sum(actual) AS actual,
CASE WHEN sum(expected) = sum(actual) THEN 'ok' ELSE 'mismatch' END AS status
FROM per_wallet GROUP BY operator, currency;
operator | currency | expected | actual | status
----------+----------+----------+--------+----------
op-a | TWD | 120 | 350 | mismatch
(1 row)
Expected comes to 120; the same joins and interval give this breakdown per wallet:
-- How expected is built, wallet by wallet
SELECT w.id, prev.balance AS prev, d.amount AS delta,
prev.balance + d.amount AS expected, cur.balance AS actual
FROM wallets w
JOIN balance_snapshots cur ON cur.wallet_id = w.id AND cur.cut_id = 2
LEFT JOIN balance_snapshots prev ON prev.wallet_id = w.id AND prev.cut_id = 1
LEFT JOIN (
SELECT wallet_id, sum(amount) AS amount FROM ledger
WHERE created_at > (SELECT cut_at FROM cuts WHERE id = 1)
AND created_at <= (SELECT cut_at FROM cuts WHERE id = 2)
GROUP BY wallet_id
) d ON d.wallet_id = w.id
ORDER BY w.id;
id | prev | delta | expected | actual
----+------+-------+----------+--------
w1 | 100 | 20 | 120 | 120
w2 | 50 | | | 50
w3 | | 180 | | 180
(3 rows)
w3 has no snapshot at cut 1, so prev is NULL. w2 had no movements, so the delta subquery has no row for it and the LEFT JOIN supplies NULL. Adding either missing value leaves expected as NULL. sum only adds non-null inputs, totalling 120 from w1 as against 350 across all three.
Of these two NULL sources, the new wallet’s missing snapshot is the one I ran into. The other comes from the test data; whether the original job also had it has not been checked. The PostgreSQL documentation says some aggregates return NULL when there are no input rows (see Further reading), whereas this grouped query produces no row for the inactive wallet and the outer join supplies NULL.
Zero-fill
Use coalesce for both nullable terms:
-- Version 2: both NULLs become 0
WITH delta AS (
SELECT wallet_id, sum(amount) AS amount FROM ledger
WHERE created_at > (SELECT cut_at FROM cuts WHERE id = 1)
AND created_at <= (SELECT cut_at FROM cuts WHERE id = 2)
GROUP BY wallet_id
), per_wallet AS (
SELECT w.operator, w.currency, w.id,
coalesce(prev.balance, 0) + coalesce(d.amount, 0) AS expected,
cur.balance AS actual
FROM wallets w
JOIN balance_snapshots cur ON cur.wallet_id = w.id AND cur.cut_id = 2
LEFT JOIN balance_snapshots prev ON prev.wallet_id = w.id AND prev.cut_id = 1
LEFT JOIN delta d ON d.wallet_id = w.id
)
SELECT operator, currency, sum(expected) AS expected, sum(actual) AS actual,
CASE WHEN sum(expected) = sum(actual) THEN 'ok' ELSE 'mismatch' END AS status
FROM per_wallet GROUP BY operator, currency;
operator | currency | expected | actual | status
----------+----------+----------+--------+--------
op-a | TWD | 350 | 350 | ok
(1 row)
For a wallet opened after the previous cut, filling its missing snapshot assumes a balance of 0 at that cut, with every later change recorded in the interval ledger. The missing snapshot alone does not show this. A complete ledger is also needed before a missing movement total can be treated as no balance change.
NULL can hide a per-wallet discrepancy
A per-wallet check can leave a wallet out without explicitly skipping it: if expected is NULL before filling, WHERE expected <> actual excludes that wallet. An ordinary comparison with NULL returns NULL, and WHERE keeps only rows where the condition is true. The query puts the unfilled balance in a separate column so both versions can be compared.
Set w3’s current snapshot to 999 to simulate a new wallet that does not balance, then try both rules:
-- Per-wallet check: w3's snapshot is set to 999; what does each rule catch?
BEGIN;
UPDATE balance_snapshots SET balance = 999 WHERE cut_id = 2 AND wallet_id = 'w3';
CREATE TEMP VIEW per_wallet AS
SELECT w.id,
prev.balance + d.amount AS raw_expected,
coalesce(prev.balance, 0) + coalesce(d.amount, 0) AS expected,
cur.balance AS actual
FROM wallets w
JOIN balance_snapshots cur ON cur.wallet_id = w.id AND cur.cut_id = 2
LEFT JOIN balance_snapshots prev ON prev.wallet_id = w.id AND prev.cut_id = 1
LEFT JOIN (
SELECT wallet_id, sum(amount) AS amount FROM ledger
WHERE created_at > (SELECT cut_at FROM cuts WHERE id = 1)
AND created_at <= (SELECT cut_at FROM cuts WHERE id = 2)
GROUP BY wallet_id
) d ON d.wallet_id = w.id;
SELECT 'raw <>' AS rule, id FROM per_wallet WHERE raw_expected <> actual
UNION ALL
SELECT 'coalesce IS DISTINCT FROM', id FROM per_wallet WHERE expected IS DISTINCT FROM actual;
ROLLBACK;
rule | id
---------------------------+----
coalesce IS DISTINCT FROM | w3
(1 row)
The raw <> returns no rows and so misses w3’s excess of 819 over its expected balance. If later runs look only at their own intervals, with no rerun or separate check, the first stretch of activity, including the first deposit, may go unchecked.
Zero-filling and IS DISTINCT FROM find w3. With both terms filled and the current snapshot non-null, <> and IS DISTINCT FROM give the same result. Keeping IS DISTINCT FROM would also allow a comparison if actual were later allowed to be NULL. Wallets without a current snapshot are excluded by the join, so changing the comparison cannot bring those rows back.
Distinguishing new wallets from missing snapshots
For an existing wallet whose snapshot is missing, zero-filling assumes a previous balance of 0 without evidence. Delete w2’s cut-1 snapshot and run again:
-- w2 existed all along but its previous snapshot is missing; rerun the zero-filled version and label where prev came from
BEGIN;
DELETE FROM balance_snapshots WHERE cut_id = 1 AND wallet_id = 'w2';
SELECT w.id,
CASE
WHEN prev.wallet_id IS NOT NULL THEN 'has_prev'
WHEN w.created_at > c1.cut_at THEN 'opened_after_cut'
ELSE 'snapshot_missing'
END AS prev_source,
coalesce(prev.balance, 0) + coalesce(d.amount, 0) AS expected,
cur.balance AS actual
FROM wallets w
CROSS JOIN (SELECT cut_at FROM cuts WHERE id = 1) c1
JOIN balance_snapshots cur ON cur.wallet_id = w.id AND cur.cut_id = 2
LEFT JOIN balance_snapshots prev ON prev.wallet_id = w.id AND prev.cut_id = 1
LEFT JOIN (
SELECT wallet_id, sum(amount) AS amount FROM ledger
WHERE created_at > (SELECT cut_at FROM cuts WHERE id = 1)
AND created_at <= (SELECT cut_at FROM cuts WHERE id = 2)
GROUP BY wallet_id
) d ON d.wallet_id = w.id
ORDER BY w.id;
ROLLBACK;
id | prev_source | expected | actual
----+------------------+----------+--------
w1 | has_prev | 120 | 120
w2 | snapshot_missing | 0 | 50
w3 | opened_after_cut | 180 | 180
(3 rows)
Here, w2 still has a discrepancy after zero-filling, and the amounts imply that the earlier aggregate query would report a mismatch. Even if the balances happened to match, snapshot_missing would still need investigation: the snapshot was deliberately deleted for this example, while a live system would need to find the cause. Comparing created_at with the previous cut lets the query flag existing wallets with missing snapshots for investigation.
This classification depends on trustworthy created_at values that can be compared directly with cut times. A wallet without a previous snapshot is classed as newly opened only if its creation time is later than the previous cut; an exact match is classed as a missing snapshot. Clock differences between services could therefore misclassify wallets near a cut.
The query stops at labelling the source: it still zero-fills every gap, with no example of how the labels would be handled afterwards.
All the runs above use current snapshots that are present and non-null; neither missing current snapshots nor a nullable actual has been tested. Offsetting wallet discrepancies, exact cut boundaries and clock differences are discussed as possible issues, without test cases.
Notes
- The example adds interval movements to the previous snapshot; for new wallets without that snapshot, the
LEFT JOINreturns NULL, leaving expected as NULL. sumignores NULL inputs, making expected too low and producing a mismatch here. Wallets without interval movements also produce NULL.- Under the balance and ledger assumptions above, zero-filling brings this data back to ok.
- The per-wallet
<>check misses the new wallet’s discrepancy. Zero-filling andIS DISTINCT FROMfind it. - The existing wallet with a missing snapshot has a discrepancy here. If
created_atis reliable and comparable with cut times, it can help flag missing snapshots for investigation.
Further reading
- Official PostgreSQL 16 documentation, Aggregate Functions:
sumadds only non-null inputs. Apart fromcount, the general-purpose aggregates listed there return NULL when there are no input rows.coalescecan supply a replacement value when appropriate. - Official PostgreSQL 16 documentation, Comparison Functions and Operators: ordinary comparison operators return NULL when either input is NULL.
IS DISTINCT FROMtreats NULL as a comparable value. - Official PostgreSQL 16 documentation, Conditional Expressions:
COALESCEreturns its first non-null argument.
Ideas and technical judgement by Sheng; drafted with Claude · Coordinated and drafted by Claude Fable, documentation lookup and tone by Grok (grok-4.7), second review by Codex (gpt-6-astra); examples run on Linux with PostgreSQL 16.15, using made-up test data.