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
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as Notebook from "@moku/core/Notebook";
import type { NotebookState } from "../execution.ts";

export interface Edge {
Expand All @@ -14,25 +15,16 @@ export function dependencyGraph(state: NotebookState): {
const order = state.document?.cells.map((cell) => cell.id) ?? [];
const { analysis } = state;
if (!analysis) return { order, edges: [], current: false };
const current = true;
const analyses = analysis.cells;
const definitions = new Map<string, string[]>();
for (const id of order)
for (const name of analyses[id]?.defs ?? []) {
definitions.set(name, [...(definitions.get(name) ?? []), id]);
}
const byPair = new Map<string, Edge>();
for (const to of order)
for (const name of analyses[to]?.refs ?? []) {
for (const from of definitions.get(name) ?? []) {
if (from === to) continue;
const key = JSON.stringify([from, to]);
const edge = byPair.get(key) ?? { from, to, names: [] };
edge.names.push(name);
byPair.set(key, edge);
}
}
const edges = [...byPair.values()];
const parents = Notebook.cellParents(analysis);
const edges = order.flatMap((to) =>
(parents.get(to) ?? []).map((from) => ({
from,
to,
names: analysis.cells[to].refs.filter((name) =>
analysis.cells[from]?.defs.includes(name),
),
})),
);
const incoming = new Map<string, number>(order.map((id) => [id, 0]));
for (const edge of edges) incoming.set(edge.to, (incoming.get(edge.to) ?? 0) + 1);
const remaining = new Set<string>(order);
Expand All @@ -45,5 +37,5 @@ export function dependencyGraph(state: NotebookState): {
for (const edge of edges)
if (edge.from === id) incoming.set(edge.to, (incoming.get(edge.to) ?? 0) - 1);
}
return { order: [...sorted, ...remaining], edges, current };
return { order: [...sorted, ...remaining], edges, current: true };
}
19 changes: 19 additions & 0 deletions apps/@moku-launcher/tests/graph-explainer/execution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,25 @@ Vitest.test("cycles remain inspectable without losing or duplicating cells", ()
NodeAssert.deepEqual(new Set(graph.order), new Set(["source", "consumer"]));
});

Vitest.test(
"host parents can add an unnamed edge and suppress an inferred edge",
() => {
const state = example();
state.analysis = {
...state.analysis,
cells: {
source: { ...state.analysis.cells.source, parents: [state.cells.consumer.id] },
consumer: { ...state.analysis.cells.consumer, parents: [] },
},
};
NodeAssert.deepEqual(dependencyGraph(state), {
current: true,
order: ["consumer", "source"],
edges: [{ from: "consumer", to: "source", names: [] }],
});
},
);

Vitest.test("not executed does not mean skipped, and explicit skip is retained", () => {
const cell = example().cells.consumer;
NodeAssert.equal(cellStatus(cell, undefined, []), "pending");
Expand Down
32 changes: 32 additions & 0 deletions packages/@moku-core/src/Notebook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,38 @@ export function cellIndex(
return cells;
}

/**
* Returns the direct parents of each cell in an analyzed revision.
*
* For hosts that omit parent IDs, infers dependencies from definitions and references.
*/
export function cellParents(
analysis: typeof Protocol.Analysis.Type,
): ReadonlyMap<string, readonly string[]> {
const cells = Object.entries(analysis.cells);
const parents = new Map<string, readonly string[]>();
for (const [id, cell] of cells) {
if (cell.parents !== undefined) parents.set(id, cell.parents);
}
if (parents.size === cells.length) return parents;

const definitions = new Map<string, string[]>();
for (const [id, cell] of cells) {
for (const name of cell.defs) {
const owners = definitions.get(name);
if (owners) owners.push(id);
else definitions.set(name, [id]);
}
}
for (const [id, cell] of cells) {
if (parents.has(id)) continue;
const inferred = new Set(cell.refs.flatMap((name) => definitions.get(name) ?? []));
inferred.delete(id);
parents.set(id, [...inferred]);
}
return parents;
}

/**
* Creates a cell ID that the caller has not reserved.
*
Expand Down
24 changes: 7 additions & 17 deletions packages/@moku-minimap/src/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ export interface Item {
readonly id: string;
readonly definitions: readonly string[];
readonly references: readonly string[];
/** IDs of the cell's direct dependencies. */
readonly parents: readonly string[];
}

export interface Trace {
Expand All @@ -26,24 +28,12 @@ export class Graph {
readonly current: boolean,
) {
this.#items = new Map(items.map((item) => [item.id, item]));
const definitions = new Map<string, string[]>();
for (const item of items) {
this.#parents.set(item.id, new Set());
this.#children.set(item.id, new Set());
for (const name of item.definitions) {
const owners = definitions.get(name) ?? [];
owners.push(item.id);
definitions.set(name, owners);
}
}
for (const item of items) {
for (const name of item.references) {
for (const owner of definitions.get(name) ?? []) {
// Reading a name defined by the same cell is not an inter-cell edge.
if (owner === item.id) continue;
this.#parents.get(item.id)?.add(owner);
this.#children.get(owner)?.add(item.id);
}
this.#parents.set(item.id, new Set(item.parents));
for (const parent of item.parents) {
const children = this.#children.get(parent);
if (children) children.add(item.id);
else this.#children.set(parent, new Set([item.id]));
}
}
}
Expand Down
30 changes: 14 additions & 16 deletions packages/@moku-minimap/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,15 @@ export function make(state: Notebook.Interface["state"]) {
const currentAnalysis = Atom.map(structure, ({ analysis }) => analysis);
// Errors and execution events are deliberately absent from graph identity.
const topology = Atom.map(structure, ({ document, analysis }): Topology => {
const current = analysis !== null;
const parents = analysis && Notebook.cellParents(analysis);
return {
current,
items: (document?.cells.map((cell) => cell.id) ?? [])

.map((id) => ({
id,
definitions: current ? (analysis?.cells[id]?.defs ?? []) : [],
references: current ? (analysis?.cells[id]?.refs ?? []) : [],
})),
current: analysis !== null,
items: (document?.cells ?? []).map(({ id }) => ({
id,
definitions: analysis?.cells[id]?.defs ?? [],
references: analysis?.cells[id]?.refs ?? [],
parents: parents?.get(id) ?? [],
})),
};
}).pipe(Atom.withEquality(sameTopology));
const ids = Atom.map(topology, ({ items }) => items.map((item) => item.id)).pipe(
Expand Down Expand Up @@ -142,10 +141,9 @@ export function make(state: Notebook.Interface["state"]) {
const downstream = active?.downstream.has(id) ?? false;
const parents = value.dependencies(id);
const children = value.dependents(id);
const direct =
active !== null &&
(value.dependencies(active.item.id).has(id) ||
value.dependents(active.item.id).has(id));
const directParent = active !== null && children.has(active.item.id);
const directChild = active !== null && parents.has(active.item.id);
const direct = directParent || directChild;
const work = get(execution(id));
const currentWork =
work?.code_fingerprint === cell.code_fingerprint ? work : undefined;
Expand Down Expand Up @@ -175,8 +173,7 @@ export function make(state: Notebook.Interface["state"]) {
highlighted: new Set(
item.definitions.filter(
(name) =>
active?.item.references.includes(name) ||
(active && value.dependents(active.item.id).has(id)),
directChild || (directParent && active.item.references.includes(name)),
),
),
relation,
Expand Down Expand Up @@ -217,7 +214,8 @@ function sameTopology(a: Topology, b: Topology): boolean {
(item, i) =>
item.id === b.items[i].id &&
sameArray(item.definitions, b.items[i].definitions) &&
sameArray(item.references, b.items[i].references),
sameArray(item.references, b.items[i].references) &&
sameArray(item.parents, b.items[i].parents),
)
);
}
Expand Down
39 changes: 18 additions & 21 deletions packages/@moku-minimap/tests/graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { Graph } from "../src/graph.ts";
Vitest.test("direct edges and transitive dependencies stay distinct", () => {
const graph = new Graph(
[
{ id: "result", definitions: [], references: ["y"] },
{ id: "source", definitions: ["x"], references: [] },
{ id: "middle", definitions: ["y"], references: ["x"] },
{ id: "result", definitions: [], references: ["y"], parents: ["middle"] },
{ id: "source", definitions: ["x"], references: [], parents: [] },
{ id: "middle", definitions: ["y"], references: ["x"], parents: ["source"] },
],
true,
);
Expand All @@ -18,21 +18,18 @@ Vitest.test("direct edges and transitive dependencies stay distinct", () => {
);
});

Vitest.test(
"cycles exclude the starting cell and unresolved names add no edges",
() => {
const graph = new Graph(
[
{ id: "a", definitions: ["x"], references: ["x", "y", "missing"] },
{ id: "b", definitions: ["y"], references: ["x"] },
],
true,
);
Vitest.expect(graph.dependencies("a")).toEqual(new Set(["b"]));
Vitest.expect(graph.trace("a")).toEqual({
upstream: new Set(["b"]),
downstream: new Set(["b"]),
});
Vitest.expect(graph.trace("missing")).toBeUndefined();
},
);
Vitest.test("tracing a cycle excludes the starting cell", () => {
const graph = new Graph(
[
{ id: "a", definitions: ["x"], references: ["y"], parents: ["b"] },
{ id: "b", definitions: ["y"], references: ["x"], parents: ["a"] },
],
true,
);
Vitest.expect(graph.dependencies("a")).toEqual(new Set(["b"]));
Vitest.expect(graph.trace("a")).toEqual({
upstream: new Set(["b"]),
downstream: new Set(["b"]),
});
Vitest.expect(graph.trace("missing")).toBeUndefined();
});
28 changes: 28 additions & 0 deletions packages/@moku-minimap/tests/minimap.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,34 @@ Vitest.test(
},
);

Vitest.test(
"a parent-only change updates the selected cell's connections",
async () => {
const initial = fixture();
const view = await mount(initial, (cell) => [...cell.highlighted].join(", "));
await React.act(async () => view.rows()[1].click());
Vitest.expect(view.element.textContent).toContain("0 upstream · 2 downstream");
const { cells } = initial.analysis;
await view.update({
...initial,
analysis: {
...initial.analysis,
cells: {
...cells,
middle: { ...cells.middle, parents: [] },
isolated: { ...cells.isolated, parents: [initial.document.cells[1].id] },
},
},
});
Vitest.expect(view.element.textContent).toContain("0 upstream · 1 downstream");
Vitest.expect(view.rows()[3].dataset.direct).toBe("true");
Vitest.expect(view.rows()[2].dataset.relation).toBe("unrelated");
await React.act(async () => view.rows()[2].click());
Vitest.expect(view.rows()[1].textContent).toBe("");
Vitest.expect(view.rows()[0].textContent).toBe("z");
},
);

Vitest.test(
"shifted endpoints do not retain overview arms beyond their connections",
async () => {
Expand Down
Loading