Skip to content

Commit 9507318

Browse files
authored
Merge pull request #345 from ThePumpingLemma/dgrochowski/bounded-merge-diff
Bound the character diff on web saves
2 parents 6592407 + 19c6309 commit 9507318

7 files changed

Lines changed: 419 additions & 105 deletions

File tree

Lines changed: 13 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
require "diff/lcs"
2-
31
module Coplan
42
module Plans
53
# Converts (old_content, new_content) into an ordered array of replace_exact
@@ -19,6 +17,10 @@ module Plans
1917
# (one entry per hunk, not one per character), which keeps OT
2018
# transforms cheap when later edits rebase through this version.
2119
#
20+
# `granularity: :character` (web saves) compares characters directly so
21+
# a one-word edit stays one word. Plans::TextDiff bounds the search cost
22+
# and falls back to one replacement if the budget is exhausted.
23+
#
2224
# Operations are emitted in left-to-right order over the OLD content, and
2325
# each `_pre_resolved_ranges` accounts for cumulative deltas from prior
2426
# ops in the sequence — so applying them via ApplyOperations one after
@@ -37,26 +39,21 @@ def initialize(old_content:, new_content:, granularity: :line)
3739
def call
3840
return [] if @old_content == @new_content
3941

40-
old_lines = @granularity == :character ? @old_content.each_char.to_a : @old_content.lines
41-
new_lines = @granularity == :character ? @new_content.each_char.to_a : @new_content.lines
42-
43-
# offsets[i] = character offset of the start of line i (offsets[len] = total chars).
4442
# Positions throughout the codebase (anchor_start/anchor_end, resolved_range, etc.)
4543
# are character offsets, NOT byte offsets — so unicode is handled correctly.
46-
old_offsets = build_line_offsets(old_lines)
47-
new_offsets = build_line_offsets(new_lines)
48-
49-
sdiff = Diff::LCS.sdiff(old_lines, new_lines)
50-
hunks = group_hunks(sdiff)
44+
replacements =
45+
if @granularity == :character
46+
TextDiff.hunks(@old_content, @new_content).map { |hunk| [ hunk[:from], hunk[:to], hunk[:text] ] }
47+
else
48+
TextDiff.line_hunks(@old_content, @new_content).map do |old_from, old_to, new_from, new_to|
49+
[ old_from, old_to, @new_content[new_from...new_to] ]
50+
end
51+
end
5152

5253
cumulative_delta = 0
5354

54-
hunks.map do |hunk|
55-
old_start, old_end = char_range(hunk[:old_lines], hunk[:old_anchor], old_offsets)
56-
new_start, new_end = char_range(hunk[:new_lines], hunk[:new_anchor], new_offsets)
57-
55+
replacements.map do |old_start, old_end, new_text|
5856
old_text = @old_content[old_start...old_end] || ""
59-
new_text = @new_content[new_start...new_end] || ""
6057

6158
# Shift positions to account for prior ops' deltas. Because hunks
6259
# are emitted left-to-right and don't overlap, all prior ops are
@@ -75,74 +72,6 @@ def call
7572
op
7673
end
7774
end
78-
79-
private
80-
81-
def build_line_offsets(lines)
82-
offsets = [ 0 ]
83-
running = 0
84-
lines.each do |line|
85-
running += line.length
86-
offsets << running
87-
end
88-
offsets
89-
end
90-
91-
# Groups consecutive non-"=" sdiff entries into hunks. Each hunk
92-
# records the line indexes it touches on each side. Pure insertions
93-
# have an empty :old_lines list; pure deletions have an empty
94-
# :new_lines list — those use the recorded anchor as a zero-width
95-
# insertion point in that side.
96-
def group_hunks(sdiff)
97-
hunks = []
98-
current_old = []
99-
current_new = []
100-
current_old_anchor = nil
101-
current_new_anchor = nil
102-
in_hunk = false
103-
104-
flush = lambda do
105-
if in_hunk
106-
hunks << {
107-
old_lines: current_old.any? ? (current_old.min..current_old.max).to_a : [],
108-
new_lines: current_new.any? ? (current_new.min..current_new.max).to_a : [],
109-
old_anchor: current_old_anchor,
110-
new_anchor: current_new_anchor
111-
}
112-
current_old = []
113-
current_new = []
114-
current_old_anchor = nil
115-
current_new_anchor = nil
116-
in_hunk = false
117-
end
118-
end
119-
120-
sdiff.each do |ctx|
121-
if ctx.action == "="
122-
flush.call
123-
next
124-
end
125-
126-
in_hunk = true
127-
current_old_anchor ||= ctx.old_position
128-
current_new_anchor ||= ctx.new_position
129-
current_old << ctx.old_position if %w[- !].include?(ctx.action)
130-
current_new << ctx.new_position if %w[+ !].include?(ctx.action)
131-
end
132-
133-
flush.call
134-
hunks
135-
end
136-
137-
# Returns [start, end] character offsets for a hunk's line list. For a
138-
# pure insertion/deletion (empty line list), uses the anchor as a
139-
# zero-width range at offsets[anchor].
140-
def char_range(line_indexes, anchor, offsets)
141-
return [ offsets[anchor], offsets[anchor] ] if line_indexes.empty?
142-
first = line_indexes.first
143-
last = line_indexes.last
144-
[ offsets[first], offsets[last + 1] ]
145-
end
14675
end
14776
end
14877
end

‎engine/app/services/coplan/plans/merge_text.rb‎

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
require "diff/lcs"
2-
31
module Coplan
42
module Plans
53
# A three-way, character-range merge. Both sides are compared with the
@@ -8,25 +6,7 @@ class MergeText
86
class Conflict < StandardError; end
97

108
def self.hunks(before, after)
11-
result = []
12-
position = 0
13-
pending = nil
14-
Diff::LCS.sdiff(before.each_char.to_a, after.each_char.to_a).each do |change|
15-
if change.action == "="
16-
result << pending if pending
17-
pending = nil
18-
position += 1
19-
else
20-
pending ||= { from: position, to: position, text: "" }
21-
unless change.action == "+"
22-
position += 1
23-
pending[:to] = position
24-
end
25-
pending[:text] += change.new_element unless change.action == "-"
26-
end
27-
end
28-
result << pending if pending
29-
result
9+
TextDiff.hunks(before, after)
3010
end
3111

3212
def self.overlap?(left, right)
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
require "diff/lcs"
2+
3+
module Coplan
4+
module Plans
5+
# Character-offset replacements between two document versions. Skip common
6+
# edges, use LCS for small changes, and use a bounded Myers shortest-edit
7+
# search for larger changes. Never infer character positions from lines:
8+
# matching the wrong repeated line can misplace comments or concurrent edits.
9+
# If the search exhausts its budget, replace the entire changed middle.
10+
module TextDiff
11+
MAX_CHARACTER_CELLS = 1_000_000
12+
13+
# One budget for the whole search, counting frontier states and character
14+
# comparisons. Stored frontier entries also consume this budget, bounding
15+
# the backtracking trace as well as CPU work.
16+
MAX_SEARCH_STEPS = 1_000_000
17+
18+
module_function
19+
20+
# [{ from:, to:, text: }]: replace before[from...to] with text.
21+
def hunks(before, after)
22+
return [] if before == after
23+
24+
prefix = common_prefix_length(before, after)
25+
suffix = common_suffix_length(before, after, prefix)
26+
old_middle = before[prefix...(before.length - suffix)]
27+
new_middle = after[prefix...(after.length - suffix)]
28+
replacement = [ { from: prefix, to: prefix + old_middle.length, text: new_middle } ]
29+
return replacement if old_middle.empty? || new_middle.empty?
30+
return character_hunks(old_middle, new_middle, prefix) if small?(old_middle, new_middle)
31+
32+
bounded_character_hunks(old_middle, new_middle, prefix) || replacement
33+
end
34+
35+
# Myers' frontier records the furthest old-text position on each diagonal
36+
# after d insertions/deletions. An array index i represents diagonal 2*i-d.
37+
# Equal characters advance along a diagonal without another edit. A found
38+
# path is shortest; an exhausted search returns no partial alignment.
39+
def bounded_character_hunks(before, after, offset)
40+
return if [ before.length, after.length ].max > MAX_SEARCH_STEPS
41+
42+
old = before.codepoints
43+
fresh = after.codepoints
44+
frontier = [ 0 ]
45+
trace = []
46+
steps = 0
47+
(0..old.length + fresh.length).each do |distance|
48+
next_frontier = []
49+
(0..distance).each do |index|
50+
steps += 1
51+
return if steps > MAX_SEARCH_STEPS
52+
53+
insertion = index.zero? || (index < distance && frontier[index - 1] < frontier[index])
54+
x = insertion ? frontier[index] : frontier[index - 1] + 1
55+
y = x - (2 * index - distance)
56+
while x < old.length && y < fresh.length
57+
steps += 1
58+
return if steps > MAX_SEARCH_STEPS
59+
break unless old[x] == fresh[y]
60+
x += 1
61+
y += 1
62+
end
63+
next_frontier << x
64+
if x >= old.length && y >= fresh.length
65+
return backtrack(trace, old.length, fresh.length, fresh, after.encoding, offset)
66+
end
67+
end
68+
trace << next_frontier
69+
frontier = next_frontier
70+
end
71+
end
72+
73+
def backtrack(trace, x, y, fresh, encoding, offset)
74+
edits = []
75+
trace.length.downto(1) do |distance|
76+
frontier = trace[distance - 1]
77+
diagonal = x - y
78+
index = (diagonal + distance) / 2
79+
insertion = index.zero? || (index < distance && frontier[index - 1] < frontier[index])
80+
previous_x = insertion ? frontier[index] : frontier[index - 1]
81+
previous_y = previous_x - (insertion ? diagonal + 1 : diagonal - 1)
82+
edits << { from: offset + previous_x, to: offset + previous_x + (insertion ? 0 : 1),
83+
text: insertion ? fresh[previous_y].chr(encoding) : +"" }
84+
x, y = previous_x, previous_y
85+
end
86+
87+
edits.reverse_each.with_object([]) do |edit, hunks|
88+
if hunks.last && hunks.last[:to] == edit[:from]
89+
hunks.last[:to] = edit[:to]
90+
hunks.last[:text] << edit[:text]
91+
else
92+
hunks << edit
93+
end
94+
end
95+
end
96+
97+
# [[old_from, old_to, new_from, new_to]]: runs of changed whole lines,
98+
# as character offsets into each side. A pure insertion or deletion is
99+
# an empty range at the line where it happens.
100+
def line_hunks(before, after)
101+
old_lines = before.lines
102+
new_lines = after.lines
103+
old_offsets = line_offsets(old_lines)
104+
new_offsets = line_offsets(new_lines)
105+
groups = []
106+
current = nil
107+
Diff::LCS.sdiff(old_lines, new_lines).each do |change|
108+
if change.action == "="
109+
groups << current if current
110+
current = nil
111+
next
112+
end
113+
current ||= { old: [], new: [], old_anchor: change.old_position, new_anchor: change.new_position }
114+
current[:old] << change.old_position if %w[- !].include?(change.action)
115+
current[:new] << change.new_position if %w[+ !].include?(change.action)
116+
end
117+
groups << current if current
118+
groups.map do |group|
119+
[ *offset_range(group[:old], group[:old_anchor], old_offsets),
120+
*offset_range(group[:new], group[:new_anchor], new_offsets) ]
121+
end
122+
end
123+
124+
def character_hunks(before, after, offset)
125+
result = []
126+
position = offset
127+
pending = nil
128+
Diff::LCS.sdiff(before.each_char.to_a, after.each_char.to_a).each do |change|
129+
if change.action == "="
130+
result << pending if pending
131+
pending = nil
132+
position += 1
133+
else
134+
pending ||= { from: position, to: position, text: +"" }
135+
unless change.action == "+"
136+
position += 1
137+
pending[:to] = position
138+
end
139+
pending[:text] << change.new_element unless change.action == "-"
140+
end
141+
end
142+
result << pending if pending
143+
result
144+
end
145+
146+
def small?(before, after)
147+
before.length * after.length <= MAX_CHARACTER_CELLS
148+
end
149+
150+
def common_prefix_length(before, after, limit = [ before.length, after.length ].min)
151+
# String#[] at successive character indexes rescans UTF-8 from the
152+
# start. Walk characters once so non-ASCII documents stay linear too.
153+
characters = after.each_char
154+
length = 0
155+
before.each_char do |character|
156+
break if length == limit || character != characters.next
157+
length += 1
158+
end
159+
length
160+
end
161+
162+
def common_suffix_length(before, after, prefix)
163+
limit = [ before.length, after.length ].min - prefix
164+
common_prefix_length(before.reverse, after.reverse, limit)
165+
end
166+
167+
def line_offsets(lines)
168+
lines.each_with_object([ 0 ]) { |line, offsets| offsets << offsets.last + line.length }
169+
end
170+
171+
def offset_range(indexes, anchor, offsets)
172+
return [ offsets[anchor], offsets[anchor] ] if indexes.empty?
173+
174+
[ offsets[indexes.min], offsets[indexes.max + 1] ]
175+
end
176+
end
177+
end
178+
end

‎spec/requests/human_document_editor_spec.rb‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,29 @@ def acquire
119119
expect(response.parsed_body["revision"]).to eq(1)
120120
end
121121

122+
it "saves stale distant edits without moving a repeated quote or the other writer's edit" do
123+
prefix = "# #{plan.title}\n\n"
124+
middle = (1..100).map { |i| "Unchanged line #{i}.\n" }.join
125+
base = prefix + "repeat\nrepeat\nrepeat\n" + middle + "c\nb\n"
126+
set_version_fixture(plan.current_plan_version, content_markdown: base)
127+
thread = create(:comment_thread, plan: plan, anchor_text: "repeat", anchor_revision: 1,
128+
anchor_start: prefix.length, anchor_end: prefix.length + 6)
129+
remote = prefix + "repeat?\nrepeat\nrepeat\n" + middle + "c\nb\n"
130+
local = prefix + "Xrepeat\nrepeat\nrepeat\n" + middle + "ac\nb\n"
131+
132+
patch update_content_plan_path(plan), params: { content: remote, base_revision: 1 }, as: :json
133+
expect(response).to have_http_status(:ok)
134+
remote_version = plan.reload.current_plan_version
135+
136+
patch update_content_plan_path(plan), params: { content: local, base_revision: 1 }, as: :json
137+
expect(response).to have_http_status(:ok)
138+
expect(plan.reload.current_content).to eq(prefix + "Xrepeat?\nrepeat\nrepeat\n" + middle + "ac\nb\n")
139+
expect(plan.current_plan_version.actor_type).to eq("human")
140+
expect(remote_version.reload.content_markdown).to eq(remote)
141+
expect(thread.reload).not_to be_out_of_date
142+
expect([ thread.anchor_start, thread.anchor_end ]).to eq([ prefix.length + 1, prefix.length + 7 ])
143+
end
144+
122145
it "retires a legacy human lease without acquiring a replacement" do
123146
Coplan::EditLease.acquire!(plan: plan, holder_type: "human", holder_id: author.id, lease_token: token)
124147
delete editor_lease_plan_path(plan), as: :json

0 commit comments

Comments
 (0)