Skip to content

Commit 340e9d8

Browse files
committed
Merge pull request #8 from martinal/master
High-level description of a toolchain for diffing and merging of notebooks. Currently prototype implementation exists as the nbdime project.
2 parents 3e2be10 + 7ea2c63 commit 340e9d8

File tree

1 file changed

+281
-0
lines changed

1 file changed

+281
-0
lines changed

notebook-diff/notebook-diff.md

Lines changed: 281 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,281 @@
1+
# Diffing and merging notebooks
2+
3+
## Problem
4+
5+
Diffing and merging notebooks is not properly handled by standard linebased diff and merge tools.
6+
7+
8+
## Proposed Enhancement
9+
10+
* Make a package containing tools for diff and merge of notebooks
11+
* Command line functionality:
12+
- A command nbdiff with diff output as json or pretty-printed to console
13+
- A command nbmerge which should be git compatible
14+
- Command line tools for interactive resolution of merge conflicts
15+
- Optional launching of web gui for interactive resolution of merge conflicts
16+
- All command line functionality is also available through the Python package
17+
* Web gui functionality:
18+
- A simple server with a web api to access diff and merge functionality
19+
- A web gui for displaying notebook diffs
20+
- A web gui for displaying notebook merge conflicts
21+
- A web gui for interactive resolution of notebook merge conflicts
22+
* Plugin framework for mime type specific diffing
23+
24+
25+
## Detailed Explanation
26+
27+
Preliminary work resides in [nbdime](https://github.com/martinal/nbdime).
28+
29+
Fundamentally, we envision use cases mainly in the categories
30+
of a merge command for version control integration, and
31+
diff command for inspecting changes and automated regression
32+
testing. At the core of it all is the diff algorithms, which
33+
must handle not only text in source cells but also a number of
34+
data formats based on mime types in output cells.
35+
36+
Cell source is usually the primary content, and output can presumably
37+
be regenerated. In general it is not possible to guarantee that merged
38+
sources and merged output is consistent or makes any kind of
39+
sense. For many use cases options to silently drop output instead of
40+
requiring conflict resolution will produce a smoother workflow.
41+
However such data loss should only happen when explicitly requested.
42+
43+
44+
### Basic use cases of notebook diff
45+
46+
* View difference between two versions of a file:
47+
`nbdiff base.ipynb remote.ipynb`
48+
* Store difference between two versions of a file to a patch file
49+
`nbdiff base.ipynb remote.ipynb patch.json`
50+
* Compute diff of notebooks for use in a regression test framework:
51+
```
52+
import nbdime
53+
di = nbdime.diff_notebooks(a, b)
54+
assert not di
55+
```
56+
* View difference of output cells after re-executing notebook
57+
58+
59+
Variations will be added on demand with arguments to the nbdiff command, e.g.:
60+
61+
* View diff of sources only
62+
* View diff of output cells (basic text diff of output cells, image diff with external tool)
63+
64+
65+
### Basic use cases of notebook merge
66+
67+
The main use case for the merge tool will be a git-compatible commandline merge tool:
68+
```
69+
nbmerge base.ipynb local.ipynb remote.ipynb merged.ipynb
70+
```
71+
which can be called from git and launch a console tool or web gui for conflict resolution if needed.
72+
Ideally the web gui can reuse as much as possible from Jupyter Notebook.
73+
74+
Goals:
75+
76+
* Trouble free automatic merge when no merge conflicts occur
77+
* Optional behaviour to drop conflicting output, execution counts, and eventual other secondary data
78+
* Easy to use interactive conflict resolution
79+
80+
81+
### Notes on initial implementation
82+
83+
* An initial version of diff gui can simply show e.g. two differing
84+
images side by side, but later versions should do something more
85+
clever.
86+
87+
* An initial version of merge can simply join or optionally delete
88+
conflicting output.
89+
90+
* An initial version of conflict resolution can be to output a
91+
notebook with conflicts marked within cells, to be manually edited
92+
as a regular jupyter notebook.
93+
94+
95+
## Diff format
96+
97+
The diff object represents the difference between two objects A and
98+
B as a list of operations (ops) to apply to A to obtain B. Each
99+
operation is represented as a dict with at least two items:
100+
```
101+
{ "op": <opname>, "key": <key> }
102+
```
103+
The objects A and B are either mappings (dicts) or sequences (lists),
104+
and a different set of ops are legal for mappings and sequences.
105+
Depending on the op, the operation dict usually contains an
106+
additional argument, documented below.
107+
108+
109+
### Diff format for mappings
110+
111+
For mappings, the key is always a string. Valid ops are:
112+
113+
* `{ "op": "remove", "key": <string> }`: delete existing value at key
114+
* `{ "op": "add", "key": <string>, "value": <value> }`: insert new value at key not previously existing
115+
* `{ "op": "replace", "key": <string>, "value": <value> }`: replace existing value at key with new value
116+
* `{ "op": "patch", "key": <string>, "diff": <diffobject> }`: patch existing value at key with another diffobject
117+
118+
119+
### Diff format for sequences (list and string)
120+
121+
For sequences the key is always an integer index. This index is
122+
relative to object A of length N. Valid ops are:
123+
124+
* `{ "op": "removerange", "key": <string>, "length": <n>}`: delete the values A[key:key+length]
125+
* `{ "op": "addrange", "key": <string>, "valuelist": <values> }`: insert new items from valuelist before A[key], at end if key=len(A)
126+
* `{ "op": "patch", "key": <string>, "diff": <diffobject> }`: patch existing value at key with another diffobject
127+
128+
129+
### Relation to JSONPatch
130+
131+
The above described diff representation has similarities with the
132+
JSONPatch standard but is different in some significant ways:
133+
134+
* JSONPatch contains operations "move", "copy", "test" not used by
135+
nbdime, and nbdime contains operations "addrange", "removerange", and
136+
"patch" not in JSONPatch.
137+
138+
* Instead of providing a recursive "patch" op, JSONPatch uses a deep
139+
JSON pointer based "path" item in each operation instead of the "key"
140+
item nbdime uses. This way JSONPatch can represent the diff object as
141+
a single list instead of the 'tree' of lists that nbdime uses. The
142+
advantage of the recursive approach is that e.g. all changes to a cell
143+
are grouped and do not need to be collected.
144+
145+
* JSONPatch uses indices that relate to the intermediate (partially
146+
patched) object, meaning transformation number n cannot be interpreted
147+
without going through the transformations up to n-1. In nbdime the
148+
indices relate to the base object, which means 'delete cell 7' means
149+
deleting cell 7 of the base notebook independently of the previous
150+
transformations in the diff.
151+
152+
A conversion function can fairly easily be implemented.
153+
154+
155+
## High level diff algorithm approach
156+
157+
The package will contain both generic and notebook-specific variants of diff algorithms.
158+
159+
The generic diff algorithms will handle most json-compatible objects:
160+
161+
* Arbitrary nested structures of dicts and lists are allowed
162+
163+
* Leaf values can be any strings and numbers
164+
165+
* Dict keys must always be strings
166+
167+
The generic variants will by extension produce correct diffs for
168+
notebooks, but the notebook-specific variants aim to produce more
169+
meaningful diffs. "Meaningful" is a subjective concept and the
170+
algorithm descriptions below are therefore fairly high-level with
171+
many details left up to the implementation.
172+
173+
174+
175+
### Handling nested structures by alignment and recursion
176+
177+
The diff of objects A and B is computed recursively, handling dicts
178+
and lists with different algorithms.
179+
180+
181+
### Diff approach for dicts
182+
183+
When computing the diff of two dicts, items are always aligned by key
184+
value, i.e. under no circumstances are values under different keys
185+
compared or diffed. This makes both diff and merge quite
186+
straightforward. Modified leaf values that are both a list or both a
187+
dict will be diffed recursively, with the diff object recording a
188+
"patch" operation. Any other modified leaf values are considered
189+
replaced.
190+
191+
192+
### Diff approach for lists
193+
194+
We wish to diff sequences and also recurse and diff aligned elements
195+
within the sequences. The core approach is to first align elements,
196+
requiring some heuristic for comparing elements, and then recursively
197+
diff the elements that are determined equal. *These heuristics will
198+
contain the bulk of the notebook-specific diff algorithm
199+
customizations.*
200+
201+
The most used approach for computing linebased diffs of source code is
202+
to solve the longest common subsequence (lcs) problem or some
203+
variation of it. We extend the vanilla LCS problem by allowing
204+
customizable predicates for approximate equality of two items,
205+
allowing e.g. a source cell predicate to determine that two pieces of
206+
source code are approximately equal and should be considered the same
207+
cell, or an output cell predicate to determine that two bitmap images
208+
are almost equal.
209+
210+
In addition we have an experimental multilevel algorithm that employs
211+
a basic LCS algorithm with a sequence of increasingly relaxed equality
212+
predicates, allowing e.g. prioritizing equality of source+output over
213+
just equality of source. Note that determining good heuristics and
214+
refining the above mentioned algorithms will be a significant part of
215+
the work and some experimentation must be allowed. In particular the
216+
behaviour of the multilevel approach must be investigated further and
217+
other approaches could be considered..
218+
219+
220+
### Displaying metadata diffs
221+
222+
The notebook format has metadata in various locations,
223+
including on each cell, output, and top-level on the notebook.
224+
These are dictionaries with potentially arbitrary JSON content.
225+
Computing metadata diffs is not different from any other dictionary diff.
226+
However, metadata generally does not have a visual representation in the live notebook,
227+
but it must be indicated in the diff view if there are changes.
228+
We will explore various represenentations of metadata changes in the notebook view.
229+
The most primitive would be to display the raw dictionary diff as a JSON field in the notebook view,
230+
near the displayable item the metadata is associated with.
231+
232+
233+
### Note about the potential addition of a "move" transformation
234+
235+
In the current implementation there is no "move" operation.
236+
Furthermore we make some assumptions on the structure of the json
237+
objects and what kind of transformations are meaningful in a diff.
238+
239+
Items swapping position in a list will be considered added and removed
240+
instead of moved, but in a future iteration adding a "move" operation
241+
is an option to be considered. The main use case for this would be to
242+
resolve merges without conflicts when cells in a notebook are
243+
reordered on one side and modified on the other side.
244+
245+
Even if we add the move operation, values will never be moved between
246+
keys in a dict, e.g.:
247+
248+
diff({"a":"x", "b":"y"}, {"a":"y", "b":"x"})
249+
250+
will be:
251+
252+
[{"op": "replace", "key": "a", "value": "y"},
253+
{"op": "replace", "key": "b", "value": "x"}]
254+
255+
In a notebook context this means for example that data will never be
256+
considered to move across input cells and output cells.
257+
258+
259+
## Merge format
260+
261+
A merge takes as input a base object (notebook) and local and remote
262+
objects (notebooks) that are modified versions of base. The merge
263+
computes the diffs base->local and base->remote and tries to apply all
264+
changes from each diff to base. The merge returns a merged object
265+
(notebook) contains all successfully applied changes from both sides,
266+
and two diff objects merged->local and merged->remote which contain
267+
the remaining conflicting changes that need manual resolution.
268+
269+
270+
## Pros and Cons
271+
272+
Pros associated with this implementation include:
273+
* Improved workflows when placing notebooks in version control systems
274+
* Possibility to use notebooks for self-documenting regression tests
275+
276+
Cons associated with this implementation include:
277+
* Vanilla git installs will not receive the improved behaviour, i.e. this will require installation of the package. To reduce the weight of this issue the package should avoid unneeded heavy dependencies.
278+
279+
280+
## Interested Contributors
281+
@martinal @minrk

0 commit comments

Comments
 (0)