Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ Everything to date; Concord's history begins 2026-10 with the commits below.
- A per-asset reconciliation `tolerance` (smallest units): a holder whose chain and register
balances differ by no more than it is treated as matched. Schema: `ORG_MIGRATIONS` v5 adds
`assets.tolerance` (#564).
- Stored headline figures per asset (#575): the overview and `GET /api/assets/:id` read each
asset's supply, holder and event counts and open-break counts from one row, rewritten after
every change that moves them, so a poll no longer replays events or rebuilds the controls
log. Schema: `ORG_MIGRATIONS` entry 6 adds the `asset_stats` table.
- CSV templates can include one illustrative example row with `?example=1` or `?example=true` (#200).
- The accounting core (`feat(core)`, `c402eae`): holdings replay from CAP-67 events, position
and movement reconciliation with typed breaks, corporate-action entitlements (dividend,
Expand Down
26 changes: 25 additions & 1 deletion docs/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,14 @@ erDiagram
assets ||--o{ runs : "asset_id"
assets ||--o{ actions : "asset_id"
assets ||--o{ break_notes : "asset_id"
assets ||--o| asset_stats : "asset_id"
registers ||--o{ register_positions : "register_id"
registers ||--o{ runs : "register_id"
```

Every arrow is `ON DELETE CASCADE`. Deleting an asset therefore deletes its events, opening
balances, registers (and through them their positions and runs), journal, instructions, corporate
actions and break notes. Deleting a register deletes its positions *and the runs made from it*.
actions, break notes and stored figures. Deleting a register deletes its positions *and the runs made from it*.
`meta` stands alone.

### `meta`
Expand Down Expand Up @@ -263,6 +264,29 @@ existed). One row per `setNote` call: `id`, `asset_id`, `scope`, `key`, `fingerp
`note`, `author`, `author_id`, `at`. It is what the audit pack lists as `signoffHistory` and what
`GET /api/assets/:id/notes/history?scope=&key=` returns, oldest first.

### `asset_stats`

Each asset's headline figures (added in migration 6), so the dashboard's polled
`GET /api/overview` and `GET /api/assets/:id` read one row instead of replaying events and
rebuilding the controls log. Primary key `asset_id`. Derived data: a missing row is recomputed
and stored on the next read (`Concord.assetSummary`, `services/api/src/concord.ts`).

| Column | Type | Notes |
|---|---|---|
| `asset_id` | TEXT | → `assets.id` |
| `supply` | TEXT | Current supply in whole units, formatted as the overview shows it. |
| `holder_count` | INTEGER | Addresses with a non-zero balance. |
| `event_count` | INTEGER | Indexed events. |
| `incomplete` | INTEGER | `1` when some holder's derived balance is negative (history missing). |
| `last_run` | TEXT (JSON), null | `{ id, asOf, status, openBreaks }` of the latest reconciliation. |
| `open_reconciliation`, `open_controls`, `open_actions` | INTEGER | Open breaks in the latest run, the controls log, and all corporate actions. |
| `updated_at` | TEXT | |

The row is rewritten at the end of every change that can move a figure (`Concord.refreshStats`):
a sync pass (also one that adds nothing, since the controls log runs to the read-through time),
a rebuild, a reconciliation, a deleted register, a sign-off, an instructions import and a
corporate action's reconciliation. An asset that has never been synced is always recomputed.

## Control database (`control.db`)

```mermaid
Expand Down
84 changes: 82 additions & 2 deletions services/api/src/concord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,31 @@ function toEvent(row: Row): AssetEvent {
return ev;
}

/** An asset's headline figures, as the overview shows them and `asset_stats` stores them. */
interface AssetStats {
supply: string;
holderCount: number;
eventCount: number;
incomplete: boolean;
lastRun: { id: number; asOf: string; status: "clean" | "breaks"; openBreaks: number } | null;
openBreaks: { reconciliation: number; controls: number; actions: number };
}

function statsFromRow(row: Row): AssetStats {
return {
supply: String(row.supply),
holderCount: Number(row.holder_count),
eventCount: Number(row.event_count),
incomplete: Number(row.incomplete) === 1,
lastRun: row.last_run ? (JSON.parse(String(row.last_run)) as AssetStats["lastRun"]) : null,
openBreaks: {
reconciliation: Number(row.open_reconciliation),
controls: Number(row.open_controls),
actions: Number(row.open_actions),
},
};
}

/**
* One workspace: every operation the API and the CLI expose over a single database.
* Reads the chain, never writes it.
Expand Down Expand Up @@ -631,6 +656,8 @@ export class Concord {
movementWindowHours,
asset.id,
);
// The matching windows decide which controls break, and so the stored open-break count.
this.refreshStats(asset.id);
return this.asset(asset.id);
}

Expand Down Expand Up @@ -670,6 +697,8 @@ export class Concord {
);
});
this.touch(asset.id);
// The history is gone until the next pass; a deferred rebuild must not keep showing it.
this.refreshStats(asset.id);
if (options.defer) void this.sync(asset.id).catch(() => {});
else await this.sync(asset.id);
return this.asset(asset.id);
Expand Down Expand Up @@ -744,9 +773,17 @@ export class Concord {
if (asset.syncError) {
this.db.write("UPDATE assets SET sync_error = NULL, sync_error_at = NULL WHERE id = ?", asset.id);
}
// Even a pass that added nothing moved the read-through time the controls log runs to.
this.refreshStats(asset.id);
return out;
} catch (err) {
if (this.removing.has(asset.id)) throw err;
// Pages written before the failure are committed; the figures must include them.
try {
this.refreshStats(asset.id);
} catch {
// The sync failure below is the one to report.
}
this.db.write(
"UPDATE assets SET sync_error = ?, sync_error_at = ? WHERE id = ?",
describeFailure(err),
Expand Down Expand Up @@ -1024,6 +1061,8 @@ export class Concord {
)?.count ?? 0;
const removed = this.db.write("DELETE FROM registers WHERE id = ? AND asset_id = ?", registerId, asset.id);
if (removed === 0) throw new NotFound("no such register for this asset");
// Its runs went with it, and the latest run may have been one of them.
this.refreshStats(asset.id);
return { runs };
}

Expand Down Expand Up @@ -1319,6 +1358,7 @@ export class Concord {
}
}
});
this.refreshStats(asset.id);
return { instructions: parsed.instructions.length, added, replaced, removed, issues: parsed.issues };
}

Expand Down Expand Up @@ -1499,6 +1539,7 @@ export class Concord {
now(),
JSON.stringify(result),
);
this.refreshStats(asset.id);
return this.run(id);
}

Expand Down Expand Up @@ -1843,6 +1884,7 @@ ul { margin: 6px 0 0; padding-left: 20px; }
at,
);
});
this.refreshStats(asset.id);
return { ok: true };
}

Expand Down Expand Up @@ -2046,6 +2088,7 @@ ul { margin: 6px 0 0; padding-left: 20px; }
breaks: [],
};
this.db.write("UPDATE actions SET result = ?, reconciled_at = ? WHERE id = ?", JSON.stringify(result), now(), id);
this.refreshStats(asset.id);
return this.action(id);
}

Expand Down Expand Up @@ -2226,6 +2269,7 @@ ul { margin: 6px 0 0; padding-left: 20px; }
...(cashFlowResult ? { cashInLieu: cashFlowResult } : {}),
};
this.db.write("UPDATE actions SET result = ?, reconciled_at = ? WHERE id = ?", JSON.stringify(result), now(), id);
this.refreshStats(asset.id);
return this.action(id);
}

Expand Down Expand Up @@ -2442,15 +2486,26 @@ ul { margin: 6px 0 0; padding-left: 20px; }
};
}

/** One asset with the headline figures the dashboard lists. */
/**
* One asset with the headline figures the dashboard lists. The figures come from the
* asset's `asset_stats` row, which every change that can move them rewrites (`refreshStats`),
* so a poll reads one row however long the history is.
*/
assetSummary(asset: AssetRecord) {
// Never indexed: the controls log runs up to the clock, and there is nothing to replay.
const row = asset.syncedAt ? this.db.get("SELECT * FROM asset_stats WHERE asset_id = ?", asset.id) : undefined;
const stats = row ? statsFromRow(row) : this.refreshStats(asset.id);
return { ...asset, ...stats };
}

/** The headline figures recomputed from the data, ignoring any stored row. */
private computeStats(asset: AssetRecord): AssetStats {
const state = this.state(asset);
const run = this.latestRun(asset.id);
const controls = this.controls(asset.id);
const actions = this.actions(asset.id);
const events = this.db.get<{ n: number }>("SELECT COUNT(*) AS n FROM events WHERE asset_id = ?", asset.id)!.n;
return {
...asset,
supply: formatUnits(state.supply, asset.decimals),
holderCount: state.balances.size,
eventCount: events,
Expand All @@ -2464,6 +2519,31 @@ ul { margin: 6px 0 0; padding-left: 20px; }
};
}

/**
* Recompute and store an asset's headline figures. Called at the end of every change that can
* move them: a sync pass, a rebuild, a reconciliation or a deleted register, a sign-off, an
* instructions import and a corporate action's reconciliation.
*/
private refreshStats(assetId: string): AssetStats {
const asset = this.asset(assetId);
const stats = this.computeStats(asset);
this.db.write(
`INSERT OR REPLACE INTO asset_stats (asset_id, supply, holder_count, event_count, incomplete, last_run,
open_reconciliation, open_controls, open_actions, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
asset.id,
stats.supply,
stats.holderCount,
stats.eventCount,
stats.incomplete ? 1 : 0,
stats.lastRun ? JSON.stringify(stats.lastRun) : null,
stats.openBreaks.reconciliation,
stats.openBreaks.controls,
stats.openBreaks.actions,
now(),
);
return stats;
}

/** Everything an auditor needs for a period, with a digest over the content. */
auditExport(ref: string, period: { from?: string; to?: string } = {}) {
const asset = this.asset(ref);
Expand Down
17 changes: 17 additions & 0 deletions services/api/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,23 @@ ALTER TABLE assets ADD COLUMN movement_window_hours INTEGER NOT NULL DEFAULT 24;
`,
// v5: per-asset reconciliation tolerance (smallest units as TEXT to preserve bigint precision).
`ALTER TABLE assets ADD COLUMN tolerance TEXT;`,
// v6: each asset's headline figures, so the dashboard's polled overview reads one row instead
// of replaying events and rebuilding the controls log. Derived data: a missing row is
// recomputed on the next read.
`
CREATE TABLE asset_stats (
asset_id TEXT PRIMARY KEY REFERENCES assets (id) ON DELETE CASCADE,
supply TEXT NOT NULL,
holder_count INTEGER NOT NULL,
event_count INTEGER NOT NULL,
incomplete INTEGER NOT NULL,
last_run TEXT,
open_reconciliation INTEGER NOT NULL,
open_controls INTEGER NOT NULL,
open_actions INTEGER NOT NULL,
updated_at TEXT NOT NULL
);
`,
];

/** Identity: who may sign in, and which workspace each session is bound to. */
Expand Down
Binary file added services/api/test/fixtures/db/org-v6.db
Binary file not shown.
10 changes: 10 additions & 0 deletions services/api/test/fixtures/make-db-fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,16 @@ build(join(outDir, "org-v5.db"), ORG_MIGRATIONS.slice(0, 5), (db) => {
VALUES ('usd-mainnet', 'mainnet', 'USD', 'GISSUER1', 'US Dollar', 7, 'baseline', 'ready', '5', '2024-01-01T00:00:00Z')`);
});

// v6 adds each asset's stored headline figures; one row proves the table survives later upgrades.
build(join(outDir, "org-v6.db"), ORG_MIGRATIONS.slice(0, 6), (db) => {
db.exec("INSERT INTO meta (key, value) VALUES ('fixture', 'org-v6')");
db.exec(`INSERT INTO assets (id, network, code, issuer, name, decimals, start_mode, state, created_at)
VALUES ('usd-mainnet', 'mainnet', 'USD', 'GISSUER1', 'US Dollar', 7, 'baseline', 'ready', '2024-01-01T00:00:00Z')`);
db.exec(`INSERT INTO asset_stats (asset_id, supply, holder_count, event_count, incomplete, last_run,
open_reconciliation, open_controls, open_actions, updated_at)
VALUES ('usd-mainnet', '1000', 2, 5, 0, NULL, 0, 1, 0, '2024-01-02T00:00:00Z')`);
});

build(join(outDir, "control-v1.db"), CONTROL_MIGRATIONS.slice(0, 1), (db) => {
db.exec(`INSERT INTO users (id, email, name, email_verified, created_at)
VALUES ('u1', 'alice@example.org', 'Alice', 1, '2024-01-01T00:00:00Z')`);
Expand Down
16 changes: 16 additions & 0 deletions services/api/test/migrations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,22 @@ describe("databases written by earlier builds", () => {
});
});

it("adds an empty asset_stats table to a v5 workspace database", () => {
upgraded("org-v5.db", ORG_MIGRATIONS, (db) => {
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM asset_stats")?.n).toBe(0);
});
});

it("opens the v6 workspace database and keeps its stored asset figures", () => {
upgraded("org-v6.db", ORG_MIGRATIONS, (db) => {
expect(db.get<{ value: string }>("SELECT value FROM meta WHERE key = 'fixture'")?.value).toBe("org-v6");
expect(db.get("SELECT supply, open_controls FROM asset_stats WHERE asset_id = 'usd-mainnet'")).toEqual({
supply: "1000",
open_controls: 1,
});
});
});

it("opens the v1 control database with the current migrations and keeps its rows", () => {
upgraded("control-v1.db", CONTROL_MIGRATIONS, (db) => {
expect(db.get<{ name: string }>("SELECT name FROM users WHERE id = 'u1'")?.name).toBe("Alice");
Expand Down
5 changes: 5 additions & 0 deletions services/api/test/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ describe("schema cascade deletion", () => {
INSERT INTO break_note_history (asset_id, scope, key, fingerprint, status, note, at)
VALUES ('A', 'scope', 'kA', 'fp', 'open', 'note', '2026-01-01'),
('B', 'scope', 'kB', 'fp', 'open', 'note', '2026-01-01');

INSERT INTO asset_stats (asset_id, supply, holder_count, event_count, incomplete, open_reconciliation,
open_controls, open_actions, updated_at)
VALUES ('A', '100', 1, 1, 0, 0, 0, 0, '2026-01-01'),
('B', '100', 1, 1, 0, 0, 0, 0, '2026-01-01');
`);

// Verify before deletion: each child table has 2 rows (one for A, one for B)
Expand Down
Loading
Loading