Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions server/core/hashing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
43 changes: 30 additions & 13 deletions server/memory/store/refusals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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):
Expand All @@ -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]],
*,
Expand All @@ -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(
{
**{
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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)
Expand Down
11 changes: 8 additions & 3 deletions server/memory/store/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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), '{'), "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — This projection changes the content hash for existing objects with null or empty members. A read on either build can return a token that the other build rejects for the same unchanged row. The compatibility notes reproduce the mismatch with the untouched previous build. Keep the token usable across the rollout and add a two-build test against that untouched baseline.

"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 = """
Expand All @@ -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,
Expand Down
Loading
Loading