Skip to content
Closed
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
78 changes: 78 additions & 0 deletions docs/pr-164.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Add resource_usage_logs table to SQLite

Closes #164

## What

Introduces a dedicated `resource_usage_logs` table that records per-transaction
CPU, memory, and fee-parameter snapshots for any tracked Soroban contract.

Previously, resource data was tied exclusively to TTL-extension transactions
in `extension_history`. This new table is transaction-agnostic, making it
usable by any future code path that wants to persist resource consumption
without performing an extension.

## Schema

New table added to `src/db/schema.sql`:

```sql
CREATE TABLE IF NOT EXISTS resource_usage_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
contract_id TEXT NOT NULL REFERENCES contracts(id) ON DELETE CASCADE,
cpu_insns INTEGER NOT NULL,
mem_bytes INTEGER NOT NULL,
fee_instructions INTEGER,
fee_read_ledger_entries INTEGER,
fee_write_ledger_entries INTEGER,
fee_read_bytes INTEGER,
fee_write_bytes INTEGER,
fee_transaction_size INTEGER,
fee_historical_ledger INTEGER,
fee_rent_ledger INTEGER,
fee_refundable INTEGER,
recorded_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_resource_usage_logs_contract_id ON resource_usage_logs(contract_id);
CREATE INDEX IF NOT EXISTS idx_resource_usage_logs_recorded_at ON resource_usage_logs(recorded_at DESC);
```

All fee columns are nullable — not every RPC response includes a full fee breakdown.
`cpu_insns` and `mem_bytes` are required as they are always present in a simulation result.

A migration file (`src/db/migrations/001_resource_usage_logs.sql`) is also
included so that existing `sorokeep.db` files are upgraded automatically on
next startup via the `Migrator`.

## Repository API (`src/db/repositories.ts`)

Three new exported functions following the exact patterns used by the rest
of the file:

| Function | Description |
|---|---|
| `insertResourceUsageLog(db, log)` | Insert a new log entry; returns the new row id |
| `getResourceUsageLogs(db, contractId, options?)` | Query logs newest-first; supports `limit` and `since` filters |
| `getLatestResourceUsageLog(db, contractId)` | Convenience helper — returns the single most-recent row |

## Tests

Written **before** the implementation (TDD):

`tests/db/resource_usage_logs.test.ts` — 20 tests covering:

- Schema: table existence, index existence, foreign-key enforcement
- `insertResourceUsageLog`: happy path, null fee columns, duplicate entries
allowed, invalid `contract_id` rejected, zero values, caller-supplied
timestamp
- `getResourceUsageLogs`: empty result, DESC ordering, per-contract isolation,
`limit` option, negative-limit guard, `since` filter
- `getLatestResourceUsageLog`: empty result, most-recent selection, cross-contract isolation

## Checklist

- [x] Tests written first (red → green)
- [x] Schema migration runs on a fresh in-memory DB
- [x] All 20 new tests pass
- [x] Full test suite passes (495 tests, 0 failures)
- [x] No existing tests broken
11 changes: 0 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions src/db/migrations/001_resource_usage_logs.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-- Migration 001: add resource_usage_logs table (issue #164)
--
-- Stores per-transaction CPU, memory, and fee-parameter snapshots so that
-- operators can track resource consumption over time without relying on
-- extension_history (which is specific to TTL-extension transactions).

CREATE TABLE IF NOT EXISTS resource_usage_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
contract_id TEXT NOT NULL REFERENCES contracts(id) ON DELETE CASCADE,
cpu_insns INTEGER NOT NULL,
mem_bytes INTEGER NOT NULL,
fee_instructions INTEGER,
fee_read_ledger_entries INTEGER,
fee_write_ledger_entries INTEGER,
fee_read_bytes INTEGER,
fee_write_bytes INTEGER,
fee_transaction_size INTEGER,
fee_historical_ledger INTEGER,
fee_rent_ledger INTEGER,
fee_refundable INTEGER,
recorded_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_resource_usage_logs_contract_id
ON resource_usage_logs(contract_id);

CREATE INDEX IF NOT EXISTS idx_resource_usage_logs_recorded_at
ON resource_usage_logs(recorded_at DESC);
148 changes: 148 additions & 0 deletions src/db/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -822,3 +822,151 @@ export function hasUnresolvedResourceAlert(
if (!row || typeof row.usage_percent === "undefined") return false;
return row.usage_percent >= currentUsagePercent;
}

// ─── Resource Usage Logs (issue #164) ────────────────────────────────────────

/**
* A single resource-usage snapshot captured per Soroban transaction.
* All fee columns are nullable because not every RPC response includes the
* full fee breakdown.
*/
export interface ResourceUsageLog {
id: number;
contract_id: string;
cpu_insns: number;
mem_bytes: number;
fee_instructions: number | null;
fee_read_ledger_entries: number | null;
fee_write_ledger_entries: number | null;
fee_read_bytes: number | null;
fee_write_bytes: number | null;
fee_transaction_size: number | null;
fee_historical_ledger: number | null;
fee_rent_ledger: number | null;
fee_refundable: number | null;
recorded_at: string;
}

/**
* Insert a new resource-usage log entry.
*
* @returns The auto-assigned row id of the inserted entry.
*/
export function insertResourceUsageLog(
db: Database.Database,
log: {
contract_id: string;
cpu_insns: number;
mem_bytes: number;
fee_instructions?: number | null;
fee_read_ledger_entries?: number | null;
fee_write_ledger_entries?: number | null;
fee_read_bytes?: number | null;
fee_write_bytes?: number | null;
fee_transaction_size?: number | null;
fee_historical_ledger?: number | null;
fee_rent_ledger?: number | null;
fee_refundable?: number | null;
/** Optional ISO-8601 timestamp; defaults to CURRENT_TIMESTAMP when omitted. */
recorded_at?: string;
},
): number {
const result = db.prepare(`
INSERT INTO resource_usage_logs (
contract_id,
cpu_insns,
mem_bytes,
fee_instructions,
fee_read_ledger_entries,
fee_write_ledger_entries,
fee_read_bytes,
fee_write_bytes,
fee_transaction_size,
fee_historical_ledger,
fee_rent_ledger,
fee_refundable,
recorded_at
) VALUES (
@contract_id,
@cpu_insns,
@mem_bytes,
@fee_instructions,
@fee_read_ledger_entries,
@fee_write_ledger_entries,
@fee_read_bytes,
@fee_write_bytes,
@fee_transaction_size,
@fee_historical_ledger,
@fee_rent_ledger,
@fee_refundable,
COALESCE(@recorded_at, CURRENT_TIMESTAMP)
)
`).run({
contract_id: log.contract_id,
cpu_insns: log.cpu_insns,
mem_bytes: log.mem_bytes,
fee_instructions: log.fee_instructions ?? null,
fee_read_ledger_entries: log.fee_read_ledger_entries ?? null,
fee_write_ledger_entries: log.fee_write_ledger_entries ?? null,
fee_read_bytes: log.fee_read_bytes ?? null,
fee_write_bytes: log.fee_write_bytes ?? null,
fee_transaction_size: log.fee_transaction_size ?? null,
fee_historical_ledger: log.fee_historical_ledger ?? null,
fee_rent_ledger: log.fee_rent_ledger ?? null,
fee_refundable: log.fee_refundable ?? null,
recorded_at: log.recorded_at ?? null,
});
Comment on lines +870 to +918

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Store recorded_at in one canonical format.

Line 902 falls back to SQLite's CURRENT_TIMESTAMP (YYYY-MM-DD HH:MM:SS), while this API also accepts ISO-8601 strings like 2025-01-15T12:00:00.000Z. getResourceUsageLogs() and getLatestResourceUsageLog() then compare and sort recorded_at as raw TEXT, so mixed formats misorder same-day rows and can make since drop later auto-stamped entries. Normalize both defaults and caller-supplied values to one fixed-width UTC format before persisting them.

Possible fix
-        /** Optional ISO-8601 timestamp; defaults to CURRENT_TIMESTAMP when omitted. */
+        /** Optional canonical UTC ISO-8601 timestamp. */
         recorded_at?: string;
@@
-            COALESCE(`@recorded_at`, CURRENT_TIMESTAMP)
+            COALESCE(`@recorded_at`, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Apply the same default expression in src/db/schema.sql and src/db/migrations/001_resource_usage_logs.sql, and add a regression test that mixes an omitted recorded_at with an explicit ISO timestamp on the same date.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/** Optional ISO-8601 timestamp; defaults to CURRENT_TIMESTAMP when omitted. */
recorded_at?: string;
},
): number {
const result = db.prepare(`
INSERT INTO resource_usage_logs (
contract_id,
cpu_insns,
mem_bytes,
fee_instructions,
fee_read_ledger_entries,
fee_write_ledger_entries,
fee_read_bytes,
fee_write_bytes,
fee_transaction_size,
fee_historical_ledger,
fee_rent_ledger,
fee_refundable,
recorded_at
) VALUES (
@contract_id,
@cpu_insns,
@mem_bytes,
@fee_instructions,
@fee_read_ledger_entries,
@fee_write_ledger_entries,
@fee_read_bytes,
@fee_write_bytes,
@fee_transaction_size,
@fee_historical_ledger,
@fee_rent_ledger,
@fee_refundable,
COALESCE(@recorded_at, CURRENT_TIMESTAMP)
)
`).run({
contract_id: log.contract_id,
cpu_insns: log.cpu_insns,
mem_bytes: log.mem_bytes,
fee_instructions: log.fee_instructions ?? null,
fee_read_ledger_entries: log.fee_read_ledger_entries ?? null,
fee_write_ledger_entries: log.fee_write_ledger_entries ?? null,
fee_read_bytes: log.fee_read_bytes ?? null,
fee_write_bytes: log.fee_write_bytes ?? null,
fee_transaction_size: log.fee_transaction_size ?? null,
fee_historical_ledger: log.fee_historical_ledger ?? null,
fee_rent_ledger: log.fee_rent_ledger ?? null,
fee_refundable: log.fee_refundable ?? null,
recorded_at: log.recorded_at ?? null,
});
/** Optional canonical UTC ISO-8601 timestamp. */
recorded_at?: string;
},
): number {
const result = db.prepare(`
INSERT INTO resource_usage_logs (
contract_id,
cpu_insns,
mem_bytes,
fee_instructions,
fee_read_ledger_entries,
fee_write_ledger_entries,
fee_read_bytes,
fee_write_bytes,
fee_transaction_size,
fee_historical_ledger,
fee_rent_ledger,
fee_refundable,
recorded_at
) VALUES (
`@contract_id`,
`@cpu_insns`,
`@mem_bytes`,
`@fee_instructions`,
`@fee_read_ledger_entries`,
`@fee_write_ledger_entries`,
`@fee_read_bytes`,
`@fee_write_bytes`,
`@fee_transaction_size`,
`@fee_historical_ledger`,
`@fee_rent_ledger`,
`@fee_refundable`,
COALESCE(`@recorded_at`, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
)
`).run({
contract_id: log.contract_id,
cpu_insns: log.cpu_insns,
mem_bytes: log.mem_bytes,
fee_instructions: log.fee_instructions ?? null,
fee_read_ledger_entries: log.fee_read_ledger_entries ?? null,
fee_write_ledger_entries: log.fee_write_ledger_entries ?? null,
fee_read_bytes: log.fee_read_bytes ?? null,
fee_write_bytes: log.fee_write_bytes ?? null,
fee_transaction_size: log.fee_transaction_size ?? null,
fee_historical_ledger: log.fee_historical_ledger ?? null,
fee_rent_ledger: log.fee_rent_ledger ?? null,
fee_refundable: log.fee_refundable ?? null,
recorded_at: log.recorded_at ?? null,
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/db/repositories.ts` around lines 870 - 918, The resource usage log
persistence path in insertResourceUsageLog currently stores mixed recorded_at
formats because it falls back to SQLite CURRENT_TIMESTAMP while callers may pass
ISO-8601 strings, which breaks TEXT-based sorting and filtering in
getResourceUsageLogs and getLatestResourceUsageLog. Update
insertResourceUsageLog to normalize both the default and any supplied
log.recorded_at into one fixed-width UTC format before calling
db.prepare(...).run(...), and make the same default expression consistent in the
resource_usage_logs schema and migration. Add a regression test that inserts one
row with omitted recorded_at and another with an explicit ISO timestamp on the
same day to verify ordering and since filtering.


return result.lastInsertRowid as number;
}

/**
* Return resource-usage logs for a contract, newest first.
*
* @param options.limit Maximum number of rows to return (must be ≥ 0).
* @param options.since ISO-8601 lower-bound for recorded_at (inclusive).
*/
export function getResourceUsageLogs(
db: Database.Database,
contractId: string,
options: { limit?: number; since?: string } = {},
): ResourceUsageLog[] {
const { limit, since } = options;

if (limit !== undefined && limit < 0) {
throw new Error("limit must be non-negative");
}

const conditions: string[] = ["contract_id = @contractId"];
if (since !== undefined) {
conditions.push("recorded_at >= @since");
}

const where = conditions.join(" AND ");
const limitClause = limit !== undefined ? `LIMIT ${limit}` : "";

return db.prepare(`
SELECT *
FROM resource_usage_logs
WHERE ${where}
ORDER BY recorded_at DESC, id DESC
${limitClause}
`).all({ contractId, since: since ?? null }) as ResourceUsageLog[];
}

/**
* Return the single most-recent resource-usage log for a contract,
* or `undefined` if none exist.
*/
export function getLatestResourceUsageLog(
db: Database.Database,
contractId: string,
): ResourceUsageLog | undefined {
return db.prepare(`
SELECT *
FROM resource_usage_logs
WHERE contract_id = ?
ORDER BY recorded_at DESC, id DESC
LIMIT 1
`).get(contractId) as ResourceUsageLog | undefined;
}
21 changes: 21 additions & 0 deletions src/db/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,27 @@ CREATE TABLE IF NOT EXISTS resource_alert_configs (
UNIQUE(contract_id, channel_type, channel_target)
);

CREATE TABLE IF NOT EXISTS resource_usage_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
contract_id TEXT NOT NULL REFERENCES contracts(id) ON DELETE CASCADE,
cpu_insns INTEGER NOT NULL,
mem_bytes INTEGER NOT NULL,
fee_instructions INTEGER,
fee_read_ledger_entries INTEGER,
fee_write_ledger_entries INTEGER,
fee_read_bytes INTEGER,
fee_write_bytes INTEGER,
fee_transaction_size INTEGER,
fee_historical_ledger INTEGER,
fee_rent_ledger INTEGER,
fee_refundable INTEGER,
recorded_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_resource_usage_logs_contract_id
ON resource_usage_logs(contract_id);
CREATE INDEX IF NOT EXISTS idx_resource_usage_logs_recorded_at
ON resource_usage_logs(recorded_at DESC);

CREATE TABLE IF NOT EXISTS resource_alerts_fired (
id INTEGER PRIMARY KEY AUTOINCREMENT,
resource_alert_config_id INTEGER NOT NULL REFERENCES resource_alert_configs(id) ON DELETE CASCADE,
Expand Down
Loading
Loading