feat(snippets): un-merge — reverse one source out of a merged survivor
CI & Build / Python lint (push) Successful in 3s
CI & Build / integration (push) Successful in 24s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Python tests (push) Successful in 54s
CI & Build / Build & push image (push) Successful in 40s

Closes the last of milestone #232. The task said to settle the design
before coding; here is what was settled and why.

THE HAZARD. Restoring a merged-in source from the trash brought the record
back but never stripped its locations off the survivor, so both claimed
the same call sites and the reverse lookup read the duplicate claims as
real. Subtracting blindly is not a fix: a location can arrive from a
source AND genuinely be the survivor's own, and _normalize_locations dedups
them into one, so blind subtraction would strip a call site the survivor
owns. Same problem defeated partial un-merge — `merged_from` recorded ids,
not which locations came from which source.

THE ANSWER. Record per-source attribution AT MERGE TIME, where it is known
exactly: each entry keeps only what that source ADDED, computed
incrementally as sources fold in. Anything the survivor already had, or an
earlier source already brought, is attributed to nobody. Both open
questions fall out of that one change — partial un-merge is exact, and a
survivor-owned location can never be stripped, because it was never
attributed in the first place.

The shape moved from [id] to [{id, locations, tags}]. Free to do: the
corpus holds one snippet and zero merges, so there is no legacy data (rule
#22). A bare int still normalizes to {"id": n} — not legacy tolerance, but
because snippet_fields falls back to PARSING THE BODY when a row has no
`data`, and the body's provenance line can only carry ids. Such an entry
shows history and refuses un-merge with a reason rather than guessing.

WHICH SURFACE. Neither option in the task, quite. Making trash-restore
notice the merge would teach the generic trash path snippet semantics for
one record type. Instead un-merge OWNS the restore: one operation, one
authorization check, trash stays ignorant. Restoring by hand is still
allowed and still leaves both records claiming the same places — so
un-merge treats an already-alive source as the normal case and goes
straight to the subtraction that repairs it. That is the state that
motivated the feature, not an error.

Adds trash.restore_entity(user_id, type, id) — the missing inverse of
delete(), which returns a batch id callers don't keep. Restores the whole
batch, since the batch is the entity plus its cascade.

Refs #2165

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaYUaouG9jjhATyuxCKrQs
This commit is contained in:
2026-07-28 18:42:29 -04:00
parent 6db791965f
commit fe63f3985b
11 changed files with 624 additions and 30 deletions
+41 -5
View File
@@ -148,7 +148,9 @@ def test_merge_snippet_fields_unions_locations_and_tags():
["py", "snippet", "helper"])
src2 = ({"language": "py", "locations": [{"repo": "a", "path": "a.py", "symbol": "f"}]}, # dup loc
["snippet"])
locs, extra = s.merge_snippet_fields(target_fields, ["py", "snippet", "core"], [src1, src2])
locs, extra, contributions = s.merge_snippet_fields(
target_fields, ["py", "snippet", "core"], [src1, src2]
)
# target location first, then unique source locations; dup dropped.
assert locs == [
{"repo": "a", "path": "a.py", "symbol": "f"},
@@ -157,6 +159,14 @@ def test_merge_snippet_fields_unions_locations_and_tags():
# extra tags unioned, language + "snippet" markers excluded.
assert extra == ["core", "helper"]
# Attribution (#2165): only what each source ACTUALLY added. src2's location
# is one the target already had, so it contributed nothing — un-merging it
# must not strip a call site the survivor owns in its own right.
assert contributions[0]["locations"] == [{"repo": "b", "path": "b.py", "symbol": "g"}]
assert contributions[0]["tags"] == ["helper"]
assert contributions[1]["locations"] == []
assert contributions[1]["tags"] == []
# --- the queryable mirror (notes.data, migration 0070) -----------------------
@@ -253,19 +263,44 @@ def test_data_and_body_round_trip_to_the_same_fields():
def test_normalize_merged_from_keeps_history_order_and_drops_junk():
"""Order is history, not sorting — earlier merges stay first."""
assert s._normalize_merged_from([9, 3, 9, "4", None, 0, -2, "x"]) == [9, 3, 4]
assert s.merged_from_ids([9, 3, 9, "4", None, 0, -2, "x"]) == [9, 3, 4]
assert s._normalize_merged_from(None) == []
def test_normalize_merged_from_carries_per_source_attribution():
"""The shape that makes un-merge exact (#2165): each entry holds what THAT
source contributed, so reversing one can't strip what the survivor owns."""
loc = {"repo": "a", "path": "a.py", "symbol": "f"}
out = s._normalize_merged_from([{"id": 7, "locations": [loc], "tags": ["x"]}])
assert out == [{"id": 7, "locations": [loc], "tags": ["x"]}]
def test_a_bare_id_normalizes_to_an_entry_with_no_attribution():
"""Not legacy tolerance: snippet_fields falls back to PARSING THE BODY when a
row has no `data`, and the body's provenance line can only carry ids. Such an
entry still shows history; un-merge refuses it rather than guessing."""
assert s._normalize_merged_from([5]) == [{"id": 5}]
def test_compose_body_renders_merged_from_and_parse_reads_it_back():
body = s.compose_body(code="x = 1", merged_from=[12, 13])
assert "**Merged from:** #12, #13" in body
got = s.parse_snippet_fields("n — u", body, None)
assert got["merged_from"] == [12, 13]
# Ids survive the body round-trip; attribution cannot, since the body only
# ever renders ids — which is exactly why `data` is the authority for it.
assert s.merged_from_ids(got["merged_from"]) == [12, 13]
# The code fence still comes last — provenance is header metadata.
assert body.rstrip().endswith("```")
def test_compose_body_renders_ids_from_rich_entries():
body = s.compose_body(
code="x = 1",
merged_from=[{"id": 12, "locations": [{"repo": "", "path": "a.py", "symbol": ""}]}],
)
assert "**Merged from:** #12" in body
def test_compose_body_omits_merged_from_when_there_is_none():
"""A snippet that was never merged says nothing about merging."""
assert "Merged from" not in s.compose_body(code="x = 1")
@@ -273,7 +308,8 @@ def test_compose_body_omits_merged_from_when_there_is_none():
def test_compose_data_mirrors_merged_from():
assert s.compose_data(name="f", merged_from=[3, 3, 2])["merged_from"] == [3, 2]
got = s.compose_data(name="f", merged_from=[3, 3, 2])["merged_from"]
assert s.merged_from_ids(got) == [3, 2]
assert "merged_from" not in s.compose_data(name="f")
@@ -283,7 +319,7 @@ def test_snippet_fields_prefers_the_data_columns_merged_from():
body = s.compose_body(code="x = 1", merged_from=[12])
note = _Note(title="n — u", body=body, tags=["snippet"],
data=s.compose_data(name="n", merged_from=[12, 13]))
assert s.snippet_fields(note)["merged_from"] == [12, 13]
assert s.merged_from_ids(s.snippet_fields(note)["merged_from"]) == [12, 13]
def test_snippet_to_dict_includes_parsed_fields():