fix: dedup content hashes per conversation and per wing

normalize() joined every conversation in a Claude.ai privacy export
bundle into one string before it was hashed, so re-exporting the bundle
with one new conversation added changed the whole-file hash and the
existing conversations were re-mined as duplicates. Split normalization
into normalize_conversations() so each conversation can be hashed and
deduped on its own.

Also scope the content-hash map by wing — mining the same transcript
into a second wing is a deliberate re-file, not a duplicate, and was
leaving that wing with only the registry sentinel.
This commit is contained in:
rohan richard
2026-07-20 22:35:21 +05:30
parent 283dae45e3
commit 54397a5cc0
4 changed files with 275 additions and 84 deletions
+62 -54
View File
@@ -21,7 +21,7 @@ from typing import Optional
from .collision_scan import assert_no_collisions
from .ids import ID_RECIPE, make_convo_drawer_id, make_convo_sentinel_id
from .normalize import normalize
from .normalize import normalize_conversations
from .entities import entities_metadata
from .palace import (
NORMALIZE_VERSION,
@@ -630,35 +630,30 @@ def _is_ai_tool_path(path: Path) -> bool:
return False
def _skip_content_duplicate(
dry_run: bool,
collection,
filepath: Path,
content_hash: str,
def _split_new_and_duplicate_conversations(
conversations: list,
wing: str,
agent: str,
extract_mode: str,
source_file: str,
mined_content_hashes: dict,
progress: str,
) -> bool:
"""Register and report a content-duplicate file, if this content_hash is
already filed under a different source_file. Returns True if skipped.
) -> tuple:
"""Hash each conversation and split them into (new, duplicate) lists.
Repeated exports from Claude/ChatGPT commonly land under a new filename
each run even when the conversation itself is unchanged, so the
source_file-keyed mtime skip never recognizes them. Registering the
duplicate here means the next run skips it via the cheap mtime check
instead of re-normalizing and re-hashing it.
A conversation is a duplicate when its hash is already registered under
a *different* source_file in the same wing — mining the same transcript
into a second wing is a deliberate re-file, not a repeat, so the lookup
is scoped to (wing, hash). Returns ([(hash, text), ...] new, [(hash,
dup_source_file), ...] duplicates).
"""
if dry_run:
return False
source_file = str(filepath)
dup_source = mined_content_hashes.get(content_hash)
if dup_source is None or dup_source == source_file:
return False
_register_file(collection, source_file, wing, agent, extract_mode, content_hash)
print(f" = {progress} {filepath.name[:50]:50} duplicate of {Path(dup_source).name}")
return True
new_items = []
duplicates = []
for conversation in conversations:
content_hash = hashlib.sha256(conversation.strip().encode("utf-8")).hexdigest()
dup_source = mined_content_hashes.get((wing, content_hash))
if dup_source is None or dup_source == source_file:
new_items.append((content_hash, conversation))
else:
duplicates.append((content_hash, dup_source))
return new_items, duplicates
def _is_unchanged_since_last_mine(source_file: str, mined_mtimes: dict) -> bool:
@@ -778,7 +773,7 @@ def _compute_hallways_for_wing_safe(wing, collection, drawers_filed, config=None
print(f" (hallways skipped: {exc})")
def _normalize_convo_content(
def _normalize_convo_conversations(
filepath: Path,
source_file: str,
cfg_min_chunk_size: int,
@@ -787,24 +782,32 @@ def _normalize_convo_content(
agent: str,
extract_mode: str,
dry_run: bool,
) -> Optional[str]:
"""Normalize a transcript file, registering it as filed when there's
nothing worth mining. Returns None when the caller should skip the file
(normalize failed, or normalized content is too short to chunk).
) -> Optional[list]:
"""Normalize a transcript file into its individual conversations,
registering it as filed when there's nothing worth mining. Returns None
when the caller should skip the file (normalize failed, or normalized
content is too short to chunk).
Kept as separate conversations rather than joined into one string so
dedup can hash and skip per conversation — a Claude.ai privacy export
bundles every conversation into a single file, and hashing the joined
bundle means one new conversation added to a re-export changes the
whole-file hash and hides the conversations that didn't change.
"""
try:
content = normalize(str(filepath))
conversations = [c for c in normalize_conversations(str(filepath)) if c]
except (OSError, ValueError):
if not dry_run:
_register_file(collection, source_file, wing, agent, extract_mode)
return None
if not content or len(content.strip()) < cfg_min_chunk_size:
total_len = sum(len(c.strip()) for c in conversations)
if not conversations or total_len < cfg_min_chunk_size:
if not dry_run:
_register_file(collection, source_file, wing, agent, extract_mode)
return None
return content
return conversations
def _mine_convos_impl(
@@ -894,7 +897,7 @@ def _mine_convos_impl(
files_skipped += 1
continue
content = _normalize_convo_content(
conversations = _normalize_convo_conversations(
filepath,
source_file,
cfg_min_chunk_size,
@@ -904,29 +907,33 @@ def _mine_convos_impl(
extract_mode,
dry_run,
)
if content is None:
if conversations is None:
continue
content_hash = hashlib.sha256(content.strip().encode("utf-8")).hexdigest()
# Same conversation, different path: this exact transcript is
# already filed under another source_file (e.g. a fresh Claude/ChatGPT
# export bundle re-exports conversations that haven't changed under
# new filenames). Skip it instead of filing a duplicate set of drawers.
if _skip_content_duplicate(
dry_run,
collection,
filepath,
content_hash,
wing,
agent,
extract_mode,
mined_content_hashes,
progress=f"[{i:4}/{len(files)}]",
):
# Hash and dedup per conversation, not per file: a Claude/ChatGPT
# privacy export bundles every conversation into one file, so a
# re-export that adds one new conversation changes the whole-file
# hash and would hide the conversations that didn't change if we
# hashed the joined bundle. Conversations whose hash is already
# filed under a different source_file in this wing are dropped;
# the rest are re-joined and mined as usual.
new_items, duplicates = _split_new_and_duplicate_conversations(
conversations, wing, source_file, mined_content_hashes
)
if not new_items:
if not dry_run:
_register_file(collection, source_file, wing, agent, extract_mode)
dup_source = duplicates[0][1]
print(
f" = [{i:4}/{len(files)}] {filepath.name[:50]:50} "
f"duplicate of {Path(dup_source).name}"
)
files_skipped += 1
continue
content = "\n\n".join(text for _, text in new_items)
content_hash = ",".join(h for h, _ in new_items)
# Chunk — either exchange pairs or general extraction
if extract_mode == "general":
from .general_extractor import extract_memories
@@ -994,7 +1001,8 @@ def _mine_convos_impl(
for r, n in room_delta.items():
room_counts[r] += n
mined_content_hashes[content_hash] = source_file
for h, _ in new_items:
mined_content_hashes[(wing, h)] = source_file
total_drawers += drawers_added
files_mined += 1
print(f" + [{i:4}/{len(files)}] {filepath.name[:50]:50} +{drawers_added}")
+86 -20
View File
@@ -114,10 +114,10 @@ def strip_noise(text: str) -> str:
return text.strip()
def normalize(filepath: str) -> str:
"""
Load a file and normalize to transcript format if it's a chat export.
Plain text files pass through unchanged.
def _read_transcript_file(filepath: str) -> str:
"""Read a transcript source file with the same safety checks normalize()
and normalize_conversations() both need: no symlinks, regular files only,
size-capped, BOM-tolerant.
"""
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
if os.path.islink(filepath):
@@ -132,7 +132,7 @@ def normalize(filepath: str) -> str:
raise IOError(f"File too large ({file_stat.st_size // (1024 * 1024)} MB): {filepath}")
with os.fdopen(fd, "r", encoding="utf-8-sig", errors="replace") as f:
fd = -1
content = f.read()
return f.read()
except OSError as e:
raise IOError(f"Could not read {filepath}: {e}") from e
finally:
@@ -142,6 +142,14 @@ def normalize(filepath: str) -> str:
except OSError:
pass
def normalize(filepath: str) -> str:
"""
Load a file and normalize to transcript format if it's a chat export.
Plain text files pass through unchanged.
"""
content = _read_transcript_file(filepath)
if not content.strip():
return content
@@ -162,40 +170,88 @@ def normalize(filepath: str) -> str:
return content
def normalize_conversations(filepath: str) -> list:
"""Like normalize(), but keeps each conversation in a bundle export as a
separate string instead of joining them into one.
A Claude.ai privacy export packs every conversation into a single JSON
file, and normalize() joins them with "\\n\\n".join(...) into one blob.
That collapses conversation boundaries, so content-hash dedup keyed on
the whole file breaks the moment the bundle is re-exported with one new
conversation added — the file-level hash changes even though none of
the existing conversations did. This returns the pieces un-joined so
callers can hash and dedup per conversation instead.
Non-bundle formats (a single Claude Code session, a ChatGPT export,
plain text, ...) always normalize to one conversation, so this returns
a one-element list for those — identical dedup granularity to before.
"""
content = _read_transcript_file(filepath)
if not content.strip():
return []
lines = content.split("\n")
if sum(1 for line in lines if line.strip().startswith(">")) >= 3:
return [content]
ext = Path(filepath).suffix.lower()
if ext in (".json", ".jsonl") or content.strip()[:1] in ("{", "["):
split = _try_normalize_json_split(content)
if split:
return split
return [content]
def _try_normalize_json(content: str) -> Optional[str]:
"""Try all known JSON chat schemas."""
"""Try all known JSON chat schemas, joining a multi-conversation bundle
into one string. See ``_try_normalize_json_split`` for the unjoined form.
"""
split = _try_normalize_json_split(content)
if split is None:
return None
return "\n\n".join(split)
def _try_normalize_json_split(content: str) -> Optional[list]:
"""Try all known JSON chat schemas, returning each conversation found as
a separate list entry (bundle formats) or a single-element list.
"""
normalized = _try_claude_code_jsonl(content)
if normalized:
return normalized
return [normalized]
normalized = _try_codex_jsonl(content)
if normalized:
return normalized
return [normalized]
normalized = _try_gemini_jsonl(content)
if normalized:
return normalized
return [normalized]
normalized = _try_pi_jsonl(content)
if normalized:
return normalized
return [normalized]
try:
data = json.loads(content)
except json.JSONDecodeError:
return None
for parser in (
_try_gemini_json,
_try_claude_ai_json,
_try_chatgpt_json,
_try_continue_json,
_try_slack_json,
):
normalized = _try_gemini_json(data)
if normalized:
return [normalized]
split = _try_claude_ai_json_split(data)
if split:
return split
for parser in (_try_chatgpt_json, _try_continue_json, _try_slack_json):
normalized = parser(data)
if normalized:
return normalized
return [normalized]
return None
@@ -509,6 +565,16 @@ def _try_gemini_json(data) -> Optional[str]:
def _try_claude_ai_json(data) -> Optional[str]:
"""Claude.ai JSON export: flat messages list or privacy export with chat_messages."""
split = _try_claude_ai_json_split(data)
if split is None:
return None
return "\n\n".join(split)
def _try_claude_ai_json_split(data) -> Optional[list]:
"""Same as ``_try_claude_ai_json`` but keeps each conversation in a
privacy export as its own list entry instead of joining them.
"""
if isinstance(data, dict):
data = data.get("messages", data.get("chat_messages", []))
if not isinstance(data, list):
@@ -526,13 +592,13 @@ def _try_claude_ai_json(data) -> Optional[str]:
if len(messages) >= 2:
transcripts.append(_messages_to_transcript(messages))
if transcripts:
return "\n\n".join(transcripts)
return transcripts
return None
# Flat messages list
messages = _collect_claude_messages(data)
if len(messages) >= 2:
return _messages_to_transcript(messages)
return [_messages_to_transcript(messages)]
return None
+27 -10
View File
@@ -1353,9 +1353,11 @@ def prefetch_mined_set(
return mined
def prefetch_content_hashes(collection, extract_mode: Optional[str] = None) -> dict[str, str]:
"""Pre-fetch content_hash -> source_file for drawers already filed at the
current NORMALIZE_VERSION, in one bulk pass.
def prefetch_content_hashes(
collection, extract_mode: Optional[str] = None
) -> dict[tuple[str, str], str]:
"""Pre-fetch (wing, content_hash) -> source_file for drawers already
filed at the current NORMALIZE_VERSION, in one bulk pass.
Repeated exports from Claude/ChatGPT land under a new filename each run
(timestamped bundle, regenerated slug, etc.) even when the conversation
@@ -1366,10 +1368,20 @@ def prefetch_content_hashes(collection, extract_mode: Optional[str] = None) -> d
normalized transcript text, so the convo miner can recognize "this exact
conversation is already filed under a different path" and skip it.
Only the first source_file seen for a given hash is kept — good enough
to detect and skip a repeat, the point is not to track every alias.
Keyed by (wing, content_hash) rather than content_hash alone — mining
the same transcript into a second wing is a deliberate re-file, not a
duplicate, and should produce real drawers in that wing rather than
just the registry sentinel.
A drawer's ``content_hash`` metadata may hold several comma-joined
SHA-256 hashes: a privacy-export bundle normalizes to one conversation
per drawer set, but the hash is computed per conversation so that a
re-export with one new conversation added doesn't change the hash of
the ones that didn't. Only the first source_file seen for a given
(wing, hash) pair is kept — good enough to detect and skip a repeat,
the point is not to track every alias.
"""
hashes: dict[str, str] = {}
hashes: dict[tuple[str, str], str] = {}
try:
total = collection.count()
offset = 0
@@ -1377,15 +1389,20 @@ def prefetch_content_hashes(collection, extract_mode: Optional[str] = None) -> d
batch = collection.get(limit=1000, offset=offset, include=["metadatas"])
for meta in batch["metadatas"]:
meta = meta or {}
content_hash = meta.get("content_hash")
content_hash_field = meta.get("content_hash")
src = meta.get("source_file")
if not content_hash or not src:
wing = meta.get("wing")
if not content_hash_field or not src or not wing:
continue
if not _metadata_matches_extract_mode(meta, extract_mode):
continue
version = meta.get("normalize_version", 1)
if version >= NORMALIZE_VERSION and content_hash not in hashes:
hashes[content_hash] = src
if version < NORMALIZE_VERSION:
continue
for content_hash in content_hash_field.split(","):
key = (wing, content_hash)
if content_hash and key not in hashes:
hashes[key] = src
if not batch["ids"]:
break
offset += len(batch["ids"])
+100
View File
@@ -1,3 +1,4 @@
import json
import os
import tempfile
import shutil
@@ -610,6 +611,105 @@ def test_mine_convos_skips_same_content_under_new_filename(capsys):
shutil.rmtree(tmpdir, ignore_errors=True)
def _privacy_export_bundle(conversations):
"""Build a Claude.ai privacy-export-shaped JSON payload: an array of
conversation objects, each with its own chat_messages list."""
return [
{
"chat_messages": [
{"sender": "human", "text": turn}
if i % 2 == 0
else {"sender": "assistant", "text": turn}
for i, turn in enumerate(turns)
]
}
for turns in conversations
]
def test_mine_convos_skips_same_conversation_within_re_exported_bundle(capsys):
"""A Claude.ai privacy export bundles every conversation into one JSON
file. Re-exporting that bundle under a new filename with one additional
conversation must not re-file the conversations that didn't change --
hashing the whole bundle would change the file-level hash the moment
any conversation is added, hiding the ones that are still duplicates.
"""
tmpdir = tempfile.mkdtemp()
try:
convo_a = ["What is the plan?", "CONVO_A_MARKER: start with the schema."]
convo_b = ["Any risks?", "CONVO_B_MARKER: migration ordering is the main one."]
convo_c = ["What's next?", "CONVO_C_MARKER: covers the new work."]
bundle1 = _privacy_export_bundle([convo_a, convo_b])
(Path(tmpdir) / "export_2026-01-01.json").write_text(json.dumps(bundle1))
palace_path = os.path.join(tmpdir, "palace")
mine_convos(tmpdir, palace_path, wing="test")
client = chromadb.PersistentClient(path=palace_path)
col = client.get_collection("mempalace_drawers")
docs_after_first = col.get(include=["documents"])["documents"]
assert any("CONVO_A_MARKER" in d for d in docs_after_first)
assert any("CONVO_B_MARKER" in d for d in docs_after_first)
# Re-export: same two conversations plus one genuinely new one, all
# under a fresh filename (as a real re-export from Claude would do).
bundle2 = _privacy_export_bundle([convo_a, convo_b, convo_c])
(Path(tmpdir) / "export_2026-02-01.json").write_text(json.dumps(bundle2))
mine_convos(tmpdir, palace_path, wing="test")
col = client.get_collection("mempalace_drawers")
docs = col.get(include=["documents"])["documents"]
a_hits = sum(1 for d in docs if "CONVO_A_MARKER" in d)
b_hits = sum(1 for d in docs if "CONVO_B_MARKER" in d)
c_hits = sum(1 for d in docs if "CONVO_C_MARKER" in d)
assert a_hits == 1, f"conversation A re-filed from the updated bundle: {a_hits} copies"
assert b_hits == 1, f"conversation B re-filed from the updated bundle: {b_hits} copies"
assert c_hits >= 1, "new conversation C was not filed at all"
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
def test_content_dedup_is_scoped_per_wing():
"""Mining the same transcript content into a second wing must file real
drawers there, not just the registry sentinel -- the content-hash map
is a dedup signal within a wing, not a cross-wing "already have this
content anywhere" gate.
"""
tmpdir = tempfile.mkdtemp()
try:
transcript = (
"> What is the plan?\nStart with the schema, then the API.\n\n"
"> Any risks?\nMigration ordering is the main one.\n"
)
dir_a = Path(tmpdir) / "wing_a_src"
dir_b = Path(tmpdir) / "wing_b_src"
dir_a.mkdir()
dir_b.mkdir()
(dir_a / "session.txt").write_text(transcript)
(dir_b / "session.txt").write_text(transcript)
palace_path = os.path.join(tmpdir, "palace")
mine_convos(str(dir_a), palace_path, wing="wing_a")
mine_convos(str(dir_b), palace_path, wing="wing_b")
client = chromadb.PersistentClient(path=palace_path)
col = client.get_collection("mempalace_drawers")
wing_b_docs = col.get(where={"wing": "wing_b"}, include=["documents", "metadatas"])
real_drawers = [
d
for d, m in zip(wing_b_docs["documents"], wing_b_docs["metadatas"])
if m.get("room") != "_registry"
]
assert real_drawers, (
"wing_b holds only the registry sentinel -- content dedup leaked across wings"
)
assert any("Migration ordering is the main one" in d for d in real_drawers)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
def test_prefetch_mined_set_returns_stored_mtime():
"""prefetch_mined_set's dict carries each source_file's stored mtime,
not just membership."""