Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions .changeset/zero-swift-shared-rows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'zero-swift': patch
---

The replica and the queries' sources now share each synced row instead of each keeping its own copy, so 100,000 synced rows of 10 columns take 75 MB instead of 127 MB. Pokes and optimistic mutations also apply 4–15% faster.
38 changes: 25 additions & 13 deletions swift/Sources/Zero/Client/Engine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@ final class Engine {
let mutatorNames = mutators.keys.sorted()
// The store `Zero.prepare` opened and read, unless it can't be used.
let adopted = prepared.flatMap { ReplicaDatabase.adopt($0, name: name) }
// The tables' row layouts: the stored rows load in them, so the
// replica and the sources share each row.
let layouts = prepared?.branch.layouts ?? IVMBranch.layouts(schema)
var database: ReplicaDatabase
var openFailure: StorageFailure?
var corrupt = false
Expand All @@ -243,11 +246,12 @@ final class Engine {
do {
if adopted != nil, let prepared {
joined = try database.initClient(
clientID, mutatorNames: mutatorNames, now: base.now,
clientID, mutatorNames: mutatorNames, now: base.now, layouts: layouts,
prepared: prepared.groupID.map { ($0, prepared.group) })
onPrepared = prepared.groupID == nil || joined.clientGroupID == prepared.groupID
} else {
joined = try database.initClient(clientID, mutatorNames: mutatorNames, now: base.now)
joined = try database.initClient(
clientID, mutatorNames: mutatorNames, now: base.now, layouts: layouts)
}
} catch is ReplicaDatabase.CorruptData {
// What the client group holds doesn't decode, so the client state
Expand All @@ -257,15 +261,17 @@ final class Engine {
database.drop()
database.release()
(database, openFailure, _) = ReplicaDatabase.open(options.storage, name: name)
joined = try database.initClient(clientID, mutatorNames: mutatorNames, now: base.now)
joined = try database.initClient(
clientID, mutatorNames: mutatorNames, now: base.now, layouts: layouts)
}
} catch {
// The client group can't be read: run on memory, as when the open
// fails.
database.release()
database = ReplicaDatabase.fallback(name: name, storage: options.storage)
openFailure = StorageFailure(error)
joined = try database.initClient(clientID, mutatorNames: mutatorNames, now: base.now)
joined = try database.initClient(
clientID, mutatorNames: mutatorNames, now: base.now, layouts: layouts)
}
let (clientGroupID, group) = joined
self.database = database
Expand Down Expand Up @@ -300,7 +306,7 @@ final class Engine {
mutations.map { (MutationKey(clientID: $0.clientID, id: $0.id), $0.aggregateWrites) },
uniquingKeysWith: { $1 })
let preparedBranch = onPrepared ? prepared : nil
self.ivmMain = preparedBranch?.branch ?? IVMBranch(schema: schema)
self.ivmMain = preparedBranch?.branch ?? IVMBranch(schema: schema, layouts: layouts)
let loop = self.loop
self.connectionManager = ConnectionManager(
disconnectTimeout: options.disconnectTimeoutMs, scheduler: scheduler,
Expand Down Expand Up @@ -1584,7 +1590,7 @@ final class Engine {
timestamp: pending.timestamp, aggregateWrites: Self.aggregateWrites(write)))
])
do {
try context.processChanges(diff, rows: tx.rows)
try context.processChanges(diff)
} catch {
// As in JS, the mutation stays committed and pending, but isn't
// pushed now, and its client outcome is the error.
Expand Down Expand Up @@ -1724,7 +1730,7 @@ final class Engine {
snapshot.cookie = poke.cookie
let patchWrite = KVWrite(snapshot.map)
do {
try ReplicaStore.apply(poke.patch, to: patchWrite)
try ReplicaStore.apply(poke.patch, to: patchWrite, layouts: ivmMain.layouts)
} catch {
throw PokeError(error.description)
}
Expand Down Expand Up @@ -1812,7 +1818,11 @@ final class Engine {
}
_ = try mutator(tx, m.args)
for (key, value) in restoring[MutationKey(m)] ?? [:] {
if let value { write.set(key.string, value) } else { write.delete(key.string) }
if let value {
write.set(key.string, KVValue(value, at: key.string, layouts: ivmMain.layouts))
} else {
write.delete(key.string)
}
}
main = write.map
branch = fork
Expand All @@ -1833,7 +1843,7 @@ final class Engine {
private static func aggregateWrites(_ write: KVWrite) -> [JSKey: JSONValue?] {
var writes: [JSKey: JSONValue?] = [:]
for key in write.writes where key.string.hasPrefix(Keys.aggregatesPrefix) {
writes[key] = .some(write.get(key.string))
writes[key] = .some(write.get(key.string)?.json)
}
return writes
}
Expand Down Expand Up @@ -1942,8 +1952,10 @@ final class Engine {
for case .update(let key, _, _) in patch {
guard let value = write.get(key) else { continue }
let table = Keys.sourceName(key)
guard let primaryKey = schema.tables[table]?.primaryKey else { continue }
let row = value.objectValue ?? [:]
guard let primaryKey = schema.tables[table]?.primaryKey,
let layout = ivmMain.layouts[table]
else { continue }
let row = value.sourceRow(layout)
if let rowKey = try? Keys.primaryKeyString(table: table, primaryKey: primaryKey, row: row) {
guard StringCompare.equal(rowKey, key) else {
throw PokeError("update of \(key) changes its primary key to \(rowKey)")
Expand All @@ -1953,9 +1965,9 @@ final class Engine {
// JS keeps a row whose merge leaves it without a usable primary key,
// and fails once a second one collides with it in the source.
guard let source = ivmMain.source(table) else { continue }
let sourceRow = Row(row, layout: source.layout)
let sourceRow = row.conformed(to: source.layout)
let compare = source.primaryIndex.data.compare
let previous = store.main.get(key).map { Row($0.objectValue ?? [:], layout: source.layout) }
let previous = store.main.get(key)?.sourceRow(source.layout)
let replacesItself = previous.map { compare($0, sourceRow) == 0 } ?? false
if (!replacesItself && source.primaryIndex.data.contains(sourceRow))
|| keyless[table, default: []].contains(where: { compare($0, sourceRow) == 0 })
Expand Down
39 changes: 21 additions & 18 deletions swift/Sources/Zero/Client/IVMBranch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,28 @@
final class IVMBranch {
private var sources: [String: MemorySource?]
private let schema: ZeroSchema
/// The layout of each table's rows. Forks share them, so the rows a
/// mutator writes in a fork go into this branch's sources as they are.
private let layouts: [String: RowLayout]
/// The layout of each table's rows. Forks share them, and the replica
/// keeps its rows in them, so the replica and the sources of a branch
/// and its forks share each row.
let layouts: [String: RowLayout]
/// The synced aggregates a child row's mutation moves, shared with the
/// forks: it is query metadata, not row state.
private let optimism: AggregateOptimism
/// Only the main branch registers optimistic aggregates and releases
/// aggregate sources (see `aggregateSource`).
private let isFork: Bool

convenience init(schema: ZeroSchema) {
convenience init(schema: ZeroSchema, layouts: [String: RowLayout]? = nil) {
self.init(
schema: schema, sources: [:], layouts: schema.tables.mapValues { RowLayout($0) },
schema: schema, sources: [:], layouts: layouts ?? Self.layouts(schema),
optimism: AggregateOptimism(), isFork: false)
}

/// A layout for each table's rows.
static func layouts(_ schema: ZeroSchema) -> [String: RowLayout] {
schema.tables.mapValues { RowLayout($0) }
}

private init(
schema: ZeroSchema, sources: [String: MemorySource?], layouts: [String: RowLayout],
optimism: AggregateOptimism, isFork: Bool
Expand Down Expand Up @@ -99,10 +105,10 @@ final class IVMBranch {

/// Applies the row changes of `diff` (`applyDiffs`): the aggregate rows
/// under `a/`, then the table rows under `e/`, which is key order. A run
/// of adds to one source is pushed together. A row in `rows`, by key, is
/// the one a transaction wrote, which is the value the diff has for it.
/// The main branch then releases the aggregate sources nothing uses.
func apply(_ diff: KVDiff, rows written: [String: Row] = [:]) {
/// of adds to one source is pushed together. A row the replica keeps in
/// the source's layout goes in as it is, shared with the replica. The
/// main branch then releases the aggregate sources nothing uses.
func apply(_ diff: KVDiff) {
var i = 0
// JS's throw ends `applyDiffs` at the change an operator failed on.
while i < diff.count, !PipelineFailure.hasFailed {
Expand All @@ -118,12 +124,12 @@ final class IVMBranch {
// A relationship aggregate's or a grouped query's rows replayed
// before its query materializes (a reload): the source takes the
// row's shape, and the builder reuses it.
let row: JSONValue
let row: KVValue
switch op {
case .del(_, let old): row = old
case .add(_, let new), .change(_, _, let new): row = new
}
let (columns, primaryKey) = Self.inferAggregateSchema(name, row.objectValue ?? [:])
let (columns, primaryKey) = Self.inferAggregateSchema(name, row.json.objectValue ?? [:])
source = aggregateSource(name, columns: columns, primaryKey: primaryKey)
}
guard let source else {
Expand All @@ -132,13 +138,10 @@ final class IVMBranch {
}
switch op {
case .del(_, let old):
source.push(.remove(Row(old.objectValue ?? [:], layout: source.layout)))
source.push(.remove(old.sourceRow(source.layout)))
i += 1
case .change(let key, let old, let new):
source.push(
.edit(
written[key] ?? Row(new.objectValue ?? [:], layout: source.layout),
oldRow: Row(old.objectValue ?? [:], layout: source.layout)))
case .change(_, let old, let new):
source.push(.edit(new.sourceRow(source.layout), oldRow: old.sourceRow(source.layout)))
i += 1
case .add:
// The source's own prefix: the key up to the slash after its name.
Expand All @@ -150,7 +153,7 @@ final class IVMBranch {
while i < diff.count, case .add(let key, let value) = diff[i],
key.utf8.starts(with: sourcePrefix.utf8)
{
rows.append(written[key] ?? Row(value.objectValue ?? [:], layout: source.layout))
rows.append(value.sourceRow(source.layout))
i += 1
}
source.pushAdds(rows)
Expand Down
4 changes: 2 additions & 2 deletions swift/Sources/Zero/Client/Inspector.swift
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public struct InspectorClient: Sendable {
done(
Result {
var map: [String: JSONValue] = [:]
for e in try self.state.kv(engine, self.id).entries { map[e.key] = e.value }
for e in try self.state.kv(engine, self.id).entries { map[e.key] = e.value.json }
return map
})
}
Expand All @@ -174,7 +174,7 @@ public struct InspectorClient: Sendable {
done(
Result {
try self.state.kv(engine, self.id).scan(prefix: Keys.entitiesPrefix + table + "/")
.compactMap { $0.value.objectValue.map(Row.init) }
.compactMap { $0.value.json.objectValue.map(Row.init) }
})
}
}
Expand Down
2 changes: 1 addition & 1 deletion swift/Sources/Zero/Client/MutationTracker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ final class MutationTracker {
largest = max(largest, mutationID)
switch op {
case .add(_, let value):
let result = try MutationResult(json: value)
let result = try MutationResult(json: value.json)
switch result {
case .ok(let data): try processMutationOk(clientID, mutationID, data)
case .error(let e): try processMutationError(clientID, mutationID, e)
Expand Down
9 changes: 7 additions & 2 deletions swift/Sources/Zero/Client/Prepare.swift
Original file line number Diff line number Diff line change
Expand Up @@ -210,12 +210,17 @@ final class PreparedReplica: @unchecked Sendable {
return nil
}
let file = FileID(path)
// The stored rows load in the branch's layouts, so the replica and its
// sources share them.
let layouts = IVMBranch.layouts(schema)
let read: (ReplicaDatabase.Records, String?, StoredGroup, Int64)
do {
read = try store.sync { db in
let records = try ReplicaDatabase.readRecords(from: db, directory: store.directory)
let match = ReplicaDatabase.matchingGroup(records.groups, mutatorNames: mutatorNames)
let group = try match.map { try SQLiteStore.loadGroup($0.id, from: db) } ?? StoredGroup()
let group =
try match.map { try SQLiteStore.loadGroup($0.id, from: db, layouts: layouts) }
?? StoredGroup()
db.setBusyTimeout(ms: SQLiteDatabase.busyTimeoutMs)
return (records, match?.id, group, try dataVersion(db))
}
Expand All @@ -225,7 +230,7 @@ final class PreparedReplica: @unchecked Sendable {
}
let (records, groupID, group, version) = read

let branch = IVMBranch(schema: schema)
let branch = IVMBranch(schema: schema, layouts: layouts)
branch.apply(KVDiff(adding: group.entries.entries))
let metrics = PreparedMetrics()
let delegate = BranchDelegate(branch)
Expand Down
4 changes: 2 additions & 2 deletions swift/Sources/Zero/Client/QueryContext.swift
Original file line number Diff line number Diff line change
Expand Up @@ -223,13 +223,13 @@ final class QueryContext {
/// Pushes `diff` into the branch and flushes the views. A push an
/// operator fails (where JS throws from it) still flushes what the views
/// got, as JS's `finally` does, and then throws.
func processChanges(_ diff: KVDiff, rows: [String: Row] = [:]) throws {
func processChanges(_ diff: KVDiff) throws {
releasePreparedViews()
if let branchFailure { throw branchFailure }
var failure: PipelineError?
batchViewUpdates {
do {
try PipelineFailure.capture { branch.apply(diff, rows: rows) }
try PipelineFailure.capture { branch.apply(diff) }
} catch {
failure = error as? PipelineError ?? PipelineError("\(error)")
}
Expand Down
Loading
Loading