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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions apps/server/server/domains/collab/.context/apply.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ clock; a restore that brings nothing back is `done` with `restored: 0` and says
named this command), `left_out purged` (no command of kind `discard`, `undo_discard` or `unapply`
is stored under the id: the day-30 purge took it, or it never was; or what the entry held was
purged), with `leftOut` counting purged nodes beside a partial restore. A restore reopens a draft only if
Live's text has not overtaken it: `reopen` with `leaveOutEdited` compares, on the base the draft reopens with
Live's text has not overtaken it: `reopen` with `leaveOutEdited` reads an empty document as no blocks (as `blocksEqual` does: after the Un-Apply of a create, Live holds none while the base keeps an empty paragraph, and nobody edited that) and compares, on the base the draft reopens with
(its waiting Un-Applies replayed on a copy, since the check runs before the draft is open), the token ranges
Live changed since that base with the ranges the draft changed, both uncleaned (a long paragraph's
edits stay small hunks, `boundedDiff`, up to 1,000 edit operations; past that its hunks are `approx` and
Expand All @@ -252,7 +252,7 @@ counts as its review changes in `leftOut` and as `left_out changed_since` in `se
A left-out draft stays closed under its Discard (`closed_by` kept, so the day-30 purge still deletes it) with
`closed_cause = left_out`: a restore that answered takes it out of Trash's entry and `closedBy()`, so no entry
leaves the same thing out on every Restore. Every other reader (the model's write path, receipts, the purge)
reads it as the Discard's draft. `brought` names the documents whose text came back and whose tree changes did;
reads it as the Discard's draft. The restore still replays the draft's waiting Un-Applies onto the closed draft (`appendRows` with `draft: "any"`), so its base and Apply records no longer hold an Apply that was taken back. `brought` names the documents whose text came back and whose tree changes did;
Trash's Undo of the restore discards exactly those halves. An Un-Apply's reopen does not ask
(its own Apply wrote that text). A purged Work's branch is a 404
at the route. A branch of another project is a 404 too. A Work or
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,14 +247,14 @@ export type AppendCommitted = {
* Shape A's storage half, inside the caller's savepoint. The `UPDATE` is the sequence point:
* it bumps `revision` at whatever value it holds (no revision predicate, no retry) and holds
* the row lock to `COMMIT`, so journal ids are allocated in commit order per draft (tail
* order). It still refuses a closed or frozen draft. After the lock, one separate
* statement reads the committed prefix `since` the caller's base (a fresh READ COMMITTED
* order). It still refuses a closed or frozen draft unless the caller says `draft: "any"`. After
* the lock, one separate statement reads the committed prefix `since` the caller's base (a fresh READ COMMITTED
* snapshot, so every row committed before this lock), and `finalize` decides what to insert.
* Any outcome but `appended` throws `DraftWriteRollback` so the savepoint undoes the bump.
*/
export async function appendRowsWithinTx(
db: DrizzleDb,
input: Pick<AppendRowsInput, "draftId" | "base" | "finalize" | "work">,
input: Pick<AppendRowsInput, "draftId" | "base" | "finalize" | "work" | "draft">,
): Promise<AppendCommitted> {
const [locked] = await db
.update(documentDrafts)
Expand All @@ -266,7 +266,7 @@ export async function appendRowsWithinTx(
.where(
and(
eq(documentDrafts.id, input.draftId),
eq(documentDrafts.status, "active"),
input.draft === "any" ? undefined : eq(documentDrafts.status, "active"),
input.work === "any" ? undefined : draftOwnerActive,
),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ export function createDrizzleDraftStore(
const committed = await appendRowsWithinTx(tx, {
draftId: input.draftId,
work: input.work,
draft: input.draft,
base: input.base,
async finalize(read) {
prefix = { rows: read.tail.length, moved: read.checkpoint !== null };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,13 @@ import type { UpdateJournal } from "@meridian/agent-edit/integration";
import type { BranchId, CommandId, DocumentId, DraftOwner } from "@meridian/contracts";
import type { Database } from "@meridian/database";
import { applyCommandEffects, documentDrafts } from "@meridian/database/schema";
import { buildDocumentSchema, PROSEMIRROR_FRAGMENT_NAME } from "@meridian/prosemirror-schema";
import {
buildDocumentSchema,
isEmptyDocument,
PROSEMIRROR_FRAGMENT_NAME,
} from "@meridian/prosemirror-schema";
import { and, asc, eq, inArray, isNotNull, ne, sql } from "drizzle-orm";
import type { Node as PMNode } from "prosemirror-model";
import * as Y from "yjs";
import { currentDrizzleDb, deferUntilDrizzleCommit } from "../../../shared/drizzle-transaction.js";
import type { TreeListStore } from "../../context/ports/tree-list-store.js";
Expand Down Expand Up @@ -169,12 +174,15 @@ export function createReopenDrafts(
} else drafts.push(draft);
}
// A left-out draft stays closed under its Discard, which the purge still reaches, and leaves
// the entry: Restore answered for it.
if (leftOut.length > 0)
// the entry: Restore answered for it. Its waiting Un-Applies still finish, so its base stops
// holding their text and its Apply records stop claiming an Apply that was taken back.
if (leftOut.length > 0) {
await tx
.update(documentDrafts)
.set({ closedCause: "left_out" })
.where(inArray(documentDrafts.id, leftOutIds));
await replay(leftOutIds);
}
let swapped = 0;
for (const draft of drafts) {
const [newer] = await tx
Expand Down Expand Up @@ -223,7 +231,7 @@ export function createReopenDrafts(
};

/**
* How many changes of the closed draft Live's text has since overtaken (all of them or none):
* How many changes of the closed draft Live's text has since overtaken (all of them or none),
* Live edited the text the draft changed, or wrote a pure insertion at its edge, since the base the
* draft last saw (a pull merges only into an open draft, so that base is stale). Token ranges of
* the uncleaned diffs, which stay exact on a long paragraph, over the same base tokens, so they
Expand All @@ -242,13 +250,18 @@ export function createReopenDrafts(
);
const waiting = await waitingReversals(draft.draftId);
if (waiting.length > 0) reverseBaseHalf(doc, waiting);
const baseBlocks = readBlocks(doc.getXmlFragment(REVIEW_BASE_FRAGMENT), schema);
// An empty document is no blocks, as `blocksEqual` reads it: the Un-Apply of a create leaves
// Live with none while the base keeps its empty paragraph, and nobody edited that.
const emptyAsNone = (blocks: PMNode[]) => (isEmptyDocument(blocks) ? [] : blocks);
const baseBlocks = emptyAsNone(readBlocks(doc.getXmlFragment(REVIEW_BASE_FRAGMENT), schema));
const draftBlocks = readBlocks(doc.getXmlFragment(PROSEMIRROR_FRAGMENT_NAME), schema);
doc.destroy();
const snapshot = await deps.live.read(draft.documentId as DocumentId);
const live = storedDocument(snapshot);
try {
const liveBlocks = readBlocks(live.getXmlFragment(PROSEMIRROR_FRAGMENT_NAME), schema);
const liveBlocks = emptyAsNone(
readBlocks(live.getXmlFragment(PROSEMIRROR_FRAGMENT_NAME), schema),
);
const changed = diffBlocks(baseBlocks, draftBlocks);
const edits = diffBlocks(baseBlocks, liveBlocks, { cleanup: false });
// A hunk from a spent diff budget only bounds its edit: it is no evidence of overlap, on
Expand Down Expand Up @@ -364,6 +377,7 @@ export function createReopenDrafts(
const base = await deps.coordinator.loadBase(draftId);
const write = deps.coordinator.prepareAppend(base, [], {
work: "any",
draft: "any",
authorServerRows: (prefix) => reverseBaseHalf(prefix, reversals).rows,
});
try {
Expand Down
6 changes: 5 additions & 1 deletion apps/server/server/domains/collab/domain/draft-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export type DraftRuntime = {
admitted?: Y.Doc;
authorServerRows?: AuthorServerRows;
work?: "active" | "any";
draft?: "open" | "any";
precondition?: SavePrecondition;
},
): PreparedDraftAppend;
Expand Down Expand Up @@ -152,6 +153,7 @@ export type PreparedDraftWrite = {
/** The content the write was prepared as, before any lock; read it, never mutate it. */
readonly candidate: Y.Doc;
persist(): Promise<boolean>;
/** Installation waits for the surrounding transaction's commit, so a later rollback installs nothing. */
transfer(): void;
dispose(): void;
};
Expand Down Expand Up @@ -436,11 +438,12 @@ export function createDraftRuntime(input: DraftRuntimeInput): DraftRuntime {
admitted?: Y.Doc;
authorServerRows?: AuthorServerRows;
work?: "active" | "any";
draft?: "open" | "any";
precondition?: SavePrecondition;
},
): PreparedDraftAppend {
const { snapshot, replica } = base;
const { admitted, authorServerRows, work = "active", precondition } = options ?? {};
const { admitted, authorServerRows, work = "active", draft, precondition } = options ?? {};
let prefix: Y.Doc;
try {
prefix = cloneReplica(replica);
Expand Down Expand Up @@ -486,6 +489,7 @@ export function createDraftRuntime(input: DraftRuntimeInput): DraftRuntime {
draftId: snapshot.draftId,
documentId: snapshot.documentId,
work,
draft,
base: { checkpointRevision: replica.checkpointRevision, seq: replica.seq },
async finalize(read) {
const judged = await finalizeAppend(read, {
Expand Down
2 changes: 2 additions & 0 deletions apps/server/server/domains/collab/domain/draft-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,8 @@ export type AppendRowsInput = {
documentId: DocumentId;
/** Background rebases keep archived drafts current; incoming edits require active Work. */
work?: "active" | "any";
/** `any` appends to a closed draft too: a Restore finishing the Un-Applies of a draft it leaves out. */
draft?: "open" | "any";
/** The checkpoint and highest row the caller's base replica holds. */
base: DraftReadSince;
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ export class MemoryDraftStore implements DraftStore {
async appendRows(input: AppendRowsInput): Promise<AppendRowsOutcome> {
const documentDraft = this.drafts.get(input.draftId);
if (
documentDraft?.status !== "active" ||
!documentDraft ||
(input.draft !== "any" && documentDraft.status !== "active") ||
(input.work !== "any" && documentDraft.lifecycle !== "active")
)
return { status: "refused" };
Expand Down
Loading