Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
67355bd
ADFA-7296 SQLite debugger: record row and change events in the extension
claude Nov 25, 2026
02c384f
ADFA-7296 Apply spotless formatting to EventDecoder and its test
davidschachterADFA Nov 25, 2026
ce76bcb
ADFA-7296 Don't read row text through a NULL pointer when SQLite is o…
davidschachterADFA Nov 25, 2026
76be5b0
ADFA-7296 Cap max_row_bytes at 64 KiB so a row record always fits a r…
davidschachterADFA Nov 25, 2026
8592704
ADFA-7296 README: the row limit's cap and the measured cost of counti…
davidschachterADFA Nov 25, 2026
490feb0
ADFA-7296 README: the row event kind and interface version 3
davidschachterADFA Nov 25, 2026
4f971a8
ADFA-7296 EventDecoderTest: make the 4-byte number case reach the wid…
davidschachterADFA Nov 25, 2026
e16ea45
ADFA-7296 Merge origin/stage at 661279963 into sqlite-debugger/ADFA-7296
davidschachterADFA Nov 26, 2026
0c9a19e
ADFA-7296 test: size the fake engine's records as the native ones
davidschachterADFA Nov 26, 2026
2d674ec
ADFA-7296 EventDecoder: refuse a row count its bytes cannot hold
davidschachterADFA Nov 27, 2026
5d8acf6
ADFA-7296 Fix CodeRabbit findings: no big-blob reads, unknown changes…
davidschachterADFA Dec 1, 2026
dd7ee19
ADFA-7296 README: a query inside a leftover transaction can read stale
davidschachterADFA Dec 1, 2026
f4c3722
ADFA-7379 SQLite debugger: an 80-byte event record with an execution_…
davidschachterADFA Dec 1, 2026
6750d46
ADFA-7379 SQLite debugger: an execution id on STATEMENT, ROW and PROF…
davidschachterADFA Dec 1, 2026
ec05501
ADFA-7379 SQLite debugger: keep the execution id across a SQLITE_SCHE…
davidschachterADFA Dec 1, 2026
b9a3129
style: spotless reformat, no functional change
davidschachterADFA Dec 1, 2026
90c6286
ADFA-7379 SQLite debugger: a trigger step is not a nested statement
davidschachterADFA Dec 2, 2026
8a60b2b
ADFA-7296 SQLite debugger: changes only from a DML statement's own count
davidschachterADFA Dec 2, 2026
9c4d0fe
ADFA-7379 SQLite debugger: correct the eviction, version, cost and ro…
davidschachterADFA Dec 2, 2026
22009aa
ADFA-7296 SQLite debugger: the UTF-16 row-size cost is an accepted limit
davidschachterADFA Dec 2, 2026
bc41ff2
ADFA-7296 SQLite debugger: fix the WITH ... INSERT changes test
davidschachterADFA Dec 2, 2026
4ffc26d
ADFA-7296 SQLite debugger: refuse a cut number or null, keep the fake…
davidschachterADFA Dec 2, 2026
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
20 changes: 17 additions & 3 deletions subprojects/sqlite-debugger/README.md

Large diffs are not rendered by default.

302 changes: 289 additions & 13 deletions subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c

Large diffs are not rendered by default.

90 changes: 81 additions & 9 deletions subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ extern "C" {
#endif

// The interface version. Raise it when anything below changes shape.
#define SQLITEDBG_INTERFACE_VERSION 2
// 4: the event record has execution_id (72 to 80 bytes).
#define SQLITEDBG_INTERFACE_VERSION 4

// sqlite3_auto_extension's type. On a device the JNI layer looks it up in libsqlite3x.so with
// dlsym (requery exports every sqlite3_ function); host tests pass SQLite's own.
Expand Down Expand Up @@ -85,31 +86,84 @@ enum {
SQLITEDBG_EVENT_PROFILE = 2,
// The app asked SQLite to close the connection (SQLITE_TRACE_CLOSE); sql is empty.
SQLITEDBG_EVENT_CLOSE = 3,
// A statement returned a row (SQLITE_TRACE_ROW). Recorded only while a client is connected and
// row recording is on (sqlitedbg_set_row_capture); the data is the row's values, in the row
// layout below, not SQL. rows is the row's number in its statement, from 1.
SQLITEDBG_EVENT_ROW = 4,
};

enum {
// sql was cut at max_sql_bytes.
// The data was cut: SQL at max_sql_bytes, or a row's values at the row limits.
SQLITEDBG_EVENT_TRUNCATED = 1u << 0,
// sql has its bound values written in (sqlite3_expanded_sql). Only while a client is
// connected (sqlitedbg_set_client_connected): expanding a 1 MB value costs 2 MB on every run.
SQLITEDBG_EVENT_EXPANDED = 1u << 1,
// SQLITEDBG_EVENT_PROFILE only: rows were left unrecorded while row recording was on, because the
// statement returned more than the per-statement limit, or because the producer could not record
// a row (the byte budget is below a row header, or an allocation failed).
SQLITEDBG_EVENT_ROWS_CUT = 1u << 2,
};

// One event as sqlitedbg_read_events copies it out: this header, then sql_bytes of UTF-8 (no
// terminating NUL), then zero padding to a multiple of 8 bytes. Fields are in the CPU's byte order
// One event as sqlitedbg_read_events copies it out: this header, then data_bytes of data, then zero
// padding to a multiple of 8 bytes. The data is UTF-8 SQL (no terminating NUL) for every kind but
// SQLITEDBG_EVENT_ROW, whose data is its values (below). Fields are in the CPU's byte order
// (little-endian on every ABI we build). The JNI layer hands the bytes to Kotlin unchanged, so
// EventDecoder.kt mirrors this layout; change both together.
typedef struct sqlitedbg_event_record {
uint32_t record_bytes; // the whole record, padding included
uint32_t kind; // SQLITEDBG_EVENT_STATEMENT, _PROFILE or _CLOSE
uint32_t kind; // SQLITEDBG_EVENT_STATEMENT, _PROFILE, _CLOSE or _ROW
uint64_t seq; // 1, 2, 3...: every event made, dropped or not, gets the next one
uint64_t connection_id; // sqlitedbg_connection.id
int64_t thread_id; // gettid() of the thread running the statement
int64_t time_ns; // CLOCK_REALTIME when the event happened
int64_t duration_ns; // SQLITEDBG_EVENT_PROFILE only; -1 for the others
uint32_t flags; // SQLITEDBG_EVENT_TRUNCATED, SQLITEDBG_EVENT_EXPANDED
uint32_t sql_bytes;
} sqlitedbg_event_record; // 56 bytes; the SQL text follows
uint32_t flags; // SQLITEDBG_EVENT_TRUNCATED, _EXPANDED, _ROWS_CUT
uint32_t data_bytes;
// SQLITEDBG_EVENT_PROFILE: the rows the statement returned, whether or not they were recorded.
// SQLITEDBG_EVENT_ROW: this row's number, from 1. -1 otherwise, and -1 for a statement the
// extension did not see start (SQLite's own nested statements, or more than
// SQLITEDBG_STATEMENT_SLOTS statements stepped in turn on one connection).
int64_t rows;
// SQLITEDBG_EVENT_PROFILE of a statement that may write (sqlite3_stmt_readonly false): the rows
// it changed itself, as sqlite3_changes64 counts them (not those changed by triggers or foreign
// key actions); 0 when it changed none, as a CREATE TABLE. -1 (unknown) for a read-only
// statement, for the other kinds, when rows is -1, and when the statement had not finished when
// the event fired (reset or finalized part way, as an INSERT ... RETURNING stepped once, or a step
// that returned SQLITE_BUSY): its count is then partial or not yet set. Also -1 when the
// connection's total changed while the statement ran and it is not an INSERT, UPDATE, DELETE or
// REPLACE (a leading WITH counts), as a PRAGMA stepped across another statement's INSERT: the
// count sqlite3_changes64 holds is then that statement's.
int64_t changes;
// The run of a statement this event belongs to: the seq of its STATEMENT record, on that record
// and on the PROFILE and ROW records of the run. 0: none or unknown (a trigger's STATEMENT, a
// statement nested in a callback, an EXPLAIN, a CLOSE, or a statement the extension did not see
// start). A statement evicted from its slot keeps its id on its STATEMENT and on the ROW events
// recorded before the eviction; its later rows are not recorded, and its PROFILE has 0. Not contiguous,
// and restarting with the process like seq.
uint64_t execution_id;
} sqlitedbg_event_record; // 80 bytes; the data follows

// How many statements per connection the extension follows at once, to number their rows and count
// their changes. A connection that steps more statements in turn than this loses the oldest:
// its rows are not recorded and its PROFILE event has rows and changes -1.
#define SQLITEDBG_STATEMENT_SLOTS 16

// The data of an SQLITEDBG_EVENT_ROW: this header, then `kept` values, each a sqlitedbg_row_value
// followed by stored_bytes of value. Nothing is aligned: read each field with memcpy.
typedef struct sqlitedbg_row_header {
uint32_t columns; // sqlite3_column_count of the statement
uint32_t kept; // values that follow; fewer than columns when the row limit was reached
} sqlitedbg_row_header; // 8 bytes

typedef struct sqlitedbg_row_value {
uint8_t type; // SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB or SQLITE_NULL
uint8_t cut; // 1 if fewer than full_bytes were stored
uint16_t reserved; // 0
uint32_t stored_bytes; // bytes that follow: 8 for INTEGER (int64) and FLOAT (IEEE double),
// 0 for NULL, UTF-8 for TEXT (cut at a character boundary), BLOB bytes
uint32_t full_bytes; // the value's whole size (sqlite3_column_bytes for TEXT and BLOB)
// A value over 1 MiB that does not fit the limits is not read: stored_bytes 0, cut 1.
} sqlitedbg_row_value; // 12 bytes

typedef struct sqlitedbg_read_result {
// The seq of the last event copied out, or if none was, `after` moved past any dropped events
Expand Down Expand Up @@ -137,9 +191,27 @@ typedef struct sqlitedbg_read_result {
void sqlitedbg_read_events(uint64_t after, void *out, size_t out_bytes, sqlitedbg_read_result *result);

// Whether a client is connected. While it is, statements are recorded with their bound values
// written in. Off at install.
// written in, and rows if row recording is on. Off at install.
void sqlitedbg_set_client_connected(int connected);

// Turns row recording on (max_rows_per_statement > 0) or off (0, as at install). While it is on and
// a client is connected, the first max_rows_per_statement rows of each statement become
// SQLITEDBG_EVENT_ROW events. TEXT and BLOB values longer than max_value_bytes are cut (0: 256), and
// a row's data stops at max_row_bytes (0: 4 KiB; at most SQLITEDBG_MAX_ROW_BYTES; never more than
// half the buffer less one header).
// Each value is read with the accessor of its own type (sqlite3_column_type first), so the app sees
// the same values and types afterwards: sqlite3_column_text converts a value in place, and on a BLOB
// it makes the app's own sqlite3_column_type return SQLITE_TEXT (SQLite 3.49.1, sqlitedbg_test.c). Rows of statements the extension did
// not see start are never recorded: that drops the rows of SQLite's own nested statements, such as
// the schema read a CREATE TABLE runs. PROFILE events count rows whether or not this is on.
void sqlitedbg_set_row_capture(uint32_t max_rows_per_statement, uint32_t max_value_bytes,
uint32_t max_row_bytes);

// The largest max_row_bytes that sqlitedbg_set_row_capture keeps; a larger one is lowered to it.
// sqlitedbg_read_events stops at the first record that does not fit its buffer, so a row record must
// stay well below the 256 KiB the server reads at a time (DatabaseTools.EVENT_BATCH_BYTES).
#define SQLITEDBG_MAX_ROW_BYTES (64u * 1024u)

// Server connections

#define SQLITEDBG_SERVER_BUSY_MS 3000
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ enum class EventKind(

/** The app asked SQLite to close the connection; [Event.sql] is empty. */
CLOSE(3),

/**
* A statement returned a row, recorded only while a client is connected and row recording is on.
* [Event.row] holds its values, [Event.rows] its number in the statement; [Event.sql] is empty.
*/
ROW(4),
}

data class Event(
Expand All @@ -103,10 +109,48 @@ data class Event(
/** Set for [EventKind.PROFILE] only. */
val durationNanos: Long?,
val sql: String,
/** [sql] was cut at the extension's limit. */
/** [sql] was cut at the extension's limit, or for [EventKind.ROW], [row] was (see [RowValues]). */
val truncated: Boolean,
/** [sql] has its bound values written in. */
val expanded: Boolean,
/**
* [EventKind.PROFILE]: the rows the statement returned, recorded or not. [EventKind.ROW]: the row's
* number in its statement, from 1. Null otherwise, and for a statement the extension did not see start.
*/
val rows: Long? = null,
/**
* [EventKind.PROFILE] of a statement that may write: the rows it changed itself, as
* `sqlite3_changes64` counts them (not those changed by triggers); 0 when it changed none. Null for a
* read-only statement, for the other kinds, and when the statement had not finished (reset or finalized
* part way, or its step returned `SQLITE_BUSY`), as the count is then unknown.
*/
val changes: Long? = null,
/**
* [EventKind.PROFILE]: rows went unrecorded while row recording was on, because the statement returned
* more than the per-statement limit, or because the producer could not record a row (the byte budget
* was below a row header, or an allocation failed).
*/
val rowsCut: Boolean = false,
/** [EventKind.ROW] only: the row's values. */
val row: RowValues? = null,
/**
* The run of a statement this event belongs to: the [seq] of its [EventKind.STATEMENT] event, on that
* event and on the [EventKind.PROFILE] and [EventKind.ROW] events of the run. Null when there is none or
* it is unknown, and for [EventKind.CLOSE].
*/
val executionId: Long? = null,
)

data class RowValues(
/** The statement's column count. */
val columnCount: Int,
/**
* The values kept, in column order: null, [Long], [Double], [String] or [ByteArray]. Fewer than
* [columnCount] when the row's data reached its limit.
*/
val values: List<Any?>,
/** Indexes into [values] of TEXT and BLOB values that were cut at the value limit. */
val cutIndexes: Set<Int>,
)

data class EventBatch(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
* Decodes the records `sqlitedbg_read_events` copies out. Mirrors `sqlitedbg_event_record` in
* `sqlitedbg.h`: change both together. Little-endian, because the CPU is on every ABI we build.
* Decodes the records `sqlitedbg_read_events` copies out. Mirrors `sqlitedbg_event_record` and the
* row layout (`sqlitedbg_row_header`, `sqlitedbg_row_value`) in `sqlitedbg.h`: change both together.
* Little-endian, because the CPU is on every ABI we build.
*/
internal object EventDecoder {
/** `sizeof(sqlitedbg_event_record)`. */
const val HEADER_BYTES = 56
const val HEADER_BYTES = 80

private const val OFFSET_RECORD_BYTES = 0
private const val OFFSET_KIND = 4
Expand All @@ -19,10 +20,24 @@ internal object EventDecoder {
private const val OFFSET_TIME_NS = 32
private const val OFFSET_DURATION_NS = 40
private const val OFFSET_FLAGS = 48
private const val OFFSET_SQL_BYTES = 52
private const val OFFSET_DATA_BYTES = 52
private const val OFFSET_ROWS = 56
private const val OFFSET_CHANGES = 64
private const val OFFSET_EXECUTION_ID = 72

private const val FLAG_TRUNCATED = 1
private const val FLAG_EXPANDED = 2
private const val FLAG_ROWS_CUT = 4

internal const val ROW_HEADER_BYTES = 8
internal const val ROW_VALUE_BYTES = 12

// SQLite's fundamental types, as sqlite3_column_type returns them.
private const val SQLITE_INTEGER = 1
private const val SQLITE_FLOAT = 2
private const val SQLITE_TEXT = 3
private const val SQLITE_BLOB = 4
private const val SQLITE_NULL = 5

/**
* The records in the first [length] bytes of [bytes].
Expand All @@ -40,16 +55,22 @@ internal object EventDecoder {
while (offset < length) {
require(length - offset >= HEADER_BYTES) { "record at $offset is cut off by the end of the data" }
val recordBytes = buffer.getInt(offset + OFFSET_RECORD_BYTES)
val sqlBytes = buffer.getInt(offset + OFFSET_SQL_BYTES)
require(sqlBytes >= 0 && recordBytes >= 0 && recordBytes % 8 == 0 && sqlBytes <= recordBytes - HEADER_BYTES) {
"record at $offset has record_bytes=$recordBytes sql_bytes=$sqlBytes"
val dataBytes = buffer.getInt(offset + OFFSET_DATA_BYTES)
require(dataBytes >= 0 && recordBytes >= 0 && recordBytes % 8 == 0 && dataBytes <= recordBytes - HEADER_BYTES) {
"record at $offset has record_bytes=$recordBytes data_bytes=$dataBytes"
}
require(recordBytes <= length - offset) { "record at $offset runs past the end of the data" }
val kindValue = buffer.getInt(offset + OFFSET_KIND)
val kind =
EventKind.values().firstOrNull { it.nativeValue == kindValue }
?: throw IllegalArgumentException("record at $offset has unknown kind $kindValue")
val flags = buffer.getInt(offset + OFFSET_FLAGS)
val dataStart = offset + HEADER_BYTES
// -1 in the record: does not apply, or the extension did not see the statement start
val rows = buffer.getLong(offset + OFFSET_ROWS).takeIf { it >= 0 && (kind == EventKind.PROFILE || kind == EventKind.ROW) }
val changes = buffer.getLong(offset + OFFSET_CHANGES).takeIf { it >= 0 && kind == EventKind.PROFILE }
// 0 in the record: none or unknown; CLOSE never has one
val executionId = buffer.getLong(offset + OFFSET_EXECUTION_ID).takeIf { it != 0L && kind != EventKind.CLOSE }
events +=
Event(
seq = buffer.getLong(offset + OFFSET_SEQ),
Expand All @@ -58,12 +79,80 @@ internal object EventDecoder {
threadId = buffer.getLong(offset + OFFSET_THREAD_ID),
timeEpochNanos = buffer.getLong(offset + OFFSET_TIME_NS),
durationNanos = if (kind == EventKind.PROFILE) buffer.getLong(offset + OFFSET_DURATION_NS) else null,
sql = String(bytes, offset + HEADER_BYTES, sqlBytes, Charsets.UTF_8),
sql = if (kind == EventKind.ROW) "" else String(bytes, dataStart, dataBytes, Charsets.UTF_8),
truncated = flags and FLAG_TRUNCATED != 0,
expanded = flags and FLAG_EXPANDED != 0,
rows = rows,
changes = changes,
rowsCut = kind == EventKind.PROFILE && flags and FLAG_ROWS_CUT != 0,
row = if (kind == EventKind.ROW) decodeRow(bytes, buffer, dataStart, dataBytes) else null,
executionId = executionId,
)
offset += recordBytes
}
return events
}

private fun decodeRow(
bytes: ByteArray,
buffer: ByteBuffer,
start: Int,
length: Int,
): RowValues {
require(length >= ROW_HEADER_BYTES) { "row at $start is shorter than its header" }
val end = start + length
val columns = buffer.getInt(start)
val kept = buffer.getInt(start + 4)
require(columns >= 0 && kept in 0..columns) { "row at $start has columns=$columns kept=$kept" }
// Each value takes at least ROW_VALUE_BYTES. Checked before ArrayList(kept) allocates: a count near
// Int.MAX_VALUE throws OutOfMemoryError there, before any value's own check runs.
require(kept <= (length - ROW_HEADER_BYTES) / ROW_VALUE_BYTES) {
"row at $start has kept=$kept, more values than its $length bytes hold"
}
val values = ArrayList<Any?>(kept)
Comment thread
davidschachterADFA marked this conversation as resolved.
Resolved
val cut = HashSet<Int>()
var pos = start + ROW_HEADER_BYTES
repeat(kept) { i ->
require(end - pos >= ROW_VALUE_BYTES) { "row at $start: value $i is cut off" }
val type = buffer.get(pos).toInt() and 0xff
val isCut = buffer.get(pos + 1).toInt() != 0
val stored = buffer.getInt(pos + 4)
val full = buffer.getInt(pos + 8)
pos += ROW_VALUE_BYTES
require(stored in 0..(end - pos) && full >= stored && isCut == (stored < full)) {
"row at $start: value $i has stored_bytes=$stored full_bytes=$full cut=$isCut"
}
values +=
when (type) {
SQLITE_INTEGER, SQLITE_FLOAT -> {
require(stored == 8) { "row at $start: number $i is $stored bytes" }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// The producer never cuts a number: full_bytes is the stored 8.
require(full == stored) { "row at $start: number $i has stored_bytes=$stored full_bytes=$full" }
if (type == SQLITE_INTEGER) buffer.getLong(pos) else buffer.getDouble(pos)
}

SQLITE_TEXT -> {
String(bytes, pos, stored, Charsets.UTF_8)
}

SQLITE_BLOB -> {
bytes.copyOfRange(pos, pos + stored)
}

SQLITE_NULL -> {
require(stored == 0) { "row at $start: null $i has $stored bytes" }
require(full == 0) { "row at $start: null $i has full_bytes=$full" }
null
}

else -> {
throw IllegalArgumentException("row at $start: value $i has unknown type $type")
}
}
if (isCut) cut += i
pos += stored
}
require(pos == end) { "row at $start has ${end - pos} bytes after its last value" }
return RowValues(columns, values, cut)
}
}
Loading
Loading