Skip to content
Draft
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
11 changes: 11 additions & 0 deletions .changeset/preserve-detached-root-ranges.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@fluidframework/tree": minor
"fluid-framework": minor
"__section": tree
---

Preserve node ranges during repair-data preparation and transaction minimization

SharedTree processes requests for removed content as ranges instead of enumerating each node before checking whether its content is already available.
Transaction minimization also preserves ranges moved out of newly built subtrees instead of emitting a separate build for each moved node.
These changes reduce bookkeeping for eligible ranges without changing the resulting tree content.
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,47 @@ export function chunkField(
return [...chunkRange(cursor, policy, length, false)];
}

/**
* Gets one owned chunk reference for a range of nodes in the current field.
* The cursor starts and ends in field mode.
* Only chunks that intersect the range are read, and partial uniform chunks retain their shape and value encoding.
*/
export function chunkFieldRange(
cursor: ITreeCursorSynchronous,
policy: ChunkCompressor,
range: IndexRange,
): TreeChunk {
assertNonNegativeSafeInteger(range.start);
assertNonNegativeSafeInteger(range.end);
assert(
range.start <= range.end && range.end <= cursor.getFieldLength(),
"Chunk range must be within the current field",
);
if (range.start === range.end) {
return combineChunks([]);
}

cursor.enterNode(range.start);
const firstChunkStart = cursor.chunkStart;
cursor.seekNodes(range.end - 1 - cursor.fieldIndex);
const lastChunkEnd = cursor.chunkStart + cursor.chunkLength;
cursor.seekNodes(firstChunkStart - cursor.fieldIndex);
const chunks = chunkRange(cursor, policy, lastChunkEnd - firstChunkStart, false);
if (cursor.mode === CursorLocationType.Nodes) {
cursor.exitNode();
}

// Splitting the start first prevents the end split from shifting its saved chunk index.
const start = splitFieldAtIndex(chunks, range.start - firstChunkStart, policy);
const end = splitFieldAtIndex(chunks, range.end - firstChunkStart, policy);
for (const [index, chunk] of chunks.entries()) {
if (index < start || index >= end) {
chunk.referenceRemoved();
}
}
return combineChunks(chunks.slice(start, end));
}

/**
* Get a TreeChunk for the current field (and its children) of cursor.
* Like {@link chunkField}, but forces the results into a single TreeChunk.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export {
type IChunker,
chunkFieldSingle,
chunkField,
chunkFieldRange,
combineChunks,
} from "./chunkTree.js";
export { buildChunkedForest } from "./chunkedForest.js";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
type ChangeFamily,
type ChangeFamilyEditor,
type ChangeRebaser,
type DeltaDetachedNodeId,
type DetachedNodeRange,
type DeltaRoot,
type NormalizedFieldUpPath,
type NormalizedUpPath,
Expand Down Expand Up @@ -109,7 +109,7 @@ export function intoDelta(taggedChange: TaggedChange<ModularChangeset>): DeltaRo
}

/**
* Returns the set of removed roots that should be in memory for the given change to be applied.
* Returns ranges of detached node IDs that should be in memory for the given change to be applied.
* A removed root is relevant if any of the following is true:
* - It is being inserted
* - It is being restored
Expand All @@ -122,7 +122,7 @@ export function intoDelta(taggedChange: TaggedChange<ModularChangeset>): DeltaRo
*
* @param change - The change to be applied.
*/
export function relevantRemovedRoots(change: ModularChangeset): Iterable<DeltaDetachedNodeId> {
export function relevantRemovedRoots(change: ModularChangeset): Iterable<DetachedNodeRange> {
return relevantModularRemovedRoots(change);
}

Expand Down
1 change: 1 addition & 0 deletions packages/dds/tree/src/feature-libraries/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export {
type TreeChunk,
chunkTree,
chunkField,
chunkFieldRange,
chunkFieldSingle,
buildChunkedForest,
defaultChunkPolicy,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import {
cheapRebaseValidation,
deltaFieldMapHasChanges,
expandDetachedFieldRanges,
makeAnonChange,
makeChangeAtomId,
makeDetachedFieldIndex,
Expand All @@ -21,7 +20,7 @@ import {
type TreeChunk,
} from "../../core/index.js";
import { brand, type Mutable, type RangeQueryResult } from "../../util/index.js";
import { chunkTree, defaultChunkPolicy } from "../chunked-forest/index.js";
import { chunkFieldRange, defaultChunkPolicy } from "../chunked-forest/index.js";
import {
getFromChangeAtomIdMap,
newChangeAtomIdBTree,
Expand Down Expand Up @@ -593,41 +592,39 @@ class ModularChangeMinimizer {
(deltaForBuilds as Mutable<DeltaRoot<unknown>>).fields = new Map();

const forest = forestFactory();
const detachedFieldIndex = makeDetachedFieldIndex();
const detachedFieldIndex = makeDetachedFieldIndex("Temp");

visitDelta(deltaForBuilds, forest.acquireVisitor(), detachedFieldIndex, undefined);
const visitor = forest.acquireVisitor();
visitDelta(deltaForBuilds, visitor, detachedFieldIndex, undefined, true);
visitor.free();
const squashedBuilds = newChangeAtomIdBTree<TreeChunk>();
const cursor = forest.getCursorAboveDetachedFields();
for (const entry of expandDetachedFieldRanges(detachedFieldIndex.ranges())) {
for (const entry of detachedFieldIndex.ranges()) {
cursor.enterField(detachedFieldIndex.toFieldKey(entry.root));

const rootId: ChangeAtomId = {
revision: entry.id.major,
localId: brand(entry.id.minor),
};

const attachEntry = getAttachFieldForDetach(
residualChange.crossFieldKeys,
residualChange.rootNodes,
rootId,
1,
);
assert(
attachEntry.length === 1,
0xd3b /* TODO: Handle chunks which are only partially attached */,
);

const isAttached = attachEntry.value !== undefined;
if (isAttached) {
cursor.enterNode(entry.index);
setInChangeAtomIdMap(
squashedBuilds,
for (let offset = 0; offset < entry.count; ) {
const rootId: ChangeAtomId = {
revision: entry.id.major,
localId: brand(entry.id.minor + offset),
};
const attachEntry = getAttachFieldForDetach(
residualChange.crossFieldKeys,
residualChange.rootNodes,
rootId,
chunkTree(cursor, { policy: defaultChunkPolicy, idCompressor: undefined }),
entry.count - offset,
);
cursor.exitNode();
if (attachEntry.value !== undefined) {
setInChangeAtomIdMap(
squashedBuilds,
rootId,
chunkFieldRange(
cursor,
{ policy: defaultChunkPolicy, idCompressor: undefined },
{ start: entry.index + offset, end: entry.index + offset + attachEntry.length },
),
);
}
offset += attachEntry.length;
}

cursor.exitField();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import { assert, fail, unreachableCase } from "@fluidframework/core-utils/internal";
import { UsageError } from "@fluidframework/telemetry-utils/internal";
import { BTree } from "@tylerbu/sorted-btree-es6";
import type { BTree } from "@tylerbu/sorted-btree-es6";
import { lt } from "semver-ts";

import {
Expand All @@ -20,6 +20,7 @@ import {
type ChangeRebaser,
type ChangesetLocalId,
type DeltaDetachedNodeId,
type DetachedNodeRange,
EditBuilder,
type FieldKey,
type FieldKindIdentifier,
Expand Down Expand Up @@ -54,7 +55,6 @@ import {
brand,
idAllocatorFromMaxId,
idAllocatorFromState,
getOrCreate,
mergeTupleBTrees,
type TupleBTree,
RangeMap,
Expand Down Expand Up @@ -1799,7 +1799,7 @@ function composeBuildsDestroysAndRefreshers(
}

/**
* Returns the set of removed roots that should be in memory for the given change to be applied.
* Returns ranges of detached node IDs that should be in memory for the given change to be applied.
* A removed root is relevant if any of the following is true:
* - It is being inserted
* - It is being restored
Expand All @@ -1813,9 +1813,7 @@ function composeBuildsDestroysAndRefreshers(
* @param change - The change to be applied.
* @param fieldKinds - The field kinds to delegate to.
*/
export function* relevantRemovedRoots(
change: ModularChangeset,
): Iterable<DeltaDetachedNodeId> {
export function* relevantRemovedRoots(change: ModularChangeset): Iterable<DetachedNodeRange> {
const rootIds: ChangeAtomIdRangeMap<boolean> = newChangeAtomIdRangeMap();
addAttachesToSet(change, rootIds);
addRenamesToSet(change, rootIds);
Expand All @@ -1824,12 +1822,27 @@ export function* relevantRemovedRoots(
rootIds.set({ revision, localId }, 1, true);
}

for (const entry of rootIds.entries()) {
for (let offset = 0; offset < entry.length; offset++) {
const detachId = offsetChangeAtomId(entry.start, offset);
yield makeDetachedNodeId(detachId.revision, detachId.localId);
let previous: DetachedNodeRange | undefined;
for (const { start, length } of rootIds.entries()) {
if (
previous !== undefined &&
previous.id.major === start.revision &&
previous.id.minor + previous.count === start.localId
) {
previous = { id: previous.id, count: previous.count + length };
} else {
if (previous !== undefined) {
yield previous;
}
previous = {
id: makeDetachedNodeId(start.revision, start.localId),
count: length,
};
}
}
if (previous !== undefined) {
yield previous;
}
}

function addAttachesToSet(
Expand Down Expand Up @@ -1887,51 +1900,67 @@ function addRenamesToSet(
* removes any refreshers from the provided change that are not relevant to the change.
*
* @param change - The change that possibly has missing or superfluous refreshers. Not mutated by this function.
* @param getDetachedNode - The function to retrieve a tree chunk from the corresponding detached node id.
* @param getDetachedNodes - Retrieves a nonempty prefix of the requested detached node IDs.
* The returned length must not exceed the requested count.
* A defined value transfers one owned chunk reference, whose top-level length must equal the returned length.
* An undefined value identifies a missing prefix.
* @param removedRoots - The set of removed roots that should be in memory for the given change to be applied.
* Can be retrieved by calling {@link relevantRemovedRoots}.
* @param requireRefreshers - when true, this function enforces that all relevant removed roots have a
* corresponding build or refresher.
*/
export function updateRefreshers(
change: ModularChangeset,
getDetachedNode: (id: DeltaDetachedNodeId) => TreeChunk | undefined,
removedRoots: Iterable<DeltaDetachedNodeId>,
getDetachedNodes: (
id: DeltaDetachedNodeId,
count: number,
) => RangeQueryResult<TreeChunk | undefined>,
removedRoots: Iterable<DetachedNodeRange>,
requireRefreshers: boolean = true,
): ModularChangeset {
const refreshers = newChangeAtomIdBTree<TreeChunk>();
const chunkLengths: Map<RevisionTag | undefined, BTree<number, number>> = new Map();
const coveredRoots = newChangeAtomIdRangeMap<boolean>();

if (change.builds !== undefined) {
for (const [[revision, id], chunk] of change.builds.entries()) {
const lengthTree = getOrCreate(chunkLengths, revision, () => new BTree());
lengthTree.set(id, chunk.topLevelLength);
coveredRoots.set({ revision, localId: id }, chunk.topLevelLength, true);
}
}

for (const root of removedRoots) {
if (change.builds !== undefined) {
const lengthTree = chunkLengths.get(root.major);

if (lengthTree !== undefined) {
const lengthPair = lengthTree.getPairOrNextLower(root.minor);
if (lengthPair !== undefined) {
const [firstMinor, length] = lengthPair;

// if the root minor is within the length of the minor of the retrieved pair
// then there's no need to check for the detached node
if (root.minor < firstMinor + length) {
continue;
}
}
for (const { id, count } of removedRoots) {
let offset = 0;
while (offset < count) {
const start = {
revision: id.major,
localId: brand<ChangesetLocalId>(id.minor + offset),
};
const covered = coveredRoots.getFirst(start, count - offset);
if (covered.value !== undefined) {
// If the detached node IDs are already covered by builds or earlier queries,
// then there's no need to retrieve their content.
offset += covered.length;
continue;
}
}

const node = getDetachedNode(root);
if (node === undefined) {
assert(!requireRefreshers, 0x8cd /* detached node should exist */);
} else {
refreshers.set([root.major, brand(root.minor)], node);
const { value: nodes, length } = getDetachedNodes(
makeDetachedNodeId(start.revision, start.localId),
covered.length,
);
assert(
Number.isSafeInteger(length) && length > 0 && length <= covered.length,
"Detached nodes must cover a nonempty prefix of the requested range",
);
if (nodes === undefined) {
assert(!requireRefreshers, 0x8cd /* detached node should exist */);
} else {
assert(
nodes.topLevelLength === length,
"Refresher chunk length must match its detached node ID range",
);
refreshers.set([start.revision, start.localId], nodes);
}
coveredRoots.set(start, length, true);
offset += length;
}
}

Expand Down
Loading