diff --git a/pkgs/atlas-search/atlas_search.py b/pkgs/atlas-search/atlas_search.py index db4aa14fe0..7d51e41db2 100755 --- a/pkgs/atlas-search/atlas_search.py +++ b/pkgs/atlas-search/atlas_search.py @@ -107,10 +107,39 @@ VEC_TABLE = "vec_snowflake_m_v2_768_f32" RRF_K = 10 SENS_ORDER = ["shareable", "personal", "local-only", "secret-bearing"] +DISCLOSURE_CONTEXT_CEILINGS = { + "fleet-internal": "local-only", + "hosted-per-user": "personal", + "public-surface": "shareable", + "local-owner": "secret-bearing", +} +EXCLUDED_DISPOSITION = "excluded_personal_life" BWS_TOKEN_NAMES = ["turso.atlas-ro-token", "turso.atlas-read-only-token", "atlas-ro"] TOKEN_CACHE = os.path.expanduser("~/.cache/atlas-search/turso-token.json") MESSAGE_TEXT_CAP = 50000 + +def effective_sensitivity_ceiling(context, caller_ceiling): + """Intersect the caller grant with the destination context. + + Unknown contexts fail closed to the public-surface ceiling, matching + atlas-core's outbound default. + """ + context_ceiling = DISCLOSURE_CONTEXT_CEILINGS.get(context, "shareable") + if caller_ceiling not in SENS_ORDER: + return "shareable" + return min((context_ceiling, caller_ceiling), key=SENS_ORDER.index) + + +def disclosure_allows(classification, ceiling): + """Return whether a raw classification may cross this disclosure boundary.""" + if classification == EXCLUDED_DISPOSITION or classification not in SENS_ORDER: + return False + return ( + ceiling in SENS_ORDER + and SENS_ORDER.index(classification) <= SENS_ORDER.index(ceiling) + ) + for _k in ("NO_PROXY", "no_proxy"): if "[" in os.environ.get(_k, ""): os.environ[_k] = "localhost,127.0.0.1" @@ -592,30 +621,36 @@ def vector_search(self, qvec, allowed_ids, pool): # ------------------------------------------------------------ filters ----- class Filters: def __init__(self, args): - self.kinds = split_csv(args.kind) - self.topics = split_csv(args.topic) - self.projects = split_csv(args.project) - self.clients = split_csv(args.client) - if args.max_sensitivity not in SENS_ORDER: + self.kinds = split_csv(getattr(args, "kind", None)) + self.topics = split_csv(getattr(args, "topic", None)) + self.projects = split_csv(getattr(args, "project", None)) + self.clients = split_csv(getattr(args, "client", None)) + self.context = getattr(args, "context", "local-owner") + caller_ceiling = getattr(args, "max_sensitivity", "secret-bearing") + if caller_ceiling not in SENS_ORDER: die(f"--max-sensitivity must be one of {SENS_ORDER}") - self.max_sensitivity = args.max_sensitivity - self.allowed_sens = SENS_ORDER[: SENS_ORDER.index(args.max_sensitivity) + 1] - self.since = args.since + self.max_sensitivity = caller_ceiling + self.effective_ceiling = effective_sensitivity_ceiling( + self.context, caller_ceiling + ) + self.allowed_sens = SENS_ORDER[: SENS_ORDER.index(self.effective_ceiling) + 1] + self.since = getattr(args, "since", None) self.until = None - if args.until: + until = getattr(args, "until", None) + if until: try: - d = date.fromisoformat(args.until) + d = date.fromisoformat(until) except ValueError: - die(f"--until must be YYYY-MM-DD, got {args.until}") + die(f"--until must be YYYY-MM-DD, got {until}") self.until_exclusive = (d + timedelta(days=1)).isoformat() - self.until = args.until + self.until = until else: self.until_exclusive = None - if args.since: + if self.since: try: - date.fromisoformat(args.since) + date.fromisoformat(self.since) except ValueError: - die(f"--since must be YYYY-MM-DD, got {args.since}") + die(f"--since must be YYYY-MM-DD, got {self.since}") def where(self, be): """SQL fragment + params, assuming aliases c/m/s/l and the @@ -1021,10 +1056,14 @@ def result_entry(be, args, fused_entry, d, vec_dist): } if cid in vec_dist and vec_dist[cid] is not None: entry["vector_distance"] = round(vec_dist[cid], 6) + ceiling = effective_sensitivity_ceiling( + getattr(args, "context", "local-owner"), + getattr(args, "max_sensitivity", "secret-bearing"), + ) if args.expand: - entry["context"] = neighbor_map(be, d, args.expand) + entry["context"] = neighbor_map(be, d, args.expand, ceiling) if args.with_message: - entry["message"] = message_obj(be, d) + entry["message"] = message_obj(be, d, ceiling) return entry @@ -1090,9 +1129,17 @@ def grouped_output(be, args, filters, ranked, vec_dist, notes): if e["chunk_id"] in vec_dist and vec_dist[e["chunk_id"]] is not None: ce["vector_distance"] = round(vec_dist[e["chunk_id"]], 6) if args.expand: - ce["context"] = neighbor_map(be, d, args.expand) + ceiling = effective_sensitivity_ceiling( + getattr(args, "context", "local-owner"), + getattr(args, "max_sensitivity", "secret-bearing"), + ) + ce["context"] = neighbor_map(be, d, args.expand, ceiling) if args.with_message: - ce["message"] = message_obj(be, d) + ceiling = effective_sensitivity_ceiling( + getattr(args, "context", "local-owner"), + getattr(args, "max_sensitivity", "secret-bearing"), + ) + ce["message"] = message_obj(be, d, ceiling) chunks.append(ce) results.append( { @@ -1143,31 +1190,62 @@ def fetch_details(be, chunk_ids): rows = be.execute(sql, list(chunk_ids)) out = {} for r in rows: - r["eff_sensitivity"] = r.get("chunk_sensitivity") or r.get("l_sensitivity") + chunk_sensitivity = r.get("chunk_sensitivity") + r["eff_sensitivity"] = ( + r.get("l_sensitivity") if chunk_sensitivity is None else chunk_sensitivity + ) out[r["chunk_id"]] = r return out -def neighbor_map(be, d, n): +def neighbor_map(be, d, n, ceiling="secret-bearing"): rows = be.execute( "SELECT id, chunk_idx, text FROM chunks WHERE message_id = ? " "AND chunk_idx BETWEEN ? AND ? ORDER BY chunk_idx", [d["message_id"], d["chunk_idx"] - n, d["chunk_idx"] + n], ) + details = fetch_details(be, [r["id"] for r in rows]) + allowed = { + r["id"] + for r in rows + if (detail := details.get(r["id"])) + # Output authorization is based on the chunk's own classification. + # Session labels are metadata, not a fallback grant for an unclassified + # chunk at a destination boundary. + and disclosure_allows(detail.get("chunk_sensitivity"), ceiling) + } before = [ {"chunk_id": r["id"], "text": r["text"]} for r in rows - if r["chunk_idx"] < d["chunk_idx"] + if r["chunk_idx"] < d["chunk_idx"] and r["id"] in allowed ] after = [ {"chunk_id": r["id"], "text": r["text"]} for r in rows - if r["chunk_idx"] > d["chunk_idx"] + if r["chunk_idx"] > d["chunk_idx"] and r["id"] in allowed ] return {"before": before, "after": after} -def message_obj(be, d): +def message_obj(be, d, ceiling="secret-bearing"): + # A full message is indivisible: withhold it if any chunk in it is + # excluded or cannot be proven to fit the same output boundary. + classifications = be.execute( + "SELECT " + + be.sens_expr + + " AS sensitivity FROM chunks c " + "JOIN messages m ON m.id = c.message_id " + "JOIN sessions s ON s.id = m.session_id " + + f"LEFT JOIN {be.labels_table} l ON l.session_id = s.id " + + be.sens_join + + " WHERE c.message_id = ?", + [d["message_id"]], + ) + if not classifications or any( + not disclosure_allows(r.get("sensitivity"), ceiling) + for r in classifications + ): + return None rows = be.execute( "SELECT id, role, text FROM messages WHERE id = ?", [d["message_id"]] ) @@ -1186,9 +1264,12 @@ def message_obj(be, d): # ------------------------------------------------------------ get-chunk --- def run_get_chunk(be, args): + filters = Filters(args) details = fetch_details(be, [args.chunk_id]) d = details.get(args.chunk_id) - if d is None: + if d is None or not disclosure_allows( + d.get("chunk_sensitivity"), filters.effective_ceiling + ): die(f"chunk {args.chunk_id} not found", code=1) out = { "chunk_id": d["chunk_id"], @@ -1203,7 +1284,9 @@ def run_get_chunk(be, args): "session_id": d["session_id"], } if args.neighbors: - out["context"] = neighbor_map(be, d, args.neighbors) + out["context"] = neighbor_map( + be, d, args.neighbors, filters.effective_ceiling + ) notes = list(getattr(be, "notes", [])) if notes: out["notes"] = notes @@ -1320,6 +1403,20 @@ def add_backend_args(p): ) +def add_disclosure_args(p, max_sensitivity_default): + p.add_argument( + "--context", + default="local-owner", + help="destination disclosure context (default local-owner; unknown values fail closed)", + ) + p.add_argument( + "--max-sensitivity", + choices=SENS_ORDER, + default=max_sensitivity_default, + help=f"caller clearance ceiling in {'<'.join(SENS_ORDER)} (default {max_sensitivity_default})", + ) + + def add_vector_args(p): p.add_argument( "--model", @@ -1377,12 +1474,7 @@ def main(): ps.add_argument("--client") ps.add_argument("--since", help="YYYY-MM-DD, on sessions.created_at (inclusive)") ps.add_argument("--until", help="YYYY-MM-DD, on sessions.created_at (inclusive)") - ps.add_argument( - "--max-sensitivity", - default="personal", - help="ceiling in shareable + # public-surface). For labels this CLI is deliberately stricter + # than atlas-core chunk_classification, which resolves an unknown + # label to secret-bearing (servable at local-owner): unclassified + # content is never served here, matching the search ceiling + # filter, which already excluded NULL sensitivity before #12623. + self.assertEqual( + atlas_search.effective_sensitivity_ceiling("unknown", "secret-bearing"), + "shareable", + ) + for label in (None, "", "internal", "Shareable"): + with self.subTest(label=label): + self.assertFalse(atlas_search.disclosure_allows(label, "secret-bearing")) + self.assertFalse( + atlas_search.disclosure_allows("excluded_personal_life", "secret-bearing") + ) + + def test_context_intersection_matches_exhaustive_reference_model(self): + # Oracle: an independent rank-based model of the design's four + # destination ceilings, caller intersection, and fail-closed labels. + ranks = {label: rank for rank, label in enumerate( + ("shareable", "personal", "local-only", "secret-bearing") + )} + contexts = { + "fleet-internal": "local-only", + "hosted-per-user": "personal", + "public-surface": "shareable", + "local-owner": "secret-bearing", + } + classifications = (*ranks, None, "", "unknown", "excluded_personal_life") + for context, context_ceiling in contexts.items(): + for caller, caller_rank in ranks.items(): + ceiling = min(context_ceiling, caller, key=ranks.__getitem__) + with self.subTest(context=context, caller=caller): + self.assertEqual( + atlas_search.effective_sensitivity_ceiling(context, caller), + ceiling, + ) + for classification in classifications: + expected = ( + classification in ranks + and classification != "excluded_personal_life" + and ranks[classification] <= ranks[ceiling] + ) + with self.subTest(classification=classification): + self.assertEqual( + atlas_search.disclosure_allows(classification, ceiling), + expected, + ) + + +class SQLiteFixtureBackend: + name = "local" + sens_expr = "cs.sensitivity" + labels_table = "session_labels" + sens_join = "LEFT JOIN v_chunk_sens cs ON cs.id = c.id" + vec_table = "unused" + + def __init__(self): + self.con = sqlite3.connect(":memory:") + self.con.row_factory = sqlite3.Row + self.con.executescript( + """ + CREATE TABLE chunks (id INTEGER, message_id INTEGER, chunk_idx INTEGER, text TEXT); + CREATE TABLE messages (id INTEGER, role TEXT, text TEXT, session_id INTEGER); + CREATE TABLE sessions (id INTEGER, title TEXT, client TEXT, created_at TEXT); + CREATE TABLE session_labels ( + session_id INTEGER, kind TEXT, topics TEXT, projects TEXT, sensitivity TEXT + ); + CREATE TABLE v_chunk_sens (id INTEGER, sensitivity TEXT); + INSERT INTO sessions VALUES (7, 'title', 'client', '2026-01-01'); + INSERT INTO messages VALUES (9, 'user', 'whole raw message', 7); + INSERT INTO session_labels VALUES (7, 'chat', '[]', '[]', 'shareable'); + INSERT INTO chunks VALUES (1, 9, 0, 'safe before'); + INSERT INTO chunks VALUES (2, 9, 1, 'safe target'); + INSERT INTO chunks VALUES (3, 9, 2, 'personal neighbor'); + INSERT INTO chunks VALUES (4, 9, 3, 'excluded neighbor'); + INSERT INTO chunks VALUES (5, 9, 4, 'unclassified neighbor'); + INSERT INTO v_chunk_sens VALUES (1, 'shareable'); + INSERT INTO v_chunk_sens VALUES (2, 'shareable'); + INSERT INTO v_chunk_sens VALUES (3, 'personal'); + INSERT INTO v_chunk_sens VALUES (4, 'excluded_personal_life'); + """ + ) + self.notes = [] + + def execute(self, sql, args=()): + return [dict(row) for row in self.con.execute(sql, args).fetchall()] + + +class DisclosureOutputTests(unittest.TestCase): + def setUp(self): + self.backend = SQLiteFixtureBackend() + + def tearDown(self): + self.backend.con.close() + + def test_get_chunk_filters_neighbors_at_destination_context(self): + # Oracle: design §4 — public-surface permits shareable only; excluded + # material remains ineligible even when a neighbor is requested. + args = SimpleNamespace( + chunk_id=2, + neighbors=2, + max_sensitivity="secret-bearing", + context="public-surface", + ) + result = atlas_search.run_get_chunk(self.backend, args) + self.assertEqual( + result["context"], + {"before": [{"chunk_id": 1, "text": "safe before"}], "after": []}, + ) + + def test_missing_chunk_classification_does_not_inherit_session_label(self): + # Oracle: raw chunk classification must be known before admission; + # session-level shareable metadata cannot authorize an unclassified chunk. + details = atlas_search.fetch_details(self.backend, [5])[5] + self.assertIsNone(details["chunk_sensitivity"]) + self.assertFalse( + atlas_search.disclosure_allows( + details.get("chunk_sensitivity"), "shareable" + ) + ) + args = SimpleNamespace( + chunk_id=2, + neighbors=3, + max_sensitivity="secret-bearing", + context="public-surface", + ) + result = atlas_search.run_get_chunk(self.backend, args) + self.assertNotIn(5, [c["chunk_id"] for c in result["context"]["after"]]) + + def test_full_message_withheld_if_any_chunk_exceeds_boundary(self): + # Oracle: full-message hydration cannot bypass the same output boundary. + details = atlas_search.fetch_details(self.backend, [2])[2] + self.assertIsNone(atlas_search.message_obj(self.backend, details, "shareable")) + + def test_search_filters_candidates_by_context_and_caller_intersection(self): + args = SimpleNamespace( + kind=None, + topic=None, + project=None, + client=None, + since=None, + until=None, + max_sensitivity="secret-bearing", + context="hosted-per-user", + ) + filters = atlas_search.Filters(args) + self.assertEqual(filters.allowed_sens, ["shareable", "personal"]) + + def test_full_message_is_returned_when_every_chunk_is_allowed(self): + self.backend.execute( + "UPDATE v_chunk_sens SET sensitivity='shareable'", [] + ) + self.backend.execute( + "INSERT INTO v_chunk_sens VALUES (5, 'shareable')", [] + ) + details = atlas_search.fetch_details(self.backend, [2])[2] + self.assertEqual( + atlas_search.message_obj(self.backend, details, "shareable")["text"], + "whole raw message", + ) + + +if __name__ == "__main__": + unittest.main()