Let's build a computational notebook using TypeScript, focusing on the core structure: modeling the notebook as a Directed Acyclic Graph (DAG) of cells, and implementing symbol-level dependency tracking with incremental recomputation via topological scheduling and batched transactions.
🧠 Goals Recap
Model notebook as a DAG of cells.
Track dependencies at the symbol (cell) level.
Recompute via incremental topological scheduling.
Use batched transactions to avoid glitches.
🧱 Core Concepts
1. Cell
Each cell has:
A unique identifier (ID)
Source code (as a string)
Output (result of execution)
A set of symbols it defines
A set of symbols it uses (dependencies)
2. DAG of Cells
Each cell is a node in the DAG.
Edges represent symbol-level dependencies between cells.
3. Incremental Recomputation
When a cell changes:
Find all cells that depend on its output (via symbol usage)
Schedule recomputation in topological order
Use transactions to batch changes and prevent intermediate invalid states
class Notebook {
private cells: Map<CellId, Cell> = new Map();
private symbolToCells: Map<SymbolName, Set<CellId>> = new Map(); // which cells define a symbol
private graph: Map<CellId, Set<CellId>> = new Map(); // cell -> dependent cells
private reverseGraph: Map<CellId, Set<CellId>> = new Map(); // for topo sort
// Add or update a cell
addOrUpdateCell(id: CellId, code: string): void {
const oldCell = this.cells.get(id);
// Parse code (simplified)
const { definedSymbols, usedSymbols } = this.parseCode(code);
const newCell: Cell = {
id,
code,
definedSymbols,
usedSymbols,
output: undefined
};
// Remove old dependencies if cell existed
if (oldCell) {
this.removeCell(id);
}
// Add new cell
this.cells.set(id, newCell);
// Register defined symbols
for (const sym of definedSymbols) {
if (!this.symbolToCells.has(sym)) {
this.symbolToCells.set(sym, new Set());
}
this.symbolToCells.get(sym)!.add(id);
}
// Build graph edges from dependencies
for (const sym of usedSymbols) {
const providers = this.symbolToCells.get(sym) || new Set();
for (const providerId of providers) {
this.addEdge(providerId, id);
}
}
}
private parseCode(code: string): {
definedSymbols: Set<SymbolName>,
usedSymbols: Set<SymbolName>
} {
// Simplified parsing (in real notebook, use AST)
const definedSymbols = new Set<SymbolName>();
const usedSymbols = new Set<SymbolName>();
const lines = code.split('\n');
for (const line of lines) {
const assignMatch = line.match(/^\s*([a-zA-Z_]\w*)\s*=/);
if (assignMatch) {
definedSymbols.add(assignMatch[1]);
}
const refMatches = line.match(/([a-zA-Z_]\w*)/g);
if (refMatches) {
for (const ref of refMatches) {
if (!definedSymbols.has(ref)) {
usedSymbols.add(ref);
}
}
}
}
return { definedSymbols, usedSymbols };
}
private removeCell(id: CellId): void {
const cell = this.cells.get(id);
if (!cell) return;
// Remove from symbol map
for (const sym of cell.definedSymbols) {
const set = this.symbolToCells.get(sym);
if (set) {
set.delete(id);
if (set.size === 0) {
this.symbolToCells.delete(sym);
}
}
}
// Remove edges
this.graph.delete(id);
this.reverseGraph.delete(id);
for (const dep of this.graph.keys()) {
const deps = this.graph.get(dep);
if (deps) deps.delete(id);
}
for (const dep of this.reverseGraph.keys()) {
const revDeps = this.reverseGraph.get(dep);
if (revDeps) revDeps.delete(id);
}
this.cells.delete(id);
}
private addEdge(from: CellId, to: CellId): void {
if (!this.graph.has(from)) this.graph.set(from, new Set());
if (!this.reverseGraph.has(to)) this.reverseGraph.set(to, new Set());
this.graph.get(from)!.add(to);
this.reverseGraph.get(to)!.add(from);
}
// Run a transaction
runTransaction(changes: CellId[], executeFn: (cell: Cell) => Promise<any>): void {
const scheduled = this.topologicalSort(changes);
const updatedCells = new Set<CellId>();
const execute = async () => {
for (const id of scheduled) {
const cell = this.cells.get(id);
if (!cell) continue;
// Simulate execution
try {
cell.output = await executeFn(cell);
} catch (e) {
cell.output = `Error: ${e}`;
}
updatedCells.add(id);
}
};
execute().catch(console.error);
}
// Topological sort of affected cells
private topologicalSort(changed: CellId[]): CellId[] {
const result: CellId[] = [];
const inDegree = new Map<CellId, number>();
const queue: CellId[] = [];
// Build in-degree map
for (const id of this.cells.keys()) {
inDegree.set(id, 0);
}
for (const [from, toSet] of this.graph.entries()) {
for (const to of toSet) {
const current = inDegree.get(to) || 0;
inDegree.set(to, current + 1);
}
}
// Start from changed nodes
for (const id of changed) {
queue.push(id);
}
while (queue.length > 0) {
const id = queue.shift()!;
result.push(id);
const children = this.graph.get(id) || new Set();
for (const child of children) {
const current = inDegree.get(child)!;
inDegree.set(child, current - 1);
if (current === 1) {
queue.push(child);
}
}
}
return result;
}
}
✅ Usage Example
ts
const notebook = new Notebook();
// Define a simple notebook
notebook.addOrUpdateCell("A", "x = 42");
notebook.addOrUpdateCell("B", "y = x + 1");
notebook.addOrUpdateCell("C", "z = y * 2");
// Simulate execution
notebook.runTransaction(["A"], async (cell) => {
// In real notebook, this would be dynamic evaluation
console.log(`Running cell ${cell.id}: ${cell.code}`);
let result;
eval(cell.code); // ⚠️ Only for demo — use sandboxed evaluator in real use
return eval(cell.code.split('=')[0].trim()); // return value of symbol
});
🔄 Batched Transactions
When a cell is edited, we:
Update its dependencies
Find all affected downstream cells
Schedule a topological recomputation
Execute all in order, updating state in a batch
This prevents glitches (e.g., intermediate invalid states where dependent cells refer to outdated values).
🧪 Testing
You can test:
Changing a cell updates downstream cells
Adding/removing symbols updates the DAG
Cycles are not allowed (would break topological sort)
🧱 Next Steps (Future Enhancements)
Use AST parsing instead of regex
Add execution sandboxing
Implement undo/redo via transaction logs
Store state in IndexedDB or file system
UI integration (e.g., React)
🧾 Summary
This implementation:
Models notebook as a DAG of cells
Tracks dependencies at the symbol level
Uses incremental recomputation via topological sort
Applies changes in batched transactions to avoid glitches
Would you like me to turn this into a runnable Node.js or browser-based notebook demo?