diff --git a/.changes/development-reset-secret-guard.fixed.md b/.changes/development-reset-secret-guard.fixed.md new file mode 100644 index 00000000..3e2f5347 --- /dev/null +++ b/.changes/development-reset-secret-guard.fixed.md @@ -0,0 +1 @@ +开发库重置会在清空数据前检查用于重新配置数据库角色的密码。缺少密码时保留原有数据。 diff --git a/.changes/extension-state-guard.fixed.md b/.changes/extension-state-guard.fixed.md new file mode 100644 index 00000000..5b669111 --- /dev/null +++ b/.changes/extension-state-guard.fixed.md @@ -0,0 +1 @@ +恢复 Extension 共享状态的数据库写入保护:禁止插入非空状态或删除仍持有状态的 Extension,避免原生数据库调用绕过状态生命周期。已部署数据库通过新增迁移修复,既有数据不被改写。 diff --git a/.changes/graph-path-pagination.fixed.md b/.changes/graph-path-pagination.fixed.md new file mode 100644 index 00000000..3a7f083f --- /dev/null +++ b/.changes/graph-path-pagination.fixed.md @@ -0,0 +1 @@ +修复图导航最短路径在大量平行关系遮住较早关系时误报不存在的问题:遍历完整的 endpoint 分页,继续遵守调用方的跳数与 Block 探索预算。 diff --git a/.changes/lexical-unicode-excerpt.fixed.md b/.changes/lexical-unicode-excerpt.fixed.md new file mode 100644 index 00000000..01ca2958 --- /dev/null +++ b/.changes/lexical-unicode-excerpt.fixed.md @@ -0,0 +1 @@ +修复词法检索在多语种正文中返回错误摘录的问题。命中词之前出现 ß 等大小写折叠后长度变化的字符时,摘录仍按原文位置展示命中内容。 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c2c3d022..734b3d3f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,8 +47,6 @@ jobs: --health-interval 5s --health-timeout 5s --health-retries 12 - env: - PRODUCTION_PREFLIGHT_TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/inkcre steps: - name: Checkout uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 @@ -72,11 +70,8 @@ jobs: RELEASE_PR: ${{ github.event.pull_request.head.ref == 'release/next' }} run: bash scripts/automation/repository_check.sh release-intent - - name: Run repository contract - run: pdm run check - - - name: Verify ChatGPT deployment lifecycle - run: pdm run python -m pytest -q deploy/integrations/chatgpt/tests + - name: Run repository static and package checks + run: pdm run check:code - name: Initialize disposable business-test database env: @@ -86,15 +81,15 @@ jobs: POSTGREST_DATABASE_PASSWORD: ci-postgrest-test-password-at-least-32-bytes run: pdm run db:init --profile development - - name: Run required PostgreSQL business scenarios + - name: Run the repository suite with disposable PostgreSQL env: + CORE_DATABASE_PASSWORD: ci-core-test-password-at-least-32-bytes + POSTGREST_DATABASE_PASSWORD: ci-postgrest-test-password-at-least-32-bytes INKCRE_TEST_DATABASE_URL: postgresql+psycopg://inkcre_core:ci-core-test-password-at-least-32-bytes@127.0.0.1:5432/inkcre MIGRATION_DATABASE_URL: postgresql+psycopg://postgres:postgres@127.0.0.1:5432/inkcre + INKCRE_TEST_POSTGRES_ADMIN_URL: postgresql://postgres:postgres@127.0.0.1:5432/inkcre run: pdm run test:database - - name: Verify documentation publication and partial Preview reporting - run: pdm run python -m pytest -q scripts/tests/test_extension_documentation.py scripts/tests/test_preview_delivery.py - - name: Build and verify all first-party wheels env: SOURCE_DATE_EPOCH: "315532800" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index edd2e096..0563126c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,10 +25,9 @@ pdm run check `doctor` reports a mismatch when the local toolchain does not match that contract. Git hook 需要在每个本地 checkout 安装;提交前会执行与 CI 相同的格式和 lint 入口。 -移动仓库目录后,需要重建含旧绝对路径的虚拟环境入口并重新安装 hook;CI 的完整 -`check` 仍是交付检查依据。 +移动仓库目录后,需要重建含旧绝对路径的虚拟环境入口并重新安装 hook;CI 使用同一份检查配置。 -`check` is the same hermetic repository gate used by CI. It verifies the lock and +`check` runs the local repository gate. CI runs its static and package checks before executing the same test collection with disposable PostgreSQL. It verifies the lock and requirements export, migration configuration and append-only baseline, Ruff formatting, repository lint, static types, and the repository test suite. Use narrower commands while iterating: @@ -38,6 +37,11 @@ pdm run lint pdm run check:foundation ``` +默认测试覆盖 `tests/`、`scripts/tests/` 和 ChatGPT 伴随进程生命周期,排除显式 `acceptance`。 +数据库回归由 `pdm run test:database` 在一次性 PostgreSQL 集群执行;环境输入、各验证层的含义及 +真实供应商验收边界见[开发环境](docs/40-deployment/development-environment.md#required-environment-variables)。 +本机重型构建(包括检查中的 wheel 构建)使用 `agent-build` 启动,例如 `agent-build pdm run check`。 + Verification follows the organization-wide [Verification and Test Policy](https://github.com/InKCre/.github/blob/main/TESTING.md). The remaining migration, integration, and acceptance suites are repository-local admitted exceptions; they do not diff --git a/app/business/extension/distribution.py b/app/business/extension/distribution.py index 99ac8e5a..f514920a 100644 --- a/app/business/extension/distribution.py +++ b/app/business/extension/distribution.py @@ -1,61 +1,10 @@ -"""Core facade for Distribution acquisition owned by the Extension Runtime.""" - -import typing -from pathlib import Path +"""Core imports for the Extension Runtime's package acquisition API.""" from inkcre_extension_runtime_core_py.distribution import ( AcquiredDistribution, - PipDistributionConsumer as RuntimePipDistributionConsumer, + PipDistributionConsumer, ) from inkcre_extension_runtime_core_py.modules import DistributionModules -from .release import ExtensionReleaseDescriptor, PythonReleaseDescriptor - - -class DistributionConsumer(typing.Protocol): - def download( - self, - release: ExtensionReleaseDescriptor, - association: PythonReleaseDescriptor, - host_version: str, - wheel_dir: Path, - ) -> Path: ... - - def apply( - self, - extension_wheel: Path, - release: ExtensionReleaseDescriptor, - association: PythonReleaseDescriptor, - host_version: str, - ) -> AcquiredDistribution: ... - - -class PipDistributionConsumer: - def __init__(self, origin: str) -> None: - self._runtime = RuntimePipDistributionConsumer(origin) - - def download( - self, - release: ExtensionReleaseDescriptor, - association: PythonReleaseDescriptor, - host_version: str, - wheel_dir: Path, - ) -> Path: - return self._runtime.download(release, association, host_version, wheel_dir) - - def apply( - self, - extension_wheel: Path, - release: ExtensionReleaseDescriptor, - association: PythonReleaseDescriptor, - host_version: str, - ) -> AcquiredDistribution: - return self._runtime.apply(extension_wheel, release, association, host_version) - -__all__ = [ - "AcquiredDistribution", - "DistributionConsumer", - "DistributionModules", - "PipDistributionConsumer", -] +__all__ = ["AcquiredDistribution", "DistributionModules", "PipDistributionConsumer"] diff --git a/app/business/extension/main.py b/app/business/extension/main.py index 631c1c09..b607f36c 100644 --- a/app/business/extension/main.py +++ b/app/business/extension/main.py @@ -38,7 +38,6 @@ from .distribution import ( AcquiredDistribution, - DistributionConsumer, DistributionModules, PipDistributionConsumer, ) @@ -57,7 +56,6 @@ PythonReleaseDescriptor, RegistryReleaseClient, ReleaseState, - ReleaseResolver, require_python_association, validate_coordinate, ) @@ -68,7 +66,6 @@ ) from .state import ( ExtensionParticipation, - ExtensionStore, InstalledExtension, ExtensionStateService, ) @@ -121,7 +118,7 @@ class _ActiveExtensionModel: name: str config: dict[str, typing.Any] - store: ExtensionStore + store: ExtensionStateService peer_id: typing.Any distribution: str version: str @@ -179,20 +176,8 @@ class RunningExtension: class ExtensionHost: """Core’s Python-only runtime over shared identities and Peer selections.""" - def __init__( - self, - *, - store: ExtensionStore | None = None, - release_client: ReleaseResolver | None = None, - distribution_consumer: DistributionConsumer | None = None, - registry_origin_resolver: typing.Callable[[], typing.Awaitable[str]] | None = None, - ) -> None: - self.store = store or ExtensionStateService() - self.release_client = release_client - self.distribution_consumer = distribution_consumer - self.registry_origin_resolver = ( - registry_origin_resolver or resolve_extension_registry_origin - ) + def __init__(self) -> None: + self.store = ExtensionStateService() self.running: dict[str, RunningExtension] = {} self.fastapi_app: fastapi.FastAPI | None = None self._loaded_versions: dict[str, str] = {} @@ -325,7 +310,7 @@ def _resolve( version: str, *, allow_yanked: bool, - release_client: ReleaseResolver, + release_client: RegistryReleaseClient, ): release = release_client.get(name, version) if release.state is ReleaseState.yanked and allow_yanked: @@ -564,17 +549,13 @@ async def patch_config( name, {**current.config, **patch}, peer_id=peer_id ) - async def _operation_consumers( - self, - ) -> tuple[ReleaseResolver, DistributionConsumer]: - if self.release_client is not None and self.distribution_consumer is not None: - return self.release_client, self.distribution_consumer - origin = await self.registry_origin_resolver() - release_client = self.release_client or RegistryReleaseClient( - origin, settings.extension_registry_timeout_seconds + @staticmethod + async def _operation_consumers() -> tuple[RegistryReleaseClient, PipDistributionConsumer]: + origin = await resolve_extension_registry_origin() + return ( + RegistryReleaseClient(origin, settings.extension_registry_timeout_seconds), + PipDistributionConsumer(origin), ) - consumer = self.distribution_consumer or PipDistributionConsumer(origin) - return release_client, consumer async def provision_enabled_distributions(self) -> None: """Apply missing exact enabled Python pins before this process starts serving.""" diff --git a/app/business/extension/release.py b/app/business/extension/release.py index 584d8646..fbcdcc20 100644 --- a/app/business/extension/release.py +++ b/app/business/extension/release.py @@ -1,7 +1,5 @@ """Core facade for exact Release resolution owned by the Extension Runtime.""" -import typing - from inkcre_extension_runtime_core_py.contracts import ( ExtensionReleaseDescriptor, PythonReleaseDescriptor, @@ -17,10 +15,6 @@ from app.version import CORE_VERSION -class ReleaseResolver(typing.Protocol): - def get(self, name: str, version: str) -> ExtensionReleaseDescriptor: ... - - def require_python_association( release: ExtensionReleaseDescriptor, ) -> PythonReleaseDescriptor: @@ -31,7 +25,6 @@ def require_python_association( "ExtensionReleaseDescriptor", "PythonReleaseDescriptor", "RegistryReleaseClient", - "ReleaseResolver", "ReleaseState", "require_python_association", "simple_project_and_index_urls", diff --git a/app/business/extension/state.py b/app/business/extension/state.py index 187034ce..9f79ecb7 100644 --- a/app/business/extension/state.py +++ b/app/business/extension/state.py @@ -46,69 +46,6 @@ class ExtensionParticipation(pydantic.BaseModel): ] -class ExtensionStore(typing.Protocol): - async def list(self) -> tuple[InstalledExtension, ...]: ... - - async def get(self, name: str) -> InstalledExtension | None: ... - - async def ensure(self, name: str, nickname: str) -> InstalledExtension: ... - - async def uninstall(self, name: str) -> None: ... - - async def read_config(self, name: str) -> dict[str, typing.Any]: ... - - async def update_config( - self, name: str, config: dict[str, typing.Any] - ) -> InstalledExtension: ... - - async def read_state(self, name: str) -> dict[str, typing.Any]: ... - - async def mutate_state( - self, name: str, transform: StateMutation - ) -> dict[str, typing.Any]: ... - - async def mutate_config_and_state( - self, - name: str, - transform: ConfigStateMutation, - ) -> tuple[dict[str, typing.Any], dict[str, typing.Any]]: ... - - async def list_participations( - self, peer_id: uuid.UUID - ) -> tuple[ExtensionParticipation, ...]: ... - - async def get_participation( - self, peer_id: uuid.UUID, name: str - ) -> ExtensionParticipation | None: ... - - async def select_participation( - self, - peer_id: uuid.UUID, - name: str, - distribution: str, - version: str, - ) -> ExtensionParticipation: ... - - async def resolve_legacy_python_participation( - self, peer_id: uuid.UUID, name: str, version: str - ) -> ExtensionParticipation: ... - - async def set_participation_enabled( - self, peer_id: uuid.UUID, name: str, enabled: bool - ) -> ExtensionParticipation: ... - - async def remove_participation(self, peer_id: uuid.UUID, name: str) -> None: ... - - async def update_participation_config_schema( - self, - peer_id: uuid.UUID, - name: str, - distribution: str, - version: str, - schema: dict[str, typing.Any], - ) -> ExtensionParticipation: ... - - class ExtensionStateService: """Transactional adapter over shared identity and Peer-scoped state.""" diff --git a/app/database_contract/catalog.py b/app/database_contract/catalog.py index fa983733..7d2660c8 100644 --- a/app/database_contract/catalog.py +++ b/app/database_contract/catalog.py @@ -1,8 +1,5 @@ """Deterministic catalog, seed, and development reset operations.""" -from hashlib import sha256 -import json - from psycopg import sql from psycopg.types.json import Jsonb @@ -202,77 +199,3 @@ def truncate_development(database_url: str | None = None) -> None: cursor.execute( sql.SQL("TRUNCATE TABLE {} RESTART IDENTITY CASCADE").format(relations) ) - - -def development_baseline_fingerprint( - database_url: str | None = None, -) -> str: - """Return a value-safe fingerprint of deterministic baseline records.""" - with database_connection(database_url) as connection: - with connection.cursor() as cursor: - _require_development(cursor) - document: dict[str, object] = {} - for key, query in ( - ( - "ai_dialects", - sql.SQL( - "SELECT id, description, config_schema FROM {}.ai_dialects ORDER BY id" - ).format(sql.Identifier(PROTOCOL_SCHEMA)), - ), - ( - "extensions", - sql.SQL("SELECT name, nickname FROM {}.extensions ORDER BY name").format( - sql.Identifier(PROTOCOL_SCHEMA) - ), - ), - ( - "job_types", - sql.SQL( - "SELECT id, description, parameters_schema, default_timeout_seconds " - "FROM {}.job_types ORDER BY id" - ).format(sql.Identifier(PROTOCOL_SCHEMA)), - ), - ( - "storage_types", - sql.SQL( - "SELECT id, description, config_schema, writable " - "FROM {}.storage_types ORDER BY id" - ).format(sql.Identifier(PROTOCOL_SCHEMA)), - ), - ( - "source_types", - sql.SQL( - "SELECT id, description, config_schema, collect_config_schema, " - "backfill_config_schema FROM {}.sources_types ORDER BY id" - ).format(sql.Identifier(PROTOCOL_SCHEMA)), - ), - ( - "storages", - sql.SQL("SELECT id, type, nickname, config FROM {}.storages ORDER BY id").format( - sql.Identifier(PROTOCOL_SCHEMA) - ), - ), - ( - "development_peer", - sql.SQL( - "SELECT id::text, name, application_version, labels, config, config_schema, " - "capabilities, " - "EXTRACT(EPOCH FROM lease_expires_at)::bigint, " - "EXTRACT(EPOCH FROM created_at)::bigint " - "FROM {}.peers WHERE id = %s" - ).format(sql.Identifier(PROTOCOL_SCHEMA)), - ), - ): - if key == "development_peer": - cursor.execute(query, (DEVELOPMENT_PEER_ID,)) - else: - cursor.execute(query) - document[key] = cursor.fetchall() - - encoded = json.dumps( - document, - default=str, - separators=(",", ":"), - sort_keys=True, - ).encode() - return sha256(encoded).hexdigest() diff --git a/app/database_contract/lifecycle.py b/app/database_contract/lifecycle.py index d0fc976f..3789c022 100644 --- a/app/database_contract/lifecycle.py +++ b/app/database_contract/lifecycle.py @@ -45,18 +45,15 @@ def initialize( seed_development() -def reset_development( - confirmation: str, - *, - secrets: RoleSecrets | None = None, -) -> None: +def reset_development(confirmation: str) -> None: """Restore the deterministic development baseline after a double guard.""" if confirmation != RESET_CONFIRMATION: raise ValueError(f"confirmation must be exactly {RESET_CONFIRMATION}") + role_secrets = RoleSecrets.from_environment() truncate_development() migrate() - provision_roles(secrets or RoleSecrets.from_environment()) + provision_roles(role_secrets) reconcile_builtins() seed_development() diff --git a/cli/pyproject.toml b/cli/pyproject.toml index 25ee9765..f42945e0 100644 --- a/cli/pyproject.toml +++ b/cli/pyproject.toml @@ -45,3 +45,7 @@ select = ["E", "F", "I", "UP", "B"] [tool.pyrefly] project-includes = ["src"] +# The checkout may live below a hidden worktree directory. Only exclude local +# generated files; Pyrefly 0.56's absolute hidden-path heuristic hides src too. +disable-project-excludes-heuristics = true +project-excludes = ["**/__pycache__/**", ".venv/**"] diff --git a/cli/tests/test_cli.py b/cli/tests/test_cli.py new file mode 100644 index 00000000..c2d50596 --- /dev/null +++ b/cli/tests/test_cli.py @@ -0,0 +1,453 @@ +"""Executable CLI contracts against isolated files and an independent HTTP fixture.""" + +import json +import os +import shutil +import subprocess +import sysconfig +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +import jwt + +CORE_PEER = "00000000-0000-4000-8000-000000000011" +WEB_PEER = "00000000-0000-4000-8000-000000000012" + + +def extension_status(peer, supported, selected=None, schema=None): + return { + "peer_id": peer, + "supported_distributions": [supported], + "extensions": [ + { + "name": "inkcre/rss", + "peer_id": peer, + "supported_distributions": [supported], + "distribution": selected, + "version": "1.2.3" if selected else None, + "enabled": schema is not None, + "config_schema": schema, + "loaded_version": "1.2.3" if schema else None, + "running": schema is not None, + "restart_required": False, + "operation": None, + "error": None, + } + ], + } + + +class CLIContracts(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.command = shutil.which("inkcre-cli", path=sysconfig.get_path("scripts")) + if cls.command is None: + raise FileNotFoundError("Install the CLI project with pdm install -p cli") + + class Handler(BaseHTTPRequestHandler): + def respond(self): + cls.requests.append( + { + "method": self.command, + "path": self.path, + "authorization": self.headers.get("Authorization"), + "body": self.rfile.read(int(self.headers.get("Content-Length", "0"))), + } + ) + status, content, media_type = cls.responses.get( + (self.command, self.path), + (500, b'{"detail":"unexpected request"}', "application/json"), + ) + cls.release_response.wait() + try: + self.send_response(status) + self.send_header("Content-Type", media_type) + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + except (BrokenPipeError, ConnectionResetError): + pass # A cancelled Job observation deliberately closes the response socket. + + do_GET = do_POST = do_DELETE = respond + + def log_message(self, *args): + pass + + cls.server = HTTPServer(("127.0.0.1", 0), Handler) + cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) + cls.thread.start() + cls.url = f"http://127.0.0.1:{cls.server.server_port}" + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + cls.thread.join() + + def setUp(self): + type(self).requests = [] + type(self).responses = {} + type(self).release_response = threading.Event() + self.release_response.set() + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.connections_file = self.root / "connections.json" + self.personal = { + "base_url": self.url + "/personal", + "jwt_secret": "personal-synthetic-secret-at-least-32-bytes", + } + self.work = { + "base_url": self.url + "/work", + "jwt_secret": "work-synthetic-secret-at-least-32-bytes", + } + self.connections_file.write_text( + json.dumps({"default": "personal", "connections": {"personal": self.personal}}), + encoding="utf-8", + ) + + def invoke(self, *arguments, input=None): + env = {key: value for key, value in os.environ.items() if not key.startswith("INKCRE_CLI_")} + env["NO_PROXY"] = "127.0.0.1,localhost" + return subprocess.run( + [ + self.command, + "--connections-file", + str(self.connections_file), + "--json", + *arguments, + ], + input=input, + capture_output=True, + text=True, + env=env, + timeout=10, + check=False, + ) + + def json_response(self, method, path, value, status=200): + self.responses[method, path] = (status, json.dumps(value).encode(), "application/json") + + def success(self, result): + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stderr, "") + return json.loads(result.stdout) + + def test_connections_survive_new_processes_and_temporary_selection(self): + self.connections_file.unlink() + for name, connection in (("personal", self.personal), ("work", self.work)): + self.success( + self.invoke("connection", "set", name, "--input", "-", input=json.dumps(connection)) + ) + listed = self.success(self.invoke("connection", "list")) + self.assertEqual( + listed, + { + "default": "personal", + "connections": { + "personal": {"base_url": self.url + "/personal"}, + "work": {"base_url": self.url + "/work"}, + }, + }, + ) + self.success(self.invoke("connection", "use", "work")) + for options, prefix, secret in ( + (("--connection", "personal"), "personal", self.personal["jwt_secret"]), + ((), "work", self.work["jwt_secret"]), + ): + self.json_response("GET", f"/{prefix}/peers/self", {"id": prefix}) + self.assertEqual(self.success(self.invoke(*options, "peer", "get")), {"id": prefix}) + request = self.requests[-1] + claims = jwt.decode( + request["authorization"].removeprefix("Bearer "), + secret, + algorithms=["HS256"], + audience="inkcre-api", + issuer="inkcre-peer", + ) + self.assertEqual(claims["role"], "authenticated") + self.success(self.invoke("connection", "delete", "work")) + self.assertEqual( + self.success(self.invoke("connection", "list")), + {"default": None, "connections": {"personal": {"base_url": self.url + "/personal"}}}, + ) + + def test_invalid_connection_reports_local_field_error_without_overwriting_saved_value(self): + result = self.invoke( + "connection", + "set", + "personal", + "--input-json", + '{"base_url":"not-a-url","jwt_secret":"x"}', + ) + self.assertEqual(result.returncode, 2) + self.assertEqual(result.stdout, "") + errors = json.loads(result.stderr)["detail"] + self.assertEqual( + [(item["loc"], item["type"]) for item in errors], [(["base_url"], "url_parsing")] + ) + self.assertEqual(self.success(self.invoke("connection", "get", "personal")), self.personal) + self.assertEqual(self.requests, []) + + def test_http_failure_and_failed_job_have_distinct_exit_contracts(self): + self.json_response( + "GET", "/personal/jobs/17", {"detail": "invalid credentials"}, status=401 + ) + rejected = self.invoke("job", "get", "17") + self.assertEqual(rejected.returncode, 1) + self.assertEqual(rejected.stdout, "") + self.assertEqual( + json.loads(rejected.stderr), {"detail": "invalid credentials", "http_status": 401} + ) + record = {"id": 17, "status": "failed", "state": {"error": "source unavailable"}} + self.json_response("GET", "/personal/jobs/17", record) + self.assertEqual(self.success(self.invoke("job", "get", "17")), record) + + def test_partial_batch_keeps_full_success_and_errors_on_separate_stream(self): + records = [ + {"type": "block", "id": 42, "content": "正文" * 5000}, + { + "type": "relation", + "id": 8, + "error": {"code": "not_found", "message": "relation 8 not found"}, + }, + ] + self.json_response("POST", "/personal/entities/get", records) + result = self.invoke("get", "block:42", "relation:8") + self.assertEqual(result.returncode, 1) + self.assertEqual(json.loads(result.stdout), records) + self.assertEqual(len(result.stdout.splitlines()), 1) + self.assertIn("逐项错误", json.loads(result.stderr)["detail"]) + self.assertEqual( + json.loads(self.requests[0]["body"]), + { + "entities": [{"type": "block", "id": 42}, {"type": "relation", "id": 8}], + "content": "raw", + }, + ) + + def test_job_wait_budget_cancels_inflight_read_without_aborting_job(self): + self.json_response("GET", "/personal/jobs/17", {"id": 17, "status": "running"}) + # Hold the HTTP response until the CLI exits, so only its total observation + # budget can finish the command. The fixture uses no sleeps or timeout response. + self.release_response.clear() + try: + result = self.invoke("job", "wait", "17", "--for", "0.5s") + finally: + self.release_response.set() + self.assertEqual(result.returncode, 1) + self.assertEqual(result.stdout, "") + self.assertIn("尚未取得 Job 记录", json.loads(result.stderr)["detail"]) + self.assertEqual( + [(request["method"], request["path"]) for request in self.requests], + [("GET", "/personal/jobs/17")], + ) + + def test_extension_selections_target_the_requested_peer_and_return_its_receipt(self): + path = "/personal/extensions/inkcre/rss/selection" + receipt = extension_status(WEB_PEER, "module_federation") + for distribution, suffix, options in ( + ("python", "", []), + ("module_federation", f"?route_to_peer={WEB_PEER}", ["--peer", WEB_PEER]), + ): + with self.subTest(distribution=distribution): + selected = extension_status( + WEB_PEER if options else CORE_PEER, distribution, distribution + ) + self.json_response("POST", path + suffix, selected) + self.assertEqual( + self.success( + self.invoke( + "extension", + "select", + "inkcre/rss", + "--distribution", + distribution, + "--version", + "1.2.3", + *options, + ) + ), + selected, + ) + self.assertEqual( + json.loads(self.requests[-1]["body"]), + {"distribution": distribution, "version": "1.2.3"}, + ) + self.json_response("DELETE", path + f"?route_to_peer={WEB_PEER}", receipt) + self.assertEqual( + self.success(self.invoke("extension", "unselect", "inkcre/rss", "--peer", WEB_PEER)), + receipt, + ) + self.assertEqual( + [(r["method"], r["path"]) for r in self.requests], + [ + ("POST", path), + ("POST", path + f"?route_to_peer={WEB_PEER}"), + ("DELETE", path + f"?route_to_peer={WEB_PEER}"), + ], + ) + + def test_extension_schema_and_status_read_the_current_peer(self): + schema = {"type": "object", "properties": {"token": {"type": "string"}}} + status = extension_status(CORE_PEER, "python", "python", schema) + self.json_response("POST", "/personal/extension-management/v2", status) + for command, expected in ( + (["config", "replace", "inkcre/rss", "--schema"], schema), + (["status", "inkcre/rss"], status), + ): + with self.subTest(command=command): + self.assertEqual(self.success(self.invoke("extension", *command)), expected) + self.assertEqual( + json.loads(self.requests[-1]["body"]), + {"action": "status", "extension": "inkcre/rss"}, + ) + + def test_source_schema_embeds_usable_local_refs_and_omits_the_type_selector(self): + endpoint_schema = { + "properties": {"type": {"type": "string"}, "config": {}}, + "required": ["type", "config"], + } + owner_schema = { + "$defs": {"Mailbox": {"enum": ["inbox", "archive"]}}, + "properties": {"folder": {"$ref": "#/$defs/Mailbox"}}, + } + self.json_response( + "GET", + "/personal/openapi.json", + { + "paths": { + "/sources": { + "post": { + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/NewSource"} + } + } + } + } + } + }, + "components": {"schemas": {"NewSource": endpoint_schema}}, + }, + ) + self.json_response( + "GET", "/personal/source-types/example.mail", {"config_schema": owner_schema} + ) + form = self.success(self.invoke("source", "create", "--type", "example.mail", "--schema")) + self.assertEqual(set(form["properties"]), {"config"}) + self.assertEqual(form["required"], ["config"]) + pointer = form["properties"]["config"]["properties"]["folder"]["$ref"] + self.assertTrue(pointer.startswith("#/")) + resolved = form + for key in pointer[2:].split("/"): + resolved = resolved[key] + self.assertEqual(resolved, {"enum": ["inbox", "archive"]}) + + def test_mixed_recall_keeps_second_mode_results_when_first_request_fails(self): + suffix = f"?route_to_peer={CORE_PEER}" + self.json_response( + "POST", "/personal/retrieval/lexical" + suffix, {"detail": "unavailable"}, 503 + ) + ranked = [ + { + "type": "block", + "entity": { + "id": id_, + "resolver": "core.text.v1", + "content": content, + "storage": None, + "created_at": "2026-01-01T00:00:00Z", + "updated_at": "2026-01-01T00:00:00Z", + }, + "score": score, + } + for id_, content, score in ((8, "archive", 0.95), (5, "prior notes", 0.8)) + ] + semantic = {"profile": 7, "metric": "cosine", "matches": ranked} + self.json_response("POST", "/personal/retrieval/semantic" + suffix, semantic) + result = self.invoke( + "recall", + "archive", + "--mode", + "lexical", + "--mode", + "semantic", + "--limit", + "2", + "--profile", + "7", + "--peer", + CORE_PEER, + ) + self.assertEqual(result.returncode, 1) + self.assertIn("逐项错误", json.loads(result.stderr)["detail"]) + self.assertEqual( + json.loads(result.stdout), + [ + {"mode": "lexical", "error": {"detail": "unavailable", "http_status": 503}}, + {"mode": "semantic", **semantic}, + ], + ) + self.assertCountEqual( + [(r["path"], json.loads(r["body"])) for r in self.requests], + [ + ("/personal/retrieval/lexical" + suffix, {"query": "archive", "limit": 2}), + ( + "/personal/retrieval/semantic" + suffix, + {"query": "archive", "profile": 7, "options": {"limit": 2}}, + ), + ], + ) + + def test_binary_export_remains_readable_after_directory_move_without_refetch(self): + # Handwritten protocol fixture, independent of Core's MIME producer and CLI decoder. + mime = ( + b"--fixture\r\nContent-Type: application/json\r\n\r\n" + b'{"value":{"a/b~c":[null],"ordinary":null,"text":"cid:blob"},' + b'"parts":{"/a~1b~0c/0":"blob"}}\r\n' + b"--fixture\r\nContent-Type: application/octet-stream\r\nContent-ID: \r\n\r\n" + b"\x00\xffhello\r\n--fixture--\r\n" + ) + for content, media_type, nested in ( + (mime, 'multipart/related; boundary="fixture"', True), + (b"\x00\xffwhole", "application/octet-stream", False), + ): + with self.subTest(media_type=media_type): + self.responses[ + "POST", "/personal/blocks/42/resolver/methods/get_solved_content" + ] = ( + 200, + content, + media_type, + ) + result = self.invoke( + "resolver", + "invoke", + "block:42", + "--method", + "get_solved_content", + "--output-dir", + str(self.root / "exports"), + ) + entry = Path(self.success(result)["file"]) + moved = self.root / ("nested" if nested else "raw") + entry.parent.rename(moved) + entry = moved / entry.name + if nested: + saved = json.loads(entry.read_text(encoding="utf-8")) + self.assertIsNone(saved["ordinary"]) + self.assertEqual(saved["text"], "cid:blob") + binary = Path(saved["a/b~c"][0]["file"]) + self.assertEqual((entry.parent / binary).read_bytes(), b"\x00\xffhello") + else: + self.assertEqual(entry.read_bytes(), b"\x00\xffwhole") + self.assertEqual([json.loads(r["body"]) for r in self.requests], [{}, {}]) + + +if __name__ == "__main__": + unittest.main() diff --git a/cli/tests/test_extension.py b/cli/tests/test_extension.py deleted file mode 100644 index 04b0cfd3..00000000 --- a/cli/tests/test_extension.py +++ /dev/null @@ -1,99 +0,0 @@ -"""CLI requests and receipts at the Extension management v2 HTTP boundary.""" - -import json -import unittest - -import httpx -from click.testing import CliRunner - -from inkcre_cli.command import Invocation -from inkcre_cli.connection import Connection -from inkcre_cli.http import CoreRESTClient -from inkcre_cli.main import cli - - -class ExtensionSelectionTests(unittest.TestCase): - def invoke(self, arguments, handler): - invocation = Invocation() - client = CoreRESTClient( - Connection(base_url="http://core.test", jwt_secret="test-only-secret-at-least-32-bytes") - ) - client.client.close() - client.client = httpx.Client(transport=httpx.MockTransport(handler)) - invocation._client = client - try: - return CliRunner().invoke(cli, ["--json", "extension", *arguments], obj=invocation) - finally: - invocation.close() - - def test_select_uses_v2_body_and_optional_target_peer(self): - for distribution, peer in (("python", None), ("module_federation", "web-peer")): - with self.subTest(distribution=distribution): - requests = [] - - def handle(request, requests=requests, distribution=distribution): - requests.append(request) - return httpx.Response( - 200, json={"distribution": distribution, "enabled": False} - ) - - arguments = [ - "select", - "inkcre/rss", - "--distribution", - distribution, - "--version", - "1.2.3", - ] - if peer: - arguments += ["--peer", peer] - result = self.invoke(arguments, handle) - self.assertEqual(result.exit_code, 0, result.output) - self.assertEqual(len(requests), 1) - request = requests[0] - self.assertEqual(request.method, "POST") - self.assertEqual(request.url.path, "/extensions/inkcre/rss/selection") - self.assertEqual(dict(request.url.params), {"route_to_peer": peer} if peer else {}) - self.assertEqual( - json.loads(request.content), {"distribution": distribution, "version": "1.2.3"} - ) - self.assertEqual(json.loads(result.output)["enabled"], False) - - def test_unselect_preserves_status_receipt(self): - receipt = {"peer_id": "web-peer", "extensions": [{"distribution": None, "enabled": False}]} - - def handle(request): - self.assertEqual(request.method, "DELETE") - self.assertEqual(request.url.path, "/extensions/inkcre/rss/selection") - self.assertEqual(dict(request.url.params), {"route_to_peer": "web-peer"}) - return httpx.Response(200, json=receipt) - - result = self.invoke(["unselect", "inkcre/rss", "--peer", "web-peer"], handle) - self.assertEqual(result.exit_code, 0, result.output) - self.assertEqual(json.loads(result.output), receipt) - - def test_config_schema_comes_from_current_peer_not_shared_identity(self): - schema = {"type": "object", "properties": {"token": {"type": "string"}}} - status = { - "peer_id": "core-peer", - "extensions": [{"name": "inkcre/rss", "config_schema": schema}], - } - - def handle(request): - self.assertEqual(request.method, "POST") - self.assertEqual(request.url.path, "/extension-management/v2") - self.assertEqual( - json.loads(request.content), {"action": "status", "extension": "inkcre/rss"} - ) - return httpx.Response(200, json=status) - - result = self.invoke(["config", "replace", "inkcre/rss", "--schema"], handle) - self.assertEqual(result.exit_code, 0, result.output) - self.assertEqual(json.loads(result.output), schema) - result = self.invoke(["status", "inkcre/rss"], handle) - self.assertEqual(result.exit_code, 0, result.output) - self.assertEqual(json.loads(result.output), status) - - -if __name__ == "__main__": - unittest.main() diff --git a/deploy/integrations/chatgpt/launcher.py b/deploy/integrations/chatgpt/launcher.py index 42620195..5f30172c 100644 --- a/deploy/integrations/chatgpt/launcher.py +++ b/deploy/integrations/chatgpt/launcher.py @@ -22,14 +22,14 @@ def ready(url): return False -def stop(children, grace=20): +def stop(children): """Signal process groups so a Tunnel transport child is also stopped.""" for child in children: try: os.killpg(child.pid, signal.SIGTERM) except ProcessLookupError: pass - deadline = time.monotonic() + grace + deadline = time.monotonic() + 20 for child in children: try: child.wait(timeout=max(0.01, deadline - time.monotonic())) diff --git a/deploy/integrations/chatgpt/tests/test_lifecycle.py b/deploy/integrations/chatgpt/tests/test_lifecycle.py index be762046..6085211b 100644 --- a/deploy/integrations/chatgpt/tests/test_lifecycle.py +++ b/deploy/integrations/chatgpt/tests/test_lifecycle.py @@ -27,7 +27,14 @@ def stop(signum, frame): (root / 'core-pid').write_text(str(os.getpid())) class Handler(BaseHTTPRequestHandler): def do_GET(self): - self.send_response(200 if (root / 'ready').exists() else 503) + if self.path != '/readyz': + self.send_error(404) + return + ready = (root / 'ready').exists() + if not ready: + with (root / 'not-ready-probes').open('a') as out: + out.write('x') + self.send_response(200 if ready else 503) self.end_headers() def log_message(self, *args): pass HTTPServer(('127.0.0.1', int(port)), Handler).serve_forever() @@ -93,7 +100,10 @@ def begin_tunnel(self): wait_for(lambda: len(self.tunnel_pids()) == 1) def test_waits_for_core_and_sigterm_stops_both(self): - time.sleep(0.15) + rejected = self.root / "not-ready-probes" + wait_for( + lambda: self.tunnel_pids() or (rejected.exists() and rejected.stat().st_size >= 2) + ) self.assertEqual(self.tunnel_pids(), []) self.begin_tunnel() self.process.terminate() @@ -138,6 +148,14 @@ def test_credentials_are_env_references_and_target_is_local(self): self.assertEqual(module.main(), 0) core, command, env, ready_url, health = run.call_args.args self.assertNotIn("fake-secret", " ".join(command)) + self.assertIn("--control-plane.tunnel-id=test-tunnel", command) + self.assertIn("--control-plane.api-key=env:CONTROL_PLANE_API_KEY", command) + self.assertIn( + "--mcp.extra-headers=Authorization: env:INKCRE_MCP_AUTHORIZATION", command + ) + self.assertIn( + "--mcp.discovery-extra-headers=Authorization: env:INKCRE_MCP_AUTHORIZATION", command + ) self.assertIn("--mcp.server-url=http://127.0.0.1:9999/sinks/7/mcp", command) self.assertEqual(env["INKCRE_MCP_AUTHORIZATION"], "Bearer fake-secret-pat") self.assertEqual(env["CONTROL_PLANE_API_KEY"], "fake-secret-key") diff --git a/docs/30-unit-tdd/caldav-extension.md b/docs/30-unit-tdd/caldav-extension.md index 5784d6c5..7ddf7076 100644 --- a/docs/30-unit-tdd/caldav-extension.md +++ b/docs/30-unit-tdd/caldav-extension.md @@ -89,9 +89,9 @@ Radicale 要求返回 `Last-Modified`,当前使用 DAV 根记录的时间; ## 验证依据 -`scripts/tests/caldav/` 保留 codec、图适配与事务排查脚本,不纳入默认测试收集或 CI 门槛,也不替代真机验收。按需运行 `pdm run python -m pytest -q scripts/tests/caldav`;数据库脚本要求通过 `INKCRE_TEST_DATABASE_URL` 显式指定已迁移的隔离 PostgreSQL。该目录的 `conftest.py` 复用既有隔离进程环境,禁止加载开发或 preview 的隐式连接。 +`scripts/tests/caldav/` 拥有 codec、DAV HTTP、共享图和事务回归。默认测试执行离线 codec 契约;`pdm run test:database` 和 CI 的一次性 PostgreSQL 入口执行图与 HTTP 场景。聚焦验证可运行 `pdm run python -m pytest -q scripts/tests/caldav`;数据库场景要求通过 `INKCRE_TEST_DATABASE_URL` 显式指定已迁移的可丢弃 PostgreSQL,未指定时跳过不算通过。该目录的 `conftest.py` 复用既有隔离进程环境,禁止加载开发或 preview 的隐式连接。 -这些脚本可辅助检查字段往返、Resolver 读取、ETag 冲突、提交回滚、MOVE、成员并发、凭据撤销,以及共享内容、迁移和引用保留。 +codec 固定 fixture 保护跨语言属性语法、原生参数和二进制;HTTP 场景保护 ETag 冲突、提交回滚、MOVE 身份、成员并发、凭据撤销与重新启用后读取;共享图场景保护内容引用、直接 Peer 修改及旧数据升级。这些边界有独立风险,不互相替代。DAV DELETE 本身保留信息,fixture 因此在完成保留断言后精确删除本用例创建的 Block 和 blob,不能用撤下发布充当测试数据清理。自动化仍不替代真机、反向代理及外部 HTTPS 验收。 2026-10-20 在华为 JKM-AL00a(Android 9)上使用 DAVx⁵ 4.5.14-ose、Tasks.org 15.3 及系统日历/通讯录完成了真实同步验证:重复事件与提醒、离线修改单次例外、任务完成与 diff --git a/docs/30-unit-tdd/graph-navigation-retrieval.md b/docs/30-unit-tdd/graph-navigation-retrieval.md index e87826bc..2d2ab81a 100644 --- a/docs/30-unit-tdd/graph-navigation-retrieval.md +++ b/docs/30-unit-tdd/graph-navigation-retrieval.md @@ -38,6 +38,8 @@ discard most rows on sparse endpoints. Shortest-by-hop search is bounded bidirectional BFS. Defaults are four hops and 1,000 explored Blocks; hard bounds are eight hops and 10,000 Blocks. Frontier batching is private transport/query mechanics. +Endpoint Relation pages continue until exhausted: many parallel Relations can refer to very few +Blocks, so a full Relation page cannot establish disconnection or replace the explored-Block budget. Equal-shortest results have no stable tie-break contract. Traversal retains the Relation rows it reads and assembles a candidate from that operation-local snapshot instead of rereading and rejecting ordinary concurrent changes. If candidate endpoint Blocks no longer exist when closure is assembled, the public diff --git a/docs/30-unit-tdd/mcp-sink.md b/docs/30-unit-tdd/mcp-sink.md index c317bbc8..105c9e6d 100644 --- a/docs/30-unit-tdd/mcp-sink.md +++ b/docs/30-unit-tdd/mcp-sink.md @@ -116,13 +116,14 @@ materialize;相关工具不虚假声明绝对无副作用。 ## Acceptance And Skill -`tests/info_base/integration/test_mcp_http_journey.py` 使用 disposable PostgreSQL、正常 Core/SinkManager 生命周期、 -真实 TCP Streamable HTTP/PAT 与独立 MCP Client,验证 initialize/tools/list、四类 meta → storage/resolver/AND query → -跨 HTTP 分页 → open → solved content,以及历史 Resolver、无/错 PAT。生命周期只观察公开行为:disable 后 endpoint 404、 -普通 Core API 可用,re-enable 后新独立 Client 在同 URL initialize/tools/list 成功;shutdown 后外部 TCP 连接失败且 -普通 transport/Sink 日志无关闭错误,不检查 private running/session/mount flags。语料通过 graph commands 与字节 Storage -建立;real lexical/semantic maintain 创建索引,确定性 AI dialect 提供 vectors。每种模式都有超过 K 个排名更高的 -不匹配 Block 和高分 Relation,断言过滤后确实返回目标数量/ID。另保留只读角色、SQL 白名单与不构造 handler 的低层回归。 +TCP 验收使用已迁移的私有 PostgreSQL 数据库,通过真实 MCP 客户端验证 SinkManager 启停及 PAT 授权。 +客户端从 `meta_discover` 取得 Storage ID,用它筛选、打开 Block 并读取已解析的正文。 +停用后 MCP 端点返回 404,普通 Core API 仍可用;重新启用后,新客户端能在原 URL 列出工具。 +关闭服务后,TCP 连接失败,服务日志没有关闭错误。 + +语料经图提交与字节存储写入,两种检索分别维护索引。排名高于目标的候选中,有的只满足 resolver,有的只满足 storage。 +TCP 用例按结果 ID 区分单条件和两个条件的交集,并检查过滤发生在 top-K 之前。 +只读角色用例逐页读取四类 metadata 和未加载历史 Resolver 的 Block,检查游标作用域、SQL 选列及 handler 未构造。 Server 实现 bounded `io.modelcontextprotocol/skills` extension:`skills/list`、`skills/get` 与静态 `skill://inkcre/use-inkcre/SKILL.md` Resource。Skill 建立 Block/Relation/Resolver/Storage 心智模型,不规定固定 Tool recipe。 diff --git a/docs/30-unit-tdd/semantic-retrieval.md b/docs/30-unit-tdd/semantic-retrieval.md index 792674b5..e18c49b8 100644 --- a/docs/30-unit-tdd/semantic-retrieval.md +++ b/docs/30-unit-tdd/semantic-retrieval.md @@ -79,15 +79,18 @@ stops. ## Acceptance The checked-in acceptance corpus is owned by -`tests/semantic_retrieval/acceptance/corpus/manifest.json`. It uses the real Memos API, RSS/Atom source jobs, HTTP full-text -and enclosure paths, PostgreSQL binary storage, and a pinned public-domain SQLite Architecture HTML snapshot. Readable +`tests/semantic_retrieval/acceptance/corpus/manifest.json`. It uses the real Memos API, RSS/Atom source jobs with HTTP full-text, +and a pinned public-domain SQLite Architecture HTML snapshot. Readable aliases exist only in the manifest/harness and are resolved to actual database IDs after producer execution. -The deterministic vertical proves producer graph creation, rumination Tool/GraphForm control flow, global ranking gates -and complete cleanup. It is not semantic-quality authority. Real quality requires an explicit credentialed run: +确定性集成用例使用 PostgreSQL 验证混合 Block / Relation 排序、失效和修复;整理用例通过真实 Agent 工具提交草稿,再读回持久化的图。 +完整语料的质量判断使用显式配置的真实模型。运行命令如下。 ```bash INKCRE_TEST_DATABASE_URL=... \ +INKCRE_TEST_POSTGRES_ADMIN_URL=... \ +CORE_DATABASE_PASSWORD=... \ +POSTGREST_DATABASE_PASSWORD=... \ INKCRE_ACCEPTANCE_AI_API_KEY=... \ INKCRE_ACCEPTANCE_AI_BASE_URL=... \ INKCRE_ACCEPTANCE_EMBEDDING_MODEL=... \ @@ -96,7 +99,8 @@ pdm run test:acceptance ``` Each judged query requires a primary Block in the global top three and above every explicit distractor. The rumination -query additionally requires the specific derived Pager Block to outrank its coarse source document. Provider responses, +query additionally requires the derived Pager Block to cite the implementation file named in the source and outrank its +coarse source document. Provider responses, vectors, and generated graph rows are never committed as authority. ## Explicit Non-Goals diff --git a/docs/30-unit-tdd/twitter-extension.md b/docs/30-unit-tdd/twitter-extension.md index ecb05468..9006b3c0 100644 --- a/docs/30-unit-tdd/twitter-extension.md +++ b/docs/30-unit-tdd/twitter-extension.md @@ -4,7 +4,7 @@ Python Twitter distribution 把 x-monkey 提交和 Bookmark 采集写入同一 `archive_schema.py` 只保存 x-monkey 0.2.0 的固定协议 DTO;`x_monkey.py` 把已校验的提交转成共同模型,并按固定 DTO 字段集递归投影 query 数据、构造协议状态与汇总。自由的 Article JSON 按值保留。共同模型未来新增的字段不会自动进入旧协议,无法用该协议表达的已知结构返回错误,不改写持久事实。Official/Twikit 适配器在 `api.py` 中直接产出共同模型,`bookmark.py` 与 `resolver.py` 不依赖协议 DTO。当前适配器保留它们明确映射的事实,不宣称保存完整 provider 原始响应或所有未知字段。 -`reconcile.py` 拥有本实现的身份选择、事务合并和关系维护,只返回变化集合、Block IDs 及共同读取结果,不包含 HTTP 状态或 wire 响应类型。`TwitterBatch` 没有继承远端请求的条数限制;每类 1000 条的准入边界留在 x-monkey DTO。 +`reconcile.py` 拥有本实现的身份选择、事务合并和关系维护,写入返回发生变化的原生身份集合,协议适配器据此生成逐项提交状态。`TwitterBatch` 没有继承远端请求的条数限制;每类 1000 条的准入边界留在 x-monkey DTO。 一次 submit 使用一个 `graph_uow()`。Bookmark 先完成 provider 请求,再进入 `source_uow()`,锁定 Source,使用其 `graph` 合并新主帖及实际捕获的上下文,并在同一事务内推进 cursor。主帖顺序与展开上下文分开,因此引用帖不会成为下一次书签采集的 watermark;旧的数值 cursor 在比较边界转换为十进制字符串,不重置历史状态。 @@ -28,10 +28,10 @@ Python 的 v2 Post 文本投影包含原帖 ID、链接、已捕获作者、正 Python Twitter 在 `/twitter/x-monkey/account` 自托管连接页面。用户只在自己信任的 HTTPS 部署输入已有 `JWT_SECRET`,页面使用 WebCrypto HMAC SHA-256 本地签发 60 秒普通 Peer JWT,再以同 Origin Bearer 和 JSON `{}` 请求 `POST /twitter/x-monkey/session`。该路由复用 `require_peer_jwt`,拒绝非 Core Origin、非 JSON 和带 `session_use` 的凭据,返回 `SessionResponse` JSON 并建立归档 Cookie。页面随后 GET `api/v1/session`,确认 Cookie 的 `authenticated=true` 后才显示 `Connected`、Peer 和到期时间。 -账户页以随机 nonce CSP 限定脚本,`connect-src 'self'` 限定连接目标。JWT 不进入 URL,密钥不持久化或发送给服务器。页面不加载第三方脚本,不接受任意回跳;浏览器内签名不使恶意或被篡改页面安全。 +账户页使用同源 referrer 策略,使浏览器提交断开表单时保留同源 Origin。随机 nonce CSP 限定脚本,`connect-src 'self'` 限定连接目标。JWT 不进入 URL,密钥不持久化或发送给服务器。页面不加载第三方脚本,不接受任意回跳;浏览器内签名不使恶意或被篡改页面安全。 连接不要求 Web 或 MF 分发。`setup.x_monkey_base_url` 继续供用户复制,Web Setup 只提供通向该 Core 账户页的普通链接,不持有此连接流程的密钥、JWT 签发或凭据传输逻辑。账户页显示 Peer 与到期时间,脚本通过会话检测确认连接。七天 Cookie 默认期限与协议续签仍由 Python Twitter 拥有。 -候选验证脚本与 fixture 放在 `scripts/tests/twitter`,默认 pytest 与 CI 不收集。离线合同与 HTTP 边界验证入口为 `pdm run python -m pytest -q scripts/tests/twitter/test_archive_contract.py scripts/tests/twitter/test_archive_http.py`;显式运行整个目录可用 `pdm run python -m pytest -q scripts/tests/twitter`。 +协议回归与 fixture 放在 `scripts/tests/twitter`,默认测试执行固定 wire、稀疏合并和无数据库的 HTTP/session 契约;`pdm run test:database` 和 CI 的一次性 PostgreSQL 入口执行图与发布后 HTTP 场景。聚焦离线验证入口为 `pdm run python -m pytest -q scripts/tests/twitter --ignore=scripts/tests/twitter/integration tests/extensions/twitter`;显式运行整个目录可用 `pdm run python -m pytest -q scripts/tests/twitter`。 -真实数据库场景要求显式提供 `INKCRE_TEST_DATABASE_URL`,使用已迁移的可丢弃 PostgreSQL runtime;测试只清理自己创建的精确 IDs,不重置开发库。原生 roundtrip 与真实 Twikit Bookmark 验证执行 `LexicalRetrievalManager.maintain` 的实际扫描、投影和检索链,在 HTTP Storage 字节边界断言零调用;同时检查归档不额外创建内容块、blob 或 Job。固定 fixture 同时用于原生 roundtrip 和独立上游合同验证,真实 userscript、HTTP 会话及 Web 消费仍需要各自的纵向验收。 +真实数据库场景要求显式提供 `INKCRE_TEST_DATABASE_URL`,使用已迁移的可丢弃 PostgreSQL runtime;测试只清理自己创建的精确 IDs,不重置开发库,缺少数据库时跳过不算通过。原生归档场景执行 `LexicalRetrievalManager.maintain` 的实际扫描、投影和检索,检查该路径未读取 HTTP 媒体或创建内容块、blob、Job。Twikit Bookmark 场景单独验证采集阶段未下载媒体,后续原生补充沿用同一根。backfill 的分页和请求预算由离线测试保护,第二页提交失败后首段保留、失败段回滚及进度不前移由真实 PostgreSQL 场景保护。官方 Bookmark 测试运行授权回调、账号查询和分页请求,在 X 的 HTTP 边界提供固定响应。账户页响应检查保护浏览器策略;实际浏览器可在 HTTPS 账户页依次连接、重载、断开并再次重载,核对会话状态。真实 userscript、X 授权与计费、Web 消费仍需各自的纵向验收。 diff --git a/docs/40-deployment/database-contract.md b/docs/40-deployment/database-contract.md index 4853d433..5fbb785e 100644 --- a/docs/40-deployment/database-contract.md +++ b/docs/40-deployment/database-contract.md @@ -65,6 +65,8 @@ participations for the old enabled peers. Their config schema remains only in th until a Host resolves the exact Distribution and version. The old `set_extension_peer_enabled` RPC and global Extension version/enable/schema columns are removed. Both native `inkcre_core` and authenticated PostgREST Peers can read and update the shared state object; anonymous callers cannot. + +`extensions.state` 在创建 identity 时必须为空;仍有状态的 identity 不能被删除,必须先由拥有该状态的扩展完成清理。数据库 trigger 对原生与 PostgREST 写入执行同一约束。迁移 `c7f2a6d9e410` 重新挂载 Peer participation 切换时遗漏的 trigger,不修改已有行或改写历史 revision;回退该迁移会撤销这项数据库保护。 Participation writes use the authenticated peer role under the same JWT boundary. ## PostgreSQL Binary Storage Protocol diff --git a/docs/40-deployment/development-environment.md b/docs/40-deployment/development-environment.md index 7523746f..947898de 100644 --- a/docs/40-deployment/development-environment.md +++ b/docs/40-deployment/development-environment.md @@ -99,11 +99,11 @@ pdm run check pdm run dev ``` -`doctor` and `check` do not start the application or connect to a database. The full -repository contract checks tool versions, lock/export consistency, migration integrity, -formatting, lint, settings isolation, and the complete unit-test suite. +`doctor` 不启动应用或连接数据库。`check` 验证工具版本、锁文件、迁移完整性、格式、lint、类型、 +独立 SDK wheel 和默认测试。未显式提供测试数据库时,数据库场景报告 skip;这不构成业务持久化证明。 +CI 先运行 `check:code`,再用一次性 PostgreSQL 执行同一默认集合(`test:database`),制品 job 验证真实镜像、PostgREST、导出与恢复。 -格式与 lint 的范围由 `ruff.toml` 拥有,覆盖正式源码、测试与脚本。`tasks/` 是临时实验材料,`.agents/` 是独立维护的技能;二者不参与产品门禁。成为正式验证步骤的实验应迁入 `scripts/` 或 `tests/`。已发布迁移保持不可变;独立 CLI 使用 `pdm run --project cli check` 及自己的 CI。pre-commit 的格式与 lint 钩子复用 `pdm run format:check` 和 `pdm run lint`,CI 的完整入口仍为 `pdm run check`。 +格式与 lint 的范围由 `ruff.toml` 拥有,覆盖正式源码、测试与脚本。`tasks/` 是临时实验材料,`.agents/` 是独立维护的技能;二者不参与产品门禁。成为正式验证步骤的实验应迁入 `scripts/` 或 `tests/`。已发布迁移保持不可变;独立 CLI 使用 `pdm run --project cli check` 及自己的 CI。pre-commit 的格式与 lint 钩子复用 `pdm run format:check` 和 `pdm run lint`,CI 使用相同的静态、构建和测试命令。 Use narrower read-only checks while iterating: @@ -119,6 +119,13 @@ pdm run dev:database ready The test harness disables dotenv before application imports. Repository checks do not read a developer `.env` or use its database and API credentials. +默认 `pdm run test` 收集 `tests/`、`scripts/tests/` 和 ChatGPT 伴随进程生命周期测试,并排除 +`acceptance` 标记。这三个目录在 CI 中由同一入口执行,不再额外重跑发布脚本和伴随进程测试。 +CalDAV/Twitter 的 codec、HTTP、数据库图测试保护不同契约:协议字节、认证/会话、事务/并发与 +持久化各自保留,不能用 HTTP mock 代替数据库结果,也不以本地通过推断真机或上游服务兼容。 +显式真实供应商、外部 RSS/Atom、IMAP 与人工质量验收保留 `acceptance` 标记;按各专项入口运行, +默认命令不会因为当前 shell 恰好有供应商配置就执行它们。 + ## Required Environment Variables The checked-in baseline is `.env.example`. @@ -155,13 +162,14 @@ Credentialed semantic-quality acceptance is explicit and separate from the ordin selected migrated `INKCRE_TEST_DATABASE_URL`; see the local Semantic Retrieval Unit TDD for the command and pass/fail authority. -`pdm run test:database` 是无需真实 AI/IMAP 服务的 PostgreSQL 业务回归入口,具体场景清单由 -`scripts/automation/repository_check.sh` 拥有。它要求显式 `INKCRE_TEST_DATABASE_URL`;未设置时直接失败, -不会将整组 skip 当作通过。数据库必须已经迁移且可丢弃:场景包含清空数据、事务回滚和迁移往返验证, -不能连接共享开发库、Preview 或生产。Memos 迁移场景还要求该独占 PostgreSQL 的 `MIGRATION_DATABASE_URL` -具有创建数据库权限;它建立随机命名的历史数据库,只往返附件所属 revision,并在结束后删除该数据库。 -这保留实际 migration 编排和应用下载读回,不会回退当前业务测试库或声称验证了整条历史 downgrade 链。 -CI 在自身临时 PostgreSQL service 上先初始化再执行这一组;外部服务和真实凭据验收继续由各自专项入口负责。 +`pdm run test:database` 在一次性 PostgreSQL 上运行整个默认测试集合。新场景按 pytest 配置发现,无需登记第二份路径清单。入口要求显式 `INKCRE_TEST_DATABASE_URL`(Core 角色)、 +`MIGRATION_DATABASE_URL` 和 `INKCRE_TEST_POSTGRES_ADMIN_URL`(同一独占集群的管理员连接),以及 +初始化时使用的 `CORE_DATABASE_PASSWORD`、`POSTGREST_DATABASE_PASSWORD`;缺少输入直接失败。 +数据库必须已经迁移,整个集群必须可丢弃:场景包含清空数据、事务回滚、创建数据库和角色授权验证, +不能连接共享开发库、Preview 或生产。迁移测试建立独立历史数据库并在结束后删除,不回退业务测试库; +角色凭证必须与初始化一致。执行全库索引或维护的知识验收还需要上述管理员连接和两项角色密码,借此在同一可丢弃集群中迁移一次模板,为每个场景克隆私有信息库,结束后删除。 + +数据库入口也执行 CalDAV/Twitter 持久化、Mail newsletter 图回放、Memos 与 HTTP 文档的词法召回,以及确定性向量的语义排序。CI 在自己的临时 PostgreSQL service 上初始化后运行。未执行、跳过或失败都必须分别报告,不能将整组 skip 记作通过。 ## Database Branch Workflow In CI diff --git a/docs/40-deployment/docker.md b/docs/40-deployment/docker.md index 19a8bbb9..7f08cd3d 100644 --- a/docs/40-deployment/docker.md +++ b/docs/40-deployment/docker.md @@ -94,13 +94,16 @@ secrets. ## CI Evidence The artifact job in `.github/workflows/ci.yml` builds the source image and PostgREST, then proves -the full fresh-database chain: duplicate init, JSON readiness, negative drift cases, the +the fresh-database chain through duplicate init, JSON readiness, the production PostgREST wrapper binding from `$PORT`, JWT read/write and denial behavior, -duplicate deterministic reset, Alembic metadata, and web liveness/readiness. It uses no Neon +reset of a database containing an extra Extension followed by a second reset against the same +expected catalog and seed, Alembic metadata, and web liveness/readiness. It uses no Neon or Heroku state. PR CI initializes a separate neutral runtime database, exports password-free role SQL and a -PostgreSQL 17 whole-database schema dump, and restores it as candidate validation. After strict +PostgreSQL 17 whole-database schema dump, and restores them in an empty cluster. It checks +the restored role definitions and Alembic head/schema before initialization provisions runtime +credentials and builtins. After strict required checks admit that tree to protected `main`, `artifact-publish.yml` independently repeats that export in the release workflow, embeds its same-run schema, builds the canonical service image, and publishes the image commit tag diff --git a/extensions/capture/.changes/+graph-material-limit.fixed.md b/extensions/capture/.changes/+graph-material-limit.fixed.md new file mode 100644 index 00000000..2b7d55f9 --- /dev/null +++ b/extensions/capture/.changes/+graph-material-limit.fixed.md @@ -0,0 +1 @@ +普通阅读包含图片的 Capture 时展示文件名或 MIME,词法检索保留原图信息。Python 分发现在拒绝超过 128 份材料,以及材料和附注同时为空的图。 diff --git a/extensions/capture/resolver.py b/extensions/capture/resolver.py index c7dae356..24da9962 100644 --- a/extensions/capture/resolver.py +++ b/extensions/capture/resolver.py @@ -43,6 +43,8 @@ async def get_text( materialize_missing: bool = True, ) -> str: solved = await self.get_solved_content(refresh=refresh, materialize_missing=False) + if context == "default": + return solved.metadata.filename or solved.metadata.mime_type block = await BlockService.get(solved.content_block_id) if block is None: raise ValueError("采集图片已不存在") @@ -79,6 +81,10 @@ async def _get_solved_content( raise ValueError("采集材料序号无效") elif relation.content == "annotation": annotations.append(relation.to_) + if not material_ids and not annotations: + raise ValueError("采集材料和附注不能同时为空") + if len(material_ids) > 128: + raise ValueError("一次采集最多包含 128 份材料") if sorted(material_ids) != list(range(len(material_ids))) or len(annotations) > 1: raise ValueError("采集材料顺序或附注关系无效") materials = [] diff --git a/extensions/memos/.changes/+concurrent-attachment-append.fixed.md b/extensions/memos/.changes/+concurrent-attachment-append.fixed.md new file mode 100644 index 00000000..a935e111 --- /dev/null +++ b/extensions/memos/.changes/+concurrent-attachment-append.fixed.md @@ -0,0 +1 @@ +修复向同一 Memo 并发上传附件时,稍后完成的上传可能移除先前已保存附件的问题。 diff --git a/extensions/memos/family/attachment.py b/extensions/memos/family/attachment.py index 45aaa1c6..4835ece7 100644 --- a/extensions/memos/family/attachment.py +++ b/extensions/memos/family/attachment.py @@ -243,7 +243,8 @@ async def create( ) -> SolvedAttachment: created_at = now or datetime.datetime.now(datetime.UTC) async with graph_uow() as uow: - if memo_id is not None and await MemoGraph.get_root(memo_id, uow) is None: + # Keep the read-modify-append operation under the memo's existing write lock. + if memo_id is not None and await MemoGraph.get_root(memo_id, uow, lock=True) is None: raise AttachmentNotFoundError(f"Memo memos/{memo_id} not found") block = await AttachmentGraph.create( filename=filename, diff --git a/extensions/telegram/.changes/+legacy-read-only.changed.md b/extensions/telegram/.changes/+legacy-read-only.changed.md new file mode 100644 index 00000000..a7f2284f --- /dev/null +++ b/extensions/telegram/.changes/+legacy-read-only.changed.md @@ -0,0 +1 @@ +移除旧版消息 resolver 上仅供 fixture 使用的写图方法;原有 0.1.0 消息仍可读取。 diff --git a/extensions/telegram/resolver.py b/extensions/telegram/resolver.py index aa8093f3..7a95daa2 100644 --- a/extensions/telegram/resolver.py +++ b/extensions/telegram/resolver.py @@ -14,7 +14,6 @@ from app.business.source.config import resolve_writable_storage_async from app.persistence.source.uow import source_uow from app.schemas.info_base.block import BlockForm, BlockModel -from app.schemas.info_base.main import StarsGraphForm from app.schemas.source import SourceModel from .schema import SolvedTelegramAttachment, TelegramAttachment, TelegramMessage @@ -51,13 +50,6 @@ async def _get_solved_content( del materialize_missing return TelegramMessage.model_validate_json(await self.get_raw_content(refresh=refresh)) - @classmethod - def create_graph(cls, message: TelegramMessage) -> StarsGraphForm: - """Legacy fixture seam; new collection never calls it.""" - return StarsGraphForm( - block=BlockForm(resolver=cls.__rsotype__, content=message.model_dump_json()) - ) - async def get_text( self, *, diff --git a/extensions/twitter/.changes/+archive-disconnect.fixed.md b/extensions/twitter/.changes/+archive-disconnect.fixed.md new file mode 100644 index 00000000..5a42c1a7 --- /dev/null +++ b/extensions/twitter/.changes/+archive-disconnect.fixed.md @@ -0,0 +1 @@ +修复浏览器账户页点击“断开此浏览器”时收到 403 的问题。 diff --git a/extensions/twitter/.changes/+archive-write.changed.md b/extensions/twitter/.changes/+archive-write.changed.md new file mode 100644 index 00000000..026c4ce9 --- /dev/null +++ b/extensions/twitter/.changes/+archive-write.changed.md @@ -0,0 +1,2 @@ +归档写入按原生身份报告变化,去除仅供测试使用的内部 Block ID 映射,减少批量提交时的重复遍历。 +移除旧版 Tweet Resolver 的 v1 构造方法。历史 v1 记录仍可读取,重新采集时原地升级。 diff --git a/extensions/twitter/api.py b/extensions/twitter/api.py index 324f3fc3..bfe3d77d 100644 --- a/extensions/twitter/api.py +++ b/extensions/twitter/api.py @@ -69,9 +69,8 @@ def _provider_counts(raw: dict, names: dict[str, str], observed_at: str) -> dict ) -def _official_archive( - raw_tweets: list[dict], includes: dict, observed_at: str -) -> TwitterBatch: +def _official_archive(raw_tweets: list[dict], includes: dict) -> TwitterBatch: + observed_at = _observed_at() media = [] media_ids = {} for raw in includes.get("media", ()): @@ -194,9 +193,8 @@ def _official_archive( return TwitterBatch.model_validate({"users": users, "posts": posts, "media": media}) -def _twikit_archive( - tweets: typing.Iterable[twikit.Tweet], observed_at: str -) -> TwitterBatch: +def _twikit_archive(tweets: typing.Iterable[twikit.Tweet]) -> TwitterBatch: + observed_at = _observed_at() posts: dict[str, dict] = {} users: dict[str, dict] = {} media: dict[str, dict] = {} @@ -599,11 +597,6 @@ async def get_user(self) -> tuple[str, str]: self.__user_handle = user_handle return user_id, user_handle - def _resolve_tweets( - self, raw_tweets: list[dict], includes: dict[str, list[dict]] - ) -> TwitterBatch: - return _official_archive(raw_tweets, includes, _observed_at()) - async def get_bookmarks( self, max_results: int = 20, page: str | None = None ) -> TwitterAPIResult: @@ -640,7 +633,7 @@ async def get_bookmarks( path_params={"id": self.__user_id}, query=bookmarks_query, ) - batch = self._resolve_tweets(res.get("data", []), res.get("includes", {})) + batch = _official_archive(res.get("data", []), res.get("includes", {})) return TwitterAPIResult( next_page=res.get("meta", {}).get("next_token"), previous_page=res.get("meta", {}).get("previous_token"), @@ -674,7 +667,7 @@ async def get_tweets( ), }, ) - batch = self._resolve_tweets(res.get("data", []), res.get("includes", {})) + batch = _official_archive(res.get("data", []), res.get("includes", {})) return TwitterAPIResult( next_page=res.get("meta", {}).get("next_token"), previous_page=res.get("meta", {}).get("previous_token"), @@ -751,10 +744,6 @@ async def _login(self): cookies_file=str(self.COOKIES_FILE), ) - @staticmethod - def _resolve_tweets(result: typing.Iterable[twikit.Tweet]) -> TwitterBatch: - return _twikit_archive(result, _observed_at()) - async def get_bookmarks( self, max_results: int = 20, page: str | None = None ) -> TwitterAPIResult: @@ -764,7 +753,7 @@ async def get_bookmarks( return TwitterAPIResult( next_page=res.next_cursor, previous_page=res.previous_cursor, - batch=self._resolve_tweets(res), + batch=_twikit_archive(res), primary_post_ids=tuple(tweet.id for tweet in res), ) @@ -787,7 +776,7 @@ async def get_tweets( return TwitterAPIResult( next_page=res.next_cursor, previous_page=res.previous_cursor, - batch=self._resolve_tweets(res), + batch=_twikit_archive(res), primary_post_ids=tuple(tweet.id for tweet in res), ) @@ -828,6 +817,6 @@ async def get_replies( res_tweets.extend(replies) return TwitterAPIResult( - batch=self._resolve_tweets(res_tweets), + batch=_twikit_archive(res_tweets), primary_post_ids=tuple(tweet.id for tweet in res_tweets), ) diff --git a/extensions/twitter/archive_session.py b/extensions/twitter/archive_session.py index 0c24c0d8..d5049927 100644 --- a/extensions/twitter/archive_session.py +++ b/extensions/twitter/archive_session.py @@ -150,7 +150,8 @@ def _html_page( f"default-src 'none'; {script_policy}connect-src 'self'; form-action 'self'; " "base-uri 'none'; frame-ancestors 'none'" ), - "Referrer-Policy": "no-referrer", + # A native disconnect form needs its same-origin Origin on navigation POST. + "Referrer-Policy": "same-origin", "X-Content-Type-Options": "nosniff", }, ) diff --git a/extensions/twitter/reconcile.py b/extensions/twitter/reconcile.py index 0374e3a2..d9daeb2e 100644 --- a/extensions/twitter/reconcile.py +++ b/extensions/twitter/reconcile.py @@ -37,12 +37,6 @@ Identity = tuple[str, str] -@dataclass(frozen=True) -class TwitterWriteResult: - changed: frozenset[Identity] - block_ids: dict[str, dict[str, int]] - - def _json(value: object) -> str: return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True) @@ -128,7 +122,7 @@ async def persist_twitter( uow: GraphUnitOfWork, *, text_policy: TextPolicy = "replace", -) -> TwitterWriteResult: +) -> frozenset[Identity]: """Merge a complete batch without committing the caller's graph transaction. Supplement captures retain an already known body while adding other facts. @@ -223,20 +217,10 @@ async def persist_twitter( RelationCreateForm(from_=source, to_=target, content=content) for source, target, content in sorted(desired) ) - return TwitterWriteResult( - changed=frozenset(changed), - block_ids={ - kind: { - native_id: _block_id(root) - for (candidate_kind, native_id), root in roots.items() - if candidate_kind == kind - } - for kind in KINDS - }, - ) + return frozenset(changed) -async def write_twitter(batch: TwitterBatch) -> TwitterWriteResult: +async def write_twitter(batch: TwitterBatch) -> frozenset[Identity]: async with graph_uow() as uow: return await persist_twitter(batch, uow) diff --git a/extensions/twitter/resolver.py b/extensions/twitter/resolver.py index 429e0429..58b2710f 100644 --- a/extensions/twitter/resolver.py +++ b/extensions/twitter/resolver.py @@ -1,14 +1,11 @@ import json import typing -from typing import Optional as Opt import pydantic from app.business.info_base.resolver import Resolver, ResolverManager, TextProjectionContext from app.business.info_base.resolver.label import format_label from app.business.info_base.services import BlockService -from app.schemas.info_base.block import BlockForm -from app.schemas.info_base.main import StarsGraphForm from .schema import Tweet from .model import TwitterIdentity, TwitterMedia, TwitterPost, TwitterUser from .reconcile import MEDIA_RESOLVER, POST_RESOLVER, REFERENCE_SCHEMA, USER_RESOLVER @@ -85,28 +82,6 @@ async def get_label(self, *, refresh: bool = False) -> str: first_line=True, ) - @classmethod - def create_block(cls, content: Tweet, storage: Opt[int] = None) -> BlockForm: - """Create a BlockForm from Tweet.""" - # Remove attachments from the dict for storage - tweet_dict = content.model_dump() - tweet_dict.pop("attachments", None) - tweet_dict.pop("links", None) - return BlockForm( - resolver=cls.__rsotype__, - content=json.dumps(tweet_dict), - storage=storage, - ) - - @classmethod - def create_graph(cls, content: Tweet) -> StarsGraphForm: - """Create a StarsGraphForm from Tweet.""" - block = cls.create_block(content) - return StarsGraphForm( - block=block, - out_arcs=(), - ) - Native = typing.TypeVar("Native", bound=pydantic.BaseModel) diff --git a/extensions/twitter/x_monkey.py b/extensions/twitter/x_monkey.py index b10d8d85..9e3d48c3 100644 --- a/extensions/twitter/x_monkey.py +++ b/extensions/twitter/x_monkey.py @@ -20,7 +20,7 @@ from .reconcile import ( KINDS, TwitterReadResult, - TwitterWriteResult, + Identity, read_twitter, write_twitter, ) @@ -43,12 +43,12 @@ def export_record(kind: str, record: TwitterRecord) -> JsonValue: return projected.model_dump(mode="json", exclude_unset=True) -def encode_submission(batch: ArchiveBatch, result: TwitterWriteResult) -> SubmitResponse: +def encode_submission(batch: ArchiveBatch, changed: frozenset[Identity]) -> SubmitResponse: results = { kind: [ SubmitResult( id=record.id, - status="accepted" if (kind, record.id) in result.changed else "unchanged", + status="accepted" if (kind, record.id) in changed else "unchanged", ) for record in getattr(batch, kind) ] diff --git a/inkcre_core/business/graph_navigation_retrieval/main.py b/inkcre_core/business/graph_navigation_retrieval/main.py index 1da4c943..757f7f8a 100644 --- a/inkcre_core/business/graph_navigation_retrieval/main.py +++ b/inkcre_core/business/graph_navigation_retrieval/main.py @@ -413,18 +413,29 @@ async def _frontier_relations( "both", ) ) + endpoints: list[typing.Literal["from", "to"]] = [] if needs_from: - for relation in await uow.relations.get_endpoint_page( - frontier, endpoint="from", contents=contents, limit=MAX_MAX_EXPLORED_BLOCKS - ): - if relation.id is not None: - relations[relation.id] = relation + endpoints.append("from") if needs_to: - for relation in await uow.relations.get_endpoint_page( - frontier, endpoint="to", contents=contents, limit=MAX_MAX_EXPLORED_BLOCKS - ): - if relation.id is not None: - relations[relation.id] = relation + endpoints.append("to") + for endpoint in endpoints: + cursor = None + while True: + page = await uow.relations.get_endpoint_page( + frontier, + endpoint=endpoint, + contents=contents, + cursor=cursor, + limit=MAX_MAX_EXPLORED_BLOCKS, + ) + for relation in page: + if relation.id is not None: + relations[relation.id] = relation + if len(page) < MAX_MAX_EXPLORED_BLOCKS: + break + # A Relation page is not an explored-Block budget: parallel edges can + # fill it without exhausting the reachable graph or the caller's budget. + cursor = typing.cast(RelationID, page[-1].id) return tuple(relations.values()) @classmethod diff --git a/inkcre_core/business/lexical_retrieval/main.py b/inkcre_core/business/lexical_retrieval/main.py index 0fb5bac2..6e461fc5 100644 --- a/inkcre_core/business/lexical_retrieval/main.py +++ b/inkcre_core/business/lexical_retrieval/main.py @@ -258,6 +258,15 @@ def _excerpt(label: str, text: str | None, query: str) -> str: if (candidate := folded_source.find(term.casefold())) >= 0 ] position = min(positions, default=0) + # Folding can expand a character (e.g. ß → ss). Only the original text + # owns the offsets used for the returned excerpt. + if position and len(folded_source) != len(source): + folded_end = 0 + for index, character in enumerate(source): + folded_end += len(character.casefold()) + if folded_end > position: + position = index + break start = max(0, position - _EXCERPT_LIMIT // 3) end = min(len(source), start + _EXCERPT_LIMIT) prefix = "…" if start else "" diff --git a/inkcre_core/business/peer/main.py b/inkcre_core/business/peer/main.py index a3d65d30..c76fda99 100644 --- a/inkcre_core/business/peer/main.py +++ b/inkcre_core/business/peer/main.py @@ -48,7 +48,6 @@ class _Candidate: class PeerManager: """Own Peer facts, local inbound registry, discovery, and one-shot routing.""" - _random: random.Random = random.SystemRandom() _config_contract = ConfigContract(CorePeerConfig) @classmethod @@ -248,5 +247,5 @@ async def _candidates( break if route_to_peer is None: - cls._random.shuffle(candidates) + random.SystemRandom().shuffle(candidates) return tuple(candidates) diff --git a/migrations/revision-integrity.json b/migrations/revision-integrity.json index d68940f4..154dd5a4 100644 --- a/migrations/revision-integrity.json +++ b/migrations/revision-integrity.json @@ -21,6 +21,7 @@ "c0d1e2f3a4b5_adopt_peer_capability_delegation.py": "7474fcda0b55fe2ce2047f761579459385aac9f43e7359ced881b8eb1fc6c265", "c4e8a7b6d5f0_converge_production_schema.py": "fb5687ad523c64297fe101d109918af2501bec26219de78353944a762eadfe4e", "c6d7e8f9a0b1_add_extension_setup_state.py": "5aab0d1dda6932fbac53f5a6adf4b504f994e8c860833b64fc21fb9cb8d8fc3e", + "c7f2a6d9e410_restore_extension_state_guard.py": "e4511fa9ee57d4dc27bb7fcc937c65351a335ce516d144398a11a363c9c17604", "c9d2e3f4a5b6_move_trigger_helper_internal.py": "6fab826c66cef1b16540142ae3d17ff953dc2ca49c79a4cffea95d4520701e6e", "d0e3f4a5b6c7_add_octet_stream_handler.py": "0d7127d340b878243d894e27f8b97d5982aa01c757703528d3982eb89ae9219e", "d41cc84db0c5_add_job_abort_request.py": "fc1fe04942e95c7b8c5f43dbcf369bb88479cb83f8e7dc58528f08caf7a536d2", diff --git a/migrations/versions/c7f2a6d9e410_restore_extension_state_guard.py b/migrations/versions/c7f2a6d9e410_restore_extension_state_guard.py new file mode 100644 index 00000000..e0402f9c --- /dev/null +++ b/migrations/versions/c7f2a6d9e410_restore_extension_state_guard.py @@ -0,0 +1,32 @@ +"""Restore the Extension state trigger after the Peer-participation cutover. + +Revision ID: c7f2a6d9e410 +Revises: bb5dcb562587 +""" + +from alembic import op + +from inkcre_core.database_contract import INTERNAL_SCHEMA, PROTOCOL_SCHEMA + + +revision = "c7f2a6d9e410" +down_revision = "bb5dcb562587" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # e6a1b2c3d4f5 replaced the guard function but did not reattach its trigger. + # Existing rows stay untouched; future writes obey the original state contract. + op.execute( + f""" + CREATE TRIGGER extensions_state_authority + BEFORE INSERT OR UPDATE OR DELETE ON {PROTOCOL_SCHEMA}.extensions + FOR EACH ROW + EXECUTE FUNCTION {INTERNAL_SCHEMA}.enforce_extension_state_authority() + """ + ) + + +def downgrade() -> None: + op.execute(f"DROP TRIGGER extensions_state_authority ON {PROTOCOL_SCHEMA}.extensions") diff --git a/pdm.lock b/pdm.lock index 54f5c530..ab12aec1 100644 --- a/pdm.lock +++ b/pdm.lock @@ -5,7 +5,7 @@ groups = ["default", "app", "dev", "extension-preview", "extension-publisher"] strategy = ["inherit_metadata"] lock_version = "4.5.0" -content_hash = "sha256:e8bc9b47fa7a1e15463f9582dbbbd990776ba38bb6a34ca59f0601ca130f17cf" +content_hash = "sha256:71ad33c90db1f0e2d46194d34561dac899be3eaba058c106fb1dffd464fa775c" [[metadata.targets]] requires_python = ">=3.12,<3.13" @@ -2523,6 +2523,17 @@ files = [ {file = "typer-0.21.2.tar.gz", hash = "sha256:1abd95a3b675e17ff61b0838ac637fe9478d446d62ad17fa4bb81ea57cc54028"}, ] +[[package]] +name = "types-pyyaml" +version = "6.0.12.20261122" +requires_python = ">=3.10" +summary = "Typing stubs for PyYAML" +groups = ["dev"] +files = [ + {file = "types_pyyaml-6.0.12.20261122-py3-none-any.whl", hash = "sha256:689fbbe883b60471166dede9dba6ac0dbdbcf0ea98062d7ec195430f5bbdb009"}, + {file = "types_pyyaml-6.0.12.20261122.tar.gz", hash = "sha256:7fa577c893a1db255cbb02320884ffcb97b7a219fe515bec6c5f15d5d3af41ed"}, +] + [[package]] name = "typing-extensions" version = "4.16.0" diff --git a/pyproject.toml b/pyproject.toml index 82317f8f..d66a9af1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -76,6 +76,8 @@ extension-publisher = [ dev = [ "build>=1.3.0,<2.0.0", "pytest>=9.0.2", + "PyYAML>=6.0.3,<7", + "types-PyYAML>=6.0.12,<7", "python-dotenv>=1.2.2", "pre-commit>=4.4.0", "ruff>=0.14.10", @@ -94,7 +96,7 @@ lint = "ruff check --no-cache ." format = "ruff format ." "format:check" = "ruff format --check ." typecheck = "pyrefly check --min-severity=warn --output-format=min-text --progress-bar=no" -test = "python -m pytest -q" +test = "python -m pytest -q -m 'not acceptance'" "test:database" = "bash scripts/automation/repository_check.sh database-tests" "test:acceptance" = "python -m pytest -q -m acceptance tests/semantic_retrieval/acceptance" "test:organization-acceptance" = "python -m pytest -q -s tests/organization/acceptance/test_black_box.py" @@ -102,7 +104,7 @@ test = "python -m pytest -q" "lint:migrations" = "ruff check --no-cache migrations/env.py migrations/metadata.py migrations/settings.py scripts/_tooling.py scripts/doctor.py scripts/check_lock.py scripts/check_migration_history.py scripts/database_manifest.py scripts/sanitize_preview_base.py tests/migrations" "test:migrations" = "python -m pytest -q tests/migrations" "check:migrations" = { composite = ["lint:migrations", "check:migration-history"] } -"check:automation" = { shell = "bash -n scripts/automation/*.sh" } +"check:automation" = { shell = 'for script in scripts/automation/*.sh; do bash -n "$script" || exit; done' } "check:migration-history" = "python scripts/check_migration_history.py {args}" "check:releases" = "python scripts/release.py check {args}" "build:extension-preview" = "python scripts/build_extension_preview.py {args}" @@ -112,7 +114,8 @@ test = "python -m pytest -q" "lint:database-imports" = "ruff check --config ruff.database.toml ." "lint:database-ownership" = "python scripts/check_database_boundaries.py" "lint:database-boundaries" = { composite = ["lint:database-imports", "lint:database-ownership"] } -"check" = { composite = ["check:foundation", "format:check", "lint", "lint:database-boundaries", "typecheck", "check:core-package", "test"] } +"check:code" = { composite = ["check:foundation", "format:check", "lint", "lint:database-boundaries", "typecheck", "check:core-package"] } +"check" = { composite = ["check:code", "test"] } "db:revision" = "alembic revision -m {args}" "db:generate" = "alembic revision --autogenerate -m {args}" "db:record" = "python scripts/check_migration_history.py --record-new" @@ -151,7 +154,8 @@ search-path = [".", "scripts"] python-version = "3.12" [tool.pytest.ini_options] -testpaths = ["tests"] +testpaths = ["tests", "scripts/tests", "deploy/integrations/chatgpt/tests"] +addopts = "--strict-markers" pythonpath = ["."] filterwarnings = [ "ignore:co_lnotab is deprecated, use co_lines instead\\.:DeprecationWarning:js2py_\\.utils\\.injector", diff --git a/scripts/automation/extension_publication.sh b/scripts/automation/extension_publication.sh index f3a791ee..6bdd5236 100644 --- a/scripts/automation/extension_publication.sh +++ b/scripts/automation/extension_publication.sh @@ -116,7 +116,6 @@ PY cp "$METADATA" "$CANDIDATE_ROOT/metadata.json" cp "$WHEEL" "$CANDIDATE_ROOT/$wheel_name" wheel_sha256="$(shasum -a 256 "$CANDIDATE_ROOT/$wheel_name" | cut -d ' ' -f 1)" - printf '%s\n' "$wheel_sha256" > "$CANDIDATE_ROOT/wheel.sha256" jq -n --arg extension "$EXTENSION" --arg run_id "$GITHUB_RUN_ID" \ --arg source_revision "$source_revision" --arg wheel "$wheel_name" \ --arg wheel_sha256 "$wheel_sha256" \ @@ -165,7 +164,10 @@ PY test -f "$CANDIDATE_ROOT/$wheel_name" test -f "$CANDIDATE_ROOT/$metadata_name" actual_sha256="$(shasum -a 256 "$CANDIDATE_ROOT/$wheel_name" | cut -d ' ' -f 1)" - test "$actual_sha256" = "$expected_sha256" + if [ "$actual_sha256" != "$expected_sha256" ]; then + echo "Saved wheel SHA-256 does not match the candidate manifest" >&2 + exit 1 + fi metadata_revision="$(jq -er '.prepare.python.source_revision' "$CANDIDATE_ROOT/$metadata_name")" metadata_build_id="$(jq -er '.prepare.python.build_id' "$CANDIDATE_ROOT/$metadata_name")" test "$metadata_revision" = "$GITHUB_SHA" diff --git a/scripts/automation/repository_check.sh b/scripts/automation/repository_check.sh index 1681af1e..f73ce1bc 100644 --- a/scripts/automation/repository_check.sh +++ b/scripts/automation/repository_check.sh @@ -5,13 +5,11 @@ source "$(dirname "$0")/_common.sh" case "${1:-}" in database-tests) require_env INKCRE_TEST_DATABASE_URL - # This admitted suite needs migrated, disposable PostgreSQL, but no live AI or IMAP service. - pdm run python -m pytest -q -rs \ - tests/agent/integration tests/ai/integration tests/deployment_config/integration \ - tests/info_base/integration tests/lexical_retrieval/integration \ - tests/organization/integration tests/peer/integration tests/semantic_retrieval/integration \ - tests/extensions/memos/integration tests/extensions/rss/integration/test_feed_collection.py \ - tests/migrations/test_memos_attachment_v2_migration.py + require_env MIGRATION_DATABASE_URL + require_env INKCRE_TEST_POSTGRES_ADMIN_URL + require_env CORE_DATABASE_PASSWORD + require_env POSTGREST_DATABASE_PASSWORD + pdm run test -rs ;; release-intent) arguments=() diff --git a/scripts/automation/runtime_contract.sh b/scripts/automation/runtime_contract.sh index 28160305..878e678c 100644 --- a/scripts/automation/runtime_contract.sh +++ b/scripts/automation/runtime_contract.sh @@ -3,6 +3,19 @@ source "$(dirname "$0")/_common.sh" require_env IMAGE_TAG +pg_image="pgvector/pgvector:pg17@sha256:d2ef61f42ef767baa5a1475393303cc235bcd92febd9d7014eddb48b41f3bad0" + +expect_reset_refusal() { + local database_url="$1" confirmation="$2" detail="$3" result + if result="$(docker run --rm --network host --env CORE_DATABASE_PASSWORD \ + --env "MIGRATION_DATABASE_URL=$database_url" --env POSTGREST_DATABASE_PASSWORD "$IMAGE_TAG" \ + python scripts/container.py db reset-dev --confirm "$confirmation" 2>&1)"; then + echo "db reset-dev unexpectedly succeeded" >&2 + return 1 + fi + jq -e --arg detail "$detail" \ + '.command == "reset-dev" and .error_type == "ValueError" and .detail == $detail' <<< "$result" +} case "${1:-}" in build) @@ -13,8 +26,18 @@ case "${1:-}" in --file Dockerfile.postgrest --tag "$POSTGREST_IMAGE_TAG" . ;; inspect) - docker run --rm --entrypoint python "$IMAGE_TAG" -c \ - "from pathlib import Path; required=('app','libs','utils','migrations/versions','alembic.ini','scripts/container.py','scripts/web.py','scripts/database.py','scripts/verify_postgrest_contract.py'); missing=[p for p in required if not Path(p).exists()]; assert not missing, missing; assert not Path('extensions').exists(); import os,pip,site; assert all(os.access(p,os.W_OK) for p in site.getsitepackages())" + # First-party wheels still import these legacy modules from the host image. + docker run --rm --interactive --entrypoint python "$IMAGE_TAG" - <<'PYTHON' +import os +from pathlib import Path +import pip +import site +from libs.obsrv.main import get_logger +from utils.datetime_ import get_datetimez + +assert not Path("extensions").exists() +assert all(os.access(path, os.W_OK) for path in site.getsitepackages()) +PYTHON ;; initialize) for name in CORE_DATABASE_PASSWORD MIGRATION_DATABASE_URL POSTGREST_DATABASE_PASSWORD; do require_env "$name"; done @@ -41,33 +64,45 @@ case "${1:-}" in --env PGRST_DB_ANON_ROLE=anonymous \ --env PGRST_DB_PRE_REQUEST=inkcre_internal.check_jwt \ --env "PGRST_JWT_SECRET=$JWT_SECRET" --env PGRST_JWT_AUD=inkcre-api \ + --env PGRST_SERVER_HOST=127.0.0.1 --env PGRST_ADMIN_SERVER_PORT=13001 \ --env PORT=13000 "$POSTGREST_IMAGE_TAG")" trap 'docker logs "$postgrest_id"; docker rm --force "$postgrest_id"' EXIT - for _ in $(seq 1 30); do - if docker run --rm --network host "$IMAGE_TAG" \ - python scripts/container.py db contract --json >/dev/null && - docker run --rm --network host --entrypoint python "$IMAGE_TAG" \ - scripts/verify_postgrest_contract.py --base-url http://127.0.0.1:13000 \ - --jwt-secret "$JWT_SECRET" \ - --wrong-jwt-secret ci-wrong-jwt-secret-at-least-32-bytes; then - exit 0 - fi - sleep 1 - done - exit 1 + curl --fail --silent --show-error --retry 30 --retry-delay 1 --retry-connrefused \ + --retry-max-time 30 --max-time 5 http://127.0.0.1:13001/ready + docker run --rm --network host --entrypoint python "$IMAGE_TAG" \ + scripts/verify_postgrest_contract.py --base-url http://127.0.0.1:13000 \ + --jwt-secret "$JWT_SECRET" --wrong-jwt-secret ci-wrong-jwt-secret-at-least-32-bytes ;; reset) for name in CORE_DATABASE_PASSWORD MIGRATION_DATABASE_URL POSTGREST_DATABASE_PASSWORD; do require_env "$name"; done - fingerprint() { - docker run --rm --network host --env MIGRATION_DATABASE_URL --entrypoint python \ - "$IMAGE_TAG" -c "from app.database_contract.catalog import development_baseline_fingerprint as f; print(f())" + export PGDATABASE="${MIGRATION_DATABASE_URL/postgresql+psycopg:/postgresql:}" + reset_sql() { + docker run --rm --interactive --network host --env PGDATABASE "$pg_image" \ + sh -c 'exec psql --dbname="$PGDATABASE" -X --csv --tuples-only --set ON_ERROR_STOP=1 "$@"' sh "$@" + } + snapshot() { + reset_sql < tests/development_reset_snapshot.sql | sha256sum } - baseline="$(fingerprint)" + baseline="$(snapshot)" + # Only seed the explicitly marked development database. A no-op reset must + # leave a visible difference, even if init already created all the builtins. + reset_sql --command "INSERT INTO inkcre.extensions (name) + SELECT 'inkcre/reset-acceptance' FROM inkcre_internal.contract_state + WHERE singleton AND environment = 'development'" + seeded="$(snapshot)" + test "$seeded" != "$baseline" + expect_reset_refusal "$MIGRATION_DATABASE_URL" wrong-confirmation \ + "confirmation must be exactly reset-development-data" + test "$(snapshot)" = "$seeded" + POSTGREST_DATABASE_PASSWORD= expect_reset_refusal \ + "$MIGRATION_DATABASE_URL" reset-development-data \ + "missing runtime database secret: POSTGREST_DATABASE_PASSWORD" + test "$(snapshot)" = "$seeded" for _ in 1 2; do docker run --rm --network host --env CORE_DATABASE_PASSWORD \ --env MIGRATION_DATABASE_URL --env POSTGREST_DATABASE_PASSWORD "$IMAGE_TAG" \ python scripts/container.py db reset-dev --confirm reset-development-data - test "$(fingerprint)" = "$baseline" + test "$(snapshot)" = "$baseline" done ;; web) @@ -76,11 +111,8 @@ case "${1:-}" in --env JWT_SECRET --env INKCRE_ENV_FILE --env MIGRATION_DATABASE_URL \ --env PORT=18080 "$IMAGE_TAG" python scripts/container.py web)" trap 'docker logs "$container_id"; docker rm --force "$container_id"' EXIT - for _ in $(seq 1 30); do - curl --fail --silent http://127.0.0.1:18080/livez >/dev/null && break - sleep 1 - done - curl --fail --silent http://127.0.0.1:18080/livez + curl --fail --silent --show-error --retry 30 --retry-delay 1 --retry-connrefused \ + --retry-max-time 30 --max-time 5 http://127.0.0.1:18080/livez # Async bootstrap can yield while liveness already responds; wait for readiness itself. curl --fail --silent --show-error --retry 30 --retry-delay 1 \ --retry-max-time 30 --max-time 5 http://127.0.0.1:18080/readyz @@ -90,7 +122,6 @@ case "${1:-}" in contract_directory="${RUNNER_TEMP:-/tmp}/database-contract" contract_database_url="postgresql+psycopg://postgres:postgres@127.0.0.1:5432/inkcre_contract" mkdir --parents "$contract_directory" - pg_image="pgvector/pgvector:pg17@sha256:d2ef61f42ef767baa5a1475393303cc235bcd92febd9d7014eddb48b41f3bad0" docker run --rm --network host --env PGPASSWORD=postgres "$pg_image" \ createdb --host 127.0.0.1 --username postgres inkcre_contract docker run --rm --network host --env CORE_DATABASE_PASSWORD \ @@ -121,7 +152,6 @@ case "${1:-}" in for name in CORE_DATABASE_PASSWORD POSTGREST_DATABASE_PASSWORD; do require_env "$name"; done contract_directory="${RUNNER_TEMP:-/tmp}/database-contract" restore_password=ci-restore-database-password-at-least-32-bytes - pg_image="pgvector/pgvector:pg17@sha256:d2ef61f42ef767baa5a1475393303cc235bcd92febd9d7014eddb48b41f3bad0" restore_id="$(docker run --detach --env POSTGRES_DB=inkcre \ --env "POSTGRES_PASSWORD=$restore_password" --env POSTGRES_USER=postgres \ --publish 127.0.0.1::5432 "$pg_image")" @@ -132,20 +162,34 @@ case "${1:-}" in --no-align --command 'SELECT 1' >/dev/null 2>&1; then break; fi sleep 1 done - docker exec --interactive --env "PGPASSWORD=$restore_password" "$restore_id" \ - psql --host 127.0.0.1 --username postgres --dbname inkcre \ - --variable ON_ERROR_STOP=1 < "$contract_directory/database-roles.sql" - docker exec --interactive --env "PGPASSWORD=$restore_password" "$restore_id" \ - psql --host 127.0.0.1 --username postgres --dbname inkcre \ - --variable ON_ERROR_STOP=1 < "$contract_directory/database-schema.sql" + restored_sql() { + docker exec --interactive --env "PGPASSWORD=$restore_password" "$restore_id" \ + psql --host 127.0.0.1 --username postgres --dbname inkcre \ + -X --variable ON_ERROR_STOP=1 "$@" + } + restored_sql < "$contract_directory/database-roles.sql" + restored_sql < "$contract_directory/database-schema.sql" restore_port="$(docker port "$restore_id" 5432/tcp | sed 's/.*://')" restore_database_url="postgresql+psycopg://postgres:${restore_password}@127.0.0.1:${restore_port}/inkcre" + # Check the imported roles and schema before init can recreate either. + docker run --rm --network host --env "MIGRATION_DATABASE_URL=$restore_database_url" \ + --entrypoint python "$IMAGE_TAG" scripts/export_database_roles.py | + cmp - "$contract_directory/database-roles.sql" + docker run --rm --network host --env "MIGRATION_DATABASE_URL=$restore_database_url" \ + --entrypoint alembic "$IMAGE_TAG" check + revision="$(jq -er '.revision' "$contract_directory/runtime-contract.json")" + restored_sql --set "expected_revision=$revision" < tests/restored_schema_data.sql docker run --rm --network host --env CORE_DATABASE_PASSWORD \ --env "MIGRATION_DATABASE_URL=$restore_database_url" \ --env POSTGREST_DATABASE_PASSWORD "$IMAGE_TAG" \ python scripts/container.py db init --profile runtime docker run --rm --network host --env "MIGRATION_DATABASE_URL=$restore_database_url" \ "$IMAGE_TAG" python scripts/container.py db ready --profile runtime --json + restored_sql --command "INSERT INTO inkcre.extensions (name) VALUES ('inkcre/reset-acceptance')" + expect_reset_refusal "$restore_database_url" reset-development-data \ + "operation requires a development database identity" + test "$(restored_sql --tuples-only --no-align --command \ + "SELECT count(*) FROM inkcre.extensions WHERE name = 'inkcre/reset-acceptance'")" = 1 ;; *) echo "unknown runtime contract command: ${1:-}" >&2; exit 2 ;; esac diff --git a/scripts/deploy_render_neon.py b/scripts/deploy_render_neon.py index fb0effae..e4629059 100644 --- a/scripts/deploy_render_neon.py +++ b/scripts/deploy_render_neon.py @@ -175,13 +175,12 @@ def __init__( self, api_key: str, *, - base_url: str = RENDER_API_BASE_URL, transport: httpx.BaseTransport | None = None, ) -> None: if not api_key: raise ValueError("Render API key is required") self._client = httpx.Client( - base_url=base_url, + base_url=RENDER_API_BASE_URL, headers={ "Accept": "application/json", "Authorization": f"Bearer {api_key}", diff --git a/scripts/tests/caldav/conftest.py b/scripts/tests/caldav/conftest.py index ba953049..942d64bb 100644 --- a/scripts/tests/caldav/conftest.py +++ b/scripts/tests/caldav/conftest.py @@ -1,5 +1,3 @@ """Reuse the isolated environment for explicitly selected CalDAV script checks.""" -from tests import conftest # noqa: F401 - from tests.conftest import application_core_scope as application_core_scope diff --git a/scripts/tests/caldav/test_dav_graph.py b/scripts/tests/caldav/test_dav_graph.py index 67936606..63c6a22e 100644 --- a/scripts/tests/caldav/test_dav_graph.py +++ b/scripts/tests/caldav/test_dav_graph.py @@ -9,12 +9,17 @@ import pytest from sqlalchemy import event from sqlalchemy.orm import Session +import sqlalchemy +import sqlmodel from app.engine import ASYNC_DB_ENGINE from inkcre_core.persistence.info_base.uow import graph_uow from inkcre_core.business.info_base.resolver import ResolverManager from extensions.caldav import Extension from extensions.caldav.schema import CALENDAR, GraphContent +from inkcre_core.schemas.info_base.block import BlockModel +from inkcre_core.schemas.info_base.storage import StorageBlobModel +from tests.database import TestSession from tests.extensions.runtime_support import publish_extension pytestmark = pytest.mark.skipif( @@ -27,17 +32,46 @@ @pytest.fixture def dav(): - published = publish_extension( - Extension, {"password": PASSWORD}, persist_config=True, raise_server_exceptions=False - ) - with published.client as client: - client.auth = ("inkcre", PASSWORD) - try: - yield client - finally: - assert client.portal is not None - client.portal.call(ASYNC_DB_ENGINE.dispose) + blocks, blobs = set(), set() + + def remember_created_rows(session, _flush_context): + for row in session.new: + if isinstance(row, BlockModel): + blocks.add(row.id) + elif isinstance(row, StorageBlobModel): + blobs.add(row.id) + + event.listen(Session, "after_flush", remember_created_rows) + published = None + try: + published = publish_extension( + Extension, {"password": PASSWORD}, persist_config=True, raise_server_exceptions=False + ) + with published.client as client: + client.auth = ("inkcre", PASSWORD) + try: + yield client + finally: + assert client.portal is not None + client.portal.call(ASYNC_DB_ENGINE.dispose) + finally: + if published is not None: published.unpublish() + event.remove(Session, "after_flush", remember_created_rows) + # DAV DELETE only withdraws publication. Remove the exact rows this test created + # after its retention assertions, so later whole-info-base scans stay isolated. + with TestSession() as session: + if blocks: + session.connection().execute( + sqlalchemy.delete(BlockModel).where(sqlmodel.col(BlockModel.id).in_(blocks)) + ) + if blobs: + session.connection().execute( + sqlalchemy.delete(StorageBlobModel).where( + sqlmodel.col(StorageBlobModel.id).in_(blobs) + ) + ) + session.commit() def calendar(summary="InKCre 测试"): @@ -81,131 +115,182 @@ def create_calendar(client): return path +async def resource_id(path): + from extensions.caldav.graph import DAVGraph + + async with graph_uow() as uow: + graph = DAVGraph(uow) + await graph.load() + collection_path, href = path.removeprefix("/caldav/").rsplit("/", 1) + return graph.collections[collection_path].items[href].block_id + + def test_native_roundtrip_graph_conflicts_and_sync_recovery(dav): response = dav.request("PROPFIND", "/caldav/", headers={"Depth": "1"}) assert response.status_code == 207, response.text path = create_calendar(dav) resource = path + "event.ics" - try: - response = dav.put( - resource, content=calendar().encode(), headers={"If-None-Match": "*"} - ) - assert response.status_code == 201, response.text - old_etag = response.headers["etag"] - stored = dav.get(resource) - assert stored.status_code == 200 - for fact in ( - "RRULE:FREQ=DAILY;COUNT=3", - "RECURRENCE-ID:", - "BEGIN:VALARM", - "X-INKCRE-TEST:preserved", - "单次例外", - ): - assert fact in stored.text - - async def read_info_base(): - from extensions.caldav.graph import DAVGraph - - async with graph_uow() as uow: - graph = DAVGraph(uow) - await graph.load() - root_id = ( - graph.collections[path.removeprefix("/caldav/").strip("/")] - .items["event.ics"] - .block_id - ) - assert root_id is not None - root = await uow.blocks.get(root_id) - assert root is not None - resolver = ResolverManager.get(root) - return await resolver.get_label(), await resolver.get_text() - - assert dav.portal is not None - label, text = dav.portal.call(read_info_base) - assert "InKCre 测试" in label and "X-INKCRE-TEST:preserved" in text - - barrier = Barrier(2) - - def update(summary): - barrier.wait() - return dav.put( - resource, content=calendar(summary).encode(), headers={"If-Match": old_etag} - ).status_code - - with ThreadPoolExecutor(max_workers=2) as pool: - statuses = list(pool.map(update, ("并发甲", "并发乙"))) - assert sorted(statuses) == [204, 412] - assert dav.put(resource, content=calendar().encode()).status_code == 412 - - report = ( - '' - "1" - "" - ) - initial = dav.request("REPORT", path, content=report) - assert initial.status_code == 207 - token = ET.fromstring(initial.content).findtext("{DAV:}sync-token") - assert token - same_report = report.replace("", f"{token}") - same = dav.request("REPORT", path, content=same_report) - assert not ET.fromstring(same.content).findall("{DAV:}response") - assert dav.delete( - resource, headers={"If-Match": dav.get(resource).headers["etag"]} - ).is_success - expired = dav.request("REPORT", path, content=same_report) - assert expired.status_code == 403 and "valid-sync-token" in expired.text - rescan = dav.request("PROPFIND", path, headers={"Depth": "1"}) - assert "event.ics" not in rescan.text - assert dav.get(resource).status_code == 404 - finally: - dav.delete(path) + response = dav.put(resource, content=calendar().encode(), headers={"If-None-Match": "*"}) + assert response.status_code == 201, response.text + old_etag = response.headers["etag"] + stored = dav.get(resource) + assert stored.status_code == 200 + for fact in ( + "RRULE:FREQ=DAILY;COUNT=3", + "RECURRENCE-ID:", + "BEGIN:VALARM", + "X-INKCRE-TEST:preserved", + "单次例外", + ): + assert fact in stored.text + + async def read_info_base(): + from extensions.caldav.graph import DAVGraph + + async with graph_uow() as uow: + graph = DAVGraph(uow) + await graph.load() + root_id = ( + graph.collections[path.removeprefix("/caldav/").strip("/")] + .items["event.ics"] + .block_id + ) + assert root_id is not None + root = await uow.blocks.get(root_id) + assert root is not None + resolver = ResolverManager.get(root) + return await resolver.get_label(), await resolver.get_text() + + assert dav.portal is not None + label, text = dav.portal.call(read_info_base) + assert "InKCre 测试" in label and "X-INKCRE-TEST:preserved" in text + + barrier = Barrier(2) + + def update(summary): + barrier.wait() + return dav.put( + resource, content=calendar(summary).encode(), headers={"If-Match": old_etag} + ).status_code + + with ThreadPoolExecutor(max_workers=2) as pool: + statuses = list(pool.map(update, ("并发甲", "并发乙"))) + assert sorted(statuses) == [204, 412] + assert dav.put(resource, content=calendar().encode()).status_code == 412 + + report = ( + '' + "1" + "" + ) + survivor = path + "surviving.ics" + assert ( + dav.put( + survivor, + content=calendar("仍应列出").replace("UID:inkcre-roundtrip", "UID:surviving"), + headers={"If-None-Match": "*"}, + ).status_code + == 201 + ) + initial = dav.request("REPORT", path, content=report) + assert initial.status_code == 207 + initial_result = ET.fromstring(initial.content) + assert {r.findtext("{DAV:}href") for r in initial_result.findall("{DAV:}response")} == { + resource, + survivor, + } + token = initial_result.findtext("{DAV:}sync-token") + assert token + same_report = report.replace("", f"{token}") + same = dav.request("REPORT", path, content=same_report) + assert same.status_code == 207 + same_result = ET.fromstring(same.content) + assert same_result.findtext("{DAV:}sync-token") == token + assert not same_result.findall("{DAV:}response") + assert dav.delete( + resource, headers={"If-Match": dav.get(resource).headers["etag"]} + ).is_success + expired = dav.request("REPORT", path, content=same_report) + assert expired.status_code == 403 and "valid-sync-token" in expired.text + rescan = dav.request("PROPFIND", path, headers={"Depth": "1"}) + assert rescan.status_code == 207 + assert { + r.findtext("{DAV:}href") + for r in ET.fromstring(rescan.content).findall("{DAV:}response") + } == {path, survivor} + assert dav.get(resource).status_code == 404 def test_commit_failure_rolls_back_and_never_reports_success(dav): path = create_calendar(dav) resource = path + "rollback.ics" + assert ( + dav.put( + resource, content=calendar().encode(), headers={"If-None-Match": "*"} + ).status_code + == 201 + ) + original = dav.get(resource) + commit_attempted = [] + + def fail_commit(session): + # Only fail the mutation transaction, after it has flushed changed content. + if session.info.get("caldav_test_mutated"): + commit_attempted.append(True) + raise RuntimeError("injected commit failure") + + def record_write(session, flush_context): + session.info["caldav_test_mutated"] = True + + event.listen(Session, "after_flush", record_write) + event.listen(Session, "before_commit", fail_commit) try: - assert ( - dav.put( - resource, content=calendar().encode(), headers={"If-None-Match": "*"} - ).status_code - == 201 + failed = dav.put( + resource, + content=calendar("不应保存").encode(), + headers={"If-Match": original.headers["etag"]}, ) - original = dav.get(resource) + assert failed.status_code == 500 + assert commit_attempted, "request failed before reaching the injected commit failure" + finally: + event.remove(Session, "after_flush", record_write) + event.remove(Session, "before_commit", fail_commit) + restored = dav.get(resource) + assert restored.text == original.text + assert restored.headers["etag"] == original.headers["etag"] - def fail_commit(session): - # Only fail the mutation transaction, after it has flushed changed content. - if session.info.get("caldav_test_mutated"): - raise RuntimeError("injected commit failure") - def record_write(session, flush_context): - session.info["caldav_test_mutated"] = True +def test_connection_exposes_the_public_dav_url_and_login_name(dav, monkeypatch): + from types import SimpleNamespace + from app.middleware import create_peer_jwt + from app.settings import settings + from inkcre_core.business.peer import PeerManager - event.listen(Session, "after_flush", record_write) - event.listen(Session, "before_commit", fail_commit) - try: - failed = dav.put( - resource, - content=calendar("不应保存").encode(), - headers={"If-Match": original.headers["etag"]}, - ) - assert failed.status_code == 500 - finally: - event.remove(Session, "after_flush", record_write) - event.remove(Session, "before_commit", fail_commit) - restored = dav.get(resource) - assert restored.text == original.text - assert restored.headers["etag"] == original.headers["etag"] - finally: - dav.delete(path) + config = SimpleNamespace(http_public_base_url=None) + async def current_config(): + return config -def test_tasks_contacts_and_credential_revocation(dav): + monkeypatch.setattr(PeerManager, "get_current_config_async", current_config) + headers = {"Authorization": f"Bearer {create_peer_jwt(settings.jwt_secret)}"} + missing = dav.get("/caldav/connection", headers=headers, auth=None) + assert missing.status_code == 409 + assert "Public HTTP Base URL" in missing.json()["detail"] + + config.http_public_base_url = "https://calendar.example/team" + advertised = dav.get("/caldav/connection", headers=headers, auth=None) + assert advertised.status_code == 200 + assert advertised.json() == { + "server_url": "https://calendar.example/team/caldav/", + "username": "inkcre", + } + + +def test_completed_task_roundtrip_and_credential_revocation(dav): from inkcre_core.schemas.extension import ExtensionModel from tests.database import TestSession task_path = f"/caldav/inkcre/tasks/{uuid4().hex}.ics" - contact_path = f"/caldav/inkcre/contacts/{uuid4().hex}.vcf" task = "\r\n".join( [ "BEGIN:VCALENDAR", @@ -226,37 +311,15 @@ def test_tasks_contacts_and_credential_revocation(dav): "", ] ) - contact = "\r\n".join( - [ - "BEGIN:VCARD", - "VERSION:3.0", - f"UID:{uuid4()}", - "FN:InKCre 测试联系人", - "N:测试;联系人;;;", - "TEL;TYPE=CELL:+8613800000000", - "TEL;TYPE=WORK:+8613900000000", - "EMAIL:caldav-test@example.invalid", - "ADR;TYPE=HOME:;;测试地址;上海;;;中国", - "NOTE:保留备注", - "PHOTO;ENCODING=b;TYPE=PNG:aGVsbG8=", - "X-INKCRE-TEST:kept", - "END:VCARD", - "", - ] - ) try: - for path, text in ((task_path, task), (contact_path, contact)): - response = dav.put(path, content=text.encode(), headers={"If-None-Match": "*"}) - assert response.status_code == 201, response.text + created = dav.put(task_path, content=task.encode(), headers={"If-None-Match": "*"}) + assert created.status_code == 201, created.text saved_task = dav.get(task_path).text assert ( "STATUS:COMPLETED" in saved_task and "RELATED-TO;RELTYPE=PARENT:test-parent" in saved_task ) assert "X-APPLE-SORT-ORDER:42" in saved_task - saved_contact = dav.get(contact_path).text - for value in ("+8613800000000", "+8613900000000", "保留备注", "PHOTO", "X-INKCRE-TEST"): - assert value in saved_contact with TestSession() as session: installed = session.get(ExtensionModel, "inkcre/caldav") assert installed @@ -271,35 +334,58 @@ def test_tasks_contacts_and_credential_revocation(dav): installed.config = {"password": PASSWORD} session.add(installed) session.commit() - dav.delete(task_path) - dav.delete(contact_path) - Extension.unpublish() - assert dav.get("/caldav/").status_code == 404 def test_move_rejects_stale_source_and_retains_graph_identity(dav): path = create_calendar(dav) source, target = path + "source.ics", path + "target.ics" + created = dav.put(source, content=calendar().encode(), headers={"If-None-Match": "*"}) + assert created.status_code == 201 + assert dav.portal is not None + original_id = dav.portal.call(resource_id, source) + changed = dav.put( + source, + content=calendar("新版本").encode(), + headers={"If-Match": created.headers["etag"]}, + ) + assert changed.status_code == 204 + headers = { + "Destination": "http://testserver" + target, + "If-Match": created.headers["etag"], + } + assert dav.request("MOVE", source, headers=headers).status_code == 412 + headers["If-Match"] = changed.headers["etag"] + assert dav.request("MOVE", source, headers=headers).status_code == 201 + assert dav.get(source).status_code == 404 + assert "新版本" in dav.get(target).text + assert dav.portal.call(resource_id, target) == original_id + + +def test_restart_restores_published_graph_without_recreating_objects(dav): + path = create_calendar(dav) + "restart.ics" + assert ( + dav.put(path, content=calendar(), headers={"If-None-Match": "*"}).status_code == 201 + ) + before = dav.get(path) + assert dav.portal is not None + original_id = dav.portal.call(resource_id, path) + dav.portal.call(ASYNC_DB_ENGINE.dispose) + Extension.unpublish() + assert dav.get(path).status_code == 404 + + restarted = publish_extension(Extension, {"password": PASSWORD}) try: - created = dav.put(source, content=calendar().encode(), headers={"If-None-Match": "*"}) - assert created.status_code == 201 - changed = dav.put( - source, - content=calendar("新版本").encode(), - headers={"If-Match": created.headers["etag"]}, - ) - assert changed.status_code == 204 - headers = { - "Destination": "http://testserver" + target, - "If-Match": created.headers["etag"], - } - assert dav.request("MOVE", source, headers=headers).status_code == 412 - headers["If-Match"] = changed.headers["etag"] - assert dav.request("MOVE", source, headers=headers).status_code == 201 - assert dav.get(source).status_code == 404 - assert "新版本" in dav.get(target).text + with restarted.client as client: + client.auth = ("inkcre", PASSWORD) + restored = client.get(path) + assert restored.status_code == 200 + assert restored.text == before.text + assert restored.headers["etag"] == before.headers["etag"] + assert client.portal is not None + assert client.portal.call(resource_id, path) == original_id + client.portal.call(ASYNC_DB_ENGINE.dispose) finally: - dav.delete(path) + restarted.unpublish() @pytest.mark.parametrize("change", ["move", "insert"]) @@ -337,52 +423,43 @@ async def pause_delete(self, *, lock=False): await anyio.to_thread.run_sync(resume.wait) monkeypatch.setattr(DAVGraph, "load", pause_delete) - try: - with ThreadPoolExecutor(max_workers=1) as pool: - deletion = pool.submit(dav.delete, path) + with ThreadPoolExecutor(max_workers=1) as pool: + deletion = pool.submit(dav.delete, path) + try: assert loaded.wait(10) - try: - with TestSession() as session: - collections = { - CollectionContent.model_validate_json(b.content).path: b.id - for b in session.exec( - sqlmodel.select(BlockModel).where(BlockModel.resolver == COLLECTION) - ).all() - } - source_id = collections[path.removeprefix("/caldav/").strip("/")] - target_id = collections[other.removeprefix("/caldav/").strip("/")] - assert source_id is not None and target_id is not None - member = session.exec( - sqlmodel.select(RelationModel).where( - RelationModel.from_ == source_id, RelationModel.content == "member" + with TestSession() as session: + collections = { + CollectionContent.model_validate_json(b.content).path: b.id + for b in session.exec( + sqlmodel.select(BlockModel).where(BlockModel.resolver == COLLECTION) + ).all() + } + source_id = collections[path.removeprefix("/caldav/").strip("/")] + target_id = collections[other.removeprefix("/caldav/").strip("/")] + assert source_id is not None and target_id is not None + member = session.exec( + sqlmodel.select(RelationModel).where( + RelationModel.from_ == source_id, RelationModel.content == "member" + ) + ).one() + session.connection().execute(sqlalchemy.text("SET LOCAL lock_timeout = '150ms'")) + with pytest.raises(OperationalError) as failed: + if change == "move": + member.from_ = target_id + session.add(member) + else: + item = BlockModel( + resolver=CALENDAR, + content=GraphContent( + href="new.ics", remainder=calendar("并发新增") + ).model_dump_json(), ) - ).one() - session.connection().execute(sqlalchemy.text("SET LOCAL lock_timeout = '150ms'")) - with pytest.raises(OperationalError) as failed: - if change == "move": - member.from_ = target_id - session.add(member) - else: - item = BlockModel( - resolver=CALENDAR, - content=GraphContent( - href="new.ics", remainder=calendar("并发新增") - ).model_dump_json(), - ) - session.add(item) - session.flush() - session.add(RelationModel(from_=source_id, to_=item.id, content="member")) + session.add(item) session.flush() - assert getattr(failed.value.orig, "sqlstate", None) == "55P03" - session.rollback() - finally: - resume.set() - assert deletion.result(10).is_success - assert ( - dav.request("PROPFIND", "/caldav/inkcre/", headers={"Depth": "1"}).status_code == 207 - ) - finally: - resume.set() - monkeypatch.setattr(DAVGraph, "load", original_load) - dav.delete(path) - dav.delete(other) + session.add(RelationModel(from_=source_id, to_=item.id, content="member")) + session.flush() + assert getattr(failed.value.orig, "sqlstate", None) == "55P03" + session.rollback() + finally: + resume.set() + assert deletion.result(10).is_success diff --git a/scripts/tests/caldav/test_semantic_graph.py b/scripts/tests/caldav/test_semantic_graph.py index c15b89cb..428e2479 100644 --- a/scripts/tests/caldav/test_semantic_graph.py +++ b/scripts/tests/caldav/test_semantic_graph.py @@ -31,10 +31,15 @@ ResourceContent, ) from tests.database import TestSession -from scripts.tests.caldav.test_dav_graph import dav, pytestmark, create_calendar # noqa: F401 +from scripts.tests.caldav.test_dav_graph import ( # noqa: F401 + dav, + pytestmark, + create_calendar, +) PHOTO = base64.b64decode( - "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGNQXpAHAAIbATIqos84AAAAAElFTkSuQmCC" + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGNQXpAH" + "AAIbATIqos84AAAAAElFTkSuQmCC" ) @@ -115,10 +120,12 @@ async def peer_update(): before = dav.get(path) dav.portal.call(peer_update) updated = dav.get(path) - assert ( - "+8613800000001" in updated.text and updated.headers["etag"] != before.headers["etag"] - ) - assert vobject.readOne(updated.text).photo.value == PHOTO + b"updated" + assert updated.headers["etag"] != before.headers["etag"] + contact = vobject.readOne(updated.text) + assert contact.note.value == "Shared note" + assert {tel.value for tel in contact.tel_list} == {"+8613800000001", "+8613900000000"} + assert "X-UNKNOWN;X-PARAM=kept:retained" in updated.text + assert contact.photo.value == PHOTO + b"updated" assert ( dav.put( path, content=reordered, headers={"If-Match": before.headers["etag"]} @@ -183,32 +190,33 @@ def test_child_before_parent_becomes_a_real_relation_and_survives_unpublish(dav) path = create_calendar(dav) child_uid, parent_uid = uuid4().hex, uuid4().hex child_path, parent_path = path + "child.ics", path + "parent.ics" - try: - assert ( - dav.put( - child_path, content=task(child_uid, parent_uid), headers={"If-None-Match": "*"} - ).status_code - == 201 - ) - child, fields, blocks = dav.portal.call(resource_graph, child_path) - reference = next(p for p in fields if p.field.link.name == "RELATED-TO") - assert blocks[reference.relation.to_].resolver == "core.text.v1" - assert ( - dav.put( - parent_path, content=task(parent_uid), headers={"If-None-Match": "*"} - ).status_code - == 201 - ) - parent, _, _ = dav.portal.call(resource_graph, parent_path) - child, fields, _ = dav.portal.call(resource_graph, child_path) - assert ( - next(p.relation.to_ for p in fields if p.field.link.name == "RELATED-TO") == parent.id - ) - assert "RELATED-TO" not in GraphContent.model_validate_json(child.content).remainder - assert dav.delete(parent_path).is_success - assert parent_uid in dav.get(child_path).text - finally: - dav.delete(path) + assert ( + dav.put( + child_path, content=task(child_uid, parent_uid), headers={"If-None-Match": "*"} + ).status_code + == 201 + ) + child, fields, blocks = dav.portal.call(resource_graph, child_path) + reference = next(p for p in fields if p.field.link.name == "RELATED-TO") + assert blocks[reference.relation.to_].resolver == "core.text.v1" + assert ( + dav.put( + parent_path, content=task(parent_uid), headers={"If-None-Match": "*"} + ).status_code + == 201 + ) + parent, _, _ = dav.portal.call(resource_graph, parent_path) + child, fields, _ = dav.portal.call(resource_graph, child_path) + assert ( + next(p.relation.to_ for p in fields if p.field.link.name == "RELATED-TO") == parent.id + ) + assert "RELATED-TO" not in GraphContent.model_validate_json(child.content).remainder + assert dav.delete(parent_path).is_success + assert parent_uid in dav.get(child_path).text + _, retained_fields, retained_blocks = dav.portal.call(resource_graph, child_path) + retained_reference = next(p for p in retained_fields if p.field.link.name == "RELATED-TO") + assert retained_reference.relation.to_ == parent.id + assert retained_blocks[parent.id].resolver == parent.resolver @pytest.mark.parametrize("target", ["phone", "blob"]) @@ -230,36 +238,31 @@ async def pause(self, *, lock=False): await anyio.to_thread.run_sync(resume.wait) monkeypatch.setattr(DAVGraph, "load", pause) - try: - with ThreadPoolExecutor(max_workers=1) as pool: - write = pool.submit(dav.put, path, content=card(uid), headers={"If-Match": etag}) + with ThreadPoolExecutor(max_workers=1) as pool: + write = pool.submit(dav.put, path, content=card(uid), headers={"If-Match": etag}) + try: assert loaded.wait(10) - try: - with TestSession() as session: - session.connection().execute(sqlalchemy.text("SET LOCAL lock_timeout = '150ms'")) - with pytest.raises(OperationalError) as error: - if target == "phone": - session.connection().execute( - sqlalchemy.update(BlockModel) - .where(BlockModel.id == phone) - .values(content="concurrent") - ) - else: - pointer = PostgreSQLBlobPointer.model_validate_json(photo.content) - session.connection().execute( - sqlalchemy.update(StorageBlobModel) - .where(sqlmodel.col(StorageBlobModel.id) == pointer.blob_id) - .values(data=b"concurrent") - ) - assert getattr(error.value.orig, "sqlstate", None) == "55P03" - session.rollback() - finally: - resume.set() - assert write.result(10).status_code == 204 - finally: - resume.set() - monkeypatch.setattr(DAVGraph, "load", original_load) - dav.delete(path) + with TestSession() as session: + session.connection().execute(sqlalchemy.text("SET LOCAL lock_timeout = '150ms'")) + with pytest.raises(OperationalError) as error: + if target == "phone": + session.connection().execute( + sqlalchemy.update(BlockModel) + .where(BlockModel.id == phone) + .values(content="concurrent") + ) + else: + pointer = PostgreSQLBlobPointer.model_validate_json(photo.content) + session.connection().execute( + sqlalchemy.update(StorageBlobModel) + .where(sqlmodel.col(StorageBlobModel.id) == pointer.blob_id) + .values(data=b"concurrent") + ) + assert getattr(error.value.orig, "sqlstate", None) == "55P03" + session.rollback() + finally: + resume.set() + assert write.result(10).status_code == 204 def test_legacy_promotion_is_atomic_keeps_root_id_and_unknown_fields(dav, monkeypatch): @@ -313,4 +316,3 @@ async def read(): result = dav.get("/caldav/" + collection_path + "/legacy.vcf") assert result.status_code == 200 and "X-UNKNOWN;X-PARAM=kept:retained" in result.text assert vobject.readOne(result.text).photo.value == PHOTO - dav.delete("/caldav/" + collection_path + "/") diff --git a/scripts/tests/test_extension_documentation.py b/scripts/tests/test_extension_documentation.py index feac69d9..c1e80847 100644 --- a/scripts/tests/test_extension_documentation.py +++ b/scripts/tests/test_extension_documentation.py @@ -21,6 +21,19 @@ def test_documentation_targets_the_saved_native_release(tmp_path, distribution): config = project / f"docs/{scope}/.vitepress/config.mts" config.parent.mkdir(parents=True) config.write_text("export default {}") + registry = tmp_path / "registry" + registry.mkdir() + (registry / "global.json").write_text( + json.dumps( + { + "name": "inkcre/mail", + "version": "0.9.0", + "distribution": distribution, + "scope": "global", + "etag": "previous-global", + } + ) + ) commands = tmp_path / "bin" commands.mkdir() stub = commands / "stub" @@ -31,7 +44,7 @@ def test_documentation_targets_the_saved_native_release(tmp_path, distribution): from pathlib import Path command = Path(sys.argv[0]).name args = sys.argv[1:] - root = Path(os.environ["CANDIDATE_ROOT"]) + registry = Path(os.environ["REGISTRY_FIXTURE"]) with Path(os.environ["COMMAND_LOG"]).open("a") as log: log.write(json.dumps([command, *args]) + "\\n") def option(name): @@ -40,29 +53,37 @@ def option(name): action = args[3] if action == "show": sets = [] - if (root / "published").exists(): - for candidate in root.glob("*/candidate.json"): - saved = json.loads(candidate.read_text()) - assert option("--distribution") == saved["distribution"] - assert option("--version") == saved["version"] - sets.append({ - "scope": saved["scope"], **saved["metadata"], - "snapshot_url": "https://registry-docs-" + "a" * 32 - + ".inkcre.dev/", - }) + for record in registry.glob("*.json"): + saved = json.loads(record.read_text()) + if all(saved[key] == option("--" + key) + for key in ["name", "version", "distribution"]): + sets.append(saved) print(json.dumps({"sets": sets})) elif action == "pack": output = Path(option("--output")) output.mkdir() keys = ["name", "version", "scope", "distribution"] candidate = {key: option("--" + key) for key in keys} + candidate["precondition"] = ( + option("--if-match") if "--if-match" in args else None + ) candidate["metadata"] = { "source_revision": option("--source-revision"), "build_id": option("--build-id"), } (output / "candidate.json").write_text(json.dumps(candidate)) elif action == "publish": - (root / "published").touch() + candidate = Path(option("--candidate")) / "candidate.json" + saved = json.loads(candidate.read_text()) + scope = saved["scope"] + target = registry / (scope + ".json") + previous = json.loads(target.read_text()) if target.exists() else {} + if saved["precondition"] != previous.get("etag"): + raise SystemExit("precondition failed for " + scope) + record = {**saved, **saved["metadata"], "snapshot_url": + "https://registry-docs-" + ("a" if scope == "global" else "b") * 32 + + ".inkcre.dev/"} + target.write_text(json.dumps(record)) print("{}") else: raise AssertionError(args) @@ -77,6 +98,7 @@ def option(name): **os.environ, "PATH": f"{commands}:{os.environ['PATH']}", "COMMAND_LOG": str(tmp_path / "commands.jsonl"), + "REGISTRY_FIXTURE": str(registry), "CANDIDATE_ROOT": str(tmp_path / "candidate"), "EXTENSION": "mail", "NATIVE_DISTRIBUTION": distribution, @@ -102,15 +124,14 @@ def option(name): calls = [ json.loads(line) for line in (tmp_path / "commands.jsonl").read_text().splitlines() ] - packs = [ - call for call in calls if call[:5] == ["pdm", "run", "inkcre-ext", "docs", "pack"] - ] - scopes = [call[call.index("--scope") + 1] for call in packs] - assert scopes == (["global", "python"] if distribution == "python" else ["global"]) - shows = [ - call for call in calls if call[:5] == ["pdm", "run", "inkcre-ext", "docs", "show"] - ] - assert len(shows) == 2 - for call in [*packs, *shows]: - assert call[call.index("--distribution") + 1] == distribution - assert call[call.index("--version") + 1] == "0.9.0" + expected_scopes = {"global", "python"} if distribution == "python" else {"global"} + records = [json.loads(path.read_text()) for path in registry.glob("*.json")] + assert {row["scope"] for row in records} == expected_scopes + assert all( + (row["name"], row["version"], row["distribution"]) + == ("inkcre/mail", "0.9.0", distribution) + for row in records + ) + assert {call[-1] for call in calls if call[0] == "curl"} == { + row["snapshot_url"] for row in records + } diff --git a/scripts/tests/test_preview_delivery.py b/scripts/tests/test_preview_delivery.py index c5c2dd86..026f1d34 100644 --- a/scripts/tests/test_preview_delivery.py +++ b/scripts/tests/test_preview_delivery.py @@ -24,18 +24,26 @@ def _run(script: str, command: str, environment: dict[str, str]): def test_failed_migration_keeps_observed_heads_and_reports_partial_delivery(tmp_path): binaries = tmp_path / "bin" binaries.mkdir() - observed = { + before = { "status": "error", "contract": {"revision": "candidate-contract"}, "migration": {"current": ["removed-revision"], "expected": ["candidate-head"]}, "database": {"status": "error"}, } + after = { + **before, + "migration": {"current": ["partial-revision"], "expected": ["candidate-head"]}, + } + (tmp_path / "before.json").write_text(json.dumps(before)) + (tmp_path / "after.json").write_text(json.dumps(after)) docker = binaries / "docker" docker.write_text( "#!/bin/sh\n" + 'cd "$DELIVERY_FIXTURE" || exit 1\n' 'case "$*" in\n' - f" *' db ready '*) printf '%s\\n' '{json.dumps(observed)}' ;;\n" - " *' db init '*) echo 'missing revision' >&2; exit 17 ;;\n" + " *' db ready '*) if [ -f after-init ]; then cat after.json; exit 2; fi; " + "cat before.json; exit 1 ;;\n" + " *' db init '*) touch after-init; echo 'missing revision' >&2; exit 17 ;;\n" " *) echo 'unexpected provider operation' >&2; exit 88 ;;\n" "esac\n" ) @@ -51,6 +59,7 @@ def test_failed_migration_keeps_observed_heads_and_reports_partial_delivery(tmp_ **os.environ, "PATH": f"{binaries}:{os.environ['PATH']}", "GITHUB_OUTPUT": str(output), + "DELIVERY_FIXTURE": str(tmp_path), "GITHUB_STEP_SUMMARY": str(tmp_path / "summary"), "HEAD_SHA": "a" * 40, "PR_NUMBER": "123", @@ -62,8 +71,8 @@ def test_failed_migration_keeps_observed_heads_and_reports_partial_delivery(tmp_ failed = _run("preview_delivery.sh", "converge-database", environment) assert failed.returncode == 17 values = dict(line.split("=", 1) for line in output.read_text().splitlines()) - assert json.loads(values["database_before"])["migration"] == observed["migration"] - assert json.loads(values["database_after"])["migration"] == observed["migration"] + assert json.loads(values["database_before"]) == {**before, "probe_exit": 1} + assert json.loads(values["database_after"]) == {**after, "probe_exit": 2} assert "runtime_database_url" not in values runtime_report = _run( @@ -94,6 +103,7 @@ def test_failed_migration_keeps_observed_heads_and_reports_partial_delivery(tmp_ summary = (tmp_path / "summary").read_text() assert "数据库初始化:`failure`" in summary assert "进程 release:`skipped`" in summary + assert "partial-revision" in summary assert "removed-revision" in summary assert '"version":7' in summary assert "https://snapshot.pages.dev" in summary diff --git a/scripts/tests/twitter/fixtures/native_archive.json b/scripts/tests/twitter/fixtures/native_archive.json index 730ecee6..080437db 100644 --- a/scripts/tests/twitter/fixtures/native_archive.json +++ b/scripts/tests/twitter/fixtures/native_archive.json @@ -351,7 +351,7 @@ { "id": "41", "type": "video", - "url": "https://pbs.twimg.com/cover.jpg", + "url": "https://example.org/cover.jpg", "width": 1920, "height": 1080, "alt": "演示视频", @@ -386,7 +386,7 @@ "bitrate": 256000 }, { - "url": "https://video.twimg.com/a.m3u8", + "url": "https://example.org/\nlist.m3u8", "type": "application/x-mpegURL" } ] diff --git a/scripts/tests/twitter/integration/conftest.py b/scripts/tests/twitter/integration/conftest.py new file mode 100644 index 00000000..ee1dc0c3 --- /dev/null +++ b/scripts/tests/twitter/integration/conftest.py @@ -0,0 +1,57 @@ +"""Isolate archive fixtures and remove only Blocks inserted by the current test.""" + +import json +from pathlib import Path +import typing +import uuid + +import pytest +import sqlalchemy +from sqlalchemy import event +from sqlalchemy.orm import Session +import sqlmodel + +from inkcre_core.schemas.info_base.block import BlockModel +from tests.database import TestSession + + +@pytest.fixture +def native() -> dict[str, typing.Any]: + value = json.loads( + (Path(__file__).parents[1] / "fixtures" / "native_archive.json").read_text() + ) + offset = int(uuid.uuid4().hex[:15], 16) + 10**20 + + def distinct(item): + if isinstance(item, str): + if item.isascii() and item.isdecimal(): + return str(int(item) + offset) + if isinstance(item, list): + return [distinct(child) for child in item] + if isinstance(item, dict): + return {key: distinct(child) for key, child in item.items()} + return item + + return distinct(value) + + +@pytest.fixture(autouse=True) +def tracked() -> typing.Iterator[set[int]]: + ids: set[int] = set() + + def remember_inserts(session, _context): + ids.update( + row.id for row in session.new if isinstance(row, BlockModel) and row.id is not None + ) + + event.listen(Session, "after_flush", remember_inserts) + try: + yield ids + finally: + event.remove(Session, "after_flush", remember_inserts) + if ids: + with TestSession() as db: + db.connection().execute( + sqlalchemy.delete(BlockModel).where(sqlmodel.col(BlockModel.id).in_(ids)) + ) + db.commit() diff --git a/scripts/tests/twitter/integration/test_archive_graph.py b/scripts/tests/twitter/integration/test_archive_graph.py index 43e8bd51..9fd63f71 100644 --- a/scripts/tests/twitter/integration/test_archive_graph.py +++ b/scripts/tests/twitter/integration/test_archive_graph.py @@ -5,17 +5,17 @@ import asyncio import json import os -from pathlib import Path import typing from types import SimpleNamespace from unittest import mock -import uuid import pytest import sqlalchemy from sqlalchemy import event +from sqlalchemy.orm import Session import sqlmodel import twikit +from twikit.utils import Result from inkcre_core.business.info_base.resolver import ResolverManager from inkcre_core.business.info_base.storage import HTTPStorage @@ -32,30 +32,21 @@ LexicalMaintenanceOptions, ) from inkcre_core.schemas.source import SourceModel +from extensions.twitter import Extension from extensions.twitter.api import ( TwitterAPI, TwitterAPIResult, - _official_archive, - _twikit_archive, + TwikitAPI, ) from extensions.twitter.archive_schema import ArchiveBatch, ArchiveQuery from extensions.twitter.model import TwitterBatch -from extensions.twitter.x_monkey import ( - decode_submission, - encode_submission, - query_archive, - submit_archive, -) -from extensions.twitter.bookmark import CollectConfig, Source +from extensions.twitter.x_monkey import query_archive, submit_archive +from extensions.twitter.bookmark import BackfillConfig, CollectConfig, Source from extensions.twitter.reconcile import ( MEDIA_RESOLVER, POST_RESOLVER, - REFERENCE_SCHEMA, USER_RESOLVER, - persist_twitter, ) -from extensions.twitter.resolver import TweetResolver -from extensions.twitter.schema import Tweet from tests.database import TestSession, seed_block, seed_relation @@ -65,104 +56,53 @@ ) -@pytest.fixture -def native() -> dict[str, typing.Any]: - value = json.loads( - (Path(__file__).parents[1] / "fixtures" / "native_archive.json").read_text() - ) - offset = int(uuid.uuid4().hex[:15], 16) + 10**20 - - def distinct(item): - if isinstance(item, str): - if item.isascii() and item.isdecimal(): - return str(int(item) + offset) - if item.startswith(("https://pbs.twimg.com/", "https://video.twimg.com/")): - return f"{item}{'&' if '?' in item else '?'}twitter_test={offset}" - if isinstance(item, list): - return [distinct(child) for child in item] - if isinstance(item, dict): - return {key: distinct(child) for key, child in item.items()} - return item - - return distinct(value) - - -@pytest.fixture -def tracked() -> typing.Iterator[set[int]]: - ids: set[int] = set() - yield ids - if ids: - with TestSession() as db: - db.connection().execute( - sqlalchemy.delete(BlockModel).where(sqlmodel.col(BlockModel.id).in_(tuple(ids))) - ) - db.commit() - - -async def _write(batch: ArchiveBatch | TwitterBatch, tracked: set[int]): - async with graph_uow() as uow: - result = await persist_twitter( - decode_submission(batch) if isinstance(batch, ArchiveBatch) else batch, uow - ) - tracked.update(block_id for ids in result.block_ids.values() for block_id in ids.values()) - return SimpleNamespace( - block_ids=result.block_ids, - response=encode_submission( - batch - if isinstance(batch, ArchiveBatch) - else ArchiveBatch.model_validate(batch.model_dump(mode="json", exclude_unset=True)), - result, - ), - ) +@pytest.fixture(scope="module", autouse=True) +def twitter_decoders(): + Extension.load_decoders() def _minimal(post: dict) -> dict: return {field: post[field] for field in ("id", "authorId", "createdAt")} -def _record(native_id: str) -> BlockModel: +def _record(native_id: str, resolver: str = POST_RESOLVER) -> BlockModel: with TestSession() as db: result = db.exec( sqlmodel.select(BlockModel).where( - BlockModel.resolver == POST_RESOLVER, + BlockModel.resolver == resolver, sqlalchemy.cast(BlockModel.content, sqlalchemy.JSON)["id"].as_string() == native_id, ) ).one() return result -def test_native_roundtrip_projection_and_media_are_lazy(async_runner, native, tracked): - # Importing the module registers all exact decoders, including legacy v1. - from extensions.twitter import resolver # noqa: F401 +@pytest.fixture +def metadata_only(): + def reject_materialization(session, _context): + unexpected = [ + type(row).__name__ + for row in session.new + if isinstance(row, (StorageBlobModel, JobModel)) + ] + assert not unexpected, f"metadata traversal inserted {unexpected}" + + event.listen(Session, "after_flush", reject_materialization) + try: + yield + finally: + event.remove(Session, "after_flush", reject_materialization) + +@pytest.mark.usefixtures("metadata_only") +def test_native_roundtrip_projection_and_media_are_lazy(async_runner, native, tracked): batch = ArchiveBatch.model_validate(native) - query = ArchiveQuery( - **{ - kind: [record.id for record in getattr(batch, kind)] - for kind in ("users", "posts", "media") - } - ) - with TestSession() as db: - block_count = db.exec( - sqlmodel.select(sqlmodel.func.count()).select_from(BlockModel) - ).one() - blob_count = db.exec( - sqlmodel.select(sqlmodel.func.count()).select_from(StorageBlobModel) - ).one() - job_count = db.exec(sqlmodel.select(sqlmodel.func.count()).select_from(JobModel)).one() with mock.patch.object( HTTPStorage, "get_raw_content", new_callable=mock.AsyncMock ) as fetch: fetch.side_effect = AssertionError("metadata read downloaded external media") - result = async_runner.run(_write(batch, tracked)) - assert result.response.summary.accepted == 3 - response = async_runner.run(query_archive(query)) - for kind in ("users", "posts", "media"): - assert [item.status for item in getattr(response, kind)] == ["found"] - assert [ - item.data.model_dump(mode="json", exclude_unset=True) - for item in getattr(response, kind) - ] == native[kind] + async_runner.run(submit_archive(batch)) + media = async_runner.run(query_archive(ArchiveQuery(media=[batch.media[0].id]))) + assert media.media[0].status == "found" post = _record(batch.posts[0].id) text = async_runner.run(ResolverManager.get(post).get_text(materialize_missing=False)) assert native["posts"][0]["article"]["title"] in text @@ -189,15 +129,16 @@ def test_native_roundtrip_projection_and_media_are_lazy(async_runner, native, tr ).all() assert set(indexed) == tracked assert fetch.await_count == 0 - replay = async_runner.run(_write(batch, tracked)) - assert replay.response.summary.unchanged == 3 - assert replay.block_ids == result.block_ids + original_ids = tracked.copy() + async_runner.run(submit_archive(batch)) + assert tracked == original_ids + assert _record(batch.posts[0].id).id == post.id pure_repost = { **_minimal(native["posts"][0]), "id": str(int(batch.posts[0].id) + 1000), "repostOf": batch.posts[0].id, } - async_runner.run(_write(ArchiveBatch.model_validate({"posts": [pure_repost]}), tracked)) + async_runner.run(submit_archive(ArchiveBatch.model_validate({"posts": [pure_repost]}))) repost_response = async_runner.run(query_archive(ArchiveQuery(posts=[pure_repost["id"]]))) assert repost_response.posts[0].data is not None assert ( @@ -209,15 +150,7 @@ def test_native_roundtrip_projection_and_media_are_lazy(async_runner, native, tr ) assert missing.posts[0].status == "missing" with TestSession() as db: - assert ( - db.exec(sqlmodel.select(sqlmodel.func.count()).select_from(StorageBlobModel)).one() - == blob_count - ) - assert ( - db.exec(sqlmodel.select(sqlmodel.func.count()).select_from(JobModel)).one() - == job_count - ) - media_id = result.block_ids["media"][batch.media[0].id] + media_id = _record(batch.media[0].id, MEDIA_RESOLVER).id relations = db.exec( sqlmodel.select(RelationModel).where( RelationModel.from_ == media_id, RelationModel.content == "content" @@ -227,62 +160,67 @@ def test_native_roundtrip_projection_and_media_are_lazy(async_runner, native, tr stored = db.exec( sqlmodel.select(BlockModel).where(sqlmodel.col(BlockModel.id).in_(tuple(tracked))) ).all() - assert len(stored) == len(tracked) + post_data = native["posts"][0] assert all(block.storage is None for block in stored) - assert db.exec( - sqlmodel.select(sqlmodel.func.count()).select_from(BlockModel) - ).one() == block_count + len(tracked) + assert sorted( + (block.resolver, json.loads(block.content)["id"]) for block in stored + ) == sorted( + [ + (USER_RESOLVER, post_data["authorId"]), + (MEDIA_RESOLVER, native["media"][0]["id"]), + (POST_RESOLVER, post_data["id"]), + (POST_RESOLVER, post_data["quote"]["postId"]), + (POST_RESOLVER, post_data["replyTo"]["postId"]), + (POST_RESOLVER, post_data["repostOf"]), + (POST_RESOLVER, pure_repost["id"]), + ] + ) -def test_sparse_counter_history_and_managed_edges(async_runner, native, tracked): - result = async_runner.run(_write(ArchiveBatch.model_validate(native), tracked)) +def test_sparse_counter_history_and_managed_edges(async_runner, native): + async_runner.run(submit_archive(ArchiveBatch.model_validate(native))) post = native["posts"][0] + root_id = _record(post["id"]).id + author_id = _record(post["authorId"], USER_RESOLVER).id + assert root_id is not None and author_id is not None baseline = _minimal(post) - updates = [ - ( - {"counts": {"likes": 100}, "countsObservedAt": {"likes": "2026-10-20T01:00:00Z"}}, - 100, - "2026-10-20T01:00:00Z", - "accepted", - ), - ( - {"counts": {"likes": 90}, "countsObservedAt": {"likes": "2026-10-19T01:00:00Z"}}, - 100, - "2026-10-20T01:00:00Z", - "unchanged", - ), - ( - { - "counts": {"likes": 100}, - "countsObservedAt": {"likes": "2026-10-20T02:00:00.1200Z"}, - }, - 100, - "2026-10-20T02:00:00.1200Z", - "accepted", - ), - ({"counts": {"likes": 101}}, 101, None, "accepted"), - ] - for patch, expected, observed, status in updates: - response = async_runner.run( - submit_archive(ArchiveBatch.model_validate({"posts": [{**baseline, **patch}]})) - ) - assert response.posts[0].status == status - stored = json.loads(_record(post["id"]).content) - assert stored["counts"]["likes"] == expected - assert stored.get("countsObservedAt", {}).get("likes") == observed - assert stored["text"] == post["text"] - assert stored["article"] == post["article"] - assert _record(post["id"]).id == result.block_ids["posts"][post["id"]] + # Updating only an observation timestamp is still a persisted, accepted change. + observed = "2026-10-20T02:00:00.1200Z" + patch = { + **baseline, + "counts": {"likes": post["counts"]["likes"]}, + "countsObservedAt": {"likes": observed}, + } + response = async_runner.run( + submit_archive(ArchiveBatch.model_validate({"posts": [patch]})) + ) + assert response.posts[0].status == "accepted" + stored = json.loads(_record(post["id"]).content) + assert stored["countsObservedAt"]["likes"] == observed + assert stored["text"] == post["text"] and stored["article"] == post["article"] # A changed media array replaces its edges without touching user-authored links. - root_id = result.block_ids["posts"][post["id"]] - user_link = seed_relation( - root_id, result.block_ids["users"][post["authorId"]], "my citation" - ) + user_link = seed_relation(root_id, author_id, "my citation") old_media_id = post["mediaIds"][0] replacement = str(int(old_media_id) + 1000) - update = ArchiveBatch.model_validate({"posts": [{**baseline, "mediaIds": [replacement]}]}) - async_runner.run(_write(update, tracked)) + cover = str(int(old_media_id) + 1001) + embedded = str(int(old_media_id) + 1002) + update = ArchiveBatch.model_validate( + { + "posts": [ + { + **baseline, + "mediaIds": [replacement], + "article": { + **post["article"], + "coverMediaId": cover, + "mediaIds": [embedded, replacement, cover], + }, + } + ] + } + ) + async_runner.run(submit_archive(update)) with TestSession() as db: assert db.get(RelationModel, user_link.id) is not None media_refs = [] @@ -293,32 +231,44 @@ def test_sparse_counter_history_and_managed_edges(async_runner, native, tracked) grammar = json.loads(relation.content) except ValueError: continue - if grammar.get("schema") == REFERENCE_SCHEMA and grammar["type"] == "media": + if ( + grammar.get("schema") == "extensions.twitter.reference.v1" + and grammar["type"] == "media" + ): target = db.get(BlockModel, relation.to_) assert target is not None media_refs.append((grammar["position"], json.loads(target.content)["id"])) - expected = list( - dict.fromkeys( - [replacement, post["article"]["coverMediaId"], *post["article"]["mediaIds"]] - ) - ) - assert sorted(media_refs) == list(enumerate(expected)) + assert sorted(media_refs) == [(0, replacement), (1, cover), (2, embedded)] def test_bookmark_joins_legacy_and_native_identity_without_overwriting_text( - async_runner, native, tracked + async_runner, native, monkeypatch ): post = native["posts"][0] legacy = seed_block( - TweetResolver.create_block(Tweet(id=int(post["id"]), text="旧加工 [photo]")) + BlockForm( + resolver="extensions.twitter.tweet.v1", + content=json.dumps( + { + "id": int(post["id"]), + "user_id": None, + "conversation_id": None, + "quote": None, + "text": "旧加工 [photo]", + } + ), + ) ) citation = seed_block(BlockForm(resolver="core.text.v1", content="user citation")) assert legacy.id is not None and citation.id is not None - tracked.update((legacy.id, citation.id)) reference = seed_relation(citation.id, legacy.id, "reference") old_attachment = seed_relation(legacy.id, citation.id, "attachment:photo:legacy") - result = async_runner.run(_write(ArchiveBatch.model_validate(native), tracked)) - assert result.block_ids["posts"][post["id"]] == legacy.id + with monkeypatch.context() as decoders: + decoders.delitem(ResolverManager.RESOLVER_CLS, legacy.resolver, raising=False) + Extension.load_decoders() + assert async_runner.run(ResolverManager.get(legacy).get_text()) == "旧加工 [photo]" + async_runner.run(submit_archive(ArchiveBatch.model_validate(native))) + assert _record(post["id"]).id == legacy.id with TestSession() as db: persisted_reference = db.get(RelationModel, reference.id) assert persisted_reference is not None and persisted_reference.to_ == legacy.id @@ -359,7 +309,7 @@ def test_bookmark_joins_legacy_and_native_identity_without_overwriting_text( def test_real_transaction_lock_preserves_concurrent_supplements_and_rollback( - async_runner, native, tracked + async_runner, native ): baseline = _minimal(native["posts"][0]) original_lock = BlockRepository.acquire_transaction_lock @@ -377,28 +327,21 @@ async def coordinated(repository, namespace): locked.set() await release.wait() + async def write(patch, reached_lock): + await submit_archive(ArchiveBatch.model_validate({"posts": [{**baseline, **patch}]})) + assert reached_lock.is_set(), "write completed without reaching the transaction lock" + with mock.patch.object(BlockRepository, "acquire_transaction_lock", coordinated): - first = asyncio.create_task( - submit_archive( - ArchiveBatch.model_validate({"posts": [{**baseline, "source": "client"}]}) - ), - name="first", - ) - await locked.wait() - second = asyncio.create_task( - submit_archive( - ArchiveBatch.model_validate({"posts": [{**baseline, "lang": "zh"}]}) - ), - name="second", - ) - await attempted.wait() - release.set() - await asyncio.gather(first, second) + async with asyncio.timeout(10), asyncio.TaskGroup() as writes: + writes.create_task(write({"source": "client"}, locked), name="first") + await locked.wait() + writes.create_task(write({"lang": "zh"}, attempted), name="second") + await attempted.wait() + release.set() async with graph_uow() as uow: roots = await uow.blocks.find_json_field_many( (POST_RESOLVER, USER_RESOLVER), "id", (baseline["id"], baseline["authorId"]) ) - tracked.update(block.id for block in roots) posts = [root for root in roots if root.resolver == POST_RESOLVER] assert len(posts) == 1 stored = json.loads(posts[0].content) @@ -422,7 +365,7 @@ async def coordinated(repository, namespace): ArchiveQuery(posts=[failed["id"], failed["quote"]["postId"]]) ) assert [item.status for item in absent.posts] == ["missing", "missing"] - await _write(batch, tracked) + await submit_archive(batch) assert (await query_archive(ArchiveQuery(posts=[failed["id"]]))).posts[ 0 ].status == "found" @@ -430,85 +373,110 @@ async def coordinated(repository, namespace): async_runner.run(exercise()) +def test_backfill_preserves_committed_page_when_next_commit_fails(async_runner, native): + source_type = f"{Source.__module__}.{Source.__qualname__}" + async_runner.run(SourceManager.sync_source_types_async({source_type: Source})) + source = async_runner.run( + SourceManager.create(source_type, nickname="Backfill commit failure") + ) + first_id = native["posts"][0]["id"] + second_id = str(int(first_id) + 1000) + first = _minimal(native["posts"][0]) + async_runner.run( + submit_archive( + ArchiveBatch.model_validate( + {"posts": [{**first, "text": {"text": "已归档的完整原文"}}]} + ) + ) + ) + with TestSession() as db: + persisted_source = db.get(SourceModel, source.id) + assert persisted_source is not None + persisted_source.state = {"latest_tweet_id": "42"} + db.add(persisted_source) + db.commit() + + def page(post_id, cursor): + return TwitterAPIResult( + primary_post_ids=(post_id,), + next_page=cursor, + batch=TwitterBatch.model_validate( + {"posts": [{**first, "id": post_id, "text": {"text": "书签预览"}, "lang": "zh"}]} + ), + ) + + provider = SimpleNamespace( + get_bookmarks=mock.AsyncMock(side_effect=[page(first_id, "a"), page(second_id, "b")]) + ) + flushed, commit_attempted = [], [] + + def remember_second_page(session, _context): + for row in session.new: + if isinstance(row, BlockModel) and json.loads(row.content).get("id") == second_id: + session.info["backfill_second_page"] = True + flushed.append(row.id) + + def fail_second_commit(session): + if session.info.get("backfill_second_page"): + commit_attempted.append(True) + raise RuntimeError("injected second-page commit failure") + + job = JobModel(type="core.source.backfill.v1", timeout_seconds=60) + event.listen(Session, "after_flush", remember_second_page) + event.listen(Session, "before_commit", fail_second_commit) + try: + with mock.patch.object(TwitterAPI, "new", mock.AsyncMock(return_value=provider)): + with pytest.raises(RuntimeError, match="injected second-page commit failure"): + async_runner.run( + Source(source.id).backfill(job, BackfillConfig(limit=2, page_size=1)) + ) + finally: + event.remove(Session, "after_flush", remember_second_page) + event.remove(Session, "before_commit", fail_second_commit) + + with TestSession() as db: + current = db.get(SourceModel, source.id) + assert current is not None + marker = current.state + db.delete(current) + db.commit() + assert flushed and commit_attempted + response = async_runner.run(query_archive(ArchiveQuery(posts=[first_id, second_id]))) + assert [item.status for item in response.posts] == ["found", "missing"] + committed = response.posts[0].data + assert committed is not None and committed.lang == "zh" + assert committed.text is not None and committed.text.text == "已归档的完整原文" + assert marker == {"latest_tweet_id": "42"} + assert job.state == { + "scanned": 1, + "saved": 1, + "pages": 1, + "exhausted": False, + "next_page": "a", + } + + def test_batch_lookup_tolerates_non_json_and_reports_locatable_corruption( - async_runner, native, tracked + async_runner, native ): batch = ArchiveBatch.model_validate(native) - async_runner.run(_write(batch, tracked)) + async_runner.run(submit_archive(batch)) unknown = str(int(batch.posts[0].id) + 1000) - broken = [ - seed_block(BlockForm(resolver="core.text.v1", content="ordinary non-JSON text")), - seed_block(BlockForm(resolver=POST_RESOLVER, content="broken JSON {")), - seed_block( - BlockForm( - resolver=POST_RESOLVER, - content=json.dumps({"id": unknown, "authorId": batch.posts[0].authorId}), - ) + for form in ( + BlockForm(resolver="core.text.v1", content="ordinary non-JSON text"), + BlockForm(resolver=POST_RESOLVER, content="broken JSON {"), + BlockForm( + resolver=POST_RESOLVER, + content=json.dumps({"id": unknown, "authorId": batch.posts[0].authorId}), ), - ] - tracked.update(block.id for block in broken) + ): + seed_block(form) response = async_runner.run( query_archive(ArchiveQuery(posts=[batch.posts[0].id, unknown])) ) assert [item.status for item in response.posts] == ["found", "failed"] -def test_media_metadata_roundtrips_without_content_blocks(async_runner, native, tracked): - base = int(native["media"][0]["id"]) + 1000 - records: list[dict[str, typing.Any]] = [ - {"id": str(base), "type": "photo", "url": "https://example.org/image.jpg"}, - { - "id": str(base + 1), - "type": "video", - "url": "https://pbs.twimg.com/poster.jpg", - "video": { - "variants": [ - {"url": "https://video.twimg.com/list.m3u8", "type": "application/x-mpegURL"} - ] - }, - }, - {"id": str(base + 2), "type": "photo", "url": "https://pbs.twimg.com/\nimage.jpg"}, - { - "id": str(base + 3), - "type": "video", - "url": "https://pbs.twimg.com/poster.jpg", - "video": { - "variants": [ - { - "url": f"https://video.twimg.com/{base}-low.mp4", - "type": "video/mp4", - "bitrate": 1, - }, - {"url": "https://example.org/foreign.mp4", "type": "video/mp4", "bitrate": 99}, - { - "url": f"https://video.twimg.com/{base}-high.mp4", - "type": "video/mp4", - "bitrate": 2, - }, - ] - }, - }, - ] - result = async_runner.run( - _write(ArchiveBatch.model_validate({"media": records}), tracked) - ) - response = async_runner.run( - query_archive(ArchiveQuery(media=[record["id"] for record in records])) - ) - assert [item.status for item in response.media] == ["found"] * 4 - assert [ - item.data.model_dump(mode="json", exclude_unset=True) for item in response.media - ] == records - with TestSession() as db: - content = db.exec( - sqlmodel.select(RelationModel).where( - sqlmodel.col(RelationModel.from_).in_(tuple(result.block_ids["media"].values())), - RelationModel.content == "content", - ) - ).all() - assert content == [] - - def test_representative_batch_keeps_database_round_trips_bounded( async_runner, native, tracked ): @@ -545,52 +513,24 @@ def count_round_trip(_connection, _cursor, statement, _parameters, _context, _ma event.listen(ASYNC_DB_ENGINE.sync_engine, "before_cursor_execute", count_round_trip) try: - result = async_runner.run(_write(ArchiveBatch.model_validate(raw), tracked)) + result = async_runner.run(submit_archive(ArchiveBatch.model_validate(raw))) finally: event.remove(ASYNC_DB_ENGINE.sync_engine, "before_cursor_execute", count_round_trip) - assert result.response.summary.accepted == 600 + assert result.summary.accepted == 600 # Keep the synchronous native batch bounded when Core and DB are remote. assert len(calls) < 20, {kind: calls.count(kind) for kind in set(calls)} - assert len(result.block_ids["posts"]) == 400 with TestSession() as db: - contents = db.exec( - sqlmodel.select(RelationModel).where( - sqlmodel.col(RelationModel.from_).in_(tuple(result.block_ids["media"].values())), - RelationModel.content == "content", - ) - ).all() - assert contents == [] - - -def test_official_provider_keeps_source_text_and_exact_id_semantics( - async_runner, native, tracked -): - root = native["posts"][0] - batch = _official_archive( - [ - { - "id": root["id"], - "author_id": root["authorId"], - "created_at": root["createdAt"], - "text": "@reply 原始🌏 & https://t.co/media", - "conversation_id": "1", - "referenced_tweets": [{"type": "replied_to", "id": "2"}], - } - ], - {}, - "2026-10-19T01:00:00Z", - ) - assert batch.posts[0].text is not None - assert batch.posts[0].text.text == "@reply 原始🌏 & https://t.co/media" - assert batch.posts[0].conversationId == "1" - assert batch.posts[0].replyTo is not None and batch.posts[0].replyTo.postId == "2" - result = async_runner.run(_write(batch, tracked)) - assert result.response.posts[0].status == "accepted" + by_resolver = dict( + db.exec( + sqlmodel.select(BlockModel.resolver, sqlmodel.func.count()) + .where(sqlmodel.col(BlockModel.id).in_(tracked)) + .group_by(BlockModel.resolver) + ).all() + ) + assert by_resolver == {POST_RESOLVER: 400, USER_RESOLVER: 200, MEDIA_RESOLVER: 200} -def test_twikit_bookmark_first_then_native_enrichment_keeps_one_root( - async_runner, native, tracked -): +def test_twikit_bookmark_first_then_native_enrichment_keeps_one_root(async_runner, native): post = native["posts"][0] media_id = native["media"][0]["id"] author = SimpleNamespace(id=post["authorId"], screen_name="source_handle", name="source") @@ -625,19 +565,14 @@ def test_twikit_bookmark_first_then_native_enrichment_keeps_one_root( } # Exercise the installed provider's real getters, including note-tweet selection. tweet = twikit.Tweet(mock.Mock(), raw, typing.cast(twikit.User, author)) - batch = _twikit_archive((tweet,), "2026-10-19T01:00:00Z") - assert batch.posts[0].authorId == author.id - assert batch.posts[0].replyTo is not None and batch.posts[0].text is not None - assert batch.posts[0].conversationId != batch.posts[0].replyTo.postId - assert batch.posts[0].text.text == "@mention 完整🌏 & https://t.co/source" - assert [media.id for media in batch.media] == [media_id] source_type = f"{Source.__module__}.{Source.__qualname__}" async_runner.run(SourceManager.sync_source_types_async({source_type: Source})) source = async_runner.run(SourceManager.create(source_type, nickname="Twikit first")) - provider = mock.Mock() - provider.get_bookmarks = mock.AsyncMock( - return_value=TwitterAPIResult(batch=batch, primary_post_ids=(post["id"],)) + sdk = SimpleNamespace( + _user_id=author.id, get_bookmarks=mock.AsyncMock(return_value=Result([tweet])) ) + with mock.patch.object(twikit, "Client", return_value=sdk): + provider = TwikitAPI("fixture@example.invalid", "collector", "fixture-password") try: with ( mock.patch.object( @@ -647,7 +582,7 @@ def test_twikit_bookmark_first_then_native_enrichment_keeps_one_root( HTTPStorage, "get_raw_content", new_callable=mock.AsyncMock, - side_effect=AssertionError("Bookmark indexing downloaded external media"), + side_effect=AssertionError("Bookmark collection downloaded external media"), ) as fetch, ): async_runner.run( @@ -656,30 +591,17 @@ def test_twikit_bookmark_first_then_native_enrichment_keeps_one_root( ) ) root = _record(post["id"]) - report = async_runner.run( - LexicalRetrievalManager.maintain( - LexicalMaintenanceOptions(max_records=1000, scan_page_size=50) - ) - ) - assert report.failed == 0, report.diagnostics - matches = async_runner.run(LexicalRetrievalManager.retrieve_local(post["id"])).matches - assert root.id in {match.block.id for match in matches} + stored = json.loads(root.content) + assert stored["authorId"] == author.id + assert stored["conversationId"] == raw["legacy"]["conversation_id_str"] + assert stored["replyTo"]["postId"] == raw["legacy"]["in_reply_to_status_id_str"] + assert stored["text"]["text"] == "@mention 完整🌏 & https://t.co/source" + assert stored["mediaIds"] == [media_id] assert fetch.await_count == 0 finally: - # Track native identities as well as the root created inside Source's UoW. - async def remember(): - async with graph_uow() as uow: - rows = await uow.blocks.find_json_field_many( - (POST_RESOLVER, USER_RESOLVER, MEDIA_RESOLVER), - "id", - (post["id"], author.id, raw["legacy"]["in_reply_to_status_id_str"], media_id), - ) - tracked.update(row.id for row in rows) - - async_runner.run(remember()) with TestSession() as db: db.delete(db.get(SourceModel, source.id)) db.commit() - enriched = async_runner.run(_write(ArchiveBatch.model_validate(native), tracked)) - assert enriched.block_ids["posts"][post["id"]] == root.id + async_runner.run(submit_archive(ArchiveBatch.model_validate(native))) + assert _record(post["id"]).id == root.id assert json.loads(_record(post["id"]).content)["text"] == post["text"] diff --git a/scripts/tests/twitter/integration/test_archive_http_roundtrip.py b/scripts/tests/twitter/integration/test_archive_http_roundtrip.py index e30a9b75..46318943 100644 --- a/scripts/tests/twitter/integration/test_archive_http_roundtrip.py +++ b/scripts/tests/twitter/integration/test_archive_http_roundtrip.py @@ -2,24 +2,19 @@ from __future__ import annotations -import asyncio import json import os -from pathlib import Path from types import SimpleNamespace -import uuid import pytest -import sqlalchemy import sqlmodel -from inkcre_core.persistence.info_base.uow import graph_uow from inkcre_core.business.peer import PeerManager from inkcre_core.business.source import SourceManager from inkcre_core.schemas.info_base.block import BlockModel from inkcre_core.schemas.info_base.relation import RelationModel from extensions.twitter.archive_session import SESSION_COOKIE_NAME, _issue_session_token -from extensions.twitter.reconcile import MEDIA_RESOLVER, POST_RESOLVER, USER_RESOLVER +from extensions.twitter.reconcile import POST_RESOLVER, USER_RESOLVER from tests.database import TestSession from tests.extensions.runtime_support import publish_extension @@ -29,108 +24,10 @@ ) -def _distinct_fixture() -> dict: - path = Path(__file__).parents[1] / "fixtures" / "native_archive.json" - value = json.loads(path.read_text()) - offset = int(uuid.uuid4().hex[:15], 16) + 10**20 - - def distinct(item): - if isinstance(item, str): - if item.isascii() and item.isdecimal(): - return str(int(item) + offset) - if item.startswith(("https://pbs.twimg.com/", "https://video.twimg.com/")): - return f"{item}{'&' if '?' in item else '?'}twitter_http_test={offset}" - if isinstance(item, list): - return [distinct(child) for child in item] - if isinstance(item, dict): - return {key: distinct(child) for key, child in item.items()} - return item - - return distinct(value) - - -def _archive_owned_ids( - native: dict, - *, - preexisting_ids: dict[str, set[str]] | None = None, -) -> dict[str, tuple[str, ...]]: - """Return submitted identities and only the absent references this batch creates.""" - resolvers = {"users": USER_RESOLVER, "posts": POST_RESOLVER, "media": MEDIA_RESOLVER} - defined = { - kind: {record["id"] for record in native[kind]} for kind in ("users", "posts", "media") - } - referenced = {kind: set() for kind in ("users", "posts", "media")} - for post in native["posts"]: - if "authorId" in post: - referenced["users"].add(post["authorId"]) - article = post.get("article") or {} - media_ids = list(post.get("mediaIds", ())) - if "coverMediaId" in article: - media_ids.append(article["coverMediaId"]) - media_ids.extend(article.get("mediaIds", ())) - referenced["media"].update(media_ids) - for field in ("replyTo", "quote"): - if field in post: - referenced["posts"].add(post[field]["postId"]) - if "repostOf" in post: - referenced["posts"].add(post["repostOf"]) - - existing = preexisting_ids or {} - return { - resolvers[kind]: tuple( - sorted((defined[kind] | referenced[kind]) - existing.get(resolvers[kind], set())) - ) - for kind in ("users", "posts", "media") - } - - -async def _cleanup_archive(owned_ids: dict[str, tuple[str, ...]]) -> None: - async with graph_uow() as uow: - roots = [] - for resolver, native_ids in owned_ids.items(): - if native_ids: - roots.extend(await uow.blocks.find_json_field_many((resolver,), "id", native_ids)) - tracked_ids = {block.id for block in roots if block.id is not None} - - if not tracked_ids: - return - with TestSession() as db: - for relation in db.exec( - sqlmodel.select(RelationModel).where( - sqlalchemy.or_( - sqlmodel.col(RelationModel.from_).in_(tracked_ids), - sqlmodel.col(RelationModel.to_).in_(tracked_ids), - ) - ) - ).all(): - db.delete(relation) - for block in db.exec( - sqlmodel.select(BlockModel).where(sqlmodel.col(BlockModel.id).in_(tracked_ids)) - ).all(): - db.delete(block) - db.commit() - async with graph_uow() as uow: - remaining = [] - for resolver, native_ids in owned_ids.items(): - if native_ids: - remaining.extend( - await uow.blocks.find_json_field_many((resolver,), "id", native_ids) - ) - if remaining: - raise AssertionError("cleanup left test-owned archive identities in PostgreSQL") - - -def test_real_http_submit_query_preserves_native_wire_payload(monkeypatch): +def test_real_http_submit_query_preserves_native_wire_payload(monkeypatch, native): from extensions.twitter import Extension - native = _distinct_fixture() - simple_post_id = str(int(uuid.uuid4().hex[:15], 16) + 10**30) - shared_author_id = str(int(simple_post_id) + 1) - owned_ids = _archive_owned_ids( - native, - preexisting_ids={USER_RESOLVER: {shared_author_id}}, - ) - owned_ids[POST_RESOLVER] = tuple(sorted((*owned_ids[POST_RESOLVER], simple_post_id))) + shared_author_id = native["users"][0]["id"] with TestSession() as db: shared_author = BlockModel( resolver=USER_RESOLVER, @@ -151,65 +48,75 @@ async def current_config(): monkeypatch.setattr(PeerManager, "get_current_config_async", current_config) token, _ = _issue_session_token() published = publish_extension(Extension) - shared_author_survived_cleanup = False try: with published.client as client: + session = client.get("/twitter/x-monkey/api/v1/session") + assert session.status_code == 200 + assert session.json() == { + "authenticated": False, + "registered": False, + "username": None, + "expires_at": None, + "account_url": "https://core.example/twitter/x-monkey/account", + } client.cookies.set(SESSION_COOKIE_NAME, token) + assert client.get("/twitter/setup").status_code == 401 headers = {"Origin": "https://x.com", "X-Tweet-DB-Client": "x-monkey"} - simple_post = { - "id": simple_post_id, - "authorId": shared_author_id, - "createdAt": "2026-10-19T12:00:00Z", - "text": {"text": "HTTP to PostgreSQL round trip"}, - } - simple_submit = client.post( + empty = client.post( "/twitter/x-monkey/api/v1/archive/submit", - json={"posts": [simple_post]}, - headers=headers, - ) - assert simple_submit.status_code == 200, simple_submit.text - with TestSession() as db: - simple_root = next( - block - for block in db.exec( - sqlmodel.select(BlockModel).where(BlockModel.resolver == POST_RESOLVER) - ).all() - if json.loads(block.content).get("id") == simple_post_id - ) - assert simple_root.id is not None - assert ( - db.exec( - sqlmodel.select(RelationModel).where( - sqlmodel.col(RelationModel.from_) == simple_root.id, - sqlmodel.col(RelationModel.to_) == shared_author_block_id, - ) - ).first() - is not None - ) - simple_query = client.post( - "/twitter/x-monkey/api/v1/archive/query", - json={"posts": [simple_post_id]}, - headers=headers, + json={"posts": []}, + headers={**headers, "Origin": "chrome-extension://abcdefghijklmnop"}, ) - assert simple_query.status_code == 200, simple_query.text - assert simple_query.json()["posts"] == [ - {"id": simple_post_id, "status": "found", "data": simple_post} - ] - + assert empty.status_code == 200, empty.text + assert empty.json() == { + "summary": {"accepted": 0, "unchanged": 0, "partial": 0, "failed": 0, "total": 0}, + "users": [], + "posts": [], + "media": [], + } submitted = client.post( "/twitter/x-monkey/api/v1/archive/submit", json=native, headers=headers, ) assert submitted.status_code == 200, submitted.text - assert submitted.json()["summary"]["total"] == sum( - len(native[kind]) for kind in ("users", "posts", "media") + assert submitted.json()["summary"] == { + "total": 3, + "accepted": 3, + "unchanged": 0, + "partial": 0, + "failed": 0, + } + with TestSession() as db: + citing_post = db.exec( + sqlmodel.select(BlockModel) + .join(RelationModel, sqlmodel.col(RelationModel.from_) == BlockModel.id) + .where( + RelationModel.to_ == shared_author_block_id, + BlockModel.resolver == POST_RESOLVER, + ) + ).one() + assert json.loads(citing_post.content)["id"] == native["posts"][0]["id"] + + replay = client.post( + "/twitter/x-monkey/api/v1/archive/submit", json=native, headers=headers ) - - query = { - kind: [record["id"] for record in native[kind]] - for kind in ("users", "posts", "media") + assert replay.status_code == 200, replay.text + assert replay.json()["summary"] == { + "total": 3, + "accepted": 0, + "unchanged": 3, + "partial": 0, + "failed": 0, } + for kind in ("users", "posts", "media"): + item_id = native[kind][0]["id"] + assert submitted.json()[kind] == [{"id": item_id, "status": "accepted"}] + assert replay.json()[kind] == [{"id": item_id, "status": "unchanged"}] + + query = {kind: [native[kind][0]["id"]] for kind in ("users", "posts", "media")} + missing_id = str(int(native["posts"][0]["id"]) + 1000) + query["posts"].insert(0, missing_id) queried = client.post( "/twitter/x-monkey/api/v1/archive/query", json=query, @@ -217,16 +124,10 @@ async def current_config(): ) assert queried.status_code == 200, queried.text response = queried.json() + assert response["posts"].pop(0) == {"id": missing_id, "status": "missing"} for kind in ("users", "posts", "media"): - assert [item["status"] for item in response[kind]] == ["found"] * len(native[kind]) - assert [item["data"] for item in response[kind]] == native[kind] + assert response[kind] == [ + {"id": record["id"], "status": "found", "data": record} for record in native[kind] + ] finally: published.unpublish() - asyncio.run(_cleanup_archive(owned_ids)) - with TestSession() as db: - shared_author_after_cleanup = db.get(BlockModel, shared_author_block_id) - shared_author_survived_cleanup = shared_author_after_cleanup is not None - if shared_author_after_cleanup is not None: - db.delete(shared_author_after_cleanup) - db.commit() - assert shared_author_survived_cleanup, "cleanup removed a preexisting author identity" diff --git a/scripts/tests/twitter/test_archive_contract.py b/scripts/tests/twitter/test_archive_contract.py index 43e7d20b..e88b78a2 100644 --- a/scripts/tests/twitter/test_archive_contract.py +++ b/scripts/tests/twitter/test_archive_contract.py @@ -15,18 +15,9 @@ ArchiveBatch, ArchivePost, ArchiveQuery, - QueryResponse, - SessionResponse, - SubmitResponse, ) from extensions.twitter.model import RichText, TwitterBatch, TwitterPost -from extensions.twitter.reconcile import TwitterReadResult, TwitterWriteResult -from extensions.twitter.x_monkey import ( - decode_submission, - encode_query, - encode_submission, - export_record, -) +from extensions.twitter.x_monkey import export_record @pytest.fixture @@ -35,63 +26,10 @@ def full_archive() -> dict[str, Any]: return json.loads(fixture_path.read_text(encoding="utf-8")) -def test_native_batch_preserves_complete_source_and_field_presence(full_archive): - original = copy.deepcopy(full_archive) - batch = ArchiveBatch.model_validate(full_archive) - assert batch.model_dump(mode="json", exclude_unset=True) == original - assert json.loads(batch.model_dump_json(exclude_unset=True)) == original - assert full_archive == original - assert batch.posts[0].communityNote is not None - assert batch.posts[0].communityNote.text.model_dump(exclude_unset=True) == { - "text": "来源已核实" - } - - -def test_missing_and_explicit_empty_batches_remain_distinct(): - batch = ArchiveBatch.model_validate({}) - query = ArchiveQuery.model_validate({}) - assert batch.users == batch.posts == batch.media == [] - assert query.users == query.posts == query.media == [] - assert batch.model_dump(mode="json", exclude_unset=True) == {} - assert query.model_dump(mode="json", exclude_unset=True) == {} - assert ArchiveBatch(posts=[]).model_dump(mode="json", exclude_unset=True) == {"posts": []} - - -def test_fixed_protocol_roundtrips_through_owned_facts_and_neutral_results(full_archive): - wire = ArchiveBatch.model_validate(full_archive) - native = decode_submission(wire) - assert type(native) is TwitterBatch - assert type(native.posts[0]) is TwitterPost - assert native.model_dump(mode="json", exclude_unset=True) == full_archive - records = { - (kind, record.id): record - for kind in ("users", "posts", "media") - for record in getattr(native, kind) - } - query = ArchiveQuery(users=["17"], posts=["31", "32", "33"], media=["41"]) - response = encode_query( - query, - TwitterReadResult(records=records, invalid=frozenset({("posts", "33")})), - ) - for kind in ("users", "posts", "media"): - assert ( - getattr(response, kind)[0].data.model_dump(mode="json", exclude_unset=True) - == (full_archive[kind][0]) - ) - assert [item.status for item in response.posts] == ["found", "missing", "failed"] - submitted = encode_submission( - wire, TwitterWriteResult(changed=frozenset(records), block_ids={}) - ) - assert submitted.summary.accepted == submitted.summary.total == 3 - replayed = encode_submission(wire, TwitterWriteResult(changed=frozenset(), block_ids={})) - assert replayed.summary.unchanged == 3 - - -def test_capture_batch_does_not_inherit_remote_request_limits(full_archive): - records = {"posts": [full_archive["posts"][0]] * 1001} +def test_capture_batch_does_not_inherit_remote_request_limits(): + post = {"id": "31", "authorId": "17", "createdAt": "2026-10-19T00:00:00Z"} + records = {"posts": [post] * 1001} assert len(TwitterBatch.model_validate(records).posts) == 1001 - with pytest.raises(pydantic.ValidationError): - ArchiveBatch.model_validate(records) def test_fixed_export_projects_additive_native_fields_and_retains_open_json(full_archive): @@ -111,16 +49,26 @@ class ExtendedPost(TwitterPost): exported = export_record("posts", native) assert exported == full_archive["posts"][0] assert native.model_dump(mode="json", exclude_unset=True) == post - with pytest.raises(pydantic.ValidationError): + with pytest.raises(pydantic.ValidationError) as rejected: ArchivePost.model_validate(post) + assert {(error["loc"], error["type"]) for error in rejected.value.errors()} == { + (("readingHint",), "extra_forbidden"), + (("text", "readingHint"), "extra_forbidden"), + } @pytest.mark.parametrize( "invalid_id", ["0", "01", "-1", "1.0", " 1", "1\n", "11", 1, True] ) def test_ids_are_positive_decimal_strings(invalid_id): - with pytest.raises(pydantic.ValidationError): + with pytest.raises(pydantic.ValidationError) as rejected: ArchiveQuery.model_validate({"posts": [invalid_id]}) + assert [(error["loc"], error["type"]) for error in rejected.value.errors()] == [ + ( + ("posts", 0), + "string_pattern_mismatch" if isinstance(invalid_id, str) else "string_type", + ) + ] @pytest.mark.parametrize( @@ -131,6 +79,7 @@ def test_ids_are_positive_decimal_strings(invalid_id): (("users", 0, "counts", "likes"), 1.0), (("users", 0, "counts", "likes"), "1"), (("posts", 0, "createdAt"), "2026-02-29T00:00:00Z"), + (("posts", 0, "createdAt"), None), (("posts", 0, "createdAt"), "2026-10-19T00:00:00.123Z"), (("posts", 0, "createdAt"), "2026-10-19T00:00:00+00:00"), (("posts", 0, "countsObservedAt", "likes"), "2026-10-19T24:00:00Z"), @@ -163,50 +112,32 @@ def test_invalid_native_records_fail_instead_of_coercing_or_discarding( for part in path[:-1]: current = current[part] current[path[-1]] = invalid - with pytest.raises(pydantic.ValidationError): + with pytest.raises(pydantic.ValidationError) as rejected: ArchiveBatch.model_validate(full_archive) + assert all(error["loc"][: len(path)] == path for error in rejected.value.errors()) -@pytest.mark.parametrize("kind", ["users", "posts", "media"]) -def test_query_and_submission_have_per_kind_limits(full_archive, kind): +@pytest.mark.parametrize( + "kind,record", + [ + ("users", {"id": "17", "handle": "author", "name": "Author"}), + ("posts", {"id": "31", "authorId": "17", "createdAt": "2026-10-19T00:00:00Z"}), + ("media", {"id": "41", "type": "photo", "url": "https://example.org/photo"}), + ], +) +def test_query_and_submission_have_per_kind_limits(kind, record): assert len(getattr(ArchiveQuery.model_validate({kind: ["1"] * 1000}), kind)) == 1000 - with pytest.raises(pydantic.ValidationError): + with pytest.raises(pydantic.ValidationError) as rejected_query: ArchiveQuery.model_validate({kind: ["1"] * 1001}) - record = full_archive[kind][0] + assert [(error["loc"], error["type"]) for error in rejected_query.value.errors()] == [ + ((kind,), "too_long") + ] assert len(getattr(ArchiveBatch.model_validate({kind: [record] * 1000}), kind)) == 1000 - with pytest.raises(pydantic.ValidationError): + with pytest.raises(pydantic.ValidationError) as rejected_batch: ArchiveBatch.model_validate({kind: [record] * 1001}) - - -def test_query_submit_and_session_wire_roundtrip(full_archive): - query = { - "users": [{"id": "17", "status": "found", "data": full_archive["users"][0]}], - "posts": [{"id": "31", "status": "missing"}], - "media": [{"id": "41", "status": "failed", "error": "invalid stored archive"}], - } - assert ( - QueryResponse.model_validate(query).model_dump(mode="json", exclude_unset=True) == query - ) - submission = { - "summary": {"total": 4, "accepted": 1, "unchanged": 1, "partial": 1, "failed": 1}, - "users": [{"id": "17", "status": "accepted"}], - "posts": [{"id": "31", "status": "unchanged"}, {"id": "32", "status": "partial"}], - "media": [{"id": "41", "status": "failed", "reason": "invalid media"}], - } - assert ( - SubmitResponse.model_validate(submission).model_dump(mode="json", exclude_unset=True) - == submission - ) - session = { - "authenticated": False, - "registered": False, - "username": None, - "expires_at": None, - "account_url": None, - } - assert SessionResponse.model_validate(session).model_dump(mode="json") == session - with pytest.raises(pydantic.ValidationError): - ArchivePost.model_validate({"id": "31", "authorId": "17", "createdAt": None}) + assert [(error["loc"], error["type"]) for error in rejected_batch.value.errors()] == [ + ((kind,), "too_long") + ] def test_merge_is_recursive_replaces_arrays_and_does_not_mutate_inputs(): @@ -262,6 +193,10 @@ def test_counter_observations_merge_independently_and_compare_instants(): "quotes": "2026-10-19T01:00:00Z", }, } + assert ( + merge_archive_record(existing, {"countsObservedAt": {"likes": "2026-10-20T00:00:00Z"}}) + == existing + ) def test_untimed_changes_remove_only_the_changed_counters_previous_time(): @@ -278,25 +213,6 @@ def test_untimed_changes_remove_only_the_changed_counters_previous_time(): } -def test_equal_counts_keep_new_observation_metadata_and_replay_is_unchanged(): - existing: dict[str, Any] = { - "counts": {"likes": 10}, - "countsObservedAt": {"likes": "2026-10-19T01:00:00Z"}, - } - incoming: dict[str, Any] = { - "counts": {"likes": 10}, - "countsObservedAt": {"likes": "2026-10-19T01:00:00.001Z"}, - } - merged = merge_archive_record(existing, incoming) - assert merged == incoming - assert merged != existing - assert merge_archive_record(merged, incoming) == merged - assert ( - merge_archive_record(existing, {"countsObservedAt": incoming["countsObservedAt"]}) - == existing - ) - - def test_capture_time_comparison_matches_javascript_millisecond_precision(): existing: dict[str, Any] = { "counts": {"likes": 10}, diff --git a/scripts/tests/twitter/test_archive_http.py b/scripts/tests/twitter/test_archive_http.py index c0703579..d997404d 100644 --- a/scripts/tests/twitter/test_archive_http.py +++ b/scripts/tests/twitter/test_archive_http.py @@ -5,6 +5,7 @@ import time from types import SimpleNamespace +from bs4 import BeautifulSoup from fastapi import FastAPI from fastapi.testclient import TestClient import jwt @@ -15,8 +16,6 @@ from app.middleware import create_peer_jwt from app.settings import Settings, settings from extensions.twitter import archive_http, archive_session -from extensions.twitter.archive_schema import QueryResponse, SubmitResponse, SubmitSummary -from tests.extensions.runtime_support import publish_extension @pytest.fixture @@ -31,8 +30,12 @@ async def current_config(): return TestClient(app, base_url="https://core.example") -def _session_cookie() -> str: +def _session_cookie(*, expires_at: int | None = None) -> str: token, _ = archive_session._issue_session_token() + if expires_at is not None: + claims = jwt.decode(token, options={"verify_signature": False}) + claims["exp"] = expires_at + token = jwt.encode(claims, settings.jwt_secret, algorithm=JWT_ALGORITHM) return token @@ -72,14 +75,28 @@ def test_connect_exchanges_same_origin_bearer_for_scoped_cookie(archive_client): assert "Path=/prefix/twitter/x-monkey/" in cookie readback = archive_client.get( "/twitter/x-monkey/api/v1/session", - headers={"Cookie": cookie.split(";", 1)[0]}, + headers={ + "Origin": "chrome-extension://abcdefghijklmnop", + "Cookie": cookie.split(";", 1)[0], + "Sec-Fetch-Mode": "cors", + }, ) assert readback.status_code == 200 assert readback.json()["authenticated"] is True + assert ( + readback.json()["account_url"] == "https://core.example/prefix/twitter/x-monkey/account" + ) + assert "nosniff" in readback.headers["x-content-type-options"] + assert "set-cookie" not in readback.headers def test_session_exchange_rejects_non_peer_or_cross_origin_credentials(archive_client): session_cookie = _session_cookie() + valid_session = archive_client.get( + "/twitter/x-monkey/api/v1/session", + headers={"Cookie": f"{archive_session.SESSION_COOKIE_NAME}={session_cookie}"}, + ) + assert valid_session.json()["authenticated"] is True missing_bearer = archive_client.post( "/twitter/x-monkey/session", json={}, @@ -99,6 +116,7 @@ def test_session_exchange_rejects_non_peer_or_cross_origin_credentials(archive_c }, ) assert session_as_bearer.status_code == 401 + assert session_as_bearer.json() == {"error": "ordinary Peer credential required"} foreign_origin = archive_client.post( "/twitter/x-monkey/session", @@ -109,90 +127,73 @@ def test_session_exchange_rejects_non_peer_or_cross_origin_credentials(archive_c }, ) assert foreign_origin.status_code == 403 + assert foreign_origin.json() == {"error": "same-origin request required"} -def test_account_page_uses_nonce_csp_and_only_same_origin_webcrypto(archive_client): +def test_account_page_scopes_scripts_and_connections_with_nonce_csp(archive_client): response = archive_client.get("/twitter/x-monkey/account") assert response.status_code == 200 - assert 'id="jwt-secret" type="password"' in response.text - assert "JWT_SECRET" in response.text - assert '

尚未连接。

' in response.text - assert "status.textContent = 'Connected'" in response.text - assert "crypto.subtle" in response.text - assert "exp: now + 60" in response.text - assert "fetch('./session'" in response.text - assert "fetch('./api/v1/session'" in response.text - assert "localStorage" not in response.text and "sessionStorage" not in response.text + page = BeautifulSoup(response.text, "html.parser") + assert page.find("input", type="password") is not None + assert "尚未连接。" in page.get_text() csp = response.headers["content-security-policy"] - nonce = response.text.split('