Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
1 change: 1 addition & 0 deletions changelog.d/branch-switch-unsaved.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `switchBranch()` and `fork()` no longer leave the manager initialized for the branch that the store left when the store selects the branch and then fails to save the selection. Chronicle 0.6 and 0.7 keep such a selection in effect. Chronicle 0.8 keeps the open store on its branch, so there the switch is a refusal, as before. The call now rejects, saying that the switch took effect and may not be saved, and that the manager's `sync()` saves it once the store can write. The manager refuses work until `setStrategy(getStrategy())` initializes it on the branch. Where a failed switch leaves the store on another branch, or the store can't say which, the call says so and the manager refuses work too. A `fork()` whose switch the store refuses now names the branch that it created. Where saving a new branch fails and the store keeps it, as chronicle 0.6 and 0.7 do, `fork()`, `branchAt()` and `derive()` now reject with an error that names the branch, with the store's error as its `cause`.
172 changes: 149 additions & 23 deletions src/context-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,19 +370,28 @@ interface DerivableStore {
* From switchBranch() or fork(), the call's branch selection, and a fork's
* branch creation, had already happened: `branch` names the branch, and
* `created` says whether this call created it. A caller never needs to retry
* a fork to learn whether it happened. From setStrategy(), `branch` is
* undefined.
* a fork to learn whether it happened. Where the call's own switch threw and
* a newer initialization began while the call read the store's branch, the
* selection may not have happened, or may not be saved: the message says
* that the switch threw, and `cause` is what it threw. From setStrategy(),
* `branch` is undefined.
*/
export class InitializationSupersededError extends Error {
readonly branch: string | undefined;
readonly created: boolean;

constructor(selection?: { branch: string; created: boolean }) {
constructor(selection?: { branch: string; created: boolean; failed?: { error: unknown } }) {
const failed = selection?.failed;
super(
selection
? `ContextManager.${selection.created ? 'fork created and selected' : 'switchBranch selected'} ` +
`branch "${selection.branch}", but its strategy initialization was superseded by a newer initialization`
: 'Strategy initialization was superseded by a newer initialization',
!selection
? 'Strategy initialization was superseded by a newer initialization'
: failed
? `ContextManager.${selection.created ? 'fork created' : 'switchBranch to'} branch "${selection.branch}"` +
`${selection.created ? ', its switch' : ''} threw, and a newer initialization superseded it: ` +
`${failed.error instanceof Error ? failed.error.message : String(failed.error)}`
: `ContextManager.${selection.created ? 'fork created and selected' : 'switchBranch selected'} ` +
`branch "${selection.branch}", but its strategy initialization was superseded by a newer initialization`,
failed ? { cause: failed.error } : undefined,
);
this.name = 'InitializationSupersededError';
this.branch = selection?.branch;
Expand Down Expand Up @@ -606,6 +615,8 @@ export class ContextManager {
private membrane?: Membrane;
private initializationAttempt = 0;
private initializedAttempt: number | null = null;
/** The id of the branch the store was on when `initializedAttempt` was marked ready. */
private initializedBranchId: string | null = null;
/** Whether we own the store (created it) vs app owns it (passed in) */
private ownsStore: boolean;
/** close() has run: the strategy is detached, and the manager refuses its operations (requireOpen). */
Expand Down Expand Up @@ -2696,6 +2707,11 @@ export class ContextManager {
* record then holds only the shards stored so far, so no cut could hold
* the whole body.
*
* Where saving the new branch fails and the store keeps it, as chronicle
* 0.6 and 0.7 keep a branch whose creation checkpoint fails, the call
* rejects with an error that names the branch, with the store's error as
* its `cause`. Elsewhere the store's error stands.
*
* Returns the new branch *name*, which is what `switchBranch` and `forkAt`
* expect. (Chronicle's branch APIs are name-keyed; the numeric `id` field
* on JsBranch is an internal identifier and isn't accepted by switchBranch.)
Expand All @@ -2713,7 +2729,7 @@ export class ContextManager {

// Use createBranchAt to branch at the message's sequence (time-travel),
// or at the write that presented it
const branch = this.store.createBranchAt(branchName, currentBranch.name, branchPoint);
const branch = this.createBranchSaying('branchAt', branchName, () => this.store.createBranchAt(branchName, currentBranch.name, branchPoint));

return branch.name;
}
Expand Down Expand Up @@ -2792,7 +2808,14 @@ export class ContextManager {
* mutations and strategy operations stay blocked until a successful
* switchBranch() or setStrategy(). Inspection and close remain available.
* If a newer initialization supersedes this one, the call rejects with
* InitializationSupersededError naming the branch it selected.
* InitializationSupersededError naming the branch it selected, or saying
* that its native switch threw. Where the store selects the branch and
* then the native switch fails, as chronicle 0.6 and 0.7 can (0.8 keeps
* the open store on its branch), the switch is in effect and may not be saved: the
* call rejects, saying so, the strategy isn't initialized there, and
* sync() saves the selection once the store can write. Where the failed
* switch leaves the store on another branch, the call rejects and names
* it.
*
* The switch moves the store's branch, which every manager on the store
* follows, and starts a new branch generation. Every other manager's
Expand All @@ -2807,26 +2830,121 @@ export class ContextManager {
await this.selectBranch(branchId, false);
}

/**
* Makes branch `name` through `create`. Where `create` throws and the store
* holds the branch all the same (chronicle 0.6 and 0.7 keep a branch whose
* creation checkpoint fails), the error names it, with the native error as
* its cause; elsewhere the native error stands.
*/
private createBranchSaying<T>(operation: 'branchAt' | 'fork' | 'derive', name: string, create: () => T): T {
const holds = (): boolean | undefined => {
try {
return this.store.listBranches().some((branch) => branch.name === name);
} catch {
return undefined;
}
};
const before = holds();
try {
return create();
} catch (error) {
if (before !== false || holds() !== true) throw error;
throw new Error(
`ContextManager.${operation}: branch ${name} was created, and then saving it failed, so the store holds it unsaved: ` +
`once the store can write, sync() saves it or the store's deleteBranch() removes it; a store that lost durability saves nothing until it is opened again, and the store opened again doesn't hold the branch: ${error instanceof Error ? error.message : String(error)}`,
{ cause: error },
);
}
}

private async selectBranch(name: string, created: boolean): Promise<void> {
// On chronicle 0.8.0, a rejected native selection leaves the loaded
// branch usable. An earlier chronicle can keep the switch when only its
// checkpoint failed. Once the switch succeeds, invalidate BEFORE
// fallible/reentrant bookkeeping.
this.store.switchBranch(name);
// A rejected native selection leaves the loaded branch usable. Chronicle
// 0.6 and 0.7 select the branch before they checkpoint the selection, and
// a failed checkpoint leaves the selection in effect: that is a switch,
// unsaved. Chronicle 0.8 keeps the open store on its branch. Once the
// switch succeeds, invalidate BEFORE fallible/reentrant bookkeeping.
const said = (error: unknown): string => (error instanceof Error ? error.message : String(error));
const made = created ? ' (created)' : '';
let from: string | undefined;
try {
from = this.store.currentBranch().id;
} catch {
from = undefined;
}
let unsaved: { error: unknown } | undefined;
// Fenced across the native call and the reads after a failure, which a
// store's wrapper can re-enter: the attempt isn't moved, so work already
// stamped isn't cancelled by a refusal, which gives the fence back.
const before = this.initializationAttempt;
const ready = this.initializedAttempt;
this.initializedAttempt = null;
try {
this.store.switchBranch(name);
} catch (error) {
let now: { id: string; name: string } | undefined;
try {
now = this.store.currentBranch();
} catch {
now = undefined;
}
if (this.initializationAttempt !== before) {
// A newer initialization that finished before this call's switch
// moved the store is ready on a branch that the store has left.
if (this.initializedAttempt === this.initializationAttempt && this.initializedBranchId !== now?.id) this.initializedAttempt = null;
throw new InitializationSupersededError({ branch: name, created, failed: { error } });
}
if (now !== undefined && now.id === from) {
this.initializedAttempt = ready;
if (!created) throw error;
throw new Error(`Branch selection ${name} (created) was refused, and the store stays on its branch: branch ${name} exists, and the loaded branch stays usable: ${said(error)}`, { cause: error });
}
if (now === undefined || now.name !== name) {
const invalidated = ++this.initializationAttempt;
this.initializedAttempt = null;
let found = now?.name;
try {
found = markStoreBranchSwitch(this.store).name;
} catch {
// The manager is invalidated above whether or not the generation moves.
}
if (invalidated !== this.initializationAttempt) throw new InitializationSupersededError({ branch: name, created, failed: { error } });
throw new Error(
`Branch selection ${name}${made} failed, and the store ${found !== undefined ? `is on ${found}` : "can't say which branch it is on"}: the manager is uninitialized; ` +
`setStrategy(getStrategy()) initializes it where the store is, and sync() saves the store's selection once the store can write: ${said(error)}`,
{ cause: error },
);
}
unsaved = { error };
}
const attempt = ++this.initializationAttempt;
this.initializedAttempt = null;
let requested: StoreBranchGeneration;
try {
requested = markStoreBranchSwitch(this.store);
} catch (cause) {
throw new Error(
`Branch selection ${name}${created ? ' (created)' : ''} uncertain: earlier effects may have completed; ` +
`inspect the store and selected branch before retrying; recover with switchBranch() or setStrategy(): ` +
`${cause instanceof Error ? cause.message : String(cause)}`, { cause },
`Branch selection ${name}${made} uncertain: earlier effects may have completed; ` +
`inspect the store and selected branch before retrying; recover with switchBranch() or setStrategy(): ${said(cause)}` +
(unsaved === undefined ? '' : `; the native switch had failed with the store on ${name}, so the selection may not be saved, and sync() saves it once the store can write: ${said(unsaved.error)}`),
{ cause },
);
}
if (attempt !== this.initializationAttempt) {
throw new InitializationSupersededError({ branch: name, created });
throw new InitializationSupersededError({ branch: name, created, ...(unsaved !== undefined ? { failed: unsaved } : {}) });
}
if (unsaved !== undefined) {
if (requested.name !== name) {
throw new Error(
`Branch selection ${name}${made} took effect and then the switch failed, and reconciliation found ${requested.name}: the selection may not be saved; ` +
`sync() saves the store's selection once the store can write, and setStrategy(getStrategy()) initializes this manager where the store is: ${said(unsaved.error)}`,
{ cause: unsaved.error },
);
}
throw new Error(
`Branch selection ${name}${made} took effect, and then the switch failed, so the selection may not be saved: ` +
`sync() saves it once the store can write, and setStrategy(getStrategy()) initializes this manager on it: ${said(unsaved.error)}`,
{ cause: unsaved.error },
);
}
if (requested.name !== name) {
throw new Error(`Branch selection requested ${name}, but reconciliation found ${requested.name}; no strategy initialization ran for this selection; recover with switchBranch() or setStrategy()`);
Expand All @@ -2852,7 +2970,12 @@ export class ContextManager {
* switches it. The same recovery contract as switchBranch() applies. If a
* newer initialization supersedes this one, the call rejects with
* InitializationSupersededError naming the branch it created, so a caller
* never retries a fork to learn whether it happened.
* never retries a fork to learn whether it happened. Where the store
* refuses the switch and stays on its branch, the call rejects and names
* the branch that it created, and the loaded branch stays usable. Where
* saving the new branch fails and the store keeps it (chronicle 0.6 and
* 0.7), the call rejects before any switch, with an error that names the
* branch and holds the store's error as its `cause`.
*
* A fork made while a sharded addMessage of this manager stores its
* shards (from an onMessage listener of a shard's add) is refused before
Expand All @@ -2865,7 +2988,7 @@ export class ContextManager {
const branchName = name ?? `fork-${Date.now()}`;
const currentBranch = this.store.currentBranch();
const currentSeq = this.store.currentSequence();
const branch = this.store.createBranchAt(branchName, currentBranch.name, currentSeq);
const branch = this.createBranchSaying('fork', branchName, () => this.store.createBranchAt(branchName, currentBranch.name, currentSeq));
await this.selectBranch(branch.name, true);
return branch.name;
}
Expand Down Expand Up @@ -2933,7 +3056,9 @@ export class ContextManager {
* A derive made while a sharded addMessage of this manager stores its
* shards (from an onMessage listener of a shard's add) is refused before
* it makes a branch, as branchAt is: the checkpoint would hold only the
* shards stored so far.
* shards stored so far. Where saving the new branch fails and the store
* keeps it (chronicle 0.6 and 0.7), the call rejects with an error that
* names the branch and holds the store's error as its `cause`.
*/
async derive(options: DeriveContextOptions): Promise<ContextManager> {
this.refuseCutWhileWritingShards('derive');
Expand Down Expand Up @@ -2982,9 +3107,9 @@ export class ContextManager {
: undefined;

const branch = options.branch;
const created = atHead
const created = this.createBranchSaying('derive', branch, () => (atHead
? source.createBranchWithStates(branch, parentBranch, filter)
: source.createBranchAtWithStates(branch, parentBranch, atSequence, filter);
: source.createBranchAtWithStates(branch, parentBranch, atSequence, filter)));
let derived: ContextManager | undefined;
try {
const view = source.view(branch);
Expand Down Expand Up @@ -4706,6 +4831,7 @@ export class ContextManager {
);
}
this.initializedAttempt = attempt;
this.initializedBranchId = currentBranchId;
if (this.holdReleaseNotifyPending) this.notifyHoldsReleased();
// Rows that left first: what the strategy kept of a row that left and
// was presented again is at its old place, and goes before the row is
Expand Down
Loading
Loading