diff --git a/apps/api/moon.yml b/apps/api/moon.yml index b3a88f2db..b2e15ee6b 100644 --- a/apps/api/moon.yml +++ b/apps/api/moon.yml @@ -286,7 +286,7 @@ tasks: # Live SurrealDB runtime tests (requires the CI SurrealDB service) test-live: - command: SIBYL_LIVE_SURREAL_TESTS=1 uv run pytest tests/test_surreal_live_runtime.py tests/test_surreal_live_raw_embedding_space.py tests/test_mcp_oauth_replicas.py tests/test_cache_invalidation.py tests/test_surreal_live_query_shapes.py tests/test_session_reannouncement.py tests/test_surreal_live_bot_accounts.py --no-cov -v + command: SIBYL_LIVE_SURREAL_TESTS=1 uv run pytest tests/test_surreal_live_runtime.py tests/test_surreal_live_raw_embedding_space.py tests/test_mcp_oauth_replicas.py tests/test_cache_invalidation.py tests/test_surreal_live_query_shapes.py tests/test_session_reannouncement.py tests/test_surreal_live_bot_accounts.py tests/test_surreal_live_nested_fields.py --no-cov -v inputs: - "@group(sources)" - tests/test_surreal_live_runtime.py @@ -296,6 +296,7 @@ tasks: - tests/test_surreal_live_query_shapes.py - tests/test_session_reannouncement.py - tests/test_surreal_live_bot_accounts.py + - tests/test_surreal_live_nested_fields.py options: cache: false runInCI: true diff --git a/apps/api/tests/test_surreal_live_nested_fields.py b/apps/api/tests/test_surreal_live_nested_fields.py new file mode 100644 index 000000000..be052efd0 --- /dev/null +++ b/apps/api/tests/test_surreal_live_nested_fields.py @@ -0,0 +1,252 @@ +"""Nested objects inside arrays of objects, against a live SurrealDB server. + +SurrealDB 3.x stored undeclared keys of an object inside a SCHEMAFULL table's +`array` field; 4.0 refuses the whole write instead ("Found field +'metrics[58].avg', but no such field exists"). Each test bootstraps the content +schema in a namespace of its own and writes a record the way the product does, +so it fails on either server version the moment a nested shape stops fitting. +""" + +from __future__ import annotations + +import os +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from datetime import UTC, datetime +from uuid import uuid4 + +import pytest + +from sibyl.jobs.source_imports import SourceImportRun, _run_record +from sibyl.persistence.surreal.source_import_runs import SurrealSourceImportRunRepository +from sibyl.services import telemetry as telemetry_service +from sibyl_core.backends.surreal import SurrealContentClient, bootstrap_content_schema +from sibyl_core.backends.surreal.content_schema import ( + CONTENT_SCHEMA_CURRENT_VERSION, + CONTENT_SCHEMA_NAME, + _content_schema_migrations, +) +from sibyl_core.backends.surreal.index_engine import index_engine_of +from sibyl_core.backends.surreal.records import normalize_records +from sibyl_core.backends.surreal.schema_version import ( + apply_schema_migrations, + get_schema_version, + pin_schema_compatibility_level, +) +from sibyl_core.backends.surreal.url_schemes import is_embedded_surreal_url +from sibyl_core.models.sources import SourceSkippedRecord +from sibyl_core.observability import telemetry_registry + +pytestmark = pytest.mark.skipif( + os.environ.get("SIBYL_LIVE_SURREAL_TESTS") != "1", + reason="live SurrealDB runtime smoke tests are disabled", +) + +_ROLLUP_UPSERT = "UPSERT telemetry_rollups CONTENT $record WHERE bucket_key = $bucket_key;" + + +def _live_surreal_url() -> str: + url = os.environ.get("SIBYL_SURREAL_URL", "") + if not url or is_embedded_surreal_url(url): + pytest.skip("live SurrealDB tests require SIBYL_SURREAL_URL to point at a server") + return url + + +def _client(namespace: str) -> SurrealContentClient: + return SurrealContentClient( + url=_live_surreal_url(), + namespace=namespace, + database="content", + username=os.environ.get("SIBYL_SURREAL_USERNAME", "root"), + password=os.environ.get("SIBYL_SURREAL_PASSWORD", "root"), + ) + + +async def _drop_namespace(namespace: str) -> None: + from surrealdb import AsyncSurreal + + client = AsyncSurreal(_live_surreal_url()) + try: + await client.signin( + { + "username": os.environ.get("SIBYL_SURREAL_USERNAME", "root"), + "password": os.environ.get("SIBYL_SURREAL_PASSWORD", "root"), + } + ) + await client.query(f"REMOVE NAMESPACE IF EXISTS {namespace};") + finally: + await client.close() + + +@asynccontextmanager +async def _content_store(*, bootstrap: bool = True) -> AsyncIterator[SurrealContentClient]: + namespace = f"nested_fields_{uuid4().hex}" + client = _client(namespace) + try: + if bootstrap: + await bootstrap_content_schema(client) + yield client + finally: + await client.close() + await _drop_namespace(namespace) + + +def _runtime_snapshot() -> dict[str, object]: + """What the running API would roll up: requests, queries and their labels.""" + registry = telemetry_registry() + registry.record_api_request( + method="get", route="/api/health/ready", status_code=200, duration_ms=12.5 + ) + registry.record_api_request(method="post", route="/api/search", status_code=500, duration_ms=88) + registry.record_surreal_query( + client="content", + database="content", + elapsed_ms=3.2, + statement="select", + status="ok", + retry_count=0, + query_hash="abc123", + ) + return telemetry_service.runtime_summary() + + +@pytest.mark.asyncio +async def test_live_runtime_rollup_keeps_metric_event_and_trend_entries(monkeypatch) -> None: + async with _content_store() as client: + + async def shared_client() -> SurrealContentClient: + return client + + monkeypatch.setattr(telemetry_service, "get_shared_surreal_content_client", shared_client) + monkeypatch.setattr(telemetry_service, "_last_persisted_bucket", None) + snapshot = _runtime_snapshot() + monkeypatch.setattr(telemetry_service, "runtime_summary", lambda **_: snapshot) + + bucket = telemetry_service._current_bucket() + record = await telemetry_service.persist_runtime_rollup(bucket=bucket) + + assert record is not None, "the rollup write was refused" + rows = normalize_records( + await client.execute_query( + "SELECT metrics, recent_events, trends FROM telemetry_rollups " + "WHERE bucket_key = $bucket_key;", + bucket_key=record["bucket_key"], + ) + ) + assert len(rows) == 1 + histogram = next( + metric + for metric in rows[0]["metrics"] + if metric.get("name") == "sibyl_api_request_duration_ms" + ) + assert {"avg", "p95", "labels"} <= set(histogram) + assert histogram["labels"]["route"] in {"/api/health/ready", "/api/search"} + assert any(event["labels"].get("route") for event in rows[0]["recent_events"]) + assert rows[0]["trends"] + assert "api_p95_ms" in rows[0]["trends"][0] + + +@pytest.mark.asyncio +async def test_live_source_import_keeps_skipped_and_error_entries() -> None: + async with _content_store() as client: + run = SourceImportRun( + import_id=str(uuid4()), + organization_id=str(uuid4()), + principal_id=str(uuid4()), + source_uri="file:///exports/notes.jsonl", + adapter_name="jsonl", + options={"target_memory_scope": "private"}, + policy_context={"actor": "test"}, + batch_size=50, + promotion_preview_approved=False, + ) + run.skipped_records.append( + SourceSkippedRecord( + adapter_record_id="line-7", + source_uri="file:///exports/notes.jsonl#7", + reason="duplicate_dedupe_key", + metadata={"dedupe_key": "sha256:abc", "raw_memory_id": str(uuid4())}, + ).model_dump(mode="json") + ) + run.errors.append( + { + "message": "adapter stopped", + "type": "RuntimeError", + "timestamp": datetime.now(UTC).isoformat(), + } + ) + + await SurrealSourceImportRunRepository(client).save( + _run_record(run), expected_revision=None + ) + + rows = normalize_records( + await client.execute_query( + "SELECT skipped_records, errors FROM source_imports WHERE uuid = $uuid;", + uuid=run.import_id, + ) + ) + assert rows[0]["skipped_records"][0]["metadata"]["dedupe_key"] == "sha256:abc" + assert rows[0]["errors"][0]["type"] == "RuntimeError" + + +@pytest.mark.asyncio +async def test_live_schema_version_keeps_every_migration_entry() -> None: + async with _content_store() as client: + rows = normalize_records( + await client.execute_query("SELECT migrations FROM schema_version:content;") + ) + migrations = rows[0]["migrations"] + assert [entry["version"] for entry in migrations] == list( + range(1, CONTENT_SCHEMA_CURRENT_VERSION + 1) + ) + assert migrations[-1] == { + "version": 59, + "name": "content_telemetry_rollup_flexible_entries", + } + + +@pytest.mark.asyncio +async def test_live_migration_59_opens_rollup_entries_on_an_upgraded_database() -> None: + async with _content_store(bootstrap=False) as client: + url = _live_surreal_url() + info = await pin_schema_compatibility_level(client.execute_query, client.execute_query) + before = tuple(m for m in _content_schema_migrations(url=url) if m.version <= 58) + await apply_schema_migrations( + client.execute_query, + before, + name=CONTENT_SCHEMA_NAME, + scope="content_schema_migration", + ) + assert await get_schema_version(client.execute_query, name=CONTENT_SCHEMA_NAME) == 58 + + snapshot = _runtime_snapshot() + record = { + "uuid": str(uuid4()), + "bucket_key": "209901010000", + "bucket_start": datetime(2099, 1, 1, tzinfo=UTC), + "uptime_seconds": snapshot["uptime_seconds"], + "summaries": snapshot["summaries"], + "trends": snapshot["trends"], + "metrics": snapshot["metrics"], + "recent_events": snapshot["recent_events"], + } + if index_engine_of(info) is not None: + # The failure this migration exists for: 4.0 refuses nested keys + # inside the version 58 element definitions. + with pytest.raises(Exception, match="no such field exists"): + await client.execute_query( + _ROLLUP_UPSERT, record=record, bucket_key=record["bucket_key"] + ) + + await bootstrap_content_schema(client) + + assert await get_schema_version(client.execute_query, name=CONTENT_SCHEMA_NAME) == 59 + await client.execute_query(_ROLLUP_UPSERT, record=record, bucket_key=record["bucket_key"]) + rows = normalize_records( + await client.execute_query( + "SELECT metrics FROM telemetry_rollups WHERE bucket_key = $bucket_key;", + bucket_key=record["bucket_key"], + ) + ) + assert any("avg" in metric for metric in rows[0]["metrics"]) diff --git a/packages/python/sibyl-core/src/sibyl_core/backends/surreal/content_schema.py b/packages/python/sibyl-core/src/sibyl_core/backends/surreal/content_schema.py index b9084cb57..29fc5a14f 100644 --- a/packages/python/sibyl-core/src/sibyl_core/backends/surreal/content_schema.py +++ b/packages/python/sibyl-core/src/sibyl_core/backends/surreal/content_schema.py @@ -163,7 +163,7 @@ *RAW_LEXICAL_TABLES, RAW_LEXICAL_STATE_TABLE, ) -CONTENT_SCHEMA_CURRENT_VERSION = 58 +CONTENT_SCHEMA_CURRENT_VERSION = 59 CONTENT_SCHEMA_NAME = "content" _SCHEMA_CHECK_BATCH_SIZE = 128 _CONTENT_MEMORY_SCOPE_VALUES = tuple(scope.value for scope in MemoryScope) @@ -641,6 +641,22 @@ def _load_schema_file(filename: str) -> str: DEFINE FIELD OVERWRITE errors.* ON source_imports TYPE object FLEXIBLE; """ +# A runtime rollup stores metric, event and trend rows whose labels vary by +# metric, inside arrays of objects. SurrealDB 3.x stored undeclared keys of +# such an object; 4.0 refuses the write ("Found field 'metrics[58].avg', but +# no such field exists"), so every rollup failed. Each element is FLEXIBLE, +# as the source_imports receipt arrays already were. OVERWRITE reaches tables +# whose element definitions already exist, which 4.0 reports for every array +# of objects. +CONTENT_TELEMETRY_ROLLUP_ENTRY_MIGRATION_DEFINITIONS = """ +DEFINE FIELD IF NOT EXISTS trends.* ON telemetry_rollups TYPE object FLEXIBLE; +DEFINE FIELD IF NOT EXISTS metrics.* ON telemetry_rollups TYPE object FLEXIBLE; +DEFINE FIELD IF NOT EXISTS recent_events.* ON telemetry_rollups TYPE object FLEXIBLE; +DEFINE FIELD OVERWRITE trends.* ON telemetry_rollups TYPE object FLEXIBLE; +DEFINE FIELD OVERWRITE metrics.* ON telemetry_rollups TYPE object FLEXIBLE; +DEFINE FIELD OVERWRITE recent_events.* ON telemetry_rollups TYPE object FLEXIBLE; +""" + CONTENT_SOURCE_IMPORT_REVISION_MIGRATION_DEFINITIONS = """ DEFINE FIELD IF NOT EXISTS revision ON source_imports TYPE option; UPDATE source_imports SET revision = 0 WHERE revision = NONE; @@ -1311,6 +1327,13 @@ def _content_schema_migrations(*, url: str) -> tuple[SchemaMigration, ...]: name="content_capture_sidecar_project", action=file_capture_sidecars_under_project, ), + SchemaMigration( + version=59, + name="content_telemetry_rollup_flexible_entries", + statements=tuple( + split_statements(CONTENT_TELEMETRY_ROLLUP_ENTRY_MIGRATION_DEFINITIONS) + ), + ), ) @@ -1729,6 +1752,7 @@ def _coerce_int(value: object) -> int: "CONTENT_SOURCE_IMPORT_REVISION_MIGRATION_DEFINITIONS", "CONTENT_SOURCE_URL_SCOPE_MIGRATION_DEFINITIONS", "CONTENT_TABLES", + "CONTENT_TELEMETRY_ROLLUP_ENTRY_MIGRATION_DEFINITIONS", "CONTENT_USAGE_SIGNAL_MIGRATION_DEFINITIONS", "bootstrap_content_schema", "content_schema_invariant_plan", diff --git a/packages/python/sibyl-core/src/sibyl_core/backends/surreal/schemas/content/10_tables.surql b/packages/python/sibyl-core/src/sibyl_core/backends/surreal/schemas/content/10_tables.surql index d2046d3c3..a76c6ad13 100644 --- a/packages/python/sibyl-core/src/sibyl_core/backends/surreal/schemas/content/10_tables.surql +++ b/packages/python/sibyl-core/src/sibyl_core/backends/surreal/schemas/content/10_tables.surql @@ -351,8 +351,11 @@ DEFINE FIELD IF NOT EXISTS window_seconds ON telemetry_rollups TYPE int DEFAULT DEFINE FIELD IF NOT EXISTS uptime_seconds ON telemetry_rollups TYPE number DEFAULT 0; DEFINE FIELD IF NOT EXISTS summaries ON telemetry_rollups TYPE object FLEXIBLE DEFAULT {{}}; DEFINE FIELD IF NOT EXISTS trends ON telemetry_rollups TYPE array DEFAULT []; +DEFINE FIELD IF NOT EXISTS trends.* ON telemetry_rollups TYPE object FLEXIBLE; DEFINE FIELD IF NOT EXISTS metrics ON telemetry_rollups TYPE array DEFAULT []; +DEFINE FIELD IF NOT EXISTS metrics.* ON telemetry_rollups TYPE object FLEXIBLE; DEFINE FIELD IF NOT EXISTS recent_events ON telemetry_rollups TYPE array DEFAULT []; +DEFINE FIELD IF NOT EXISTS recent_events.* ON telemetry_rollups TYPE object FLEXIBLE; DEFINE FIELD IF NOT EXISTS created_at ON telemetry_rollups TYPE datetime DEFAULT time::now(); DEFINE FIELD IF NOT EXISTS updated_at ON telemetry_rollups TYPE datetime DEFAULT time::now(); diff --git a/packages/python/sibyl-core/tests/test_surreal_nested_object_fields.py b/packages/python/sibyl-core/tests/test_surreal_nested_object_fields.py new file mode 100644 index 000000000..da08f6a50 --- /dev/null +++ b/packages/python/sibyl-core/tests/test_surreal_nested_object_fields.py @@ -0,0 +1,62 @@ +"""Every object-bearing field names what may live inside it. + +SurrealDB 3.x stored undeclared keys of an object nested in a SCHEMAFULL +table; 4.0 refuses the write ("Found field 'metrics[58].avg', but no such +field exists"). The embedded engine the unit tests run on is lenient like +3.x, so this reads the schema sources instead: a field whose type holds an +object either is FLEXIBLE, or has a FLEXIBLE element definition, or declares +the keys beneath it. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +SCHEMA_ROOT = Path(__file__).resolve().parents[1] / "src" / "sibyl_core" / "backends" / "surreal" + +_DEFINE_FIELD = re.compile( + r"DEFINE FIELD (?:IF NOT EXISTS |OVERWRITE )?(?P[\w.*\[\]]+) ON (?:TABLE )?(?P\w+)" + r"(?P[^;\"]*)", +) + + +def _definitions() -> list[tuple[str, str, str, str]]: + found = [] + for path in sorted([*SCHEMA_ROOT.rglob("*.py"), *SCHEMA_ROOT.rglob("*.surql")]): + text = path.read_text(encoding="utf-8") + for match in _DEFINE_FIELD.finditer(text): + found.append((path.name, match["table"], match["name"], match["rest"])) + return found + + +def test_the_scan_sees_the_schema() -> None: + tables = {table for _, table, _, _ in _definitions()} + assert {"entity", "users", "raw_captures", "telemetry_rollups", "schema_version"} <= tables + + +def test_every_object_field_declares_its_contents() -> None: + definitions = _definitions() + by_table: dict[str, list[tuple[str, str]]] = {} + for _, table, name, rest in definitions: + by_table.setdefault(table, []).append((name, rest)) + + undeclared = [] + for source, table, name, rest in definitions: + kind = re.search(r"\bTYPE\s+(\S+)", rest) + if kind is None or "object" not in kind[1] or "FLEXIBLE" in rest: + continue + children = [ + (child, child_rest) + for child, child_rest in by_table[table] + if child.startswith((f"{name}.", f"{name}[*]")) + ] + flexible_element = any( + child in (f"{name}.*", f"{name}[*]") and "FLEXIBLE" in child_rest + for child, child_rest in children + ) + declared_keys = any(child.count(".") > name.count(".") + 1 for child, _ in children) + if not (flexible_element or declared_keys): + undeclared.append(f"{source}: {table}.{name} {kind[1]}") + + assert undeclared == []