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
97 changes: 97 additions & 0 deletions projects/start-os/web/ui/scripts/subtree-patch-db.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,103 @@ test('releasing every watch resumes an empty replica with NOTHING, not universal
assert.deepEqual(info.values, [])
})

for (const { name, patch, expected } of [
{
name: 'insertion',
patch: [{ op: 'add', path: '/arr/0', value: 'x' }],
expected: [null, 'a', null, null],
},
{
name: 'removal',
patch: [{ op: 'remove', path: '/arr/0' }],
expected: [null, 'c'],
},
]) {
test(`narrowing preserves a selected array position through an in-flight ${name}`, t => {
const f = fixture(t)
const whole = f.watch('arr')
const second = f.watch('arr', 1)
f.db.start()
f.start(f.calls[0], 3, { arr: ['a', 'b', 'c'] })
whole.subscription.unsubscribe()
t.mock.timers.tick(5000)
assert.deepEqual(f.updates.at(-1).selection, [{ include: '/arr/1' }])
assert.deepEqual(f.cache.value.value, { arr: [null, 'b', null] })
f.revision(f.calls[0], 4, patch)
t.mock.timers.tick(250)
assert.deepEqual(f.cache.value.value, { arr: expected })
assert.equal(second.values.at(-1), expected[1])
f.extend(f.calls[0], 4)
assert.deepEqual(f.cache.value.value, { arr: expected })
assert.equal(f.cache.value.id, 4)
f.revision(f.calls[0], 5, [
{ op: 'replace', path: '/arr/1', value: 'next' },
])
t.mock.timers.tick(250)
assert.equal(second.values.at(-1), 'next')
})
}

test('failure before narrowing confirmation resumes the correctly shifted array', t => {
const f = fixture(t)
const whole = f.watch('arr')
const second = f.watch('arr', 1)
f.db.start()
f.start(f.calls[0], 3, { arr: ['a', 'b', 'c'] })
whole.subscription.unsubscribe()
t.mock.timers.tick(5000)
f.revision(f.calls[0], 4, [{ op: 'add', path: '/arr/0', value: 'x' }])
f.calls[0].events.error(new Error('closed before confirmation'))
assert.deepEqual(f.cache.value.value, { arr: [null, 'a', null, null] })
assert.equal(second.values.at(-1), 'a')
f.db.start()
assert.deepEqual(f.calls[1].since, { epoch: 'boot', id: 4 })
assert.deepEqual(f.calls[1].selection, [{ include: '/arr/1' }])
f.calls[1].events.next({
epoch: 'boot',
id: 4,
subscription: 'again',
revisions: [],
})
f.revision(f.calls[1], 5, [
{ op: 'replace', path: '/arr', value: [null, 'later', null] },
])
t.mock.timers.tick(250)
assert.deepEqual(f.cache.value.value, { arr: [null, 'later', null] })
assert.equal(second.values.at(-1), 'later')
})

test('a watch acquired while flushing revisions cannot start a second selection update', t => {
const f = fixture(t)
let requested = false
let third
const first = f.db.watch$('a').subscribe(value => {
if (value.n !== 1 || requested) return
requested = true
third = f.watch('c')
})
t.after(() => first.unsubscribe())
f.db.start()
f.start(f.calls[0], 3, { a: { n: 0 } })
f.revision(f.calls[0], 4, [{ op: 'replace', path: '/a/n', value: 1 }])
const second = f.watch('b')
assert.equal(f.updates.length, 1)
assert.deepEqual(f.updates[0].selection, [
{ include: '/a' },
{ include: '/b' },
{ include: '/c' },
])
assert.deepEqual(second.values, [])
assert.deepEqual(third.values, [])
f.extend(f.calls[0], 4, [
{ op: 'add', path: '/b', value: 2 },
{ op: 'add', path: '/c', value: 3 },
])
assert.deepEqual(second.values, [2])
assert.deepEqual(third.values, [3])
assert.equal(f.updates.length, 1)
})

test('selection changes wait for the previous extension', t => {
const f = fixture(t)
f.watch('serverInfo')
Expand Down
8 changes: 6 additions & 2 deletions projects/start-sdk/lib/test/exec.lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ test('captures output and completes when exit precedes the stdin callback', asyn
test('health checks can terminate while fast commands finish', async () => {
const { sub } = subject()
;(cp.spawn as unknown as jest.Mock).mockImplementation(() => fakeChild())
let execs!: Promise<unknown>
let entered!: () => void
const started = new Promise<void>(resolve => {
entered = resolve
Expand All @@ -116,10 +117,11 @@ test('health checks can terminate while fast commands finish', async () => {
yield
},
fn: async () => {
entered()
await Promise.all(
execs = Promise.all(
Array.from({ length: 36 }, () => sub.exec(['true'], { timeout: 25 })),
)
entered()
await execs
return { result: 'success', message: 'All folders found' }
},
},
Expand All @@ -128,6 +130,8 @@ test('health checks can terminate while fast commands finish', async () => {
await health.updateStatus()
await started
await bounded(health.term())
// Unsettled commands would spawn the next test's mocked child.
await bounded(execs)
})

test('the deadline covers a stdin callback that never arrives', async () => {
Expand Down
2 changes: 1 addition & 1 deletion shared-libs/crates/patch-db/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ watch$(...path) → BehaviorSubject per unique path → Observable to consumer

### `SubtreePatchDB<T>`

One stream carries the union of reference-counted watches, with a five-second release delay and 250ms batching. Selection changes prune the browser replica immediately and request an ordered server extension. Confirmed coverage retains provable subsets of the previous selection; no coverage is `NOTHING`, while `[]` means the whole subtree. New watches wait for coverage confirmation. Failure resumes the confirmed selection from its single epoch/revision cursor rather than replaying discarded fields.
One stream carries the union of reference-counted watches, with a five-second release delay and 250ms batching. Selection changes prune the browser replica immediately and request an ordered server extension. Until that extension arrives, revisions apply to a retained pre-change replica before projecting into the browser replica; selected array positions stay correct through in-flight insertions and removals. Watches acquired synchronously during a revision flush join the next serialized selection update. Confirmed coverage retains provable subsets of the previous selection; no coverage is `NOTHING`, while `[]` means the whole subtree. New watches wait for coverage confirmation. Failure resumes the confirmed selection from its single epoch/revision cursor rather than replaying discarded fields.

`Projection::extension` computes fields newly required by a selection against the current store value. `PatchDb::reproject` changes the listener and sends the extension under the store lock, before later revisions. The TypeScript projection module mirrors selector unions and extension semantics.

Expand Down
32 changes: 25 additions & 7 deletions shared-libs/crates/patch-db/client/lib/subtree-patch-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ export type SubtreeOptions = {
* leaves. The document is a replica of the server's under the requested selection, which
* is the union of the watches' selectors. A selection change prunes the replica at once
* and fills it from the stream's `extend` revision, which also confirms the change; a watch
* is served once the confirmed selection covers it. The document cursor is the
* is served once the confirmed selection covers it. Selected array positions remain
* correct across selection changes and preceding revisions. Selection updates remain
* serialized through synchronous watcher callbacks. The document cursor is the
* subscription's. A failed subscription is reported on {@link failures$}; {@link start}
* resumes it from the cursor.
*/
Expand All @@ -103,6 +105,8 @@ export class SubtreePatchDB<
/** Confirmed coverage within `held`; empty coverage uses `NOTHING`, never `[]`. */
private confirmed: Selection | null = null
private updating: Selection | null = null
/** Revisions preceding the extension still use the previous selection. */
private beforeUpdate?: Dump<T>
private pending: Revision[] = []
private flush?: ReturnType<typeof setTimeout>
private running = false
Expand Down Expand Up @@ -268,13 +272,17 @@ export class SubtreePatchDB<
})
}

/** Requests the desired selection once the previous request is confirmed. */
private reselect() {
const subscription = this.subscription
if (!this.running || !subscription || this.updating || !this.held) return
const desired = this.desired()
if (selectionKey(desired) === selectionKey(this.held)) return
this.applyPending()
if (this.pending.length) {
this.applyPending()
this.reselect()
return
}
this.beforeUpdate = { ...this.cache$.value }
this.held = desired
const confirmed = this.confirmed ?? NOTHING
const retained = minimalSelection([
Expand Down Expand Up @@ -317,6 +325,7 @@ export class SubtreePatchDB<
}
if (event.extend) {
this.applyPending()
this.beforeUpdate = undefined
const cache = this.cache$.value
this.apply(cache, event, false)
this.confirmed = this.updating
Expand All @@ -341,23 +350,32 @@ export class SubtreePatchDB<
this.emit(cache)
}

/** Applies a revision as the document holds it; an extension is already projected. */
/** Extensions are already projected. */
private apply(cache: Dump<T>, revision: Revision, project = true) {
if (this.cursor && revision.id > this.cursor.id)
this.cursor = { ...this.cursor, id: revision.id }
const target = (project && this.beforeUpdate) || cache
const patch =
project && this.held
project && target === cache && this.held
? projectOperations(revision.patch, this.held, path =>
Array.isArray(getValueByPointer(cache.value, pathFromArray(path))),
)
: revision.patch
patch.forEach(op => applyOperation(cache, op as Operation<unknown>))
this.publishRevision({ id: revision.id, patch }, cache)
patch.forEach(op => applyOperation(target, op as Operation<unknown>))
if (target === cache) {
this.publishRevision({ id: revision.id, patch }, cache)
} else {
this.handleDump(
{ id: revision.id, value: projectRoot(this.held!, target.value) as T },
cache,
)
}
}

private suspend() {
this.running = false
this.applyPending()
this.beforeUpdate = undefined
this.stream?.unsubscribe()
this.stream = undefined
this.subscription = null
Expand Down
Loading