diff --git a/lib/session-state.js b/lib/session-state.js index f5bf31f1..233ddc67 100644 --- a/lib/session-state.js +++ b/lib/session-state.js @@ -619,7 +619,23 @@ class SessionState { if (end - start === 1) tx.deleteBlock(start) else tx.deleteBlockRange(start, end) - const dependency = start < this.flushedLength() ? updateDependency(this, start, true) : null + const flushedLength = this.flushedLength() + const dependency = start < flushedLength ? updateDependency(this, start, true) : null + + if (dependency !== null && !this.isDefault() && end < flushedLength) { + // Truncating the dependency to the start of the cleared range makes the + // blocks after the range (end is exclusive) resolve against this + // session's own storage, so copy them over first to keep them available. + const rx = this.storage.read() + const blockPromises = [] + for (let i = end; i < flushedLength; i++) blockPromises.push(rx.getBlock(i)) + rx.tryFlush() + + const blocks = await Promise.all(blockPromises) + for (let i = 0; i < blocks.length; i++) { + if (blocks[i] !== null) tx.putBlock(end + i, blocks[i]) + } + } const flushed = await this.flush() diff --git a/test/clear.js b/test/clear.js index 4c1767ba..2a54908b 100644 --- a/test/clear.js +++ b/test/clear.js @@ -288,3 +288,26 @@ async function consumeStream(rx) { for await (const b of rx) res.push(b) return res } + +test('clear on a session with dependencies keeps the blocks after the range', async function (t) { + const a = await create(t) + await a.append(['1', '2', '3', '4', '5']) + + const s = a.session({ name: 'batch' }) + await s.ready() + + await s.clear(1, 2) + + t.ok(await s.has(0), 'block before the range is kept') + t.is(await s.has(1), false, 'block in the range is cleared') + t.ok(await s.has(2), 'block at the end of the range is kept (end is exclusive)') + t.ok(await s.has(3), 'block after the range is kept') + t.ok(await s.has(s.length - 1), 'last block is kept') + t.alike(await s.get(2), b4a.from('3'), 'block at the end boundary still resolves') + t.alike(await s.get(4), b4a.from('5'), 'last block still resolves') + + t.ok(await a.has(3), 'default session is unaffected') + t.alike(await a.get(4), b4a.from('5'), 'default session block still resolves') + + await s.close() +})