From 84b3c084a524c906f903416632411e319017a8e9 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Sat, 5 Dec 2026 14:58:10 +0800 Subject: [PATCH] Memory reads and approval hashes preserve complete JSON objects Read persisted object text before native JSON rendering so omitted members remain part of verification and approval. Preserve refusal matches against both persisted representations during upgrade and rollback. Signed-off-by: zhangxiaoyu.york --- server/core/hashing.py | 10 +- server/memory/store/refusals.py | 43 ++-- server/memory/store/sql.py | 11 +- tests/analyzer/shapes.txt | 32 +-- tests/integration/test_full_object_value.py | 190 ++++++++++++++++++ .../test_memory_refusal_capture_live_ch.py | 24 +++ tests/unit/test_full_object_value.py | 34 ++++ tests/unit/test_memory_refusals.py | 57 ++++++ tests/unit/test_version_row_value_bytes.py | 8 +- 9 files changed, 373 insertions(+), 36 deletions(-) create mode 100644 tests/integration/test_full_object_value.py create mode 100644 tests/unit/test_full_object_value.py diff --git a/server/core/hashing.py b/server/core/hashing.py index ad8d91e94cb..c981e8761cf 100644 --- a/server/core/hashing.py +++ b/server/core/hashing.py @@ -76,11 +76,17 @@ def served_content_sha256(value: Any) -> str: def served_row_value(row: Mapping[str, Any]) -> Any: """The full persisted JSON value, never a display excerpt or stored hash.""" + raw_value = row.get("value") + try: + value = json.loads(raw_value) if isinstance(raw_value, str) else raw_value + except (json.JSONDecodeError, ValueError, TypeError): + value = raw_value + if isinstance(value, dict): + return value encoded = row.get("value_json") or "{}" if isinstance(encoded, dict): encoded = json.dumps(encoded) - # Matches the authoritative SERVED_VALUE projection: the native JSON column holds - # objects, while strings and other scalar values live in the text column. + # Imports can keep their object only in value_json beside a scalar value. raw = str(encoded) if len(str(encoded)) > 2 else row.get("value") if not raw: return None diff --git a/server/memory/store/refusals.py b/server/memory/store/refusals.py index c5a2f1236ff..ff191ea1d71 100644 --- a/server/memory/store/refusals.py +++ b/server/memory/store/refusals.py @@ -175,7 +175,7 @@ async def shared_retirement(ch: _CHClient, row: Mapping[str, Any]) -> AsyncItera from server.memory.domain.promotion_source import promotion_users users = promotion_users(list(row.get("promoted_from") or []), row["org"], row["namespace"]) - base = content_policy_row(row, served_row_value(row)) + base = content_policy_row(row, _refusal_values(row)) sources = [{**base, "user_id": user or "-"} for user in sorted(users)] if users else [base] async with ( lease_writes.fenced_many( @@ -216,7 +216,7 @@ async def _shared_values_refused( ch: _CHClient, conn: Any, sources: Sequence[Mapping[str, Any]], *, erasure_only: bool = True ) -> bool: refused = False - inspected = [refusals.inspect(served_row_value(sources[0]))] + inspected = [refusals.inspect(value) for value in _refusal_values(sources[0])] keys = {(str(row["org"]), str(row["namespace"]), str(row["user_id"])) for row in sources} with sequential_reads(): for key in sorted(keys): @@ -229,6 +229,29 @@ async def _shared_values_refused( return refused +def _refusal_values(row: Mapping[str, Any]) -> list[Any]: + """Both persisted objects: recorded refusal hashes may name either one.""" + value = served_row_value(row) + native = served_row_value({"value": row.get("value_json") or "{}"}) + values = [value] + if isinstance(native, dict) and native and sha256_value(native) != sha256_value(value): + values.append(native) + return values + + +def _refusal_fingerprints(row: Mapping[str, Any]) -> set[refusals.Fingerprint]: + fingerprints: set[refusals.Fingerprint] = set() + for value in _refusal_values(row): + if row.get("capture_kind") == "metadata" and value in (None, "", {}, []): + continue + fingerprints.update( + refusals.payload_fingerprints(value) + if row.get("capture_kind") == "payload" + else refusals.fingerprint(value) + ) + return fingerprints + + def _policy( rows: Sequence[Mapping[str, Any]], *, @@ -241,15 +264,7 @@ def _policy( for row in rows: if row.get("value_truncated"): raise ValidationError("A complete value is required to record refusal policy") - value = served_row_value(row) - if row.get("capture_kind") == "metadata" and value in (None, "", {}, []): - continue - fingerprints = ( - refusals.payload_fingerprints(value) - if row.get("capture_kind") == "payload" - else refusals.fingerprint(value) - ) - for kind, units, digest in sorted(fingerprints): + for kind, units, digest in sorted(_refusal_fingerprints(row)): result.append( { **{ @@ -284,7 +299,9 @@ def _live_groups(rows: Sequence[Mapping[str, Any]]) -> dict[tuple[str, str, str] for row in rows: if row.get("tombstoned_at") is None: key = (str(row["org"]), str(row["namespace"]), str(row.get("user_id") or "-")) - groups.setdefault(key, []).append(refusals.inspect(served_row_value(row))) + groups.setdefault(key, []).extend( + refusals.inspect(value) for value in _refusal_values(row) + ) return groups @@ -746,7 +763,7 @@ async def _embedding_retirements( accepted.append(row) continue head = heads.get(identity_key(row)) - values = [served_row_value(head)] if head is not None else [] + values = _refusal_values(head) if head is not None else [] if row.get("content_excerpt"): values.append(row["content_excerpt"]) inspected = refusals.inspect(values) diff --git a/server/memory/store/sql.py b/server/memory/store/sql.py index 0f2e8aab0eb..d224a6c00fa 100644 --- a/server/memory/store/sql.py +++ b/server/memory/store/sql.py @@ -8,8 +8,13 @@ from typing import Any -# The value memory.get serves: the native JSON column when populated, else the stored text. -SERVED_VALUE = "if(length(toString(value_json)) > 2, toString(value_json), value)" +# Object text preserves null and empty members. Imports may keep their object only +# in value_json beside a scalar value. +SERVED_VALUE = ( + "if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), '{'), " + "loom.memory.value, " + "if(length(toString(value_json)) > 2, toString(value_json), loom.memory.value))" +) # A high row is reachable by key, never pushed into a code or edit prompt. FILE_LISTING_VISIBLE = """ @@ -30,7 +35,7 @@ {SERVED_VALUE} AS value, -- The stored bytes, for version rows: the preferred form -- above is a rendering, not what the writer wrote. - value AS value_text, + loom.memory.value AS value_text, toString(value_json) AS value_json, confidence, version, pinned, created_at, updated_at, expires_at, valid_at, valid_to, invalid_at, diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 9c7293ed4b3..98c6b96990d 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -124,6 +124,7 @@ 0d0074d068cf SELECT queue_id, agent, user_id, session_id, status, attempts, message_count, content_chars, written, last_error, enqueued_at, updated_at FROM loom.memory_extraction_queue FINAL PREWHERE org = {org:St 0d61f55e9bf0 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou 0db9931937d8 SELECT count() AS n FROM loom.memory WHERE org = {org:String} AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), tags), {pairs:Array(Tuple(String, String)) +0de98b385b52 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 0df388be7e18 SELECT count() AS n FROM loom.memory_projection_failures WHERE org = {org:String} AND (JSONExtractString(payload, ?) = {uid:String} OR arrayExists(e -> JSONExtractString(e, ?) = {uid:String}, JSONExtr 0df8d59119a4 SELECT org, namespace, policy_id, effect, description, actions, condition, enabled, mode, created_by, created_at, updated_at, tombstoned_at FROM loom.namespace_policies FINAL WHERE org = {org:String} 0dfeec766c5d SELECT thread_id, count() AS n FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread_id IN {tids:Array(String)} AND tombstoned_at IS NULL AND agent = {agent:String} G @@ -201,6 +202,7 @@ 181f7665f4ab SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, dateDiff(?, updated_at, now()) AS age_days, length(conflict_with) AS peers FROM loom.memory FINAL WHERE org = {org:String 182b2004f117 SELECT active, toString(contact_email) AS contact_email, password_hash = ? AS sso FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 1874492b7e5b SELECT count() AS n FROM loom.code_search_outcome WHERE org = {org:String} AND namespace = {ns:String} +18825c3ac907 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 1891df92bb07 SELECT DISTINCT org FROM ( SELECT org FROM loom.namespaces FINAL WHERE owner_email = {s:String} AND active = ? UNION ALL SELECT org FROM loom.namespace_grants FINAL WHERE lower(subject) = lower({s:Str 18beffc43c3d SELECT memory_key_a, memory_key_b, allowed_at, allowed_by, reason FROM loom.conflict_allowlist FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL ORDER BY allowed_at 18e170c06a0c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this @@ -248,6 +250,7 @@ 1d6537d88c67 SELECT m.namespace AS namespace, m.agent AS agent, m.user_id AS user_id, m.session_id AS session_id, m.memory_key AS memory_key, m.superseded_by AS superseded_by, s.memory_key AS successor_key, toStri 1d663514724c SELECT pr_number, comment_id, path, line, author, excerpt, comment_created_at, on_file, in_range FROM ( SELECT pr_number, comment_id, path, line, author, excerpt, comment_created_at, in_range, count() 1d9f830a8ec7 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value, ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, valid_a +1dad4e2f67ec SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 1daffd2ac140 SELECT count() OVER () AS total, a.memory_key AS memory_key, toString(a.memory_id) AS memory_id, a.duplicate_of AS duplicate_of FROM (SELECT memory_key, memory_id, duplicate_of FROM loom.memory FINAL 1db80df6143e SELECT count() AS n FROM loom.knowledge_gaps WHERE org = {org:String} AND namespace = {ns:String} AND ? 1dc228ffa971 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, shingles, uniqExact(path) OVER () AS admitted_files FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_l @@ -266,9 +269,7 @@ 2056fb3f58af SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} 208cd8ce06ff SELECT session_id FROM loom.session_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND tombstoned_at IS NULL AND session_id 2097d05420f8 SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU -20a337a249a5 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 20ade64c4833 SELECT count() AS n FROM loom.knowledge_source_push WHERE org = {org:String} AND namespace = {ns:String} AND ? -2123d102a83c SELECT agent, user_id, session_id, memory_key, version, if(length(toString(value_json)) > ?, toString(value_json), value) AS value FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:S 214455f1a215 SELECT count() AS n FROM loom.agent_events WHERE org = {org:String} AND (user_id = {uid:String} OR subject = {p:String}) 2151bee126f9 SELECT count() AS n FROM loom.events WHERE org = {org:String} AND namespace IN {ns:Array(String)} 21662d2b21ba SELECT coalesce( nullIf(toString(value_json.x), ?), JSONExtractString(value, ?)) AS x_g, count() AS metric FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agen @@ -313,6 +314,7 @@ 25443b779b21 ALTER TABLE loom.shared DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 25455773978c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 255a74cf0321 SELECT count() AS n FROM loom.blob_uploads WHERE org = {org:String} AND namespace = {ns:String} AND ? +255ab4430be4 SELECT agent, user_id, session_id, memory_key, version, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(toString(value_json)) > ?, toStri 256eac206d73 SELECT count() AS n FROM loom.memory_extraction_queue WHERE org = {org:String} AND namespace = {ns:String} AND ? 2586ce7689b8 SELECT ? AS x FROM loom.namespace_grants WHERE org = {org:String} AND namespace = {ns:String} AND subject = {sub:String} LIMIT ? 25a63c91aee6 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_line, cont @@ -340,6 +342,7 @@ 274615c530f2 SELECT if(format != ?, toString(format), if(JSONExtractString(metadata, ?) != ?, JSONExtractString(metadata, ?), if(blob_content_type != ?, toString(blob_content_type), if(lower(extract(if(original_fi 2787684c7098 SELECT kind, tags FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 27b43b99d5ff SELECT pattern_id, org, namespace, scope, pattern, pattern_type FROM loom.blacklist FINAL WHERE pattern_id = {pid:UUID} AND tombstoned_at IS NULL LIMIT ? +27b67727a10a SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 27e07e7e4595 ALTER TABLE loom.task_events DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 27eb9abf58ee SELECT count() AS n FROM loom.search_misses WHERE org = {org:String} AND (has({spellings:Array(String)}, asker) OR has({spellings:Array(String)}, lowerUTF8(user_id))) AND ? 280ae87ab0d8 INSERT INTO loom.oauth_signin_state (claim_key, value, expires_at) SETTINGS keeper_map_strict_mode = ?, max_execution_time = ? VALUES ({k:String}, {v:String}, {e:UInt32}) @@ -437,7 +440,6 @@ 328c58ef9dbc SELECT count() AS n FROM loom.knowledge_gaps WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 32931cd0870a SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 32a0622ffdb7 DELETE FROM loom.memory_chunks WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? -32aeaaa9dcea SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 32b8fda40451 SELECT greatest(toUInt64(toUnixTimestamp64Nano(now64(?))), max(version) + ?) AS v FROM loom.code_index_state WHERE org = {k0:String} AND namespace = {k1:String} AND state_key = {k2:String} 32cc48140047 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 330223892c54 ALTER TABLE loom.oauth_signin_state DELETE WHERE claim_key = {k:String} AND value = {v:String} SETTINGS keeper_map_strict_mode = ?, max_execution_time = ? @@ -486,6 +488,7 @@ 36c56add9f31 SELECT issue_number, max(computed_at) AS latest FROM loom.qa_link_candidates FINAL WHERE org = {org:String} AND qa_namespace = {ns:String} AND issue_number IN {nums:Array(UInt32)} GROUP BY issue_numbe 37222534b76c SELECT count() AS n FROM loom.knowledge_source_listings WHERE org = {org:String} AND namespace IN {ns:Array(String)} 374514eb8da5 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ +374b9ebbdd07 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 37740a4c5dba SELECT count() AS n FROM loom.memory_code_link_queue WHERE org = {org:String} AND user_id = {uid:String} 378589d81d6f SELECT count() AS n FROM loom.operator_edges FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 379cd09b4b77 ALTER TABLE loom.conversations DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -502,6 +505,7 @@ 38bfb0862017 SELECT chunk_id, path, kind, start_line, end_line FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} AND tombstoned_at IS NULL AND pa 38d2fca41ece SELECT org, namespace, agent, user_id, session_id, run_id, goal, user_request, expected_outcome, environment, model, consumer, status, started_at, completed_at, duration_ms, final_response, confidence 39020388c332 ALTER TABLE loom.knowledge_group_members DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +391cbe7134fc SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 391ec7e4f5b9 ALTER TABLE loom.llm_response_cache DELETE WHERE (org = {org:String} AND hasAny(window_keys, {keys:Array(String)})) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutatio 397add95d965 SELECT count() AS n FROM loom.search_misses WHERE org = {org:String} AND namespace = {ns:String} 399fdf6e4f93 SELECT count() AS n FROM loom.agent_runs WHERE org = {org:String} AND namespace = {ns:String} @@ -533,6 +537,7 @@ 3cf6ac8c7aa2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, e.agent AS agent, e.user_id AS user_id, e.session_id AS 3cfe76db564a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 3d1528d28966 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user +3d1bebbb38aa SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 3d5f2761d6fe SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: 3d5ff23ff854 ALTER TABLE loom.memory_code_links DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 3d8049f7a5b0 SELECT thread_id, count() AS msg_count, min(ts) AS first_seen, max(ts) AS last_seen FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND ts > now() - toIntervalDay({wd:UInt @@ -818,11 +823,11 @@ 5a7665a73fe8 SELECT ? FROM loom.code_test_facets WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 5a96034314da SELECT count() AS n FROM loom.memory_extraction_queue FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status IN {waiting:Array(String)} 5aa3e19175ad SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user -5aa524437811 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 5aa78267733c SELECT count() AS n FROM loom.memory_code_links FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 5aa9a77dc0c1 SELECT count() AS n FROM loom.context_blobs FINAL WHERE org = {org:String} AND namespace = {ns:String} 5ab4520a4503 SELECT count() AS n FROM loom.memory_webhook_outbox WHERE org = {org:String} AND namespace = {ns:String} 5abfc08546ac SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +5ad4f56bd82d SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 5ad558ab68b9 ALTER TABLE loom.memory_reinforcement DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync 5b18ec31d5f5 DELETE FROM loom.chunks WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? 5b39f4c73106 SELECT memory_key, record_json, created_at, (memory_key, identity_agent, user_id, session_id) IN ( SELECT memory_key, agent, user_id, session_id FROM loom.memory FINAL WHERE org = {org:String} AND nam @@ -848,7 +853,6 @@ 5e685e7d200a ALTER TABLE loom.search_misses DELETE WHERE (org = {org:String} AND (has({spellings:Array(String)}, asker) OR has({spellings:Array(String)}, lowerUTF8(user_id)))) AND ({erasure_mutation_tag:String} = 5e6c8126c33d SELECT source_uri, version, revision, content.size AS text_bytes, superseded_at IS NOT NULL AS deleted FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} AND source_uri IN 5e8b03fa60c0 SELECT session_id FROM loom.session_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND tombstoned_at IS NULL AND session_id -5e902d2cb6ad SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 5e9d05fdddf9 SELECT * FROM loom.code_scip_batches FINAL WHERE org = {org:String} AND namespace = {ns:String} AND batch_id = {bid:UUID} 5ec21e0b6ff9 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 5f07507d00b9 INSERT INTO loom.chunk_supersessions (org, namespace, embedding_model, source_uri, doc_version, superseded_at) SELECT DISTINCT org, namespace, embedding_model, source_uri, doc_version, {when:DateTime} @@ -931,7 +935,6 @@ 674c014bbb89 SELECT count() AS n FROM loom.datasets WHERE org = {org:String} AND user_id = {uid:String} AND ? 675a57195847 SELECT memory_id, version, agent, user_id, session_id, memory_key, created_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tom 6765755688ca SELECT kind, name, status, description, cardinality, created_by, updated_at FROM loom.namespace_ontology FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status = {status:String} ORDER B -679aaca08b74 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 67b04af64852 SELECT DISTINCT namespace FROM loom.documents WHERE org = {org:String} AND user_id = {uid:String} ORDER BY namespace 67b658495a69 SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND (namespace = {ns:String} AND ts < {verified_at:DateTime}) 67dfbb3578cb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this @@ -993,7 +996,6 @@ 6f025f927273 SELECT count() AS n FROM loom.knowledge_ingestions WHERE org = {org:String} AND user_id = {uid:String} 6f11f5e87057 SELECT DISTINCT path FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace = {ns:String} AND symbol_id IN {ids:Array(String)} AND tombstoned_at IS NULL 6f4a2a751075 SELECT count() AS n FROM loom.operator_edges FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} -6f553f0d8cd1 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 6f5de71aa3ff ALTER TABLE loom.datasets DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 6f5e97facae7 SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND user_id = {uid:String} 6f7989d65b42 SELECT count() AS n FROM loom.task_events WHERE org = {org:String} AND user_id = {uid:String} AND ? @@ -1068,6 +1070,7 @@ 77b5d76bd16d SELECT count() AS n FROM loom.entity_triple_rows WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 77be1ad28338 SELECT DISTINCT agent FROM loom.memory_embeddings WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL ORDER BY agent 77cd7f76783c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist +77dc4fb48c1f SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 7843812c63f3 SELECT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory AS m WHERE m.memory_type IN (?, ?, ?) AND org = {org_filter:String} AND namespace = {ns_filter:String} AND m.created_at > 78ba94b892b2 SELECT thread_id, msg_id, any(role) AS role, argMax(substringUTF8(content, ?, {listed:UInt32}), ts) AS content, max(c.saved_at) AS saved_at FROM loom.conversations AS c WHERE org = {org:String} AND na 78caa320ee42 SELECT * FROM loom.memory_embeddings FINAL PREWHERE org = {org:String} AND namespace = {ns:String} AND scope = ? AND memory_key = {k:String} WHERE tombstoned_at IS NULL SETTINGS select_sequential_cons @@ -1247,7 +1250,6 @@ 8879f43a2306 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 888ce735eb8f SELECT DISTINCT source_uri, toString(doc_id) AS id FROM loom.documents WHERE org = {org:String} AND namespace = {ns:String} AND source_uri >= {uri:String} AND (source_uri, id) > ({uri:String}, {id:Str 888f7269df70 ALTER TABLE loom.memory_exposures DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -88c56985a4c0 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 88cf97ec1c79 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_line, cont 8915a58efbcd SELECT namespace, toString(memory_id) AS canonical_id, memory_key, memory_type, value, tags, version, agent, session_id, user_id, source_class, sensitivity, toString(created_at) AS created_at, toStrin 891d25765442 SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} @@ -1336,6 +1338,7 @@ 92cd7a1258cd SELECT count() AS n FROM loom.entity_edges WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 92e6b8baf91e SELECT m.org AS org, m.namespace AS namespace, count() AS live_rows, max(m.created_at) AS last_write FROM loom.memory AS m FINAL LEFT ANTI JOIN (SELECT org, namespace FROM loom.namespaces) AS n ON m.o 9339ac2a7139 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user +9341d036ba83 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 9353e65f71a0 SELECT count() AS n FROM loom.conflict_allowlist FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} 935ffe795d8b ALTER TABLE loom.entity_edges DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 93640db868d1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this @@ -1377,6 +1380,7 @@ 977dbe0650c7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 979ee17b2127 SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR 97b465efed16 SELECT source_uri, count() AS live, countIf(embedding_model = {model:String} AND embedding_dim > ?) AS searchable, countIf(embedding_dim = ?) AS unembedded, countIf(embedding_model != {model:String}) +97f19a00048f SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 97f2b91effdf SELECT id, org, scope_type, scope_value, requester, actor, urgency, purge, mirror_marked, attempts, steps_completed, requested_at, failure_reason, residue FROM loom.erasure_requests FINAL WHERE status 982795414e49 SELECT agent, user_id, session_id, memory_key, cosineDistance(embedding, {emb:Array(Float32)}) AS dist FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory 9848ee046655 ALTER TABLE loom.memory_belief_sources DELETE WHERE (org = {org:String} AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:S @@ -1413,6 +1417,7 @@ 9bad70421959 SELECT toString(memory_id) AS memory_id, memory_key, agent, user_id, session_id, duplicate_of FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND 9bd30fe1f711 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, shingles, uniqExact(path) OVER () AS admitted_files FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_l 9bdea6b87eff SELECT actor AS name, count() AS n, count() OVER () AS total FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status IN (?, ?) AND actor != ? G +9c01881e4fcc SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to 9c400d8b7c0c ALTER TABLE loom.oauth_signin_state UPDATE value = {v:String}, expires_at = {e:UInt32} WHERE claim_key = {k:String} AND value = {old:String} SETTINGS keeper_map_strict_mode = ?, max_execution_time = ? 9c438a0de758 SELECT thread_id, argMax((agent, toString(role), substringUTF8(content, ?, {listed:UInt32})), (ts, msg_id)) AS last_turn FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AN 9c4f1355a57a SELECT countIf(status = ?) AS conflicted, countIf(status = ?) AS proposed FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status IN (?, ?) AND tombstoned_at IS NULL @@ -1474,7 +1479,6 @@ a1a9bf524c5c SELECT path, lang, size_bytes, loc, indexed_commit, count() OVER () a1bbc2e5bf93 SELECT count() AS n FROM loom.tasks FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND is_deleted = ? a1c1e7e66396 SELECT DISTINCT namespace FROM (SELECT * FROM loom.namespace_grants FINAL) WHERE org = {org:String} AND lower(subject) IN {subs:Array(String)} AND revoked_at IS NULL AND status = ? a1daaa70f3e1 SELECT count() AS n FROM loom.memory_exposures WHERE org = {org:String} AND user_id = {uid:String} -a1e41d0e65af SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows a1efde55bcc4 SELECT toString(schema_id) AS schema_id, name, description, status FROM loom.memory_schemas FINAL WHERE org = {org:String} AND namespace = {ns:String} AND name = {name:String} AND tombstoned_at IS NUL a216c9e22af7 ALTER TABLE loom.memory_chunks UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_muta a219f248e90c SELECT org, namespace, agent, user_id, session_id, memory_id, memory_key, memory_type, value, confidence, source_trace, version, tombstoned_at, created_at, expires_at, sensitivity FROM loom.memory FIN @@ -1533,12 +1537,10 @@ a6d7b1389c15 SELECT f.lang AS lang, count() AS chunks, countIf(c.embedding_dim > a6d9b3ff7668 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this a6e14fdbe6b8 SELECT namespace FROM loom.namespaces FINAL WHERE org = {org:String} AND classification = ? a701cdc94407 SELECT count() AS n FROM loom.memory_term_freq WHERE org = {org:String} AND namespace IN {ns:Array(String)} -a70c5f10eab4 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows a75ef7c42d9f SELECT count() AS n FROM loom.code_context_packs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND pr_number NOT IN ( SELECT pr_number FROM loom.code_pr_history a75f46602856 SELECT count() AS n FROM loom.memory_drops WHERE org = {org:String} AND namespace IN {ns:Array(String)} a7892d3b93cd SELECT thread_id, msg_id, any(role) AS role, argMax(substringUTF8(content, ?, {listed:UInt32}), ts) AS content, max(c.saved_at) AS saved_at FROM loom.conversations AS c WHERE org = {org:String} AND na a789ce3fb940 SELECT count() AS n FROM loom.memory_evidence WHERE org = {org:String} AND user_id = {uid:String} AND ? -a79a82c3db28 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows a7e930ac6777 SELECT toDate(coalesce(temporal_anchor, valid_at)) AS event_date, cosineDistance(embedding, {q:Array(Float32)}) AS distance, substring(content_excerpt, ?, ?) AS excerpt, memory_key, temporal_anchor IS a819ade52d8a SELECT org, namespace, source_uri, version, revision, title, ingested_at, superseded_at, if(format != ?, toString(format), if(if(JSONType(metadata, ?) = ?, JSONExtractString(metadata, ?), ?) != ?, if( a85f83c11660 SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND (namespace, memory_key) IN (SELECT namespace, memory_key FROM loom.memory WHERE org = {org:String} AND user_id = { @@ -1553,7 +1555,6 @@ a8ef32fbad8c SELECT content_sha256, count() AS chunk_count, uniqExact(source_uri a8f2636209f6 SELECT ts, event_type, org, namespace, actor, subject, request_id, row_hash FROM loom.audit_log WHERE org = {org:String} AND (NOT startsWith(namespace, {col_prefix:String}) OR namespace IN {col_readab a90054f8b1c7 SELECT DISTINCT b.? AS qid FROM system.mutations ARRAY JOIN {versions:Array(Tuple(String, UInt64))} AS b WHERE database = {db:String} AND table = {t:String} AND is_done = ? AND position(command, {pat: a92198f269fa SELECT day, runs, fails, prs, groups, steps, flips, same_commit_flips, branch_fails, last_true_fail, last_true_fail_head, last_fail_at, first_run_at, fail_hours, fail_hour_prs, fail_prs, fail_pr_fails -a937609f7c0d SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows a940d1ebe53d SELECT count() AS n FROM loom.knowledge_uploads WHERE org = {org:String} AND namespace = {ns:String} a94901681d41 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id = {id:String} AND user a98d68a7b8da SELECT DISTINCT namespace, memory_key FROM (SELECT namespace, memory_key FROM loom.memory WHERE org = {org:String} AND user_id = {uid:String}) @@ -1620,7 +1621,6 @@ b062ee2ddb58 SELECT toString(r.record_id) AS record_id FROM loom.memory_records b07bc2344da4 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status = ? b0b2f5049b7f SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status != ? AND tombstoned_at IS NULL AND agent = {agent:String} AND user_id = {uid:String} AND sess b0eeab7a67c1 SELECT org, namespace, agent, user_id, session_id, memory_key, embedding_model, length(embedding) AS vector_len FROM loom.memory_embeddings FINAL WHERE tombstoned_at IS NULL AND embedding_dim = ? AND -b0fbecd9222a SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows b10bb326c320 SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND (arrayExists(x -> splitByChar(?, x)[?] = {uid:String}, promoted_from) OR hasAny(promoted_from, {sources:Array(String)})) b12468f0e092 SELECT ? FROM loom.memory WHERE tombstoned_at IS NULL AND expires_at IS NOT NULL AND expires_at <= now() AND (org, namespace) NOT IN (SELECT org, namespace FROM loom.namespaces FINAL WHERE retention_d b12d34885e03 ALTER TABLE loom.working_memory UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mut @@ -1665,6 +1665,7 @@ b4a67c71fa3c ALTER TABLE loom.memory_usage_events DELETE WHERE (org = {org:Strin b4bd124a4089 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist b4eaaee7f731 SELECT org, namespace, agent, user_id, session_id, name, source_id, host, port, secure, user, password_enc, cluster, databases, actor, source_class, created_at, tombstoned_at, version FROM loom.query_ b4fcede7dd0d SELECT * EXCEPT (embedding) FROM loom.code_summaries FINAL WHERE (org, namespace, embedding_model, scope_type, scope_path) IN {keys:Array(Tuple(String, String, String, String, String))} AND embedding_ +b508b1983533 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to b50bb3c82af0 SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU b517057ddbb9 SELECT count() AS n FROM loom.memory_ask_precedents WHERE org = {org:String} AND hasAny(arrayConcat(window_keys, cited_keys), {keys:Array(String)}) b5372e83b5f1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this @@ -1715,6 +1716,7 @@ b8cfcd1f660b SELECT thread_id, title FROM loom.conversation_threads FINAL WHERE b8e3e3eb3c04 SELECT org, namespace, agent, user_id, session_id, memory_key, memory_type, value, actor, version, toStringCutToZero(content_sha256) AS content_sha256, redacted_at, created_at FROM loom.memory FINAL P b9044a98f4fd SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns b91605c34026 SELECT DISTINCT toString(memory_id) AS mid FROM loom.memory FINAL WHERE org = {org:String} AND namespace IN {nss:Array(String)} AND memory_id IN {ids:Array(UUID)} AND tombstoned_at IS NULL SETTINGS se +b92837e071f9 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to b97612337078 SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} b97cf55bd0f6 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status != ? AND tombstoned_at IS NULL AND status != ? AND user_id = {uid:String} AND session_id = {s b98c5b9096ba SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL @@ -1950,7 +1952,6 @@ d0be57c846ee SELECT if(consumer = ?, args[?], consumer) AS consumer_key, count() d0c38ecb1040 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model d0c98dde6333 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user d11e82174d2d SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user -d143302e86ef SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows d19be6e39b44 SELECT org, namespace, agent, user_id, session_id, scope, embedding_model, memory_key, created_at, version FROM loom.memory_embeddings FINAL PREWHERE (org, namespace, agent, user_id, session_id, memor d19d31a3306d SELECT count() AS n FROM loom.memory_reinforcement WHERE org = {org:String} AND user_id = {uid:String} AND ? d1b71b21db97 SELECT count() AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String} @@ -2065,6 +2066,7 @@ dc003d9f3eb2 SELECT toString(failure_id) AS failure_id, org, namespace, agent, p dc06a0e4e9ec SELECT count() AS n FROM loom.code_search_outcome WHERE org = {org:String} AND namespace IN {ns:Array(String)} dc0b35f711b3 INSERT INTO loom._migration_lock (name, holder, acquired_at, renewed_at, ttl_s, build_commit) SETTINGS keeper_map_strict_mode = ?, async_insert = ? VALUES ({name:String}, {me:String}, now64(?), now64( dc258476c8e1 SELECT count() AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL +dc3a78245647 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(isValidJSON(loom.memory.value) AND startsWith(trimLeft(loom.memory.value), ?), loom.memory.value, if(length(to dc8d24176f6d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this dcaad5caba4b SELECT agent, user_id, memory_key, argMax(reinforcement_count, version) AS reinforcement_count, argMax(last_reinforced_at, version) AS last_reinforced_at FROM loom.memory_reinforcement WHERE org = {or dcacca961d46 WITH arrayConcat(splitByNonAlpha(context_lc), splitByNonAlpha(content_lc)) AS words SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision, cosineDistance @@ -2202,7 +2204,6 @@ e9bc797f59c7 SELECT org, namespace, agent, user_id, session_id, memory_key, argM e9dddc21ebf5 SELECT count() AS n FROM loom.entity_triple_memories WHERE org = {org:String} AND namespace = {ns:String} AND ? e9efca2433f5 SELECT mirror, namespace FROM loom.knowledge_mirrors FINAL WHERE org = {org:String} AND namespace IN {namespaces:Array(String)} ORDER BY mirror ea49543b4032 ALTER TABLE loom.learnings_queue DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -ea81a44a29ad SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows ea8e13fd604a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist ea9ed1d6900a WITH (SELECT (toFloat64(count()), sumMap(arrayFilter(s -> has({stems:Array(String)}, s), arrayDistinct(arrayMap( t -> stem(t, ?), splitByChar(?, translate(lower(memory_key), ?, ?))))) AS ks, arrayResi eaa08409a850 SELECT owner_email, contact_email FROM loom.namespaces FINAL WHERE org = {org:String} AND ifNull(active, true) = true AND contact_email != ? AND (lower({sub:String}) = lower(owner_email) OR lower({sub @@ -2363,7 +2364,6 @@ fb7fc150938f SELECT namespace, thread_id, ts, msg_id, row_bytes, bytes_before FR fbbbcced58d9 SELECT path, splitByChar(?, arrayElement(splitByChar(?, path), ?))[?] AS stem FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND splitByChar( fbd02f260158 SELECT ts, event_type, org, namespace, actor, subject, request_id, row_hash FROM loom.audit_log WHERE request_id = {rid:String} ORDER BY ts ASC LIMIT {limit:UInt32} fbd1ef24012c SELECT count() AS n FROM loom.tasks WHERE org = {org:String} AND namespace IN {ns:Array(String)} -fbd318d47fef SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows fc00cc1815db SELECT namespace, countIf(status=?) AS pending, countIf(status=?) AS promoted, countIf(status=?) AS rejected, if(countIf(status IN (?,?)) > ?, countIf(status=?) / countIf(status IN (?,?)), ?) AS appro fc0e3b7e1c36 SELECT agent, count() AS rows, count() OVER () AS total FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id = {scope_uid:String} GROUP BY fc162bd6bbf5 SELECT * FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace = {ns:String} AND lower(name) LIKE {like:String} AND positionCaseInsensitive(name, {needle:String}) > ? AND tombstoned_at I diff --git a/tests/integration/test_full_object_value.py b/tests/integration/test_full_object_value.py new file mode 100644 index 00000000000..275c0a2ce46 --- /dev/null +++ b/tests/integration/test_full_object_value.py @@ -0,0 +1,190 @@ +"""Full object reads, attestations and approvals bind to the same content.""" + +import json +import uuid + +import httpx +import pytest + +from server.core.hashing import sha256_value +from tests.integration._resources import unique_org + +ORG = unique_org("full-object") + + +@pytest.mark.parametrize("raw", ['"import summary"', "null", ' {\n "keep": 1, "omitted": null\n}']) +async def test_imported_native_content_and_stored_object_bytes_survive_verify( + control_plane_url, mint_test_token, ch_client, raw +): + from loom import Agent + + from server.core.datetimes import naive_utc_now + from server.memory.store import MemoryRow, build_memory_version_row + + ns = f"import-{uuid.uuid4().hex[:8]}" + native = {"reasoning": "imported evidence"} if not raw.lstrip().startswith("{") else {"keep": 1} + expected = native if not raw.lstrip().startswith("{") else json.loads(raw) + row = MemoryRow( + memory_id=str(uuid.uuid4()), + org=ORG, + namespace=ns, + agent="writer", + user_id="-", + session_id="-", + memory_key="import", + memory_type="definition", + value=expected, + value_text=raw, + value_json=json.dumps(native), + confidence=0.9, + version=1, + pinned=False, + created_at=naive_utc_now(), + updated_at=naive_utc_now(), + last_reinforced_at=naive_utc_now(), + expires_at=None, + content_sha256=sha256_value(expected), + actor="process:import", + source_class="imported", + ) + persisted = build_memory_version_row(row) + ch_client.insert("loom.memory", [list(persisted.values())], column_names=list(persisted)) + token = mint_test_token(org=ORG, namespaces=[ns], roles=["writer"]) + async with Agent( + org=ORG, namespace=ns, agent="writer", base_url=control_plane_url, api_key=token + ) as agent: + read = await agent.memory.get("import") + assert read["value"] == expected and read["content_sha256"] == sha256_value(expected) + verified = await agent.memory.verify("import", if_match_sha256=read["content_sha256"]) + assert verified["changed"] + after = await agent.memory.get_by_id(row.memory_id) + assert after["value"] == expected and after["verification"] == "process" + stored = ch_client.query( + "SELECT value, toString(value_json) FROM loom.memory FINAL " + "WHERE org = {org:String} AND namespace = {ns:String}", + parameters={"org": ORG, "ns": ns}, + ).result_rows + assert len(stored) == 1 + assert stored[0][0] == raw and json.loads(stored[0][1]) == native + + +@pytest.mark.parametrize("source", ["get", "get_by_id", "bulk_get"]) +@pytest.mark.parametrize("omitted", [None, {}]) +async def test_full_read_hash_verifies_and_rejects_omitted_edits( + control_plane_url, mint_test_token, ch_client, source, omitted +): + from loom import Agent, PreconditionFailed + + ns = f"full-{uuid.uuid4().hex[:8]}" + token = mint_test_token(org=ORG, namespaces=[ns], roles=["writer"]) + async with Agent( + org=ORG, namespace=ns, agent="writer", base_url=control_plane_url, api_key=token + ) as agent: + value = {"keep": 1, "omitted": omitted} + written = await agent.memory.set("object", value, memory_type="definition") + mid = written["memory_id"] + + async def read(): + if source == "get": + return await agent.memory.get("object") + if source == "get_by_id": + return await agent.memory.get_by_id(mid) + return (await agent.memory.bulk_get(["object"]))["results"]["object"] + + detail = await read() + digest = detail["content_sha256"] + assert detail["value"] == value and digest == sha256_value(value) + for revoke in (False, True): + result = await agent.memory.verify(memory_id=mid, if_match_sha256=digest, revoke=revoke) + assert result["changed"] + after = await read() + assert after["value"] == value and after["content_sha256"] == digest + assert after["verification"] == ("none" if revoke else "process") + again = await agent.memory.verify(memory_id=mid, if_match_sha256=digest, revoke=revoke) + assert not again["changed"] + rows = ch_client.query( + "SELECT value, toString(content_sha256), toString(verified_sha256) " + "FROM loom.memory FINAL WHERE org = {org:String} " + "AND namespace = {ns:String} AND memory_id = {mid:UUID}", + parameters={"org": ORG, "ns": ns, "mid": mid}, + ).result_rows + assert len(rows) == 1 + raw, stored_hash, verified_hash = rows[0] + assert json.loads(raw) == value and stored_hash == digest + assert verified_hash == ("" if revoke else digest) + + replacement = {"keep": 1, "omitted": {} if omitted is None else None} + await agent.memory.update_by_id(mid, replacement) + current = await read() + assert current["value"] == replacement + assert current["content_sha256"] == sha256_value(replacement) != digest + for revoke in (False, True): + with pytest.raises(PreconditionFailed): + await agent.memory.verify(memory_id=mid, if_match_sha256=digest, revoke=revoke) + assert (await read())["version"] == current["version"] + + +async def test_proposal_approval_rejects_an_omitted_edit_and_accepts_the_full_read( + control_plane_url, mint_test_token +): + from server.auth.jwt import mint_token + + ns = f"proposal-{uuid.uuid4().hex[:8]}" + author = mint_test_token(org=ORG, namespaces=[ns], roles=["writer"], subject="author") + reviewer = mint_token( + subject="reviewer", + org=ORG, + namespaces=[ns], + roles=["admin", "writer"], + ttl_seconds=600, + is_service_account=False, + ) + identity = {"org": ORG, "namespace": ns, "agent": "writer", "memory_key": "object"} + async with httpx.AsyncClient(base_url=control_plane_url, timeout=60) as client: + + async def call(token, op, body): + response = await client.post( + f"/v1/{op}", json=body, headers={"Authorization": f"Bearer {token}"} + ) + assert response.status_code == 200, response.text + return response.json() + + value = {"keep": 1, "omitted": None, "nested": {}} + written = await call( + author, + "memory.set", + { + **identity, + "value": value, + "proposed": True, + "classify": False, + }, + ) + history_body = {**identity, "memory_id": written["memory_id"], "limit": 1} + read = (await call(reviewer, "memory.history", history_body))["rows"][0] + assert read["value"] == value and read["content_sha256"] == sha256_value(value) + replacement = {"keep": 1, "changed_omission": None, "nested": {}} + await call( + author, + "memory.set", + { + **identity, + "value": replacement, + "proposed": True, + "classify": False, + }, + ) + decision = { + "org": ORG, + "namespace": ns, + "memory_keys": ["object"], + "decision": "accept", + "approved_sha256": {"object": read["content_sha256"]}, + } + assert (await call(reviewer, "memory.proposal_decide", decision))["decided"] == 0 + current = (await call(reviewer, "memory.history", history_body))["rows"][0] + assert current["status"] == "proposed" and current["value"] == replacement + decision["approved_sha256"] = {"object": current["content_sha256"]} + assert (await call(reviewer, "memory.proposal_decide", decision))["decided"] == 1 + accepted = (await call(reviewer, "memory.history", history_body))["rows"][0] + assert accepted["status"] == "active" and accepted["value"] == replacement diff --git a/tests/integration/test_memory_refusal_capture_live_ch.py b/tests/integration/test_memory_refusal_capture_live_ch.py index 89153943e1c..f503cd9d988 100644 --- a/tests/integration/test_memory_refusal_capture_live_ch.py +++ b/tests/integration/test_memory_refusal_capture_live_ch.py @@ -64,6 +64,30 @@ async def test_namespace_capture_refuses_every_user_only_in_its_namespace(ch): await policy.check_clickhouse(ch, [_row(org, "closed", "alice", "unrelated fact")]) +@pytest.mark.parametrize("capture_value", ["projection", "full"]) +@pytest.mark.parametrize("restore_value", ["projection", "full"]) +@pytest.mark.parametrize( + "full,projected", + [ + ({"keep": 1, "omitted": None, "nested": {}}, {"keep": 1}), + ({"keep": 1}, {"keep": True}), + ({"keep": 1.0}, {"keep": 1}), + ], +) +async def test_persisted_object_refusals_match_both_snapshot_representations( + ch, capture_value, restore_value, full, projected +): + org = unique_org("refusal-object-upgrade") + values = {"projection": projected, "full": full} + native = json.dumps(values["projection"]) + captured = _row(org, "facts", "alice", values[capture_value], value_json=native) + await policy.record_clickhouse(ch, [captured]) + restored = _row(org, "facts", "alice", values[restore_value], value_json=native) + await _refused(ch, restored) + await policy.check_clickhouse(ch, [_row(org, "facts", "alice", "unrelated fact")]) + await policy.check_clickhouse(ch, [{**restored, "user_id": "bob"}]) + + async def test_user_capture_reaches_future_namespaces_and_derived_writer_identity(ch): org = unique_org("refusal-user") parent = _row(org, "first", "alice", "original private fact") diff --git a/tests/unit/test_full_object_value.py b/tests/unit/test_full_object_value.py new file mode 100644 index 00000000000..069c509812f --- /dev/null +++ b/tests/unit/test_full_object_value.py @@ -0,0 +1,34 @@ +"""Stored object text preserves members missing from native JSON rendering.""" + +import json + +import pytest + +from server.core.hashing import served_row_value, sha256_value + + +@pytest.mark.parametrize("omitted", [None, {}, {"empty": {}}]) +def test_object_text_is_authoritative_over_native_projection(omitted): + value = {"keep": 1, "omitted": omitted} + row = {"value": json.dumps(value), "value_json": '{"keep":1}'} + assert served_row_value(row) == value + assert sha256_value(served_row_value(row)) != sha256_value({"keep": 1}) + + +@pytest.mark.parametrize("raw", ["", '"import summary"', "null"]) +@pytest.mark.parametrize( + "encoded", ['{"reasoning":"imported evidence"}', {"reasoning": "imported evidence"}] +) +def test_native_only_import_content_remains_readable(raw, encoded): + assert served_row_value({"value": raw, "value_json": encoded}) == { + "reasoning": "imported evidence" + } + + +@pytest.mark.parametrize("value", ["plain text", '{"literal":null}', [1, None], False, 0, None]) +def test_scalar_and_array_values_keep_their_encoding(value): + assert served_row_value({"value": json.dumps(value), "value_json": "{}"}) == value + + +def test_empty_object_text_does_not_select_unrelated_native_content(): + assert served_row_value({"value": " {}", "value_json": '{"discarded":1}'}) == {} diff --git a/tests/unit/test_memory_refusals.py b/tests/unit/test_memory_refusals.py index 3356a9b6827..4db9ee40ffc 100644 --- a/tests/unit/test_memory_refusals.py +++ b/tests/unit/test_memory_refusals.py @@ -90,6 +90,63 @@ def test_absent_raw_metadata_does_not_reintroduce_a_deleted_null(): assert not matches(served_row_value(row), fingerprint(None)) +@pytest.mark.parametrize("capture", ["previous", "current"]) +@pytest.mark.parametrize("reader", ["previous", "current"]) +@pytest.mark.parametrize( + "full,projected", + [ + ({"keep": 1, "omitted": None, "nested": {}}, {"keep": 1}), + ({"keep": 1}, {"keep": True}), + ({"keep": 1.0}, {"keep": 1}), + ], +) +async def test_snapshot_refusal_survives_full_object_read_upgrade( + monkeypatch, capture, reader, full, projected +): + import json + + from server.core.errors import ValidationError + from server.identity.app.namespace_snapshot import snapshot_memory_row + from server.memory.app.snapshot_rows import restore_rows + from server.memory.store import build_memory_version_row + from server.memory.store import refusals as policy + from tests.unit.test_memory_verify import _row + + source = _row(value=full, value_text=json.dumps(full), value_json=json.dumps(projected)) + persisted = build_memory_version_row(source) + saved = snapshot_memory_row(persisted) + [restored] = restore_rows( + [saved], + org=source.org, + target_namespace=source.namespace, + rebind_agent=None, + version_base=source.version + 1, + actor="process:restore", + ) + patterns = set(fingerprint(projected)) if capture == "previous" else set() + + class CH: + async def insert(self, table, rows, **kwargs): + assert table == "loom.memory_refusals" + patterns.update((r["kind"], r["units"], r["digest"]) for r in rows) + + async def query_all(self, sql, params=None): + if "SELECT DISTINCT" in sql: + return [] + return [{"found": 1}] if patterns.intersection(params["candidates"]) else [] + + monkeypatch.setattr(policy, "_writer", lambda: "process:erase") + ch = CH() + if capture == "current": + await policy.record_clickhouse(ch, [persisted]) + if reader == "previous": + # The previous decoder chooses the saved native projection. + restored = {**restored, "value": json.dumps(projected)} + with pytest.raises(ValidationError, match="refused"): + await policy.check_clickhouse(ch, [restored]) + await policy.check_clickhouse(ch, [{**restored, "value": '"unrelated"', "value_json": "{}"}]) + + @pytest.mark.parametrize("metadata", [None, "", "{}", " { } ", {}, [], "null"]) def test_default_raw_metadata_does_not_freeze_unrelated_intake(metadata): from server.memory.store.refusals import _raw_content_values diff --git a/tests/unit/test_version_row_value_bytes.py b/tests/unit/test_version_row_value_bytes.py index 6846041f046..104967df738 100644 --- a/tests/unit/test_version_row_value_bytes.py +++ b/tests/unit/test_version_row_value_bytes.py @@ -250,9 +250,13 @@ def test_hydrate_carries_no_text_for_a_preview_page() -> None: def test_the_final_projection_selects_the_raw_column_beside_the_rendering() -> None: + from server.memory.store.sql import SERVED_VALUE + proj = mr._MEMORY_FINAL_PROJECTION - assert "value AS value_text" in proj - assert "toString(value_json), value) AS value" in proj + assert "loom.memory.value AS value_text" in proj + assert f"{SERVED_VALUE} AS value" in proj + assert "isValidJSON(loom.memory.value)" in SERVED_VALUE + assert "toString(value_json), loom.memory.value)" in SERVED_VALUE # ------------------------------------------------------------- the handlers