perf: Skip the projection pass after a local delete that cannot change it

insteadOfDelete ran the full foreign key projection after every local
delete. Its closure follows edges both ways, so it loads every row
connected to the deleted one, which in a schema whose tables all hang off
one another is nearly the whole database: one deleted row of a person's
8,000 flashcards loaded 56,000 of 56,350 CRDT rows and took about 8 s on
the calling isolate, most of it deserialising rows. Inserts and updates
have had a proof that the pass is unnecessary
(canLeaveLocalProjectionUnchanged); deletes had none.

canSkipProjectionAfterLocalDelete proves it for a delete: every table
the delete can cascade into is reached by cascade edges on id only, none
of them restricts its parent (a deleted child can release a parent
delete held back by it), none has a unique index (a released claim can
bring a contestant back) or lies in a component with a SET DEFAULT edge,
and no attempted value is pending in the connected tables. The delete's
own cascade (applyDeleteActions) then is the whole projection; otherwise
the full pass runs as before. applyDeleteActions also asks for the
visible children of a whole batch of parents at once for cascades by id,
instead of one query per parent.

On that database a single delete now takes 6-63 ms, a card with its
revisions, tags and reviews 46-145 ms instead of 28-39 s. The new tests
cover a restrict child deleted locally releasing a merged parent delete
(on the person tables, and on the chain tables, where the shortcut is
asked and declines: the test fails with the restrict condition removed)
and a cascade child deleted locally through the shortcut, its parent
then deleted by a merged remote delete. The core, server, integration
and simulation suites pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tizian 「ティツィアーン」 2026-10-17 12:46:50 +02:00
commit b5450353b9
Signed by: raisondetredev
GPG key ID: 07F6FCF405488B64
3 changed files with 262 additions and 4 deletions

View file

@ -33,6 +33,15 @@ String domainColumnPredicate(
String alias = 'd',
}) => '$alias."${columnName.escapeIdentifier()}" = ${value.sqlLiteral()}';
/// SQL predicate matching rows where [columnName] holds one of [values],
/// which must not be empty.
@internal
String domainColumnInPredicate(
String columnName,
Iterable<Object?> values, {
String alias = 'd',
}) => '$alias."${columnName.escapeIdentifier()}" IN (${values.sqlLiteralList()})';
/// SQL predicate matching rows where [columnName] differs from [value].
@internal
String domainColumnNotPredicate(

View file

@ -159,6 +159,24 @@ class CrdtForeignKeyProjector {
_foreignKeys.referencingKeysByParentTable[parentTableName] ??
const <ReferencingForeignKey>[];
for (final reference in foreignKeys) {
// A cascade by id needs no per-parent answer: ask for every visible
// child of the whole batch at once instead of one query per parent.
if (reference.action == ForeignKeyAction.cascade &&
reference.parentColumn == 'id') {
final childIds = await _context.findVisibleDomainRowIdsWhere(
tableName: reference.childTableName,
predicates: [
domainColumnInPredicate(reference.childColumn, parentIds),
],
transaction: transaction,
);
if (childIds.isNotEmpty) {
cascadeDeletes
.putIfAbsent(reference.childTableName, () => {})
.addAll(childIds);
}
continue;
}
final parentValuesById = reference.parentColumn == 'id'
? null
: await _context.readDomainColumnValues(
@ -738,6 +756,54 @@ class CrdtForeignKeyProjector {
);
}
/// Proves that a local delete of [tableName] rows leaves nothing for the
/// projection pass to decide: the delete's own cascade
/// (`applyDeleteActions`, recursively) already hid everything it hides.
///
/// Holds when, in every table the delete can cascade into, every incoming
/// edge cascades by id (no SET NULL / SET DEFAULT repairs), no outgoing edge
/// restricts (the deleted row could be the blocker of a withheld parent
/// delete), no table has a unique index (a released claim could restore a
/// contestant) or a SET DEFAULT dependency, and no attempted value is
/// pending in the tables the pass would load. Otherwise the full pass runs.
Future<bool> canSkipProjectionAfterLocalDelete(
String tableName,
Transaction transaction,
) async {
final cascadeTables = <String>{};
final queue = [tableName];
while (queue.isNotEmpty) {
final table = queue.removeLast();
if (!cascadeTables.add(table)) continue;
for (final edge
in _foreignKeys.edgesByParentTable[table] ?? const <ForeignKeyEdge>[]) {
if (edge.action != ForeignKeyAction.cascade || edge.parentColumn != 'id') {
return false;
}
queue.add(edge.childTableName);
}
}
for (final table in cascadeTables) {
if (_uniqueResolver.tableHasUniqueIndexes(table)) return false;
if (_foreignKeys.tablesWithDefaultDependencies.contains(table)) return false;
for (final edge
in _foreignKeys.edgesByChildTable[table] ?? const <ForeignKeyEdge>[]) {
if (edge.action == ForeignKeyAction.restrict ||
edge.action == ForeignKeyAction.noAction) {
return false;
}
}
}
final reachable = _foreignKeys
.connectedTables({tableName})
.where(_context.syncTableByName.containsKey)
.toSet();
return !await _ProjectionReader(
_context,
transaction,
).hasAttemptedClaims(reachable);
}
/// Whether a mutation of [tableName] may require FK or unique projection.
bool needsProjection(String tableName, Set<String>? columnNames) {
if (_foreignKeys.columnsMayAffectForeignKeys(tableName, columnNames)) {

View file

@ -1232,12 +1232,19 @@ class CrdtMutationRecorder {
null,
CrdtDataDeletedReason.userDelete,
);
await _maybeProject(
// The delete's own cascade (applyDeleteActions above) usually is the
// whole projection; only run the full pass when it can decide more.
if (!await _foreignKeyProjector.canSkipProjectionAfterLocalDelete(
tableName,
deletedRows.uuidRowIds,
null,
transaction,
);
)) {
await _maybeProject(
tableName,
deletedRows.uuidRowIds,
null,
transaction,
);
}
await _context.persistCurrentNodeHlc(
_context.hlcManagerFor(transaction),
transaction,