diff --git a/.env.example b/.env.example index e8a5de9a0b..9a9aeac4e2 100644 --- a/.env.example +++ b/.env.example @@ -29,7 +29,7 @@ POWERCONTEXT_SERVER_ACCESS_MODE=disabled # POWERCONTEXT_SERVER_AUTH_ENABLED=true # POWERCONTEXT_SERVER_AUTH_TOKEN=replace-me POWERCONTEXT_SERVER_ACCESS_DEPLOYMENT_ID=powercontext -# Multi-user deployments with scheduled jobs must bind an explicit service Principal. +# Multi-user deployments with background capabilities must bind an explicit service Principal. # POWERCONTEXT_SERVER_ACCESS_BACKGROUND_PRINCIPAL_ID=service:scheduled-processing # POWERCONTEXT_SERVER_ACCESS_BACKGROUND_PRINCIPAL_DESCRIPTION=Scheduled processing @@ -69,15 +69,23 @@ POWERCONTEXT_SERVER_DATABASE_KIND=sqlite # Runtime --------------------------------------------------------------------- POWERCONTEXT_SERVER_RUNTIME_SOURCE_WINDOW_LIMIT=100 POWERCONTEXT_SERVER_RUNTIME_MEMORY_EXTRACTION_PROFILE=coding -POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS=60 +POWERCONTEXT_SERVER_RUNTIME_MEMORY_SCHEDULE_SECONDS=60 POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SCHEDULE_SECONDS=60 POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SOURCE_WINDOW_LIMIT=10 POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MAX_CANDIDATES=20 POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_RRF_THRESHOLD=70 POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MIN_CANDIDATES=5 -POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_MAX_WORKERS=10 -POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_WORKER_TIMEOUT_SECONDS=600 +POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_MAX_WORKERS=10 +POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_WORKER_TIMEOUT_SECONDS=600 POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_ROLE=all +POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_SUPERVISOR_MODE=global +# Each Family owns its quota; dedicated creates one controller per Family. +# POWERCONTEXT_SERVER_RUNTIME_MEMORY_MAX_WORKERS=1 +# POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_MAX_WORKERS=1 +# POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_WORKERS=4 +# All migrated Families default to a 600-second total Scope invocation timeout. +# Old SCHEDULE_SECONDS, PROFILE_MAX_CONCURRENCY, and ARTIFACT_PROCESSING_MAX_WORKERS/ +# WORKER_TIMEOUT_SECONDS remain aliases; conflicting old/new values fail startup. # Optional generation-backed jobs. Enable only when their extra model cost is intended. # POWERCONTEXT_SERVER_RUNTIME_MEMORY_RERANK_ENABLED=true diff --git a/.gitignore b/.gitignore index b8e2ed20ff..e7d8d3e518 100644 --- a/.gitignore +++ b/.gitignore @@ -249,3 +249,6 @@ integrations/pi/*.tgz integrations/pi/plugins/powercontext/node_modules/ integrations/pi/plugins/powercontext/coverage/ integrations/pi/plugins/powercontext/*.tgz + +# Local acceptance databases and redacted run artifacts +.artifacts/ diff --git a/docs/en/docs/get-started/configure-models.md b/docs/en/docs/get-started/configure-models.md index dd6f3339ff..e97eb8a22a 100644 --- a/docs/en/docs/get-started/configure-models.md +++ b/docs/en/docs/get-started/configure-models.md @@ -137,7 +137,7 @@ After verifying the Server, follow the [guide for your Agent](../integrations/in ## Data and restart behavior -With no database override, SQLite stores `powercontext.db` and `scheduler.db` under the user data directory: +With no database override, SQLite stores `powercontext.db` under the user data directory: - Linux: `$XDG_DATA_HOME/powercontext`, or `~/.local/share/powercontext`; - macOS: `~/Library/Application Support/powercontext`; diff --git a/docs/en/docs/operate/artifact-processing-migration.md b/docs/en/docs/operate/artifact-processing-migration.md new file mode 100644 index 0000000000..a80bb95686 --- /dev/null +++ b/docs/en/docs/operate/artifact-processing-migration.md @@ -0,0 +1,75 @@ +--- +title: Migrate Artifact processing state +--- + +Existing Topic Memory processing databases need explicit maintenance before +starting the Scope-based Artifact Processing Supervisor. A new, empty database +is initialized automatically. An existing database with no completed migration +marker is rejected before background processing starts. + +## Plan and apply + +Inspect the plan with the deployment configuration that will run after migration: + +```shell +powercontext server processing-migrate --action plan --env-file .env +``` + +Back up the database. Stop every old background candidate and its Workers, +disable their automatic restart, and pause input writes and explicit triggers. +The command cannot establish those external conditions for you. Then run: + +```shell +powercontext server processing-migrate --action apply --env-file .env \ + --migration-id rfc1515 --batch-size 100 --maintenance-confirmed +powercontext server processing-migrate --action verify --env-file .env +``` + +`apply` commits each bounded step separately. If it stops, repeat it with the +same migration ID and configuration. Do not clear the migration marker, receipts +or old automatic targets to restart it. A receipt and its intent/Topic target +updates commit together, so repeating a committed page does not increment the +request counter again. MySQL schema changes are individually checked on resume; +the presence of an added column alone does not mark the data migration complete. + +Only resume API writes and background processes after verification reports +`ready: true`. Keep all replicas on the same mode and binding/Family mapping. +Ordinary startup rejects incomplete migration and an incompatible deployment +manifest. Changing a schedule, Worker budget or timeout does not require a mode +migration. + +## Preserved state + +The migration keeps Topic Pending, Source Cursor values and CAS generations, +evidence and publication data. Uncovered Sources become ordinary dirty state; +unconfirmed flushes and unfinished automatic targets become accepted calls. +Topic's frozen input target remains in its own table. A later ordinary Source +does not extend a known old automatic target. + +The old implementation could start catch-up calls outside an automatic wave and +finish that wave while those calls were still running. Consequently, the absence +of a wave row cannot prove that a dirty Scope was never admitted. When no frozen +target establishes the boundary, migration conservatively retains a pending +Topic Scope as an accepted invocation. Its processor resumes from the Cursor. +Closing the new automatic schedule does not cancel that recovery responsibility. +Sources with no old Pending are calibrated as ordinary dirty, without accepting +new business actions. + +The old automatic completion timestamp is retained as the new scheduling +checkpoint; migration does not restart the remaining interval from the current +time. Old automatic rows are cleared only after their durable replacement and +Cursor consistency have been verified. The obsolete table and migration receipts +remain available; the runtime no longer treats that table as an active queue. + +## Switch between global and dedicated + +Use the same coordinated shutdown and write pause. Select the new mode in every +replica's configuration, plan the change, then apply it with a **new migration +ID**, for example `global-to-dedicated-1`. Switching back also needs a new ID. +The migration advances and invalidates all old Lease generations before startup +under the new mode. It preserves request counters, dirty markers, Topic targets, +Cursor values and schedule checkpoints. It does not replay the legacy import. + +SQLite and embedded SeekDB keep their single-host `all` role in either mode. +Changing mode does not enable split-process deployment for those backends. A +rolling deployment mixing the two modes is unsupported. diff --git a/docs/en/docs/operate/configuration.md b/docs/en/docs/operate/configuration.md index 136db3157c..3e89de42cc 100644 --- a/docs/en/docs/operate/configuration.md +++ b/docs/en/docs/operate/configuration.md @@ -34,8 +34,8 @@ Without an override, the default is: - macOS: `~/Library/Application Support/powercontext`; - Windows: `%LOCALAPPDATA%\\powercontext`. -The default SQLite database is `powercontext.db` in this directory. Scheduled processing uses `scheduler.db` in the -same directory. +The default SQLite database is `powercontext.db` in this directory. The four built-in background processors persist +intents and scheduling checkpoints in the same database. Existing installations require [offline migration](artifact-processing-migration.md). ## Server @@ -73,15 +73,23 @@ Server settings use the `POWERCONTEXT_SERVER_` prefix. | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_EXTRACTION_PROFILE` | `coding` | Memory selection policy: `coding` or `conversation` | | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_RERANK_ENABLED` | `false` | Apply listwise reranking after coarse Memory retrieval | | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_RERANK_CANDIDATE_LIMIT` | `30` | Coarse candidate pool supplied to the reranker | -| `POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS` | unset | Scheduler interval; unset disables scheduling | -| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SCHEDULE_SECONDS` | unset | Per-binding Topic Memory automatic-wave interval; unset disables automatic waves | -| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SOURCE_WINDOW_LIMIT` | `10` | Maximum Sources assigned to one Topic Memory Worker, capped at 100 | +| `POWERCONTEXT_SERVER_RUNTIME_MEMORY_SCHEDULE_SECONDS` | unset | Memory automatic admission interval; `SCHEDULE_SECONDS` remains a compatibility alias | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SCHEDULE_SECONDS` | unset | Topic Memory automatic admission interval; unset disables new automatic admission | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SOURCE_WINDOW_LIMIT` | `10` | Maximum Sources per Topic Memory Window, capped at 100; one Scope invocation can finish several Windows | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MAX_CANDIDATES` | `20` | Maximum historical Topic candidates considered while processing | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_RRF_THRESHOLD` | `70` | RRF acceptance threshold normalized to `0..100` | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MIN_CANDIDATES` | `5` | Minimum historical recall count when the threshold returns too few candidates | -| `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_MAX_WORKERS` | `10` | Global child-Worker concurrency across Artifact bindings | -| `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_WORKER_TIMEOUT_SECONDS` | `600` | Supervisor timeout for one child Worker's bounded Source Window | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_MAX_WORKERS` | `10` | Topic Worker quota; `ARTIFACT_PROCESSING_MAX_WORKERS` is its compatibility alias | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_WORKER_TIMEOUT_SECONDS` | `600` | Total Scope invocation timeout, including child startup; old `ARTIFACT_PROCESSING_WORKER_TIMEOUT_SECONDS` is its alias | | `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_ROLE` | `all` | Process role: `all`, `api`, or `background` | +| `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_SUPERVISOR_MODE` | `global` | `global` owns one Lease; `dedicated` owns one Lease per registered Family | +| `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_FAMILIES` | inferred from models | JSON Family list; API-only instances can declare capabilities without model credentials | +| `POWERCONTEXT_SERVER_RUNTIME_MEMORY_MAX_WORKERS` | `1` | Independent Memory Worker quota | +| `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_MAX_WORKERS` | `1` | Independent Experience Worker quota | +| `POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_WORKERS` | `4` | Independent Profile Worker quota; alias `PROFILE_MAX_CONCURRENCY` | +| `POWERCONTEXT_SERVER_RUNTIME_MEMORY_WORKER_TIMEOUT_SECONDS` | `600` | Total Memory Scope timeout | +| `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_WORKER_TIMEOUT_SECONDS` | `600` | Total Experience Scope timeout | +| `POWERCONTEXT_SERVER_RUNTIME_PROFILE_WORKER_TIMEOUT_SECONDS` | `600` | Total Profile Scope timeout | | `POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL` | unset | Pydantic AI model used by configured extraction, generation, Handoff, and reranking operations | | `POWERCONTEXT_SERVER_INFERENCE_GENERATION_BASE_URL` | provider default | Custom generation provider base URL | | `POWERCONTEXT_SERVER_INFERENCE_GENERATION_HEADERS` | `{}` | JSON object of static generation client headers; values are secrets | @@ -104,7 +112,7 @@ Server settings use the `POWERCONTEXT_SERVER_` prefix. | `POWERCONTEXT_SERVER_INFERENCE_RERANK_MODEL_SETTINGS` | `{}` | JSON object of Pydantic AI reranker model settings | | `POWERCONTEXT_SERVER_INFERENCE_RERANK_TIMEOUT_SECONDS` | generation timeout | LLM reranker timeout | | `POWERCONTEXT_SERVER_INFERENCE_RERANK_MAX_REQUESTS` | generation request limit | Maximum model requests in one rerank operation | -| `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_SCHEDULE_SECONDS` | unset | Experience incubation interval; unset disables that job | +| `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_SCHEDULE_SECONDS` | unset | Experience automatic admission interval; unset preserves accepted work and stops new automatic admission | | `POWERCONTEXT_SERVER_EXTERNAL_SKILLS` | automatic local project targets | JSON override containing the host identity and explicit Agent Skill targets | Topic Workers enforce a durable allowance per unadvanced Scope Cursor: 3 attempts, 512 reserved provider requests, @@ -151,10 +159,24 @@ built-in static token always represents one service Principal, so it cannot dist compatibility token materializes explicit Server and per-scope roles for that Principal. Inject the deployment Authentication Provider and corresponding AccessControlService when different users or groups need different access. -Scheduled Source processing and Experience incubation run as the fixed static Principal, or as the service Principal -selected by `ACCESS_BACKGROUND_PRINCIPAL_ID`. That Principal must have `scope.contribute` for each processed scope; -new Memory entries and Candidates retain it as their direct proposed owner. An enforced multi-user deployment that -configures a schedule without this explicit Principal fails at startup. +Background Memory, Topic Memory, Experience, and Profile processing use the service Principal selected by +`ACCESS_BACKGROUND_PRINCIPAL_ID`, falling back to the fixed static Principal. That Principal must have +`scope.contribute` for each processed scope and write permission on existing Artifacts it changes. New entries, +Artifacts, and Candidates retain its ownership or owner attestation in the same transaction as processing completion. +An enforced deployment with background capabilities fails startup if its identity or authorization provider cannot +be reconstructed in a child process, even when automatic schedules are disabled: accepted work still needs recovery. +The built-in provider supports this reconstruction. Injected providers and model objects remain usable by synchronous +SDK/Server operations with background capabilities disabled (`ARTIFACT_PROCESSING_FAMILIES=[]`). + +SDK workers without a Server identity do not require Server authorization dependencies. Built-in background workers +use the built-in Source definitions. A custom Source registry requires custom processing bindings for every enabled +family, or disabling built-in background families with `ARTIFACT_PROCESSING_FAMILIES=[]`; otherwise startup fails +before accepting work. Turning off schedules alone is insufficient because explicit requests still start workers. +Custom Source registries remain available to synchronous SDK contexts and API-only composition. + +The authenticated `/metrics` endpoint exposes `powercontext_server_artifact_processing_*` observations with only a `family` +label: Worker capacity, ready/retry queues, unacknowledged Scopes, discovery and invocation duration, completions, +failures, and timeouts. Unacknowledged counts reflect the latest discovery; counters reset with the Supervisor instance. Remote, multi-user, and shared-Dashboard deployments must use `enforced`. In that mode, HTTP, MCP, Dashboard data routes, and metrics share one Server PEP. Configured Dashboard scopes are filtered by the current Principal's @@ -248,10 +270,18 @@ only the single-process `all` role. Automatic Topic Memory waves remain disabled explicit flush work remains recoverable regardless of that interval. Topic workers need file-backed SQLite: configuring a generation model with an in-memory SQLite database is rejected before processing is advertised. Use a persistent `POWERCONTEXT_SERVER_DATABASE_URL`, such as `sqlite+aiosqlite:////srv/powercontext/runtime.db`. -Memory, Experience, and Profile APScheduler jobs belong exclusively to `all`: configuring -`POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS`, `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_SCHEDULE_SECONDS`, or enabling -`POWERCONTEXT_SERVER_RUNTIME_PROFILE_SCHEDULE_ENABLED` with either split role is rejected at startup. Keep `all` -when those jobs are required; assigning them to a separate process is outside the current split-role contract. +Memory, Topic Memory, Experience, and Profile all use the Supervisor. OceanBase permits their schedules in split roles. +SQLite and embedded seekDB retain one `all` host. Every Family has its own quota and timeout in both modes; spare quota +is not shared. Disabling automatic admission preserves already accepted requests. The API and background instances must +agree on mode, registered Families and trigger capabilities. Model resources are only required by workers. Changing modes +requires [coordinated offline migration](artifact-processing-migration.md); mixed modes cannot start. +Conflicting explicit old/new configuration aliases fail startup; equal values are accepted. + +Normal Runtime startup initializes and recovers the configured search indexes. Topic Workers reuse that database +without rebuilding the unrelated Memory/Experience search projections for each Window; Topic index validation and +publication guards still apply. If an empty database is reconfigured to another Topic retrieval shape or embedding +profile, reopen existing Runtimes with the same configuration: stale Runtimes reject Topic search, exact get, and +current-head browsing with a retrieval-shape error instead of reading another vector space. Normal Runtime startup initializes and recovers the configured search indexes. Topic Workers reuse that database without rebuilding the unrelated Memory/Experience search projections for each Window; Topic index validation and @@ -299,12 +329,12 @@ and stores the canonical package bytes, then creates a pending Candidate with th generation model, semantic generation returns a capability error before persisting a Candidate; Review, package inspection and download, exact import, usage recording, and external Skill scan/list/resolve continue to work. -Experience incubation is a separate APScheduler job with its own persisted Source cursor. Each activation inspects a -fixed window of at most 32 Sources and exposes only Content Sources whose metadata contains +Experience incubation has its own Supervisor binding and persisted Source cursor. Each invocation inspects a +finite window controlled by `SOURCE_WINDOW_LIMIT` and exposes only Content Sources whose metadata contains `"kind": "task-outcome"` to the model. It creates pending Experience Candidates in the Review Inbox; it does not approve them, place them in PreparedContext, create a managed Skill, export it to an Agent target, or execute anything. -The Memory and Experience jobs share the APScheduler sidecar under `POWERCONTEXT_HOME`, but keep independent job -identities and business cursors. Unsetting one interval removes only that job. +Memory and Experience keep independent scheduling intervals, Worker quotas, and business cursors. Unsetting an interval +stops new automatic admission for that Family while preserving accepted work. See [Create and review an Experience](../workflows/create-and-review-experience.md) for setup and verification steps. ### Agent Skill targets diff --git a/docs/en/docs/operate/index.md b/docs/en/docs/operate/index.md index 7e7f71ecca..b05f22c974 100644 --- a/docs/en/docs/operate/index.md +++ b/docs/en/docs/operate/index.md @@ -10,6 +10,7 @@ Start with the operational task you need: | Task | Guide | | --- | --- | | Keep a personal Server running, deploy a container, or enable authentication | [Deploy the Server](deploy-server.md) | +| Upgrade or switch background supervision mode | [Migrate Artifact processing state](artifact-processing-migration.md) | | Inspect logs, metrics, and traces | [Observability](observability.md) | | Send traces to an analysis service | [Phoenix](trace-with-phoenix.md), [Langfuse](trace-with-langfuse.md) | | Diagnose failures and restore service or data | [Troubleshoot](troubleshoot.md) | diff --git a/docs/en/docs/operate/meta.json b/docs/en/docs/operate/meta.json index 415ca71864..f88e114867 100644 --- a/docs/en/docs/operate/meta.json +++ b/docs/en/docs/operate/meta.json @@ -3,6 +3,7 @@ "pages": [ "index", "deploy-server", + "artifact-processing-migration", "observability", "trace-with-phoenix", "trace-with-langfuse", diff --git a/docs/en/docs/operate/trace-with-phoenix.md b/docs/en/docs/operate/trace-with-phoenix.md index 3964827f3f..c175057c9c 100644 --- a/docs/en/docs/operate/trace-with-phoenix.md +++ b/docs/en/docs/operate/trace-with-phoenix.md @@ -90,7 +90,7 @@ take the write lock, so they emit no `scope.lock` span: | `memory.search` | Memory lookup for `search_memory` or `prepare_context`; embedding and reranking spans, when present, are nested beneath it. | | `memory.rerank` | One actual reranker call; model-backed reranking nests `invoke_agent memory_rerank` beneath it. | | `experience.search` | Experience recall during `prepare_context`; emitted even when recall is not configured. | -| `experience.incubation` | One Experience incubation run for a scheduled activation. | +| `experience.incubation` | One in-process Experience incubation operation. | | `context.build` | The synchronous step that selects and renders the final prepared context from recalled candidates. | The other PowerContext generation tasks appear under the same convention: `experience_incubation`, @@ -101,22 +101,28 @@ Spans are exported in batches, so allow a few seconds before refreshing. An MCP `MCP mcp.tools.call` in place of the `HTTP` span. Readiness probes are deliberately not traced, so health checks do not create single-span traces. -## Scheduled background spans +## Background Worker spans -When a scheduler interval is configured (`schedule_seconds` or `experience_schedule_seconds`), each scheduled activation -starts its own trace instead of joining an unrelated request trace. The activation is the root span with -`powercontext.operation.unit` set to `background`: +Each Scope Worker invocation starts an independent trace, whether requested by a Family schedule or an explicit flush. +Memory, Topic Memory, Experience, and Profile use the same lifecycle spans. The root has +`powercontext.operation.unit` set to `background` and never inherits an HTTP or MCP request trace: | Span | Meaning | | --- | --- | -| `scheduled.process_source_window` | One scheduled Source-window activation. Its outcome is `success`, `noop`, `failure`, or `cancelled`. | -| `scheduled.incubate_experience_candidates` | One scheduled Experience incubation activation, with the same outcome vocabulary. | -| `memory.flush` | The flush run beneath a Source-window activation; it also appears under `HTTP flush_memory`. | -| `experience.incubation` | The incubation run beneath an Experience activation. | - -Scheduled roots record only bounded counts — `powercontext.background.source_count` and -`powercontext.background.candidate_count` — and never a `scope_id`, request ID, or Memory content. Inference spans created -by a scheduled activation are nested beneath its root in the same trace. +| `artifact_processing.worker` | One bounded Scope invocation, including process startup and durable completion acknowledgement. | +| `artifact_processing.worker.start` | Spawn and start the isolated child process. | +| `artifact_processing.worker.wait` | Wait for the child result or the invocation timeout. | +| `artifact_processing.worker.acknowledge` | Verify the current fence and persisted acknowledgement of the assigned request generation. | + +The root outcome is `success` only after durable acknowledgement, including a persisted NOOP. A child that exits +successfully without acknowledging the request produces `failure`. Other outcomes include `failure`, `cancelled`, +`cursor_conflict`, and `head_conflict`. Retry attempts create new independent roots. + +Lifecycle spans record `powercontext.artifact_processing.family`; failed roots add a bounded +`powercontext.artifact_processing.failure` category such as `timeout`, `worker_failed`, +`missing_durable_acknowledgement`, or `leadership_lost`. They exclude Scope IDs, request IDs, Source data, and model +payloads. These parent-process spans describe Worker lifecycle and acknowledgement. Inference runs in isolated children +and does not attach model spans to the parent lifecycle trace. ## What is not exported diff --git a/docs/en/docs/operate/troubleshoot.md b/docs/en/docs/operate/troubleshoot.md index 860659ce9f..de247ad178 100644 --- a/docs/en/docs/operate/troubleshoot.md +++ b/docs/en/docs/operate/troubleshoot.md @@ -154,6 +154,13 @@ powercontext server run Use the same environment variable whenever you start or diagnose that instance. PowerContext creates missing parent directories for a file-backed SQLite database. +## Processing state requires maintenance + +If startup reports that the processing schema is not ready, follow +[Migrate Artifact processing state](artifact-processing-migration.md). Existing +Topic Pending, Cursor and accepted calls need explicit migration before the new +Supervisor starts. Do not remove the old processing tables to bypass this check. + ## OceanBase startup rejects an incompatible schema Current PowerContext releases compare opaque identity columns byte-for-byte with `utf8mb4_bin`. A database created by @@ -192,7 +199,7 @@ so the previous database remains available for recovery: ```bash obloader -D --csv \ - --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_source_cursors,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_topic_memory_work_budgets,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_receipt_migration_review' \ + --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_source_cursors,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_receipt_migration_review' \ -f ``` diff --git a/docs/en/docs/workflows/use-profiles.md b/docs/en/docs/workflows/use-profiles.md index 9a9da09b53..c268371ff1 100644 --- a/docs/en/docs/workflows/use-profiles.md +++ b/docs/en/docs/workflows/use-profiles.md @@ -53,10 +53,15 @@ catch-up scan. Configure a generation model and enable scheduling with: export POWERCONTEXT_SERVER_RUNTIME_PROFILE_SCHEDULE_ENABLED=true export POWERCONTEXT_SERVER_RUNTIME_PROFILE_CRON="0 2 * * *" export POWERCONTEXT_SERVER_RUNTIME_PROFILE_TIMEZONE="Asia/Shanghai" -export POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_CONCURRENCY=4 +export POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_WORKERS=4 export POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_SOURCES_PER_WINDOW=32 ``` +Automatic cron admission requires a Scope policy with `generation_enabled=true`. Scopes with no policy or a +disabled policy retain their Sources without creating automatic requests or starting Workers. Enabling the policy +makes that existing input eligible for a later cron fire. Already accepted explicit requests retain their authorization +and completion semantics. + Enforced deployments use the existing `POWERCONTEXT_SERVER_ACCESS_BACKGROUND_PRINCIPAL_ID` service identity, which must have contribution access and write access to existing Profile Artifacts. Local static-administrator deployments can reuse their existing background identity. @@ -68,7 +73,7 @@ Failures retain the cursor; lineage-only Sources are filtered. Unchanged Markdow creating an automatic Revision. No new Source means no regeneration. Windows contain at most 32 raw journal records, or 31 when the previous Profile is also evidence. -Each scan processes at most 100 windows per Scope. Multiple instances may duplicate model calls, but +Each admitted Scope invocation processes one finite window; remaining ordinary work stays dirty for the next cron opportunity. Multiple instances may duplicate model calls, but Policy/Cursor/Head checks permit only one committed result. ## Review and manual editing diff --git a/docs/zh/docs/get-started/configure-models.md b/docs/zh/docs/get-started/configure-models.md index 4c52ab07d4..ea27c0e150 100644 --- a/docs/zh/docs/get-started/configure-models.md +++ b/docs/zh/docs/get-started/configure-models.md @@ -129,7 +129,7 @@ Server 验证通过后,按[对应 Agent 的文档](../integrations/index.md) ## 数据与重启 -没有覆盖数据库设置时,SQLite 在用户数据目录保存 `powercontext.db` 和 `scheduler.db`: +没有覆盖数据库设置时,SQLite 在用户数据目录保存 `powercontext.db`: - Linux:`$XDG_DATA_HOME/powercontext`,或 `~/.local/share/powercontext`; - macOS:`~/Library/Application Support/powercontext`; diff --git a/docs/zh/docs/operate/artifact-processing-migration.md b/docs/zh/docs/operate/artifact-processing-migration.md new file mode 100644 index 0000000000..821e90dede --- /dev/null +++ b/docs/zh/docs/operate/artifact-processing-migration.md @@ -0,0 +1,58 @@ +--- +title: 迁移 Artifact 后台处理状态 +--- + +已有 Topic Memory 处理数据库必须先完成显式维护迁移,再启动按 Scope 调用的 +Artifact Processing Supervisor。全新的空数据库自动初始化。已有数据但没有迁移完成标记时, +普通启动会在后台处理开始前拒绝运行。 + +## 查看计划并执行 + +使用迁移后部署所采用的配置查看只读计划: + +```shell +powercontext server processing-migrate --action plan --env-file .env +``` + +先备份数据库,停止全部旧后台候选及 Worker,停用它们的自动重启,并暂停输入写入及显式触发。 +命令不能代替操作者完成这些外部条件。随后执行: + +```shell +powercontext server processing-migrate --action apply --env-file .env \ + --migration-id rfc1515 --batch-size 100 --maintenance-confirmed +powercontext server processing-migrate --action verify --env-file .env +``` + +`apply` 按有限步骤分别提交事务。中途退出后,使用相同迁移 ID 和配置重新执行即可; +不要清除迁移标记、收据或旧自动目标来“重新开始”。每个 Scope 的收据与 intent、Topic 目标更新 +同事务提交,重复已提交的分页不会再次增加请求计数。MySQL DDL 在恢复时逐步检查实际状态, +不会把“新列已经存在”当作数据迁移完成。 + +只有验证返回 `ready: true` 后,才恢复 API 写入和后台进程。各副本必须采用一致的运行模式及 +binding/Family 映射。普通启动会拒绝未完成迁移或不兼容的部署配置;调整周期、Worker 额度和 +超时不要求重新进行模式迁移。 + +## 保留哪些状态 + +迁移保留 Topic Pending、Source Cursor 值及 CAS generation、证据和发布数据。未覆盖的 Source +转为普通 dirty;未确认 flush 与未完成自动目标转为已接受调用。Topic 的冻结输入目标仍保存在 +领域表中,后来普通 Source 不会扩大已知的旧自动目标。 + +旧实现可能在自动波次之外启动 catch-up,并在这些调用仍运行时结束原波次。因此,没有 wave 行 +不能证明某个 dirty Scope 从未获准运行。没有冻结目标确定边界时,迁移会保守保留旧 Topic Pending +对应的调用责任,由处理器从 Cursor 恢复。关闭新配置中的自动调度不会撤销这些恢复责任。 +缺少旧 Pending 的 Source 仅校准为普通 dirty,不因此接受新的业务动作。 + +旧自动完成时间用作新调度检查基准,保留剩余等待,不从迁移当前时间重新计时。只有替代请求、 +Topic 目标与 Cursor 一致性验证通过后,才清理旧自动目标行。旧表和迁移收据保留,运行时不再把 +旧表用作活动调度队列。 + +## 切换 global 与 dedicated + +双向切换均采用同样的协调停机和写入暂停流程。修改所有副本的模式配置,查看计划,然后使用 +**新的迁移 ID** 执行,例如 `global-to-dedicated-1`;切回也需要新的 ID。迁移会推进并作废旧模式的 +全部 Lease generation,再允许新模式启动,同时保留请求计数、dirty、Topic 目标、Cursor 和调度 +检查时间,不会重复导入旧处理责任。 + +SQLite 与 embedded SeekDB 在两种模式下都保留单宿主 `all` 角色;切换模式不会开启这两个后端的 +进程角色拆分能力。不支持滚动混用两种模式。 diff --git a/docs/zh/docs/operate/configuration.md b/docs/zh/docs/operate/configuration.md index 8172114a23..b4533e93da 100644 --- a/docs/zh/docs/operate/configuration.md +++ b/docs/zh/docs/operate/configuration.md @@ -30,8 +30,8 @@ export POWERCONTEXT_HOME=/srv/powercontext - macOS:`~/Library/Application Support/powercontext`; - Windows:`%LOCALAPPDATA%\\powercontext`。 -默认 SQLite 数据库是该目录下的 `powercontext.db`。启用定时处理时,调度状态保存在同一目录的 -`scheduler.db`。 +默认 SQLite 数据库是该目录下的 `powercontext.db`。四类后台处理器的意图与调度检查点保存在同一数据库中。 +已有部署须先完成[停机迁移](artifact-processing-migration.md)。 ## Server @@ -69,15 +69,23 @@ Server 配置使用 `POWERCONTEXT_SERVER_` 前缀。 | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_EXTRACTION_PROFILE` | `coding` | Memory 选择策略:`coding` 或 `conversation` | | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_RERANK_ENABLED` | `false` | 在 Memory 粗召回后应用 listwise rerank | | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_RERANK_CANDIDATE_LIMIT` | `30` | 交给 reranker 的粗排候选池大小 | -| `POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS` | 未设置 | Scheduler 间隔;未设置即不启用 | -| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SCHEDULE_SECONDS` | 未设置 | Topic Memory 按 binding 的自动波次间隔;未设置即关闭自动波次 | -| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SOURCE_WINDOW_LIMIT` | `10` | 单个 Topic Memory Worker 最多处理的 Source 数量,硬上限为 100 | +| `POWERCONTEXT_SERVER_RUNTIME_MEMORY_SCHEDULE_SECONDS` | 未设置 | Memory 自动准入间隔;`SCHEDULE_SECONDS` 保留为兼容别名 | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SCHEDULE_SECONDS` | 未设置 | Topic Memory 自动准入间隔;未设置时不接纳新的自动调用 | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SOURCE_WINDOW_LIMIT` | `10` | 每个 Topic Memory Window 的 Source 数量上限,硬上限为 100;一次 Scope 调用可完成多个 Window | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MAX_CANDIDATES` | `20` | 处理时考虑的历史 Topic 候选上限 | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_RRF_THRESHOLD` | `70` | 归一化到 `0..100` 的 RRF 接受阈值 | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MIN_CANDIDATES` | `5` | 达到阈值的候选过少时保证的最小历史召回数 | -| `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_MAX_WORKERS` | `10` | 所有 Artifact binding 共用的全局子 Worker 并发数 | -| `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_WORKER_TIMEOUT_SECONDS` | `600` | Supervisor 对单个有界 Source Window 子 Worker 的超时 | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_MAX_WORKERS` | `10` | Topic 独立 Worker 额度;`ARTIFACT_PROCESSING_MAX_WORKERS` 是其兼容别名 | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_WORKER_TIMEOUT_SECONDS` | `600` | 包括启动的 Scope 调用总超时;旧 `ARTIFACT_PROCESSING_WORKER_TIMEOUT_SECONDS` 是其兼容别名 | | `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_ROLE` | `all` | 进程角色:`all`、`api` 或 `background` | +| `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_SUPERVISOR_MODE` | `global` | `global` 一条 Lease;`dedicated` 每个注册 Family 一条 Lease | +| `POWERCONTEXT_SERVER_RUNTIME_ARTIFACT_PROCESSING_FAMILIES` | 根据模型推导 | JSON Family 列表;API 端可无模型凭据地声明处理能力 | +| `POWERCONTEXT_SERVER_RUNTIME_MEMORY_MAX_WORKERS` | `1` | Memory 独立 Worker 额度 | +| `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_MAX_WORKERS` | `1` | Experience 独立 Worker 额度 | +| `POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_WORKERS` | `4` | Profile 独立 Worker 额度;别名 `PROFILE_MAX_CONCURRENCY` | +| `POWERCONTEXT_SERVER_RUNTIME_MEMORY_WORKER_TIMEOUT_SECONDS` | `600` | Memory Scope 总超时 | +| `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_WORKER_TIMEOUT_SECONDS` | `600` | Experience Scope 总超时 | +| `POWERCONTEXT_SERVER_RUNTIME_PROFILE_WORKER_TIMEOUT_SECONDS` | `600` | Profile Scope 总超时 | | `POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL` | 未设置 | 配置的 extraction、generation、Handoff 和 rerank 操作共用的 Pydantic AI 模型 | | `POWERCONTEXT_SERVER_INFERENCE_GENERATION_BASE_URL` | provider 默认值 | 自定义 generation provider base URL | | `POWERCONTEXT_SERVER_INFERENCE_GENERATION_HEADERS` | `{}` | generation client 静态 header JSON object;value 按 secret 处理 | @@ -100,7 +108,7 @@ Server 配置使用 `POWERCONTEXT_SERVER_` 前缀。 | `POWERCONTEXT_SERVER_INFERENCE_RERANK_MODEL_SETTINGS` | `{}` | Pydantic AI reranker model settings JSON object | | `POWERCONTEXT_SERVER_INFERENCE_RERANK_TIMEOUT_SECONDS` | generation 超时 | LLM reranker 超时 | | `POWERCONTEXT_SERVER_INFERENCE_RERANK_MAX_REQUESTS` | generation request limit | 单次 rerank operation 的最大 model request 数量 | -| `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_SCHEDULE_SECONDS` | 未设置 | Experience 孵化间隔;未设置即不启用该 job | +| `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_SCHEDULE_SECONDS` | 未设置 | Experience 自动准入间隔;未设置时保留已接受工作,停止新的自动准入 | | `POWERCONTEXT_SERVER_EXTERNAL_SKILLS` | 自动生成本机项目 target | 覆盖默认值的 host identity 和显式 Agent Skill targets JSON object | Topic Worker 对尚未推进的 Scope Cursor 强制使用持久额度:跨全部重试最多 3 次尝试、512 次预留 provider 请求和 @@ -140,9 +148,21 @@ Authentication 负责建立 Principal,Access Control 负责判断该 Principal 用户 A 和用户 B。兼容静态 token 会为这个 Principal 显式写入 Server 与各 scope 所需的 role。需要让不同用户或 group 获得不同权限时,应注入部署侧 Authentication Provider 与相应的 AccessControlService。 -定时 Source 处理和 Experience 孵化使用固定静态 Principal,或 `ACCESS_BACKGROUND_PRINCIPAL_ID` 指定的 service Principal。 -该 Principal 必须在每个被处理的 scope 上拥有 `scope.contribute`;新 Memory Entry 和 Candidate 会保留它作为直接 owner 或 -`proposed_owner`。多用户 enforced 部署配置了 schedule 却未显式指定该 Principal 时,Server 会拒绝启动。 +Memory、Topic Memory、Experience、Profile 四类后台优先使用 `ACCESS_BACKGROUND_PRINCIPAL_ID` 指定的 service Principal, +缺省时回退到固定静态 Principal。该身份须在每个被处理的 scope 上拥有 `scope.contribute`,并拥有被修改的现有 Artifact 的写权限。 +新 Entry、Artifact 与 Candidate 的 owner 或 owner attestation 和处理完成确认同事务提交。 +enforced 部署启用后台能力时,若身份或授权 provider 无法在子进程重建,启动会失败;关闭自动 schedule 仍需恢复已接受的工作, +因此不能免除此检查。内置 provider 支持重建;注入的 provider 和模型对象仍可用于关闭后台能力 +(`ARTIFACT_PROCESSING_FAMILIES=[]`)的同步 SDK/Server 操作。 + +未配置 Server 身份的 SDK Worker 不需要 Server 授权依赖。内置后台 Worker 使用内置 Source Definition。 +自定义 Source Registry 须为每个启用的 Family 提供自定义 processing binding,或通过 +`ARTIFACT_PROCESSING_FAMILIES=[]` 关闭内置后台 Family;否则启动在接受工作前失败。 +仅关闭 schedule 不足以满足要求,因为显式请求仍会启动 Worker。同步 SDK Context 和纯 API 组合仍支持自定义 Source Registry。 + +受鉴权保护的 `/metrics` 暴露 `powercontext_server_artifact_processing_*` 指标,只使用 `family` 标签,涵盖 Worker 额度、 +ready/retry 队列、未确认 Scope 数、发现与调用耗时,以及完成、失败、超时次数。未确认数反映最近一次发现结果;计数器随 +Supervisor 实例重建而重置。 远程、多用户或共享 Dashboard 必须使用 `enforced`。此模式下,HTTP、MCP、Dashboard 数据路由和 metrics 共用同一个 Server PEP;Dashboard 配置的 scope 会在返回前按当前 Principal 的 `scope.read` 判定过滤。`/v1/access/me` 返回 @@ -221,11 +241,16 @@ Handoff Report 独立默认启用,路径为 `/handoff-reports`。没有任何 自动选出一个 active Leader。SQLite 与嵌入式 seekDB 只支持单进程 `all`。未设置正数间隔时,Topic Memory 自动波次 保持关闭;显式 flush 工作的恢复不依赖该间隔。Topic Worker 要求使用文件 SQLite;内存 SQLite 配合 generation model 的配置会在声明处理能力之前被拒绝。请通过 `POWERCONTEXT_SERVER_DATABASE_URL` 指定持久数据库路径,例如 -`sqlite+aiosqlite:////srv/powercontext/runtime.db`。Memory、Experience 与 Profile APScheduler 作业只由 `all` 角色运行: -任一 split role 与 `POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS`、 -`POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_SCHEDULE_SECONDS` 或启用的 -`POWERCONTEXT_SERVER_RUNTIME_PROFILE_SCHEDULE_ENABLED` 同时配置时,进程会在启动阶段明确拒绝。需要这些旧作业时应继续 -使用 `all`;把旧作业分配到独立进程不属于当前 split-role 合同。 +`sqlite+aiosqlite:////srv/powercontext/runtime.db`。Memory、Topic Memory、Experience、Profile 均使用统一 Supervisor,OceanBase 拆分角色也可启用其周期。 +SQLite 和 embedded seekDB 仍要求单宿主 `all`。两模式均保留逐 Family 独立额度和总超时,不借用其他 Family 空闲额度。 +关闭自动准入仍恢复已接受请求。API 与后台须保持 mode、注册 Family 和可触发能力一致;模型仅在执行端必需。 +切换模式须[协调停机迁移](artifact-processing-migration.md),不能混用模式启动。 +显式同时配置的新旧别名值不同时拒绝启动,同值接受。 + +普通 Runtime 启动会初始化并恢复所配置的检索索引。Topic Worker 复用该数据库,不再为每个 Window 重建无关的 +Memory/Experience 检索投影;Topic 索引校验与发布守卫仍然执行。如果空库切换了 Topic 检索形态或 Embedding +profile,应使用相同配置重新打开已有 Runtime;旧 Runtime 会以 retrieval-shape 错误拒绝 Topic 搜索、精确读取和 +当前 Head 浏览,而不是读取另一个向量空间。 普通 Runtime 启动会初始化并恢复所配置的检索索引。Topic Worker 复用该数据库,不再为每个 Window 重建无关的 Memory/Experience 检索投影;Topic 索引校验与发布守卫仍然执行。如果空库切换了 Topic 检索形态或 Embedding @@ -278,11 +303,10 @@ fork/evolution。External Skill 精确导入和完整 package 上传不使用模 bytes,再创建 package digest 完全相同的 pending Candidate。未配置模型时,语义生成会在持久化 Candidate 前返回 capability error;Review、package 检查与下载、精确导入、usage recording 和 external Skill scan/list/resolve 仍可使用。 -Experience 孵化使用独立的 APScheduler job 和持久化 Source cursor。每次 activation 固定检查最多 32 条 Source,并且只把 metadata 包含 `"kind": "task-outcome"` 的 Content Source +Experience 孵化使用独立的 Supervisor binding 和持久化 Source cursor。每次调用按 `SOURCE_WINDOW_LIMIT` 检查有限 Source 窗口,只把 metadata 包含 `"kind": "task-outcome"` 的 Content Source 暴露给模型。该 job 会在 Review Inbox 中创建 pending Experience Candidate;它不会自动批准、进入 -PreparedContext、创建 managed Skill、将它导出到 Agent target 或执行任何内容。Memory 和 Experience job 共用 -`POWERCONTEXT_HOME` 下的 APScheduler sidecar,但拥有独立的 job identity 和业务 cursor;取消其中一个 interval -只会移除对应 job。 +PreparedContext、创建 managed Skill、将它导出到 Agent target 或执行任何内容。Memory 与 Experience 保持独立的周期、 +Worker 额度和业务 Cursor;关闭某一间隔仅停止该 Family 的新自动准入,保留已接受工作。 设置与验证步骤见[创建并审核 Experience](../workflows/create-and-review-experience.md)。 ### Agent Skill 目标 diff --git a/docs/zh/docs/operate/index.md b/docs/zh/docs/operate/index.md index 8b2cb28ec6..ed6a6b4af0 100644 --- a/docs/zh/docs/operate/index.md +++ b/docs/zh/docs/operate/index.md @@ -10,6 +10,7 @@ description: 持续运行 Server,查找部署、监控与恢复步骤。 | 任务 | 指南 | | --- | --- | | 持续运行个人 Server、部署容器或启用认证 | [部署 Server](deploy-server.md) | +| 升级或切换后台监督模式 | [迁移 Artifact 处理状态](artifact-processing-migration.md) | | 查看日志、指标和 Trace | [可观测性](observability.md) | | 将 Trace 发送到分析服务 | [Phoenix](trace-with-phoenix.md)、[Langfuse](trace-with-langfuse.md) | | 诊断失败并恢复服务或数据 | [诊断与恢复](troubleshoot.md) | diff --git a/docs/zh/docs/operate/meta.json b/docs/zh/docs/operate/meta.json index 57569a416e..b0fa9cdd5d 100644 --- a/docs/zh/docs/operate/meta.json +++ b/docs/zh/docs/operate/meta.json @@ -3,6 +3,7 @@ "pages": [ "index", "deploy-server", + "artifact-processing-migration", "observability", "trace-with-phoenix", "trace-with-langfuse", diff --git a/docs/zh/docs/operate/trace-with-phoenix.md b/docs/zh/docs/operate/trace-with-phoenix.md index 9884e54109..8896d7b0b0 100644 --- a/docs/zh/docs/operate/trace-with-phoenix.md +++ b/docs/zh/docs/operate/trace-with-phoenix.md @@ -87,7 +87,7 @@ scope 相关操作还会在 application operation 之下添加以下内部 stage | `memory.search` | `search_memory` 或 `prepare_context` 中的 Memory 查询;存在 embedding 或 reranking span 时,它们嵌套在其下。 | | `memory.rerank` | 一次实际 reranker 调用;使用模型的 reranking 会在其下嵌套 `invoke_agent memory_rerank`。 | | `experience.search` | `prepare_context` 中的 Experience recall;未配置 recall 时也会产生。 | -| `experience.incubation` | 一次 Experience incubation,出现在定时激活之下。 | +| `experience.incubation` | 一次进程内 Experience incubation 操作。 | | `context.build` | 根据召回候选同步选择并渲染最终 prepared context 的步骤。 | 其他 generation 任务遵循同样的命名约定:`experience_incubation`、`experience_generation`、`skill_generation`、 @@ -97,21 +97,26 @@ span 挂在触发它的操作之下。 span 是批量导出的,刷新前请稍等几秒。MCP 请求会用 `MCP mcp.tools.call` 取代 `HTTP` span。readiness 探活被有意 排除在 trace 之外,因此健康检查不会产生只含单个 span 的 trace。 -## 定时后台 span +## 后台 Worker span -配置了定时器间隔(`schedule_seconds` 或 `experience_schedule_seconds`)后,每次定时激活都会开启一条**独立**的 -trace,而不会并入无关的请求 trace。激活本身是根 span,其 `powercontext.operation.unit` 为 `background`: +每次 Scope Worker 调用都会开启独立 trace,包括 Family 定时计划与显式 flush 触发的请求。Memory、Topic Memory、 +Experience 和 Profile 使用相同的生命周期 span。根 span 的 `powercontext.operation.unit` 为 `background`, +不会继承 HTTP 或 MCP 请求的 trace: | Span | 含义 | | --- | --- | -| `scheduled.process_source_window` | 一次定时 Source-window 激活,outcome 为 `success`、`noop`、`failure` 或 `cancelled`。 | -| `scheduled.incubate_experience_candidates` | 一次定时 Experience incubation 激活,outcome 词表相同。 | -| `memory.flush` | Source-window 激活下的 flush 执行;它也会出现在 `HTTP flush_memory` 之下。 | -| `experience.incubation` | Experience 激活下的 incubation 执行。 | - -定时根 span 只记录有界的计数——`powercontext.background.source_count` 与 -`powercontext.background.candidate_count`——绝不携带 `scope_id`、request ID 或 Memory 内容。定时激活产生的推理 -span 会作为其根 span 的子节点嵌套在同一条 trace 中。 +| `artifact_processing.worker` | 一次有界 Scope 调用,包含进程启动与持久化完成确认。 | +| `artifact_processing.worker.start` | 创建并启动隔离的子进程。 | +| `artifact_processing.worker.wait` | 等待子进程结果或本次调用超时。 | +| `artifact_processing.worker.acknowledge` | 核对当前 fence,以及分配的请求代数是否已经持久化确认。 | + +根 span 仅在请求持久化确认后记为 `success`,包括已持久化的 NOOP。子进程正常退出但没有确认请求时记为 +`failure`。其他 outcome 包括 `failure`、`cancelled`、`cursor_conflict` 和 `head_conflict`。每次重试产生新的独立根 span。 + +生命周期 span 记录 `powercontext.artifact_processing.family`;失败根 span 还记录有界的 +`powercontext.artifact_processing.failure` 类别,例如 `timeout`、`worker_failed`、 +`missing_durable_acknowledgement` 或 `leadership_lost`。其中不含 Scope ID、request ID、Source 数据或模型正文。 +这些父进程 span 描述 Worker 生命周期和完成确认;推理在隔离子进程中执行,不会把模型 span 挂入父进程生命周期 trace。 ## 哪些内容不会被导出 diff --git a/docs/zh/docs/operate/troubleshoot.md b/docs/zh/docs/operate/troubleshoot.md index 8a82587b04..27fd4b9236 100644 --- a/docs/zh/docs/operate/troubleshoot.md +++ b/docs/zh/docs/operate/troubleshoot.md @@ -150,6 +150,12 @@ powercontext server run 每次启动或诊断该实例时都应使用同一个环境变量。对于文件型 SQLite 数据库,PowerContext 会创建缺失的父 目录。 +## 后台处理状态需要维护迁移 + +如果启动错误提示 processing schema 尚未就绪,请按 +[迁移 Artifact 后台处理状态](artifact-processing-migration.md) 完成维护。已有 Topic Pending、Cursor +和已接受调用必须迁移后才能启动新 Supervisor。不要通过删除旧处理表绕过检查。 + ## OceanBase 因 schema 不兼容而拒绝启动 当前 PowerContext 使用 `utf8mb4_bin` 对不透明 identity column 进行逐字节比较。旧版本创建的数据库可能仍然 @@ -186,7 +192,7 @@ collation,但不会包含数据库 URL 或凭据。 ```bash obloader -D --csv \ - --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_source_cursors,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_topic_memory_work_budgets,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_receipt_migration_review' \ + --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_source_cursors,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_receipt_migration_review' \ -f ``` diff --git a/docs/zh/docs/workflows/use-profiles.md b/docs/zh/docs/workflows/use-profiles.md index c49a586a3c..b34c99dd1a 100644 --- a/docs/zh/docs/workflows/use-profiles.md +++ b/docs/zh/docs/workflows/use-profiles.md @@ -50,10 +50,14 @@ PUT /v1/scopes/S_GROUP/profile-policy export POWERCONTEXT_SERVER_RUNTIME_PROFILE_SCHEDULE_ENABLED=true export POWERCONTEXT_SERVER_RUNTIME_PROFILE_CRON="0 2 * * *" export POWERCONTEXT_SERVER_RUNTIME_PROFILE_TIMEZONE="Asia/Shanghai" -export POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_CONCURRENCY=4 +export POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_WORKERS=4 export POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_SOURCES_PER_WINDOW=32 ``` +cron 自动准入只处理 Policy 中 `generation_enabled=true` 的 Scope。没有 Policy 或 Policy 已禁用时, +保留原有 Source,不产生自动请求,也不启动 Worker;启用 Policy 后,原有输入可在后续 cron 处理。 +已经接受的显式请求仍遵守原有授权和完成语义。 + 启用权限的后台任务使用已有 `POWERCONTEXT_SERVER_ACCESS_BACKGROUND_PRINCIPAL_ID` 配置; 该服务 Principal 必须获得相关 Scope 和已有 Artifact 的写权限。静态本地管理员部署可复用原有后台身份。 @@ -62,7 +66,7 @@ export POWERCONTEXT_SERVER_RUNTIME_PROFILE_MAX_SOURCES_PER_WINDOW=32 返回 updated、noop、review_pending、disabled 或 conflict。模型请求遵守现有 generation timeout 和请求上限。 失败不消费窗口;lineage_only Source 被过滤;正文没变化只推进 Cursor,不新增自动 Revision。 -每窗口最多 32 条原始 journal 记录;引用旧画像时最多 31 条。每 Scope 每轮最多 100 窗口。 +每窗口最多 32 条原始 journal 记录;引用旧画像时最多 31 条。每次准入的 Scope 调用处理一个有限窗口,剩余普通工作保留 dirty,等待后续 cron 准入。 多实例可能重复调用模型,但 Policy/Cursor/Head 校验只允许一个结果提交。没有新 Source 就不重新生成。 ## 审核、修改与回退 diff --git a/src/powercontext/builtin/artifacts/profile/management.py b/src/powercontext/builtin/artifacts/profile/management.py index d168b59f42..8416e6f482 100644 --- a/src/powercontext/builtin/artifacts/profile/management.py +++ b/src/powercontext/builtin/artifacts/profile/management.py @@ -25,12 +25,14 @@ from powercontext.artifacts import ArtifactRef from powercontext.builtin.artifacts.profile.models import ( PROFILE_ARTIFACT_ID, + PROFILE_SOURCE_WINDOW_BINDING, Profile, ProfileContent, ProfileGeneration, ProfileWriteContent, ) from powercontext.builtin.persistence.family_management import _RepositoryFamilyWriter +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.profile import ProfilePolicyRepository from powercontext.builtin.records import InvalidBaseAccessRequestError @@ -55,6 +57,7 @@ async def _coordinate(self, connection, scope_id): policy = await policies.get(connection, scope_id, for_update=True) if policy is None: policy = await policies.create(connection, scope_id) + await ArtifactProcessingIntentRepository().mark_dirty(connection, scope_id, PROFILE_SOURCE_WINDOW_BINDING) return await policies.update(connection, policy) async def create(self, connection, scope_id, artifact_id, content, direct_source, /) -> Profile: diff --git a/src/powercontext/builtin/artifacts/profile/review.py b/src/powercontext/builtin/artifacts/profile/review.py index 47808fb178..c38e1ead93 100644 --- a/src/powercontext/builtin/artifacts/profile/review.py +++ b/src/powercontext/builtin/artifacts/profile/review.py @@ -28,6 +28,7 @@ ) from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.errors import RepositoryNotFoundError +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.profile import ProfilePolicyRepository from powercontext.builtin.records import BaseValueConflictError from powercontext.builtin.review.errors import InvalidCandidateError @@ -93,6 +94,7 @@ async def decide_profile(service, connection, candidate_id, expected_version, *, SourceCursor(sequence=proposal.source_window.through), expected_generation=None if cursor is None else cursor.generation, ) + await ArtifactProcessingIntentRepository().mark_dirty(connection, service._scope_id, PROFILE_SOURCE_WINDOW_BINDING) return result diff --git a/src/powercontext/builtin/artifacts/profile/service.py b/src/powercontext/builtin/artifacts/profile/service.py index e8f2f3e552..be3c18e865 100644 --- a/src/powercontext/builtin/artifacts/profile/service.py +++ b/src/powercontext/builtin/artifacts/profile/service.py @@ -22,12 +22,13 @@ from collections.abc import Awaitable, Callable from contextlib import AbstractAsyncContextManager, nullcontext from datetime import UTC, datetime -from typing import Any, Protocol +from typing import TYPE_CHECKING, Any, Protocol from uuid import uuid4 from pydantic import BaseModel from sqlalchemy import select from sqlalchemy.exc import IntegrityError, OperationalError +from sqlalchemy.ext.asyncio import AsyncConnection from powercontext.builtin.artifacts.profile.models import ( PROFILE_ARTIFACT_ID, @@ -48,6 +49,7 @@ from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.database import AsyncDatabase, is_transaction_contention from powercontext.builtin.persistence.errors import GenerationConflictError, RepositoryNotFoundError +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.profile import ProfilePolicyRepository from powercontext.builtin.persistence.sources import SourceRepository from powercontext.builtin.persistence.tables import PROFILE_POLICIES_TABLE @@ -58,6 +60,9 @@ from powercontext.builtin.sources import SourceCursor from powercontext.errors import RevisionConflictError +if TYPE_CHECKING: + from powercontext.builtin.runtime.processing_execution import ScopeInvocation + class ProfileGenerationInput(BaseModel): previous_content: str | None @@ -121,20 +126,28 @@ async def put_policy( if current is None: if expected_version != 0: raise BaseValueConflictError("profile_policy", (scope_id,)) - return await self.policies.create( + updated = await self.policies.create( connection, scope_id, enabled=generation_enabled, activation_mode=activation_mode, ) + await ArtifactProcessingIntentRepository().mark_dirty( + connection, scope_id, PROFILE_SOURCE_WINDOW_BINDING + ) + return updated elif current.version != expected_version or expected_version == 0: raise BaseValueConflictError("profile_policy", (scope_id,)) - return await self.policies.update( + updated = await self.policies.update( connection, current, generation_enabled=generation_enabled, activation_mode=activation_mode, ) + await ArtifactProcessingIntentRepository().mark_dirty( + connection, scope_id, PROFILE_SOURCE_WINDOW_BINDING + ) + return updated except IntegrityError as error: raise BaseValueConflictError("profile_policy", (scope_id,)) from error @@ -151,10 +164,17 @@ async def flush( high_watermark: int | None = None, authorize_snapshot: Callable[[Profile | None], Awaitable[None]] | None = None, on_commit=None, + processing: ScopeInvocation | None = None, + authorize_commit: Callable[[AsyncConnection, Profile | None], Awaitable[None]] | None = None, ) -> ProfileFlushResult: async with self.operation_context(): return await self._flush( - scope_id, high_watermark=high_watermark, authorize_snapshot=authorize_snapshot, on_commit=on_commit + scope_id, + high_watermark=high_watermark, + authorize_snapshot=authorize_snapshot, + on_commit=on_commit, + processing=processing, + authorize_commit=authorize_commit, ) async def _flush( # noqa: C901 @@ -164,8 +184,12 @@ async def _flush( # noqa: C901 high_watermark: int | None = None, authorize_snapshot: Callable[[Profile | None], Awaitable[None]] | None = None, on_commit=None, + processing: ScopeInvocation | None = None, + authorize_commit: Callable[[AsyncConnection, Profile | None], Awaitable[None]] | None = None, ) -> ProfileFlushResult: async with self.database.transaction() as connection: + if processing is not None: + await processing.start(connection) policy = await self.policies.get(connection, scope_id) cursor = await self.cursors.load(connection, scope_id, PROFILE_SOURCE_WINDOW_BINDING) after = 0 if cursor is None else cursor.cursor.sequence @@ -173,8 +197,12 @@ async def _flush( # noqa: C901 high = high if high_watermark is None else min(high, high_watermark) base: dict[str, Any] = {"previous_cursor": after, "current_cursor": after, "high_watermark": high} if policy is None or not policy.generation_enabled: + if processing is not None: + await processing.complete(connection, remaining_work=after < high) return ProfileFlushResult(status="disabled", **base) if policy.pending_candidate_id is not None: + if processing is not None: + await processing.complete(connection, remaining_work=True) return ProfileFlushResult(status="review_pending", candidate_id=policy.pending_candidate_id, **base) current = await self.latest(connection, scope_id) limit = min(self.max_sources, 32 if current is None else 31) @@ -183,6 +211,8 @@ async def _flush( # noqa: C901 for item in await self.sources.list(connection, scope_id, after=after, limit=limit) if item.journal_position <= high ) + if not window and processing is not None: + await processing.complete(connection, remaining_work=False) if not window: return ProfileFlushResult(status="noop", **base) # Authorize the exact Head used by generation. The commit CAS below also @@ -215,6 +245,8 @@ async def _flush( # noqa: C901 markdown = None try: async with self.database.transaction() as connection: + if processing is not None: + await processing.guard(connection) locked = await self.policies.get(connection, scope_id, for_update=True) actual_cursor = await self.cursors.load( connection, scope_id, PROFILE_SOURCE_WINDOW_BINDING, for_update=True @@ -226,6 +258,8 @@ async def _flush( # noqa: C901 or (None if actual is None else actual.as_ref()) != (None if current is None else current.as_ref()) ): raise BaseValueConflictError("profile_processing", (scope_id,)) # noqa: TRY301 + if authorize_commit is not None: + await authorize_commit(connection, current) # CAS also serializes SQLite, whose SELECT FOR UPDATE is a no-op. updated = await self.policies.update(connection, policy) refs = tuple(item.ref for item in evidence) @@ -284,6 +318,8 @@ async def _flush( # noqa: C901 ) if on_commit is not None: await on_commit(connection, artifact, candidate) + if processing is not None: + await processing.complete(connection, remaining_work=candidate_id is not None or through < high) return ProfileFlushResult( status="review_pending" if candidate_id else ("updated" if artifact else "noop"), previous_cursor=after, diff --git a/src/powercontext/builtin/persistence/processing.py b/src/powercontext/builtin/persistence/processing.py index 39145fc31c..e5b215cfb3 100644 --- a/src/powercontext/builtin/persistence/processing.py +++ b/src/powercontext/builtin/persistence/processing.py @@ -173,6 +173,13 @@ async def request_flush( ) -> StoredArtifactProcessingPending | None: _require_identifier("scope_id", scope_id, MAX_SCOPE_ID_LENGTH) _require_identifier("binding_name", binding_name, MAX_BINDING_NAME_LENGTH) + # Match Source publication and Topic target capture: journal head is + # locked before Pending or Intent. This also freezes the accepted head. + await connection.execute( + update(SOURCE_JOURNAL_HEADS_TABLE) + .where(SOURCE_JOURNAL_HEADS_TABLE.c.scope_id == scope_id) + .values(position=SOURCE_JOURNAL_HEADS_TABLE.c.position) + ) head = await connection.scalar( select(SOURCE_JOURNAL_HEADS_TABLE.c.position).where(SOURCE_JOURNAL_HEADS_TABLE.c.scope_id == scope_id) ) diff --git a/src/powercontext/builtin/persistence/processing_intents.py b/src/powercontext/builtin/persistence/processing_intents.py new file mode 100644 index 0000000000..0635f6dd22 --- /dev/null +++ b/src/powercontext/builtin/persistence/processing_intents.py @@ -0,0 +1,275 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Coalesced Scope invocation intents, independent of domain input progress. + +Every mutation joins the caller's transaction. Domain callers publish input and +dirty/requested together; Supervisor callers must first validate their fence. +Rows are retained after completion so neither generations nor sequence IDs are +reused. Queue state and retry history are deliberately absent. +""" + +from __future__ import annotations + +from typing import cast + +from pydantic import BaseModel +from sqlalchemy import func, insert, select, update +from sqlalchemy.dialects.mysql import insert as mysql_insert +from sqlalchemy.dialects.sqlite import insert as sqlite_insert +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.persistence.errors import InvalidRepositoryArgumentError +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_BINDING_STATES_TABLE, + ARTIFACT_PROCESSING_INTENTS_TABLE, + ARTIFACT_PROCESSING_SEQUENCES_TABLE, +) +from powercontext.limits import MAX_BINDING_NAME_LENGTH, MAX_SCOPE_ID_LENGTH + + +class StoredArtifactProcessingIntent(BaseModel): + """One durable invocation counter and independent domain dirty counter.""" + + binding_name: str + scope_id: str + pending_sequence: int + dirty_generation: int + clean_generation: int + requested_generation: int + handled_generation: int + last_auto_scan_generation: int + + +class ArtifactProcessingIntentRepository: + """Persist intent counters using caller-owned short transactions.""" + + async def load( + self, + connection: AsyncConnection, + scope_id: str, + binding_name: str, + /, + *, + for_update: bool = False, + ) -> StoredArtifactProcessingIntent | None: + _require_key(scope_id, binding_name) + table = ARTIFACT_PROCESSING_INTENTS_TABLE + condition = (table.c.scope_id == scope_id) & (table.c.binding_name == binding_name) + if for_update and connection.dialect.name == "sqlite": + # SQLite ignores FOR UPDATE. Even an unmatched UPDATE opens the + # real write transaction before the read, protecting first inserts. + await connection.execute(update(table).where(condition).values(dirty_generation=table.c.dirty_generation)) + statement = select(table).where(condition) + if for_update: + statement = statement.with_for_update() + row = (await connection.execute(statement)).mappings().one_or_none() + return None if row is None else StoredArtifactProcessingIntent.model_validate(dict(row)) + + async def ensure( + self, connection: AsyncConnection, scope_id: str, binding_name: str, / + ) -> StoredArtifactProcessingIntent: + """Register a stable sequence without accepting or marking any work.""" + + current = await self.load(connection, scope_id, binding_name) + if current is not None: + return current + sequence = ARTIFACT_PROCESSING_SEQUENCES_TABLE + if connection.dialect.name == "sqlite": + seed = sqlite_insert(sequence).values(singleton=1, sequence=0).on_conflict_do_nothing() + elif connection.dialect.name == "mysql": + seed = mysql_insert(sequence).values(singleton=1, sequence=0) + seed = seed.on_duplicate_key_update(sequence=sequence.c.sequence) + else: + raise InvalidRepositoryArgumentError("dialect", "processing intents require SQLite or MySQL") + await connection.execute(seed) + # Serialize first registrations across bindings. Recheck using a current + # locked read after waiting, including under MySQL repeatable read. + await connection.execute(update(sequence).where(sequence.c.singleton == 1).values(sequence=sequence.c.sequence)) + current = await self.load(connection, scope_id, binding_name, for_update=True) + if current is not None: + return current + await connection.execute( + update(sequence).where(sequence.c.singleton == 1).values(sequence=sequence.c.sequence + 1) + ) + allocated = int( + cast(int, await connection.scalar(select(sequence.c.sequence).where(sequence.c.singleton == 1))) + ) + await connection.execute( + insert(ARTIFACT_PROCESSING_INTENTS_TABLE).values( + binding_name=binding_name, scope_id=scope_id, pending_sequence=allocated + ) + ) + return cast(StoredArtifactProcessingIntent, await self.load(connection, scope_id, binding_name)) + + async def mark_dirty( + self, connection: AsyncConnection, scope_id: str, binding_name: str, / + ) -> StoredArtifactProcessingIntent: + await self.ensure(connection, scope_id, binding_name) + table = ARTIFACT_PROCESSING_INTENTS_TABLE + await connection.execute( + update(table) + .where(table.c.scope_id == scope_id, table.c.binding_name == binding_name) + .values(dirty_generation=table.c.dirty_generation + 1) + ) + return cast( + StoredArtifactProcessingIntent, await self.load(connection, scope_id, binding_name, for_update=True) + ) + + async def request( + self, connection: AsyncConnection, scope_id: str, binding_name: str, / + ) -> StoredArtifactProcessingIntent: + await self.ensure(connection, scope_id, binding_name) + table = ARTIFACT_PROCESSING_INTENTS_TABLE + await connection.execute( + update(table) + .where(table.c.scope_id == scope_id, table.c.binding_name == binding_name) + .values(requested_generation=table.c.requested_generation + 1) + ) + return cast( + StoredArtifactProcessingIntent, await self.load(connection, scope_id, binding_name, for_update=True) + ) + + async def acknowledge( + self, + connection: AsyncConnection, + scope_id: str, + binding_name: str, + generation: int, + /, + *, + clean_generation: int | None = None, + ) -> StoredArtifactProcessingIntent: + _require_nonnegative("generation", generation) + current = await self.load(connection, scope_id, binding_name, for_update=True) + if current is None or generation > current.requested_generation: + raise InvalidRepositoryArgumentError("generation", "cannot acknowledge an unaccepted invocation") + if generation <= current.handled_generation: + return current + clean = current.clean_generation + if clean_generation is not None: + _require_nonnegative("clean_generation", clean_generation) + if clean_generation > current.dirty_generation: + raise InvalidRepositoryArgumentError("clean_generation", "cannot acknowledge unseen domain work") + clean = max(clean, clean_generation) + table = ARTIFACT_PROCESSING_INTENTS_TABLE + await connection.execute( + update(table) + .where(table.c.scope_id == scope_id, table.c.binding_name == binding_name) + .values(handled_generation=max(current.handled_generation, generation), clean_generation=clean) + ) + return cast(StoredArtifactProcessingIntent, await self.load(connection, scope_id, binding_name)) + + async def scan( + self, + connection: AsyncConnection, + binding_name: str, + /, + *, + after_sequence: int = 0, + limit: int = 100, + requested_only: bool = False, + dirty_only: bool = False, + upper_sequence: int | None = None, + ) -> tuple[StoredArtifactProcessingIntent, ...]: + _require_identifier("binding_name", binding_name, MAX_BINDING_NAME_LENGTH) + _require_nonnegative("after_sequence", after_sequence) + if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1: + raise InvalidRepositoryArgumentError("limit", "must be a positive integer") + table = ARTIFACT_PROCESSING_INTENTS_TABLE + statement = select(table).where(table.c.binding_name == binding_name, table.c.pending_sequence > after_sequence) + if upper_sequence is not None: + _require_nonnegative("upper_sequence", upper_sequence) + statement = statement.where(table.c.pending_sequence <= upper_sequence) + if requested_only: + statement = statement.where(table.c.requested_generation > table.c.handled_generation) + if dirty_only: + statement = statement.where(table.c.dirty_generation > table.c.clean_generation) + rows = (await connection.execute(statement.order_by(table.c.pending_sequence).limit(limit))).mappings() + return tuple(StoredArtifactProcessingIntent.model_validate(dict(row)) for row in rows) + + async def max_sequence(self, connection: AsyncConnection, binding_name: str, /) -> int: + _require_identifier("binding_name", binding_name, MAX_BINDING_NAME_LENGTH) + table = ARTIFACT_PROCESSING_INTENTS_TABLE + return int( + await connection.scalar( + select(func.max(table.c.pending_sequence)).where(table.c.binding_name == binding_name) + ) + or 0 + ) + + async def admit( + self, + connection: AsyncConnection, + scope_id: str, + binding_name: str, + scan_generation: int, + /, + ) -> StoredArtifactProcessingIntent: + """Idempotently accept one member of the current frozen scan. + + The caller checks ready/running/retry exclusion and validates its fence + in this transaction before calling. Existing accepted work is reused. + """ + + _require_nonnegative("scan_generation", scan_generation) + state_table = ARTIFACT_PROCESSING_BINDING_STATES_TABLE + state = ( + ( + await connection.execute( + select(state_table).where(state_table.c.binding_name == binding_name).with_for_update() + ) + ) + .mappings() + .one_or_none() + ) + if state is None or not state["scan_in_progress"] or state["scan_generation"] != scan_generation: + raise InvalidRepositoryArgumentError("scan_generation", "automatic scan is not current") + current = await self.load(connection, scope_id, binding_name, for_update=True) + if current is None: + raise InvalidRepositoryArgumentError("scope_id", "automatic member is not registered") + if current.pending_sequence > int(state["scan_upper_pending_sequence"] or 0): + raise InvalidRepositoryArgumentError("scope_id", "automatic member is outside the frozen scan") + if current.last_auto_scan_generation >= scan_generation: + return current + requested = current.requested_generation + if current.dirty_generation > current.clean_generation and requested == current.handled_generation: + requested += 1 + table = ARTIFACT_PROCESSING_INTENTS_TABLE + await connection.execute( + update(table) + .where(table.c.scope_id == scope_id, table.c.binding_name == binding_name) + .values(requested_generation=requested, last_auto_scan_generation=scan_generation) + ) + return cast(StoredArtifactProcessingIntent, await self.load(connection, scope_id, binding_name)) + + +def _require_key(scope_id: str, binding_name: str) -> None: + _require_identifier("scope_id", scope_id, MAX_SCOPE_ID_LENGTH) + _require_identifier("binding_name", binding_name, MAX_BINDING_NAME_LENGTH) + + +def _require_identifier(field: str, value: str, limit: int) -> None: + if not isinstance(value, str) or not value.strip() or value != value.strip() or len(value) > limit: + raise InvalidRepositoryArgumentError(field, "must be a non-empty trimmed identifier within the length limit") + + +def _require_nonnegative(field: str, value: int) -> None: + if not isinstance(value, int) or isinstance(value, bool) or value < 0: + raise InvalidRepositoryArgumentError(field, "must be a non-negative integer") + + +StoredIntent = StoredArtifactProcessingIntent + +__all__ = ["ArtifactProcessingIntentRepository", "StoredArtifactProcessingIntent", "StoredIntent"] diff --git a/src/powercontext/builtin/persistence/processing_migration.py b/src/powercontext/builtin/persistence/processing_migration.py new file mode 100644 index 0000000000..15e5fad831 --- /dev/null +++ b/src/powercontext/builtin/persistence/processing_migration.py @@ -0,0 +1,696 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Explicit, resumable maintenance migration of processing scheduling state. + +Stop all old hosts and Workers and pause input/API writes before applying. +Each apply call performs one bounded step and joins a caller-owned transaction. +Commit that transaction before invoking the next step. MySQL DDL may commit +independently; every DDL step therefore checks its actual postcondition again. +Ordinary runtime startup only bootstraps a provably empty database or validates +the completed marker. It never imports old work or discards old wave targets. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping +from datetime import timedelta +from typing import Any, cast + +from pydantic import BaseModel +from sqlalchemy import Boolean, and_, case, delete, exists, func, insert, inspect, literal, or_, select, update +from sqlalchemy.dialects.mysql import TINYINT +from sqlalchemy.dialects.mysql import insert as mysql_insert +from sqlalchemy.dialects.sqlite import insert as sqlite_insert +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.errors import PersistenceError +from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.supervision import database_utc_now +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_AUTO_WAVE_TARGETS_TABLE as WAVES, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_BINDING_STATES_TABLE as STATES, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_INTENTS_TABLE as INTENTS, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_LEASES_TABLE as LEASES, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_MIGRATION_RECEIPTS_TABLE as RECEIPTS, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_PENDING_TABLE as PENDING, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_SCHEMA_TABLE as SCHEMA, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_SEQUENCES_TABLE as SEQUENCES, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACTS_TABLE, + SOURCES_TABLE, +) +from powercontext.builtin.persistence.tables import ( + SOURCE_CURSORS_TABLE as CURSORS, +) +from powercontext.builtin.persistence.tables import ( + SOURCE_JOURNAL_HEADS_TABLE as HEADS, +) +from powercontext.builtin.persistence.tables import ( + TOPIC_MEMORY_PROCESSING_TARGETS_TABLE as TARGETS, +) + +PROCESSING_SCHEMA_VERSION = 1515 +_TOPIC_BINDING = "topic-memory-source-window" +_DEFAULT_BINDINGS = { + "memory-source-window": "memory", + _TOPIC_BINDING: "topic-memory", + "experience-incubation": "experience", + "profile-source-window": "profile", +} +_STATE_COLUMNS = { + "last_schedule_checkpoint_at": "DATETIME NULL", + "scan_generation": "BIGINT NOT NULL DEFAULT 0", + "scan_in_progress": "BOOLEAN NOT NULL DEFAULT 0", + "scan_upper_pending_sequence": "BIGINT NULL", +} +_NEW_TABLES = (SCHEMA, RECEIPTS, SEQUENCES, INTENTS, TARGETS) + + +class ProcessingSchemaNotReadyError(PersistenceError): + """Processing state needs explicit offline migration or a matching mode.""" + + def __init__(self, *, reason: str) -> None: + self.reason = reason + super().__init__(reason) + + +class ProcessingMigrationPlan(BaseModel): + schema_version: int = PROCESSING_SCHEMA_VERSION + phase: str + required: bool + missing_state_columns: tuple[str, ...] + legacy_pending_count: int + legacy_wave_count: int + conservative_automatic_bindings: tuple[str, ...] + + +class ProcessingMigrationProgress(BaseModel): + phase: str + processed: int = 0 + complete: bool = False + + +class ProcessingMigrationVerification(BaseModel): + ready: bool + issues: tuple[str, ...] = () + + +async def plan_processing_migration( + connection: AsyncConnection, + *, + config_manifest: Mapping[str, Any] | str | None = None, +) -> ProcessingMigrationPlan: + """Inspect migration needs without writing or exposing per-Scope data.""" + + columns = await _columns(connection, STATES.name) + marker = await _marker(connection) + manifest = _manifest(config_manifest) + return ProcessingMigrationPlan( + phase="uninitialized" if marker is None else str(marker["phase"]), + required=marker is None + or marker["phase"] != "complete" + or ( + config_manifest is not None + and _deployment_manifest(str(marker["config_manifest"])) != _deployment_manifest(manifest) + ), + missing_state_columns=tuple(name for name in _STATE_COLUMNS if name not in columns), + legacy_pending_count=await _count_if_present(connection, PENDING), + legacy_wave_count=await _count_if_present(connection, WAVES), + conservative_automatic_bindings=_automatic_bindings(manifest), + ) + + +async def bootstrap_processing_schema( + connection: AsyncConnection, + config_manifest: Mapping[str, Any] | str | None = None, +) -> None: + """Mark an empty, current-schema database ready; never upgrade legacy work. + + Call after normal create_all, before any API, domain initializer or Worker + can write. Existing complete databases are only checked. The absence of a + marker alone is never proof that a database is new. + """ + + marker = await _marker(connection) + if marker is not None: + await assert_processing_schema_ready(connection, config_manifest) + return + columns = await _columns(connection, STATES.name) + if not set(_STATE_COLUMNS) <= columns.keys(): + raise ProcessingSchemaNotReadyError(reason="Legacy processing schema requires offline processing migration") + for table in _NEW_TABLES: + if not await _has_table(connection, table.name): + raise ProcessingSchemaNotReadyError( + reason="Processing tables must be created before fresh database bootstrap" + ) + await _seed_fresh_marker(connection, _manifest(config_manifest)) + marker = await _marker(connection, for_update=True) + if marker is not None and marker["phase"] == "complete": + await assert_processing_schema_ready(connection, config_manifest) + return + for table in (HEADS, SOURCES_TABLE, ARTIFACTS_TABLE, CURSORS, PENDING, WAVES, LEASES, STATES, INTENTS): + if await _count_if_present(connection, table): + raise ProcessingSchemaNotReadyError(reason="Existing processing data requires offline processing migration") + problems = await _schema_issues(connection) + if problems: + raise ProcessingSchemaNotReadyError(reason="; ".join(problems)) + await _phase(connection, "complete") + + +async def _seed_fresh_marker(connection: AsyncConnection, manifest: str) -> None: + values = { + "singleton": 1, + "schema_version": PROCESSING_SCHEMA_VERSION, + "source_version": PROCESSING_SCHEMA_VERSION, + "phase": "bootstrap", + "migration_id": "fresh", + "config_manifest": manifest, + } + if connection.dialect.name == "sqlite": + statement = sqlite_insert(SCHEMA).values(**values).on_conflict_do_nothing() + elif connection.dialect.name == "mysql": + statement = ( + mysql_insert(SCHEMA).values(**values).on_duplicate_key_update(schema_version=SCHEMA.c.schema_version) + ) + else: + raise ProcessingSchemaNotReadyError(reason="Unsupported processing database dialect") + # An upsert serializes fresh OceanBase candidates without a read/insert + # race. Its marker is rolled back with this transaction on legacy detection. + await connection.execute(statement) + + +async def assert_processing_schema_ready( + connection: AsyncConnection, + config_manifest: Mapping[str, Any] | str | None = None, +) -> None: + """Reject incomplete migration and mixed deployment modes before dispatch.""" + + marker = await _marker(connection) + if marker is None or marker["schema_version"] != PROCESSING_SCHEMA_VERSION or marker["phase"] != "complete": + raise ProcessingSchemaNotReadyError( + reason="Processing schema is not ready; complete offline plan/apply/verify first" + ) + if config_manifest is not None and _deployment_manifest(str(marker["config_manifest"])) != _deployment_manifest( + _manifest(config_manifest) + ): + raise ProcessingSchemaNotReadyError( + reason="Processing configuration differs from the completed maintenance manifest" + ) + if not set(_STATE_COLUMNS) <= (await _columns(connection, STATES.name)).keys(): + raise ProcessingSchemaNotReadyError(reason="Processing scan schema is incomplete") + problems = await _schema_issues(connection) + if problems: + raise ProcessingSchemaNotReadyError(reason="; ".join(problems)) + + +async def apply_processing_migration( # noqa: C901 - explicit durable maintenance phases + connection: AsyncConnection, + *, + config_manifest: Mapping[str, Any] | str | None = None, + migration_id: str = "rfc1515", + batch_size: int = 100, +) -> ProcessingMigrationProgress: + """Apply one resumable step; caller commits this transaction before retry. + + A different manifest on an already migrated database is an offline mode + switch. It requires a new migration ID and invalidates every old Lease, but + never remaps domain inputs or increments accepted request counters again. + """ + + if not migration_id or len(migration_id) > 64: + raise ProcessingSchemaNotReadyError(reason="Migration ID must contain 1 to 64 characters") + if not isinstance(batch_size, int) or isinstance(batch_size, bool) or batch_size < 1: + raise ProcessingSchemaNotReadyError(reason="Migration batch size must be a positive integer") + manifest = _manifest(config_manifest) + marker = await _marker(connection) + if marker is None: + await connection.run_sync(lambda sync: SCHEMA.create(sync, checkfirst=True)) + await connection.execute( + insert(SCHEMA).values( + singleton=1, + schema_version=PROCESSING_SCHEMA_VERSION, + source_version=1490, + phase="schema", + migration_id=migration_id, + config_manifest=manifest, + ) + ) + return ProcessingMigrationProgress(phase="schema") + if marker["phase"] == "complete": + if _deployment_manifest(str(marker["config_manifest"])) == _deployment_manifest(manifest): + return ProcessingMigrationProgress(phase="complete", complete=True) + if marker["migration_id"] == migration_id: + raise ProcessingSchemaNotReadyError(reason="A mode switch requires a new migration ID") + await connection.execute( + update(SCHEMA) + .where(SCHEMA.c.singleton == 1) + .values( + source_version=PROCESSING_SCHEMA_VERSION, + phase="invalidate", + migration_id=migration_id, + config_manifest=manifest, + ) + ) + return ProcessingMigrationProgress(phase="invalidate") + if marker["migration_id"] != migration_id or marker["config_manifest"] != manifest: + raise ProcessingSchemaNotReadyError(reason="Resume the unfinished migration with its original ID and manifest") + phase = str(marker["phase"]) + if phase == "schema": + for table in (*_NEW_TABLES, STATES): + if not await _has_table(connection, table.name): + await connection.run_sync(lambda sync, owned=table: owned.create(sync, checkfirst=True)) + return ProcessingMigrationProgress(phase="schema") + columns = await _columns(connection, STATES.name) + for name, definition in _STATE_COLUMNS.items(): + if name not in columns: + # Names/definitions are fixed constants, never user SQL. + await connection.exec_driver_sql(f"ALTER TABLE {STATES.name} ADD COLUMN {name} {definition}") + return ProcessingMigrationProgress(phase="schema") + problems = await _schema_issues(connection) + if problems: + raise ProcessingSchemaNotReadyError(reason="; ".join(problems)) + await _phase(connection, "invalidate") + return ProcessingMigrationProgress(phase="invalidate") + if phase == "invalidate": + holder = "migration-" + hashlib.sha256(migration_id.encode()).hexdigest()[:24] + expired_at = await database_utc_now(connection) - timedelta(seconds=1) + await connection.execute( + update(LEASES).values( + holder_id=holder, supervisor_generation=LEASES.c.supervisor_generation + 1, lease_expires_at=expired_at + ) + ) + next_phase = "backfill" if marker["source_version"] < PROCESSING_SCHEMA_VERSION else "verify" + await _phase(connection, next_phase) + return ProcessingMigrationProgress(phase=next_phase) + if phase == "backfill": + keys = await _unmapped_keys(connection, migration_id, manifest, batch_size) + for binding_name, scope_id in keys: + await _migrate_scope(connection, migration_id, manifest, binding_name, scope_id) + if not keys: + await _phase(connection, "checkpoint") + return ProcessingMigrationProgress(phase="checkpoint") + return ProcessingMigrationProgress(phase="backfill", processed=len(keys)) + if phase == "checkpoint": + await connection.execute( + update(STATES) + .where(STATES.c.last_schedule_checkpoint_at.is_(None)) + .values(last_schedule_checkpoint_at=STATES.c.last_auto_wave_completed_at) + ) + await _phase(connection, "verify") + return ProcessingMigrationProgress(phase="verify") + if phase == "verify": + report = await verify_processing_migration(connection, config_manifest=config_manifest) + if report.issues: + raise ProcessingSchemaNotReadyError( + reason="Processing migration verification failed: " + "; ".join(report.issues) + ) + await _phase(connection, "cleanup") + return ProcessingMigrationProgress(phase="cleanup") + if phase == "cleanup": + # Only scheduling snapshots are obsolete. Topic Pending, Cursor, budget + # and evidence remain domain-owned. Keep the empty legacy table so + # create_all cannot accidentally change upgrade detection. + await connection.execute(delete(WAVES)) + await _phase(connection, "complete") + return ProcessingMigrationProgress(phase="complete", complete=True) + raise ProcessingSchemaNotReadyError(reason="Unknown processing migration phase") + + +async def verify_processing_migration( # noqa: C901 - independent persisted invariants + connection: AsyncConnection, + *, + config_manifest: Mapping[str, Any] | str | None = None, +) -> ProcessingMigrationVerification: + """Check durable postconditions using bounded pages, including on resume.""" + + marker = await _marker(connection) + if marker is None: + return ProcessingMigrationVerification(ready=False, issues=("missing migration marker",)) + issues: list[str] = [] + if marker["schema_version"] != PROCESSING_SCHEMA_VERSION: + issues.append("unsupported schema version") + if config_manifest is not None and _deployment_manifest(str(marker["config_manifest"])) != _deployment_manifest( + _manifest(config_manifest) + ): + issues.append("configuration manifest mismatch") + if not set(_STATE_COLUMNS) <= (await _columns(connection, STATES.name)).keys(): + issues.append("incomplete scan state columns") + for table in _NEW_TABLES: + if not await _has_table(connection, table.name): + issues.append("missing " + table.name) + if not issues: + issues.extend(await _schema_issues(connection)) + if issues: + return ProcessingMigrationVerification(ready=False, issues=tuple(issues)) + if marker["phase"] not in {"verify", "cleanup", "complete"}: + return ProcessingMigrationVerification(ready=False, issues=("migration backfill is not complete",)) + migration_id = str(marker["migration_id"]) + manifest = str(marker["config_manifest"]) + if marker["source_version"] < PROCESSING_SCHEMA_VERSION and marker["phase"] != "complete": + if await _unmapped_keys(connection, migration_id, manifest, 1): + issues.append("legacy inputs remain without migration receipts") + after: tuple[str, str] | None = None + while True: + statement = select(RECEIPTS).where(RECEIPTS.c.migration_id == migration_id) + if after is not None: + statement = statement.where( + or_( + RECEIPTS.c.binding_name > after[0], + and_(RECEIPTS.c.binding_name == after[0], RECEIPTS.c.scope_id > after[1]), + ) + ) + rows = ( + (await connection.execute(statement.order_by(RECEIPTS.c.binding_name, RECEIPTS.c.scope_id).limit(100))) + .mappings() + .all() + ) + if not rows: + break + for receipt in rows: + binding, scope = str(receipt["binding_name"]), str(receipt["scope_id"]) + intent = await ArtifactProcessingIntentRepository().load(connection, scope, binding) + if ( + intent is None + or intent.requested_generation < receipt["requested_generation"] + or intent.dirty_generation < receipt["dirty_generation"] + ): + issues.append("receipt has no matching invocation and dirty state") + break + snapshot = await _snapshot(connection, binding, scope) + if _snapshot_bytes(snapshot) != bytes(receipt["source_snapshot"]): + issues.append("legacy inputs or Cursor changed during maintenance") + break + if receipt["source_through"] > 0 and receipt["requested_generation"] > 0 and binding == _TOPIC_BINDING: + target = ( + ( + await connection.execute( + select(TARGETS).where(TARGETS.c.binding_name == binding, TARGETS.c.scope_id == scope) + ) + ) + .mappings() + .one_or_none() + ) + if ( + target is None + or target["source_through"] < receipt["source_through"] + or target["target_request_generation"] != receipt["requested_generation"] + ): + issues.append("accepted Topic target is missing or changed") + break + if issues: + break + after = str(rows[-1]["binding_name"]), str(rows[-1]["scope_id"]) + invalid = await connection.scalar( + select(func.count()) + .select_from(INTENTS) + .where( + or_( + INTENTS.c.clean_generation < 0, + INTENTS.c.clean_generation > INTENTS.c.dirty_generation, + INTENTS.c.handled_generation < 0, + INTENTS.c.handled_generation > INTENTS.c.requested_generation, + INTENTS.c.pending_sequence <= 0, + ) + ) + ) + if invalid: + issues.append("intent counter invariant violated") + maximum = int(await connection.scalar(select(func.max(INTENTS.c.pending_sequence))) or 0) + sequence = int(await connection.scalar(select(SEQUENCES.c.sequence).where(SEQUENCES.c.singleton == 1)) or 0) + if sequence < maximum: + issues.append("sequence allocator is behind registered intents") + return ProcessingMigrationVerification(ready=not issues and marker["phase"] == "complete", issues=tuple(issues)) + + +async def _migrate_scope( + connection: AsyncConnection, migration_id: str, manifest: str, binding_name: str, scope_id: str +) -> None: + if binding_name not in _bindings(manifest): + raise ProcessingSchemaNotReadyError(reason="Legacy binding has no explicit Family mapping: " + binding_name) + snapshot = await _snapshot(connection, binding_name, scope_id) + cursor = int(snapshot["cursor"]) + if int(snapshot["completed_through"]) > cursor: + raise ProcessingSchemaNotReadyError(reason="Completed legacy target is not covered by its Cursor") + pending_through = int(snapshot["pending_through"]) + dirty = max(int(snapshot["head"]), pending_through) > cursor + unhandled = int(snapshot["flush"]) > int(snapshot["handled_flush"]) + conservative = ( + binding_name in _automatic_bindings(manifest) and pending_through > cursor and int(snapshot["wave_count"]) == 0 + ) + accepted = unhandled or conservative or int(snapshot["unfinished_count"]) > 0 + through = max(pending_through if unhandled or conservative else 0, int(snapshot["unfinished_through"])) + if through > int(snapshot["head"]): + raise ProcessingSchemaNotReadyError(reason="Legacy processing target exceeds its Source head") + intents = ArtifactProcessingIntentRepository() + intent = await intents.ensure(connection, scope_id, binding_name) + if dirty and intent.dirty_generation == intent.clean_generation: + intent = await intents.mark_dirty(connection, scope_id, binding_name) + if accepted and intent.requested_generation == intent.handled_generation: + intent = await intents.request(connection, scope_id, binding_name) + if binding_name == _TOPIC_BINDING: + if dirty and int(snapshot["head"]) > pending_through: + await ArtifactProcessingPendingRepository().raise_source( + connection, scope_id, binding_name, int(snapshot["head"]) + ) + if accepted: + target = ( + ( + await connection.execute( + select(TARGETS) + .where(TARGETS.c.binding_name == binding_name, TARGETS.c.scope_id == scope_id) + .with_for_update() + ) + ) + .mappings() + .one_or_none() + ) + values = { + "target_request_generation": intent.requested_generation, + "source_through": through, + "captured_flush_generation": int(snapshot["flush"]), + "observed_dirty_generation": intent.dirty_generation, + } + if target is None: + await connection.execute(insert(TARGETS).values(binding_name=binding_name, scope_id=scope_id, **values)) + else: + values["source_through"] = max(through, int(target["source_through"])) + await connection.execute( + update(TARGETS) + .where(TARGETS.c.binding_name == binding_name, TARGETS.c.scope_id == scope_id) + .values(**values) + ) + # A receipt and all of its side effects commit together. Existence is tested + # by the bounded anti-join before processing; it never executes an upsert++. + await connection.execute( + insert(RECEIPTS).values( + migration_id=migration_id, + binding_name=binding_name, + scope_id=scope_id, + source_snapshot=_snapshot_bytes(await _snapshot(connection, binding_name, scope_id)), + requested_generation=intent.requested_generation, + dirty_generation=intent.dirty_generation, + source_through=through, + ) + ) + + +async def _snapshot(connection: AsyncConnection, binding_name: str, scope_id: str) -> dict[str, int]: + pending = await ArtifactProcessingPendingRepository().load(connection, scope_id, binding_name) + cursor = await SourceCursorRepository().load(connection, scope_id, binding_name) + wave = ( + ( + await connection.execute( + select( + func.count().label("count"), + func.sum(case((WAVES.c.completed.is_(False), 1), else_=0)).label("unfinished_count"), + func.max(case((WAVES.c.completed.is_(False), WAVES.c.source_through), else_=0)).label( + "unfinished_through" + ), + func.max(case((WAVES.c.completed.is_(True), WAVES.c.source_through), else_=0)).label( + "completed_through" + ), + ).where(WAVES.c.binding_name == binding_name, WAVES.c.scope_id == scope_id) + ) + ) + .mappings() + .one() + ) + return { + "pending_through": 0 if pending is None else pending.source_through, + "flush": 0 if pending is None else pending.flush_generation, + "handled_flush": 0 if pending is None else pending.handled_flush_generation, + "cursor": 0 if cursor is None else cursor.cursor.sequence, + "cursor_generation": 0 if cursor is None else cursor.generation, + "head": int(await connection.scalar(select(HEADS.c.position).where(HEADS.c.scope_id == scope_id)) or 0), + "wave_count": int(wave["count"]), + "unfinished_count": int(wave["unfinished_count"] or 0), + "unfinished_through": int(wave["unfinished_through"] or 0), + "completed_through": int(wave["completed_through"] or 0), + } + + +async def _unmapped_keys( + connection: AsyncConnection, migration_id: str, manifest: str, limit: int +) -> tuple[tuple[str, str], ...]: + queries = [select(PENDING.c.binding_name, PENDING.c.scope_id), select(WAVES.c.binding_name, WAVES.c.scope_id)] + queries.extend(select(literal(binding).label("binding_name"), HEADS.c.scope_id) for binding in _bindings(manifest)) + keys = queries[0].union(*queries[1:]).subquery() + recorded = exists( + select(1).where( + RECEIPTS.c.migration_id == migration_id, + RECEIPTS.c.binding_name == keys.c.binding_name, + RECEIPTS.c.scope_id == keys.c.scope_id, + ) + ) + rows = await connection.execute( + select(keys.c.binding_name, keys.c.scope_id) + .where(~recorded) + .order_by(keys.c.binding_name, keys.c.scope_id) + .limit(limit) + ) + return tuple((str(binding), str(scope)) for binding, scope in rows) + + +async def _phase(connection: AsyncConnection, phase: str) -> None: + await connection.execute(update(SCHEMA).where(SCHEMA.c.singleton == 1).values(phase=phase)) + + +async def _marker(connection: AsyncConnection, *, for_update: bool = False) -> Mapping[str, Any] | None: + if not await _has_table(connection, SCHEMA.name): + return None + statement = select(SCHEMA).where(SCHEMA.c.singleton == 1) + if for_update: + statement = statement.with_for_update() + row = (await connection.execute(statement)).mappings().one_or_none() + return None if row is None else dict(row) + + +async def _columns(connection: AsyncConnection, table_name: str) -> dict[str, dict[str, Any]]: + if not await _has_table(connection, table_name): + return {} + columns = await connection.run_sync(lambda sync: inspect(sync).get_columns(table_name)) + return {str(column["name"]): dict(column) for column in columns} + + +async def _schema_issues(connection: AsyncConnection) -> list[str]: # noqa: C901 - DDL postconditions + """Validate existing DDL, not merely the presence of an earlier ADD COLUMN.""" + + problems: list[str] = [] + for table in (*_NEW_TABLES, STATES): + columns = await _columns(connection, table.name) + for expected in table.columns: + actual = columns.get(expected.name) + if actual is None: + problems.append(f"missing {table.name}.{expected.name}") + continue + mysql_boolean = ( + connection.dialect.name == "mysql" + and isinstance(expected.type, Boolean) + and isinstance(actual["type"], TINYINT) + and getattr(actual["type"], "display_width", None) in {None, 1} + ) + if actual["type"]._type_affinity is not expected.type._type_affinity and not mysql_boolean: + problems.append(f"incompatible type for {table.name}.{expected.name}") + if bool(actual["nullable"]) != expected.nullable: + problems.append(f"incompatible nullability for {table.name}.{expected.name}") + if expected.server_default is not None: + actual_default = str(actual.get("default") or "").strip("()'\"") + if actual_default != str(getattr(expected.server_default, "arg", None)): + problems.append(f"incompatible default for {table.name}.{expected.name}") + if columns: + primary = await connection.run_sync(lambda sync, owned=table: inspect(sync).get_pk_constraint(owned.name)) + if tuple(primary.get("constrained_columns") or ()) != tuple(column.name for column in table.primary_key): + problems.append(f"incompatible primary key for {table.name}") + if not problems: + unique = await connection.run_sync(lambda sync: inspect(sync).get_unique_constraints(INTENTS.name)) + if not any(tuple(item.get("column_names") or ()) == ("pending_sequence",) for item in unique): + problems.append("intent pending sequence is not unique") + return problems + + +async def _has_table(connection: AsyncConnection, name: str) -> bool: + return bool(await connection.run_sync(lambda sync: inspect(sync).has_table(name))) + + +async def _count_if_present(connection: AsyncConnection, table: Any) -> int: + if not await _has_table(connection, table.name): + return 0 + return int(await connection.scalar(select(func.count()).select_from(table)) or 0) + + +def _manifest(value: Mapping[str, Any] | str | None) -> str: + decoded = json.loads(value) if isinstance(value, str) else dict(value or {}) + if not isinstance(decoded, dict): + raise ProcessingSchemaNotReadyError(reason="Processing manifest must be a JSON object") + if decoded.get("mode", "global") not in {"global", "dedicated"}: + raise ProcessingSchemaNotReadyError(reason="Unknown processing Supervisor mode") + return json.dumps(decoded, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + + +def _deployment_manifest(manifest: str) -> str: + value = json.loads(manifest) + value.pop("legacy_automatic_bindings", None) + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + + +def _bindings(manifest: str) -> dict[str, str]: + value = json.loads(manifest).get("bindings", _DEFAULT_BINDINGS) + if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k, v in value.items()): + raise ProcessingSchemaNotReadyError(reason="Manifest bindings must map stable binding names to Family names") + return cast(dict[str, str], value) + + +def _automatic_bindings(manifest: str) -> tuple[str, ...]: + value = json.loads(manifest).get("legacy_automatic_bindings", [_TOPIC_BINDING]) + if not isinstance(value, list) or any(not isinstance(item, str) for item in value): + raise ProcessingSchemaNotReadyError(reason="Legacy automatic bindings must be a list") + return tuple(value) + + +def _snapshot_bytes(value: Mapping[str, int]) -> bytes: + return json.dumps(dict(value), sort_keys=True, separators=(",", ":")).encode() + + +__all__ = [ + "PROCESSING_SCHEMA_VERSION", + "ProcessingMigrationPlan", + "ProcessingMigrationProgress", + "ProcessingMigrationVerification", + "ProcessingSchemaNotReadyError", + "apply_processing_migration", + "assert_processing_schema_ready", + "bootstrap_processing_schema", + "plan_processing_migration", + "verify_processing_migration", +] diff --git a/src/powercontext/builtin/persistence/sources.py b/src/powercontext/builtin/persistence/sources.py index b9045b4449..ba3cd56c56 100644 --- a/src/powercontext/builtin/persistence/sources.py +++ b/src/powercontext/builtin/persistence/sources.py @@ -26,6 +26,9 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncConnection +from powercontext.builtin.artifacts.experience import EXPERIENCE_INCUBATION_CURSOR_NAME +from powercontext.builtin.artifacts.profile.models import PROFILE_SOURCE_WINDOW_BINDING +from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING from powercontext.builtin.persistence.codec import load_model, stored_bytes from powercontext.builtin.persistence.errors import ( IdentityMismatchError, @@ -35,14 +38,22 @@ RepositoryNotFoundError, StoredPayloadConflictError, ) +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.tables import SOURCE_JOURNAL_HEADS_TABLE, SOURCES_TABLE from powercontext.builtin.sources.content import ContentSource +from powercontext.builtin.triggers import SOURCE_WINDOW_TRIGGER_NAME from powercontext.errors import SourceDefinitionNotFoundError from powercontext.limits import MAX_SCOPE_ID_LENGTH from powercontext.sources import Source, SourceAdapter, SourceDefinitionRegistry, SourceObservation, SourceRef _AnySourceAdapter = SourceAdapter[Any, Any, Any] _JSON_OBJECT = TypeAdapter(dict[str, JsonValue]) +SOURCE_PROCESSING_BINDINGS = ( + SOURCE_WINDOW_TRIGGER_NAME, + TOPIC_MEMORY_SOURCE_WINDOW_BINDING, + EXPERIENCE_INCUBATION_CURSOR_NAME, + PROFILE_SOURCE_WINDOW_BINDING, +) class _StoredSourcePayload(BaseModel): @@ -154,6 +165,12 @@ async def add_with_status( if stored.value != source: raise StoredPayloadConflictError("source", (scope_id, ref)) from None return stored, False + # Centralized here so capture, record projection and import all publish + # discoverable input atomically. Replayed Source identities do not dirty + # a binding again. Disabled processors simply retain ordinary dirty. + intents = ArtifactProcessingIntentRepository() + for binding_name in SOURCE_PROCESSING_BINDINGS: + await intents.mark_dirty(connection, scope_id, binding_name) return StoredSource(ref=ref, value=source, journal_position=position), True async def get( diff --git a/src/powercontext/builtin/persistence/supervision.py b/src/powercontext/builtin/persistence/supervision.py index 8c22c6e696..fcc3eced25 100644 --- a/src/powercontext/builtin/persistence/supervision.py +++ b/src/powercontext/builtin/persistence/supervision.py @@ -18,7 +18,7 @@ from collections.abc import Mapping from datetime import UTC, datetime, timedelta -from typing import Any, Literal +from typing import Any, Literal, cast from pydantic import BaseModel from sqlalchemy import func, insert, select, update @@ -29,6 +29,7 @@ ArtifactProcessingLeadershipLostError, InvalidRepositoryArgumentError, ) +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.tables import ( ARTIFACT_PROCESSING_BINDING_STATES_TABLE, ARTIFACT_PROCESSING_LEASES_TABLE, @@ -71,7 +72,11 @@ class StoredArtifactProcessingBindingState(BaseModel): """The persisted scheduling baseline for one registered binding.""" binding_name: str - last_auto_wave_completed_at: datetime | None + last_auto_wave_completed_at: datetime | None = None + last_schedule_checkpoint_at: datetime | None = None + scan_generation: int = 0 + scan_in_progress: bool = False + scan_upper_pending_sequence: int | None = None class ArtifactProcessingLeaseRepository: @@ -86,6 +91,14 @@ async def load( for_update: bool = False, ) -> StoredArtifactProcessingLease | None: _require_identifier("supervisor_group", supervisor_group, 64) + if for_update and connection.dialect.name == "sqlite": + # FOR UPDATE is omitted by SQLite. Obtain its real write lock + # BEFORE reading the term, also when the row does not exist yet. + await connection.execute( + update(ARTIFACT_PROCESSING_LEASES_TABLE) + .where(ARTIFACT_PROCESSING_LEASES_TABLE.c.supervisor_group == supervisor_group) + .values(holder_id=ARTIFACT_PROCESSING_LEASES_TABLE.c.holder_id) + ) statement = select(ARTIFACT_PROCESSING_LEASES_TABLE).where( ARTIFACT_PROCESSING_LEASES_TABLE.c.supervisor_group == supervisor_group ) @@ -272,6 +285,12 @@ async def load( for_update: bool = False, ) -> StoredArtifactProcessingBindingState | None: _require_identifier("binding_name", binding_name, MAX_BINDING_NAME_LENGTH) + if for_update and connection.dialect.name == "sqlite": + await connection.execute( + update(ARTIFACT_PROCESSING_BINDING_STATES_TABLE) + .where(ARTIFACT_PROCESSING_BINDING_STATES_TABLE.c.binding_name == binding_name) + .values(scan_generation=ARTIFACT_PROCESSING_BINDING_STATES_TABLE.c.scan_generation) + ) statement = select(ARTIFACT_PROCESSING_BINDING_STATES_TABLE).where( ARTIFACT_PROCESSING_BINDING_STATES_TABLE.c.binding_name == binding_name ) @@ -280,6 +299,45 @@ async def load( row = (await connection.execute(statement)).mappings().one_or_none() return None if row is None else _decode_binding_state(row) + async def start_scan( + self, + connection: AsyncConnection, + binding_name: str, + checkpoint_at: datetime | None = None, + /, + ) -> StoredArtifactProcessingBindingState: + """Freeze a bounded admission scan; caller must hold its valid fence.""" + + current = await self.load(connection, binding_name, for_update=True) + if current is not None and current.scan_in_progress: + return current + checkpoint = await database_utc_now(connection) if checkpoint_at is None else checkpoint_at + if checkpoint.tzinfo is not None: + checkpoint = checkpoint.astimezone(UTC).replace(tzinfo=None) + values = { + "last_schedule_checkpoint_at": checkpoint, + "scan_generation": 1 if current is None else current.scan_generation + 1, + "scan_in_progress": True, + "scan_upper_pending_sequence": await ArtifactProcessingIntentRepository().max_sequence( + connection, binding_name + ), + } + table = ARTIFACT_PROCESSING_BINDING_STATES_TABLE + if current is None: + await connection.execute(insert(table).values(binding_name=binding_name, **values)) + else: + await connection.execute(update(table).where(table.c.binding_name == binding_name).values(**values)) + return cast(StoredArtifactProcessingBindingState, await self.load(connection, binding_name)) + + async def finish_scan(self, connection: AsyncConnection, binding_name: str, /) -> None: + """End discovery without waiting for Workers; caller holds its fence.""" + + _require_identifier("binding_name", binding_name, MAX_BINDING_NAME_LENGTH) + table = ARTIFACT_PROCESSING_BINDING_STATES_TABLE + await connection.execute( + update(table).where(table.c.binding_name == binding_name).values(scan_in_progress=False) + ) + async def mark_auto_wave_completed( self, connection: AsyncConnection, @@ -321,6 +379,11 @@ async def mark_auto_wave_completed( async def database_utc_now(connection: AsyncConnection) -> datetime: """Read current UTC from the authoritative database connection.""" + if connection.dialect.name == "sqlite": + value = await connection.scalar(select(func.strftime("%Y-%m-%d %H:%M:%f", "now"))) + if isinstance(value, str): + return datetime.fromisoformat(value) + raise InvalidRepositoryArgumentError("database_time", "database did not return a timestamp") expression = func.utc_timestamp(6) if connection.dialect.name == "mysql" else func.current_timestamp() value = await connection.scalar(select(expression)) if not isinstance(value, datetime): @@ -343,6 +406,10 @@ def _decode_binding_state(row: Mapping[Any, Any]) -> StoredArtifactProcessingBin return StoredArtifactProcessingBindingState( binding_name=str(row["binding_name"]), last_auto_wave_completed_at=row["last_auto_wave_completed_at"], + last_schedule_checkpoint_at=row["last_schedule_checkpoint_at"], + scan_generation=int(row["scan_generation"]), + scan_in_progress=bool(row["scan_in_progress"]), + scan_upper_pending_sequence=row["scan_upper_pending_sequence"], ) diff --git a/src/powercontext/builtin/persistence/tables.py b/src/powercontext/builtin/persistence/tables.py index e10837fee0..bd617564eb 100644 --- a/src/powercontext/builtin/persistence/tables.py +++ b/src/powercontext/builtin/persistence/tables.py @@ -491,6 +491,85 @@ def _entry_text_type(): SHARED_METADATA, Column("binding_name", identity_string(MAX_BINDING_NAME_LENGTH), primary_key=True), Column("last_auto_wave_completed_at", DateTime(timezone=False)), + Column("last_schedule_checkpoint_at", DateTime(timezone=False)), + Column("scan_generation", BigInteger, nullable=False, server_default="0"), + Column("scan_in_progress", Boolean, nullable=False, server_default="0"), + Column("scan_upper_pending_sequence", BigInteger), + CheckConstraint("scan_generation >= 0", name="ck_pc_processing_scan_generation"), +) + +ARTIFACT_PROCESSING_SEQUENCES_TABLE = Table( + "pc_artifact_processing_sequences", + SHARED_METADATA, + Column("singleton", Integer, primary_key=True, autoincrement=False), + Column("sequence", BigInteger, nullable=False), + CheckConstraint("singleton = 1 AND sequence >= 0", name="ck_pc_processing_sequence"), +) + +ARTIFACT_PROCESSING_INTENTS_TABLE = Table( + "pc_artifact_processing_intents", + SHARED_METADATA, + Column("binding_name", identity_string(MAX_BINDING_NAME_LENGTH), primary_key=True), + Column("scope_id", identity_string(MAX_SCOPE_ID_LENGTH), primary_key=True), + Column("pending_sequence", BigInteger, nullable=False, unique=True), + Column("dirty_generation", BigInteger, nullable=False, server_default="0"), + Column("clean_generation", BigInteger, nullable=False, server_default="0"), + Column("requested_generation", BigInteger, nullable=False, server_default="0"), + Column("handled_generation", BigInteger, nullable=False, server_default="0"), + Column("last_auto_scan_generation", BigInteger, nullable=False, server_default="0"), + CheckConstraint("pending_sequence > 0", name="ck_pc_processing_intent_sequence"), + CheckConstraint( + "clean_generation >= 0 AND clean_generation <= dirty_generation", + name="ck_pc_processing_intent_dirty", + ), + CheckConstraint( + "handled_generation >= 0 AND handled_generation <= requested_generation", + name="ck_pc_processing_intent_request", + ), + CheckConstraint("last_auto_scan_generation >= 0", name="ck_pc_processing_intent_scan"), + Index("ix_pc_processing_intent_binding_sequence", "binding_name", "pending_sequence"), +) + +TOPIC_MEMORY_PROCESSING_TARGETS_TABLE = Table( + "pc_topic_memory_processing_targets", + SHARED_METADATA, + Column("binding_name", identity_string(MAX_BINDING_NAME_LENGTH), primary_key=True), + Column("scope_id", identity_string(MAX_SCOPE_ID_LENGTH), primary_key=True), + Column("target_request_generation", BigInteger, nullable=False), + Column("source_through", BigInteger, nullable=False), + Column("captured_flush_generation", BigInteger, nullable=False), + Column("observed_dirty_generation", BigInteger, nullable=False), + CheckConstraint( + "target_request_generation > 0 AND source_through >= 0 " + "AND captured_flush_generation >= 0 AND observed_dirty_generation >= 0", + name="ck_pc_topic_processing_target", + ), +) + +# These are migration receipts, not execution or retry history. They are kept +# after maintenance so a crash after legacy cleanup can still be verified. +ARTIFACT_PROCESSING_SCHEMA_TABLE = Table( + "pc_artifact_processing_schema", + SHARED_METADATA, + Column("singleton", Integer, primary_key=True, autoincrement=False), + Column("schema_version", Integer, nullable=False), + Column("source_version", Integer, nullable=False, server_default="1490"), + Column("phase", identity_string(32), nullable=False), + Column("migration_id", identity_string(64), nullable=False), + Column("config_manifest", Text, nullable=False), + CheckConstraint("singleton = 1", name="ck_pc_processing_schema_singleton"), +) + +ARTIFACT_PROCESSING_MIGRATION_RECEIPTS_TABLE = Table( + "pc_artifact_processing_migration_receipts", + SHARED_METADATA, + Column("migration_id", identity_string(64), primary_key=True), + Column("binding_name", identity_string(MAX_BINDING_NAME_LENGTH), primary_key=True), + Column("scope_id", identity_string(MAX_SCOPE_ID_LENGTH), primary_key=True), + Column("source_snapshot", _canonical_payload_type(), nullable=False), + Column("requested_generation", BigInteger, nullable=False), + Column("dirty_generation", BigInteger, nullable=False), + Column("source_through", BigInteger, nullable=False), ) TOPIC_MEMORY_WORK_BUDGETS_TABLE = Table( @@ -831,6 +910,11 @@ def _entry_text_type(): TOPIC_MEMORY_WORK_BUDGETS_TABLE, ARTIFACT_PROCESSING_PENDING_TABLE, ARTIFACT_PROCESSING_AUTO_WAVE_TARGETS_TABLE, + ARTIFACT_PROCESSING_SEQUENCES_TABLE, + ARTIFACT_PROCESSING_INTENTS_TABLE, + TOPIC_MEMORY_PROCESSING_TARGETS_TABLE, + ARTIFACT_PROCESSING_SCHEMA_TABLE, + ARTIFACT_PROCESSING_MIGRATION_RECEIPTS_TABLE, CONNECTOR_CHECKPOINTS_TABLE, SOURCE_DEFINITION_MANIFESTS_TABLE, EXTERNAL_SKILL_REGISTRATIONS_TABLE, diff --git a/src/powercontext/builtin/runtime/__init__.py b/src/powercontext/builtin/runtime/__init__.py index 8935d4c3be..c8eba03c4e 100644 --- a/src/powercontext/builtin/runtime/__init__.py +++ b/src/powercontext/builtin/runtime/__init__.py @@ -70,8 +70,6 @@ ArtifactProcessingBinding, ArtifactProcessingSupervisor, ArtifactProcessingSupervisorStatus, - ArtifactProcessingWaveKind, - ArtifactProcessingWindowSelector, ArtifactProcessingWorkAssignment, ArtifactProcessingWorkerCompletion, ArtifactProcessingWorkerFailure, @@ -188,8 +186,6 @@ "ArtifactProcessingBinding", "ArtifactProcessingSupervisor", "ArtifactProcessingSupervisorStatus", - "ArtifactProcessingWaveKind", - "ArtifactProcessingWindowSelector", "ArtifactProcessingWorkAssignment", "ArtifactProcessingWorkerCompletion", "ArtifactProcessingWorkerFailure", diff --git a/src/powercontext/builtin/runtime/application.py b/src/powercontext/builtin/runtime/application.py index 39b7a8bd5d..c07b2aaead 100644 --- a/src/powercontext/builtin/runtime/application.py +++ b/src/powercontext/builtin/runtime/application.py @@ -102,6 +102,7 @@ MAX_TOPIC_MEMORY_QUERY_LENGTH, MAX_TOPIC_MEMORY_QUERY_TERMS, MAX_TOPIC_MEMORY_SEARCH_LIMIT, + TOPIC_MEMORY_SOURCE_WINDOW_BINDING, PublishedTopicMemory, TopicMemory, TopicMemoryBrowseCursor, @@ -262,7 +263,7 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler from powercontext.builtin.handoff_report.application import HandoffReportApplication - from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingSupervisor + from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingSupervisors TopicMemorySearch = Callable[..., Awaitable[TopicMemorySearchResult]] TopicMemoryGet = Callable[[str, ArtifactRef], Awaitable[PublishedTopicMemory]] @@ -1958,7 +1959,7 @@ async def flush(self) -> TopicMemoryFlushResult: accepted = await self._runtime._topic_memory_flush(self.scope_id) if accepted and self._runtime.artifact_processing_supervisor is not None: try: - self._runtime.artifact_processing_supervisor.wake() + self._runtime.artifact_processing_supervisor.wake(TOPIC_MEMORY_SOURCE_WINDOW_BINDING) except Exception as error: log_safely( logger, @@ -2254,7 +2255,7 @@ def __init__( self.remote_skills = RemoteSkillApplication(self) self.statistics = StatisticsApplication(self) self.handoff_report: HandoffReportApplication | None = None - self.artifact_processing_supervisor: ArtifactProcessingSupervisor | None = None + self.artifact_processing_supervisor: ArtifactProcessingSupervisors | None = None self.processor = None if scope_ids is None else ScheduledSourceProcessor(self, scope_ids) self.experience_processor = ( None if scope_ids is None or experience_incubator is None else ScheduledExperienceProcessor(self, scope_ids) @@ -2289,6 +2290,14 @@ async def readiness(self) -> RuntimeReadiness: "runtime": ReadinessCheckStatus.READY, **dependencies.checks, "artifact_processing_supervisor": supervisor_status, + **( + {} + if self.artifact_processing_supervisor is None + else { + f"artifact_processing.{family}": str(details["status"]) + for family, details in self.artifact_processing_supervisor.family_status.items() + } + ), }, ) @@ -2314,7 +2323,7 @@ def start_scheduler( # noqa: C901 raise _RuntimeConfigurationError("scope_ids") if experience_schedule_seconds is not None and self.experience_processor is None: raise _RuntimeStateError("experience-incubation") - if self._scheduler is not None: + if self._scheduler is not None or self.artifact_processing_supervisor is not None: raise _RuntimeStateError("scheduler") from powercontext.builtin.runtime.scheduler import ( configure_experience_incubation_job, diff --git a/src/powercontext/builtin/runtime/artifact_processing.py b/src/powercontext/builtin/runtime/artifact_processing.py index 822a40ea95..35ca87a57c 100644 --- a/src/powercontext/builtin/runtime/artifact_processing.py +++ b/src/powercontext/builtin/runtime/artifact_processing.py @@ -12,21 +12,22 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Global Artifact Processing Supervisor and child-Worker lifecycle.""" +"""Fair, recoverable Scope scheduling and owned child-Worker lifecycles.""" from __future__ import annotations import asyncio import logging import multiprocessing +import re import sys import time import traceback as traceback_module from collections import deque -from collections.abc import Callable, Collection, Mapping, Sequence -from contextlib import suppress +from collections.abc import Awaitable, Callable, Sequence +from contextlib import nullcontext, suppress from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import UTC, datetime, timedelta from enum import StrEnum from multiprocessing.connection import Connection from multiprocessing.context import SpawnProcess @@ -34,7 +35,10 @@ from random import SystemRandom from typing import Protocol from uuid import uuid4 +from zoneinfo import ZoneInfo +from apscheduler.triggers.cron import CronTrigger +from sqlalchemy import func, select, update from sqlalchemy.ext.asyncio import AsyncConnection from typing_extensions import override @@ -44,145 +48,97 @@ from multiprocessing.popen_spawn_posix import Popen as SpawnPopen from powercontext._logging import log_safely -from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.database import AsyncDatabase -from powercontext.builtin.persistence.errors import ( - ArtifactProcessingLeadershipLostError, - ArtifactProcessingWaveIncompleteError, -) -from powercontext.builtin.persistence.processing import ( - ArtifactProcessingAutoWaveTargetRepository, - ArtifactProcessingPendingRepository, - StoredArtifactProcessingPending, -) +from powercontext.builtin.persistence.errors import ArtifactProcessingLeadershipLostError +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.supervision import ( ArtifactProcessingBindingStateRepository, ArtifactProcessingFence, ArtifactProcessingLeaseMode, ArtifactProcessingLeaseRepository, - StoredArtifactProcessingBindingState, database_utc_now, ) +from powercontext.builtin.persistence.tables import ARTIFACT_PROCESSING_INTENTS_TABLE, ARTIFACT_PROCESSING_LEASES_TABLE +from powercontext.builtin.runtime.processing_contracts import ( + ArtifactProcessingWorkAssignment, + ArtifactProcessingWorkerCompletion, + ArtifactProcessingWorkerFailure, + ArtifactProcessingWorkerHandle, + ArtifactProcessingWorkerLauncher, + ArtifactProcessingWorkerOutcome, + WorkerEntrypoint, +) +from powercontext.builtin.runtime.protocols import RuntimeTracing logger = logging.getLogger(__name__) - _OCEANBASE_TICK_SECONDS = 1.0 _OCEANBASE_LEASE_SECONDS = 15.0 _RETRY_BASE_SECONDS = 30.0 -_RETRY_CAP_SECONDS = 30.0 * 60.0 +_RETRY_CAP_SECONDS = 1800.0 _CONTROL_CONFLICT_RETRY_SECONDS = 0.1 _DISCOVERY_PAGE_SIZE = 100 -_DISCOVERY_PAGE_DELAY_SECONDS = 0.01 _RETRY_STATE_LIMIT = 1000 +_CHANNEL_QUEUE_LIMIT = _DISCOVERY_PAGE_SIZE // 2 +_DISCOVERY_PAGE_DELAY_SECONDS = 0.01 +_DISCOVERY_TIMEOUT_SECONDS = 2.0 _SPAWN_SIGTERM_GRACE_SECONDS = 1.0 _WORKER_SHUTDOWN_TIMEOUT_SECONDS = 5.0 - ProcessingKey = tuple[str, str] class ArtifactProcessingSupervisorStatus(StrEnum): - """Safe process status exposed through Runtime readiness.""" - DISABLED = "disabled" LEADER = "leader" STANDBY = "standby" DEGRADED = "degraded" -class ArtifactProcessingWaveKind(StrEnum): - """The persistence semantics used when one frozen wave completes.""" - - EXPLICIT = "explicit" - AUTOMATIC = "automatic" - - -class ArtifactProcessingWorkerOutcome(StrEnum): - """Control outcomes returned after a Worker publication attempt.""" - - SUCCEEDED = "succeeded" - CURSOR_CONFLICT = "cursor_conflict" - HEAD_CONFLICT = "head_conflict" - LEADERSHIP_LOST = "leadership_lost" - - -@dataclass(frozen=True, slots=True) -class ArtifactProcessingWorkAssignment: - """One bounded Source Window assigned to a child Worker.""" - - binding_name: str - scope_id: str - source_after: int - source_through: int - wave_target: int - claimed_flush_generation: int - cursor_generation: int | None - wave_kind: ArtifactProcessingWaveKind - fence: ArtifactProcessingFence - worker_id: str - - -@dataclass(frozen=True, slots=True) -class ArtifactProcessingWorkerFailure: - """Sanitized Worker failure metadata safe to log in the Supervisor.""" - - stage: str - error_code: str - exception_type: str - traceback: str - - -@dataclass(frozen=True, slots=True) -class ArtifactProcessingWorkerCompletion: - """A child Worker's terminal control result.""" - - outcome: ArtifactProcessingWorkerOutcome = ArtifactProcessingWorkerOutcome.SUCCEEDED - - -class ArtifactProcessingWorkerHandle(Protocol): - """One independently terminable Worker child.""" - - async def wait(self) -> ArtifactProcessingWorkerCompletion: ... - - async def terminate(self) -> None: ... - - -class ArtifactProcessingWorkerLauncher(Protocol): - """Spawn exactly one independently terminable Worker. - - Implementations must release partially-created resources if ``start`` is - cancelled. The Supervisor bounds and cancels startup independently from a - Worker's execution timeout. - """ - - async def start(self, assignment: ArtifactProcessingWorkAssignment) -> ArtifactProcessingWorkerHandle: ... - - -class ArtifactProcessingWindowSelector(Protocol): - """Choose a bounded contiguous Source window outside the control transaction.""" - - async def select(self, scope_id: str, source_after: int, source_ceiling: int, /) -> int: ... +class ArtifactProcessingPendingProvider(Protocol): + """Reconcile a bounded page of domain progress without doing business work.""" - -WorkerEntrypoint = Callable[[ArtifactProcessingWorkAssignment], ArtifactProcessingWorkerCompletion | None] + async def reconcile(self, after_scope_id: str | None, limit: int, *, fence: ArtifactProcessingFence) -> str | None: + """Return the next keyset position, or None when this pass is complete.""" + ... @dataclass(frozen=True, slots=True) class ArtifactProcessingBinding: - """Startup-only registration for one Source-driven Artifact processor.""" + """Startup registration of one Family and its independently budgeted Worker.""" binding_name: str - source_window_limit: int + artifact_family: str launcher: ArtifactProcessingWorkerLauncher + max_workers: int = 1 + worker_timeout_seconds: float = 600.0 automatic_processing_interval: timedelta | None = None - window_selector: ArtifactProcessingWindowSelector | None = None + cron: str | None = None + timezone: str = "Asia/Shanghai" + config_prefix: str | None = None + pending_provider: ArtifactProcessingPendingProvider | None = None + # Only automatic admission is filtered; already accepted requests retain + # their own Worker authorization and domain completion semantics. + automatic_scope_filter: Callable[[AsyncConnection, tuple[str, ...]], Awaitable[frozenset[str]]] | None = None def __post_init__(self) -> None: - if not self.binding_name.strip() or self.binding_name != self.binding_name.strip(): - raise ValueError("artifact processing binding_name must be non-empty and trimmed") # noqa: TRY003 - if self.source_window_limit < 1: - raise ValueError("artifact processing source_window_limit must be positive") # noqa: TRY003 - if self.automatic_processing_interval is not None and self.automatic_processing_interval.total_seconds() <= 0: - raise ValueError("artifact processing automatic interval must be positive") # noqa: TRY003 + if not self.binding_name or self.binding_name != self.binding_name.strip(): + raise ValueError("binding_name must be nonempty and trimmed") # noqa: TRY003 + if re.fullmatch(r"[a-z][a-z0-9-]*", self.artifact_family) is None: + raise ValueError("artifact_family must be a canonical Family name") # noqa: TRY003 + prefix = self.config_prefix or self.artifact_family.replace("-", "_").upper() + if re.fullmatch(r"[A-Z][A-Z0-9_]*", prefix) is None: + raise ValueError("config_prefix must be an uppercase configuration prefix") # noqa: TRY003 + object.__setattr__(self, "config_prefix", prefix) + if type(self.max_workers) is not int or self.max_workers < 1: + raise ValueError("max_workers must be a positive integer") # noqa: TRY003 + if self.worker_timeout_seconds <= 0: + raise ValueError("worker_timeout_seconds must be positive") # noqa: TRY003 + if self.automatic_processing_interval is not None: + if self.automatic_processing_interval.total_seconds() <= 0: + raise ValueError("automatic interval must be positive") # noqa: TRY003 + if self.cron is not None: + raise ValueError("interval and cron cannot both be enabled") # noqa: TRY003 + if self.cron is not None: + CronTrigger.from_crontab(self.cron, timezone=ZoneInfo(self.timezone)) @dataclass(slots=True) @@ -387,71 +343,60 @@ async def _close(self) -> None: class _WorkerExecutionError(RuntimeError): def __init__(self, failure: ArtifactProcessingWorkerFailure) -> None: + super().__init__(failure.error_code) self.failure = failure - super().__init__(f"artifact Worker failed at {failure.stage}: {failure.error_code}") class _WorkerTerminationError(RuntimeError): - """The Supervisor could not confirm termination inside its fixed bound.""" - - -class _WindowSelectionError(_WorkerExecutionError): - """A binding/Scope's evidence failed before a Worker could be assigned.""" - - -class _RetryCapacityError(RuntimeError): - """An automatic target cannot be safely evicted from the retry frontier.""" - - -class _AutomaticWaveStateError(RuntimeError): - def __init__(self, wave_id: str, detail: str) -> None: - super().__init__(f"automatic wave {wave_id} has inconsistent target state: {detail}") - - -@dataclass(slots=True) -class _WaveWork: - key: ProcessingKey - wave_kind: ArtifactProcessingWaveKind - wave_target: int - claimed_flush_generation: int - automatic_wave_id: str | None = None - - -@dataclass(slots=True) -class _AutomaticWave: - wave_id: str - binding_name: str - targets: dict[ProcessingKey, int] - deferred_targets: dict[ProcessingKey, int] = field(default_factory=dict) - discovery_after_scope_id: str | None = None - discovery_complete: bool = False - completed: set[ProcessingKey] = field(default_factory=set) + def __init__(self, handle: ArtifactProcessingWorkerHandle) -> None: + super().__init__("Worker exit could not be confirmed") + self.handle = handle @dataclass(slots=True) class _RetryState: - work: _WaveWork - consecutive_failures: int - next_retry_at: float + failures: int + deadline: float @dataclass(slots=True) class _RunningWorker: - work: _WaveWork assignment: ArtifactProcessingWorkAssignment - handle: ArtifactProcessingWorkerHandle task: asyncio.Task[ArtifactProcessingWorkerCompletion] + started_at: float @dataclass(slots=True) -class _LaunchingWorker: - work: _WaveWork - assignment: ArtifactProcessingWorkAssignment - task: asyncio.Task[ArtifactProcessingWorkerHandle] +class _FamilyState: + binding: ArtifactProcessingBinding + ready: deque[str] = field(default_factory=deque) + queued: set[str] = field(default_factory=set) + retry_queued: set[str] = field(default_factory=set) + running: dict[str, _RunningWorker] = field(default_factory=dict) + retries: dict[str, _RetryState] = field(default_factory=dict) + requested_after: int = 0 + scan_after: int = 0 + scan_generation: int = 0 + scan_in_progress: bool = False + reconcile_after: str | None = None + reconcile_complete: bool = False + notification_at_start: int = 0 + discovery_pending: bool = True + next_schedule_at: float | None = None + next_discovery_at: float = 0.0 + automatic_next: bool = False + overflow_not_before: float = 0.0 + degraded: bool = False + completed: int = 0 + failed: int = 0 + timeouts: int = 0 + unacknowledged: int = 0 + discovery_seconds: float = 0 + invocation_seconds: float = 0 class ArtifactProcessingSupervisor: - """Coordinate durable waves through a single fenced, fair global queue.""" + """One Lease and scheduling loop, with independent capacity for each Family.""" def __init__( self, @@ -459,11 +404,8 @@ def __init__( database: AsyncDatabase, bindings: Sequence[ArtifactProcessingBinding], lease_mode: ArtifactProcessingLeaseMode, - max_workers: int, - worker_timeout_seconds: float, - pending: ArtifactProcessingPendingRepository | None = None, - auto_wave_targets: ArtifactProcessingAutoWaveTargetRepository | None = None, - cursors: SourceCursorRepository | None = None, + supervisor_group: str = "global", + intents: ArtifactProcessingIntentRepository | None = None, leases: ArtifactProcessingLeaseRepository | None = None, binding_states: ArtifactProcessingBindingStateRepository | None = None, holder_id: str | None = None, @@ -472,66 +414,72 @@ def __init__( retry_base_seconds: float = _RETRY_BASE_SECONDS, retry_cap_seconds: float = _RETRY_CAP_SECONDS, retry_jitter: Callable[[], float] | None = None, + tracing: RuntimeTracing | None = None, ) -> None: - if max_workers < 1: - raise ValueError("artifact_processing_max_workers must be positive") # noqa: TRY003 - if worker_timeout_seconds <= 0: - raise ValueError("artifact_processing_worker_timeout_seconds must be positive") # noqa: TRY003 - names = [binding.binding_name for binding in bindings] - if len(names) != len(set(names)): - raise ValueError("artifact processing binding names must be unique") # noqa: TRY003 + for attribute in ("binding_name", "artifact_family", "config_prefix"): + names = [getattr(binding, attribute) for binding in bindings] + if len(names) != len(set(names)): + raise ValueError(f"artifact processing {attribute} values must be unique") # noqa: TRY003 + if supervisor_group != "global" and ( + len(bindings) != 1 or supervisor_group != f"artifact:{bindings[0].artifact_family}" + ): + raise ValueError("dedicated Supervisor must own exactly its named Family") # noqa: TRY003 self._database = database - self._bindings = {binding.binding_name: binding for binding in bindings} + self._families = {binding.binding_name: _FamilyState(binding) for binding in bindings} self._lease_mode = lease_mode - self._max_workers = max_workers - self._worker_timeout_seconds = worker_timeout_seconds - self._pending = ArtifactProcessingPendingRepository() if pending is None else pending - self._auto_wave_targets = ( - ArtifactProcessingAutoWaveTargetRepository() if auto_wave_targets is None else auto_wave_targets - ) - self._cursors = SourceCursorRepository() if cursors is None else cursors - self._leases = ArtifactProcessingLeaseRepository() if leases is None else leases - self._binding_states = ArtifactProcessingBindingStateRepository() if binding_states is None else binding_states - self.holder_id = str(uuid4()) if holder_id is None else holder_id - self._oceanbase_tick_seconds = oceanbase_tick_seconds - self._oceanbase_lease_seconds = oceanbase_lease_seconds - self._retry_base_seconds = retry_base_seconds - self._retry_cap_seconds = retry_cap_seconds - self._retry_jitter = (lambda: SystemRandom().uniform(0.8, 1.2)) if retry_jitter is None else retry_jitter - self._status = ArtifactProcessingSupervisorStatus.STANDBY + self._supervisor_group = supervisor_group + self._intents = intents or ArtifactProcessingIntentRepository() + self._leases = leases or ArtifactProcessingLeaseRepository() + self._binding_states = binding_states or ArtifactProcessingBindingStateRepository() + self.holder_id = holder_id or str(uuid4()) + self._tick = oceanbase_tick_seconds + self._lease_seconds = oceanbase_lease_seconds + self._retry_base = retry_base_seconds + self._retry_cap = retry_cap_seconds + self._jitter = retry_jitter or (lambda: SystemRandom().uniform(0.8, 1.2)) + self._tracing = tracing self._fence: ArtifactProcessingFence | None = None - self._renew_at = 0.0 - self._queue: deque[ProcessingKey] = deque() - self._queued: set[ProcessingKey] = set() - self._work: dict[ProcessingKey, _WaveWork] = {} - self._automatic_waves: dict[str, _AutomaticWave] = {} - self._automatic_discovery_queue: deque[str] = deque() - self._automatic_discovery_queued: set[str] = set() - self._discover_automatic_next = False - self._next_automatic_wake_at: float | None = None - self._discovery_after: ProcessingKey | None = None - self._pending_rescan_requested = False - self._next_discovery_wake_at: float | None = None - self._retries: dict[ProcessingKey, _RetryState] = {} - self._launching: dict[ProcessingKey, _LaunchingWorker] = {} - self._running: dict[ProcessingKey, _RunningWorker] = {} + self._status = ArtifactProcessingSupervisorStatus.STANDBY self._wake = asyncio.Event() self._stop = asyncio.Event() self._started = asyncio.Event() self._task: asyncio.Task[None] | None = None + self._renew_task: asyncio.Task[None] | None = None + self._notifications = 0 + self._rotation = 0 + self._lease_lost = False + self._unreaped: list[ArtifactProcessingWorkerHandle] = [] @property def status(self) -> ArtifactProcessingSupervisorStatus: - """Return the current safe readiness state.""" - + if self._fence is not None and any(state.degraded for state in self._families.values()): + return ArtifactProcessingSupervisorStatus.DEGRADED return self._status @property def fence(self) -> ArtifactProcessingFence | None: - """Return the current immutable term, if this candidate is Leader.""" - return self._fence + @property + def family_status(self) -> dict[str, dict[str, int | float | str]]: + return { + state.binding.artifact_family: { + "status": "degraded" if state.degraded else self._status.value, + "max_workers": state.binding.max_workers, + "used_workers": len(state.running), + "available_workers": max(0, state.binding.max_workers - len(state.running)), + "unacknowledged_requests": state.unacknowledged, + "discovery_seconds": state.discovery_seconds, + "last_invocation_seconds": state.invocation_seconds, + "ready": len(state.ready), + "retry_wait": sum(scope not in state.running and scope not in state.queued for scope in state.retries), + "completed": state.completed, + "failed": state.failed, + "timeouts": state.timeouts, + } + for state in self._families.values() + } + async def __aenter__(self) -> ArtifactProcessingSupervisor: await self.start() return self @@ -540,875 +488,667 @@ async def __aexit__(self, exc_type: object, exc_value: object, traceback: object await self.close() async def start(self) -> None: - """Start election and wait for the first bounded candidate cycle.""" - - if self._task is not None: - raise RuntimeError("Artifact Processing Supervisor is already started") # noqa: TRY003 - self._task = asyncio.create_task(self._run(), name="powercontext-artifact-processing-supervisor") - await self._started.wait() - - def wake(self) -> None: - """Reduce local flush latency; durable database state remains authoritative.""" - - # A flush may target a key already passed by the current page cursor. - # Finish that bounded traversal, then repeat it before becoming idle. - self._pending_rescan_requested = True + if self._task is None: + self._task = asyncio.create_task(self._run(), name=f"artifact-supervisor-{self._supervisor_group}") + await self._started.wait() + + def wake(self, binding_name: str | None = None) -> None: + self._notifications += 1 + for name, state in self._families.items(): + if binding_name is None or binding_name == name: + state.discovery_pending = True self._wake.set() async def close(self) -> None: - """Stop dispatching, terminate child Workers, and await the control loop.""" - - task = self._task - if task is None: - return self._stop.set() self._wake.set() - await task - self._task = None - - async def _run(self) -> None: + if self._task is not None: + self._task.cancel() + with suppress(asyncio.CancelledError): + await self._task + self._task = None + if self._unreaped: + raise _WorkerTerminationError(self._unreaped[0]) + + async def _run(self) -> None: # noqa: C901 - lifecycle and cancellation boundaries try: while not self._stop.is_set(): self._wake.clear() try: - await self._cycle() + if self._lease_lost: + await self._lose_leadership() + if self._fence is None: + await self._acquire() + if self._fence is not None: + await self._cycle() except asyncio.CancelledError: raise except ArtifactProcessingLeadershipLostError: - await self._lose_leadership(ArtifactProcessingSupervisorStatus.STANDBY) + await self._lose_leadership() except Exception as error: - await self._lose_leadership(ArtifactProcessingSupervisorStatus.DEGRADED) - log_safely( - logger, - logging.ERROR, - "Artifact Processing Supervisor control cycle failed", - exc_info=error, - extra={ - "event": "artifact_processing.supervisor.failed", - "stage": "supervisor", - "error_code": "control_cycle_failed", - "outcome": "failure", - "unit": "artifact_processing", - }, - ) + await self._lose_leadership() + self._status = ArtifactProcessingSupervisorStatus.DEGRADED + self._log_failure(None, None, error, "supervisor") finally: self._started.set() - if self._stop.is_set(): - break - timeout = self._next_wake_seconds() if self._wake.is_set(): continue + timeout = self._next_wake_seconds() try: if timeout is None: await self._wake.wait() else: - await asyncio.wait_for(self._wake.wait(), timeout=timeout) + await asyncio.wait_for(self._wake.wait(), timeout=max(timeout, 0.001)) except TimeoutError: pass finally: - await self._lose_leadership(ArtifactProcessingSupervisorStatus.STANDBY) + await self._lose_leadership() - async def _cycle(self) -> None: - await self._establish_or_renew_leadership() - if self._fence is None: - return - await self._drain_launches() - await self._drain_workers() - if self._fence is None: - return - await self._finish_ready_automatic_waves() - await self._discover_waves() - await self._dispatch_workers() - - async def _establish_or_renew_leadership(self) -> None: - loop = asyncio.get_running_loop() - if self._fence is not None: - if self._lease_mode == "single-process" or loop.time() < self._renew_at: - return - async with self._database.transaction() as connection: - renewed = await self._leases.renew( - connection, - self._fence, - self._oceanbase_lease_seconds, - ) - self._fence = renewed.fence(self._lease_mode) - self._renew_at = loop.time() + self._oceanbase_lease_seconds / 3.0 + async def _acquire(self) -> None: + await self._reap_unconfirmed_exits() + if self._unreaped: + self._status = ArtifactProcessingSupervisorStatus.DEGRADED return async with self._database.transaction() as connection: if self._lease_mode == "single-process": - acquired = await self._leases.start_single_process_term(connection, self.holder_id) + acquired = await self._leases.start_single_process_term( + connection, self.holder_id, supervisor_group=self._supervisor_group + ) else: acquired = await self._leases.try_acquire( - connection, - self.holder_id, - self._oceanbase_lease_seconds, + connection, self.holder_id, self._lease_seconds, supervisor_group=self._supervisor_group ) - if acquired is not None: - await self._auto_wave_targets.clear_all(connection) if acquired is None: - if self._status is not ArtifactProcessingSupervisorStatus.DEGRADED: - self._status = ArtifactProcessingSupervisorStatus.STANDBY + self._status = ArtifactProcessingSupervisorStatus.STANDBY return self._fence = acquired.fence(self._lease_mode) - self._renew_at = loop.time() + self._oceanbase_lease_seconds / 3.0 + self._lease_lost = False self._status = ArtifactProcessingSupervisorStatus.LEADER + for state in self._families.values(): + state.discovery_pending = True + state.reconcile_complete = False + state.reconcile_after = None + if self._lease_mode == "oceanbase": + self._renew_task = asyncio.create_task(self._renew(), name=f"artifact-lease-{self._supervisor_group}") - async def _discover_waves(self) -> None: - self._activate_due_retries() - available = _DISCOVERY_PAGE_SIZE - len(self._work) - if available <= 0: - # The frontier cannot advance until active work frees capacity. Its - # callbacks (or the OceanBase control tick) will wake us; retaining - # an already-due page deadline here would spin the control loop. - self._next_discovery_wake_at = None - self._next_automatic_wake_at = None - return - if self._automatic_discovery_queue and self._discover_automatic_next: - await self._discover_automatic_page(available) - self._discover_automatic_next = False - return - await self._discover_pending_page(available) - self._discover_automatic_next = bool(self._automatic_discovery_queue) + async def _renew(self) -> None: + try: + while self._fence is not None: + await asyncio.sleep(self._lease_seconds / 3) + fence = self._require_current_fence() + async with self._database.transaction() as connection: + await self._leases.renew(connection, fence, self._lease_seconds) + except asyncio.CancelledError: + raise + except Exception as error: + self._log_failure(None, None, error, "lease_renewal") + self._lease_lost = True + self._wake.set() - def _activate_due_retries(self) -> None: - now = asyncio.get_running_loop().time() - for key, retry in sorted(self._retries.items(), key=lambda item: item[1].next_retry_at): - if len(self._work) >= _DISCOVERY_PAGE_SIZE: - return - if key in self._work or retry.next_retry_at > now: - continue - if retry.work.automatic_wave_id is not None: - wave = self._automatic_waves.get(key[0]) - if wave is not None and key in wave.deferred_targets: - wave.targets[key] = wave.deferred_targets.pop(key) - self._work[key] = retry.work - self._enqueue(key) - - async def _discover_pending_page(self, available: int) -> None: - if self._discovery_after is None: - # Consume only BEFORE reading the first page. A wake during the - # database await must survive through the end of this traversal. - self._pending_rescan_requested = False - async with self._database.transaction() as connection: - await self._leases.require_fence(connection, self._require_current_fence()) - pending_rows = await self._pending.scan( - connection, - after=self._discovery_after, - limit=available, - ) - now = await database_utc_now(connection) - binding_states = { - name: await self._binding_states.load(connection, name) - for name, binding in self._bindings.items() - if binding.automatic_processing_interval is not None - } - automatic_page_bindings = {row.binding_name for row in pending_rows if row.binding_name in binding_states} - frozen_waves = await self._freeze_automatic_waves( - connection, - automatic_page_bindings, - binding_states, - now, + async def _cycle(self) -> None: + states = tuple(self._families.values()) + if not states: + return + ordered = states[self._rotation :] + states[: self._rotation] + self._rotation = (self._rotation + 1) % len(states) + for state in ordered: + await self._reap(state) + if self._fence is None or self._lease_lost: + raise ArtifactProcessingLeadershipLostError(self._supervisor_group, self.holder_id, 0) + now = asyncio.get_running_loop().time() + # Reserve fresh admission before retries can occupy a newly freed + # Worker. FIFO ready order then shares execution between channels. + discoverable = ( + len(state.running) < state.binding.max_workers + and self._fresh_capacity(state) > 0 + and now >= max(state.next_discovery_at, state.overflow_not_before) ) - new_wave_bindings = {wave.binding_name for wave in frozen_waves} - frozen_pending_keys = { - (row.binding_name, row.scope_id) for row in pending_rows if row.binding_name in new_wave_bindings - } - for binding_name in automatic_page_bindings - new_wave_bindings: - wave = self._automatic_waves.get(binding_name) - if wave is None: - continue - scope_ids = tuple(row.scope_id for row in pending_rows if row.binding_name == binding_name) - frozen_scope_ids = await self._auto_wave_targets.existing_scope_ids( - connection, - wave.wave_id, - binding_name, - scope_ids, - ) - frozen_pending_keys.update((binding_name, scope_id) for scope_id in frozen_scope_ids) - if pending_rows: - last = pending_rows[-1] - self._discovery_after = (last.binding_name, last.scope_id) - if len(pending_rows) < available: - self._discovery_after = None - self._next_discovery_wake_at = ( - asyncio.get_running_loop().time() + _DISCOVERY_PAGE_DELAY_SECONDS - if self._pending_rescan_requested - else None + if discoverable: + try: + async with asyncio.timeout(_DISCOVERY_TIMEOUT_SECONDS): + await self._discover(state) + state.degraded = False + except ArtifactProcessingLeadershipLostError: + raise + except Exception as error: + state.degraded = True + state.next_discovery_at = now + self._tick + self._log_failure(state, None, error, "scope_discovery") + finally: + state.discovery_seconds = asyncio.get_running_loop().time() - now + await self._activate_retries(state) + await self._dispatch(state) + + async def _discover(self, state: _FamilyState) -> None: + binding = state.binding + loop = asyncio.get_running_loop() + if not state.reconcile_complete and binding.pending_provider is not None: + state.reconcile_after = await binding.pending_provider.reconcile( + state.reconcile_after, _DISCOVERY_PAGE_SIZE, fence=self._require_current_fence() ) + state.reconcile_complete = state.reconcile_after is None + if not state.reconcile_complete: + state.next_discovery_at = loop.time() + _DISCOVERY_PAGE_DELAY_SECONDS else: - self._next_discovery_wake_at = asyncio.get_running_loop().time() + _DISCOVERY_PAGE_DELAY_SECONDS - registered = tuple(row for row in pending_rows if row.binding_name in self._bindings) - rows_by_binding: dict[str, list[StoredArtifactProcessingPending]] = {} - backing_off_bindings = {retry.work.key[0] for retry in self._retries.values()} - for pending in registered: - key = (pending.binding_name, pending.scope_id) - if ( - key not in self._work - and key not in self._retries - and pending.flush_generation > pending.handled_flush_generation - ): - self._register_work(pending, ArtifactProcessingWaveKind.EXPLICIT) - elif ( - pending.binding_name in self._automatic_waves - and pending.binding_name in backing_off_bindings - and key not in frozen_pending_keys - and key not in self._work - and key not in self._retries - ): - self._register_untracked_automatic_work(pending) - rows_by_binding.setdefault(pending.binding_name, []).append(pending) - for wave in frozen_waves: - self._automatic_waves[wave.binding_name] = wave - self._enqueue_automatic_discovery(wave.binding_name) - self._refresh_automatic_timer(rows_by_binding, binding_states, now) - - async def _discover_automatic_page(self, available: int) -> None: - wave: _AutomaticWave | None = None - while self._automatic_discovery_queue: - binding_name = self._automatic_discovery_queue.popleft() - self._automatic_discovery_queued.discard(binding_name) - candidate = self._automatic_waves.get(binding_name) - if candidate is not None and not candidate.targets and not candidate.discovery_complete: - wave = candidate - break - if wave is None: - self._wake.set() + state.reconcile_complete = True + # Alternate discovery channels so explicit traffic cannot monopolize admission. + state.automatic_next = not state.automatic_next + if state.automatic_next: + await self._discover_automatic(state) + await self._discover_requested(state) + else: + await self._discover_requested(state) + await self._discover_automatic(state) + + async def _discover_requested(self, state: _FamilyState) -> None: + capacity = self._fresh_capacity(state) + if capacity <= 0: return + if not state.discovery_pending and self._lease_mode == "single-process": + return + if state.requested_after == 0: + state.notification_at_start = self._notifications async with self._database.transaction() as connection: await self._leases.require_fence(connection, self._require_current_fence()) - target_rows = await self._auto_wave_targets.scan( + if state.requested_after == 0: + table = ARTIFACT_PROCESSING_INTENTS_TABLE + state.unacknowledged = int( + await connection.scalar( + select(func.count()) + .select_from(table) + .where( + table.c.binding_name == state.binding.binding_name, + table.c.requested_generation > table.c.handled_generation, + ) + ) + or 0 + ) + rows = await self._intents.scan( connection, - wave.wave_id, - wave.binding_name, - after_scope_id=wave.discovery_after_scope_id, - limit=available, - ) - if target_rows: - wave.discovery_after_scope_id = target_rows[-1].scope_id - if len(target_rows) < available: - wave.discovery_complete = True - page_targets: dict[ProcessingKey, int] = {} - for target in target_rows: - key = (target.binding_name, target.scope_id) - if key in self._work or key in self._retries: - wave.deferred_targets[key] = target.source_through - continue - page_targets[key] = target.source_through - self._register_automatic_work( - target.binding_name, - target.scope_id, - target.source_through, - wave_id=wave.wave_id, + state.binding.binding_name, + after_sequence=state.requested_after, + limit=min(capacity, _DISCOVERY_PAGE_SIZE), + requested_only=True, ) - wave.targets = page_targets - if not wave.targets: - self._wake.set() - - def _refresh_automatic_timer( - self, - rows_by_binding: Mapping[str, Sequence[StoredArtifactProcessingPending]], - binding_states: Mapping[str, StoredArtifactProcessingBindingState | None], - now: datetime, - ) -> None: - automatic_delays: list[float] = [] - loop_time = asyncio.get_running_loop().time() - for binding_name, state in binding_states.items(): - binding = self._bindings[binding_name] - interval = binding.automatic_processing_interval - if interval is None: - continue - rows = rows_by_binding.get(binding_name, ()) - if state is None or state.last_auto_wave_completed_at is None: - remaining = 0.0 if rows else interval.total_seconds() - else: - remaining = max(0.0, (state.last_auto_wave_completed_at + interval - now).total_seconds()) - if not rows and remaining <= 0: - remaining = interval.total_seconds() - binding_busy = ( - binding_name in self._automatic_waves - or any(key[0] == binding_name for key in self._work) - or any(retry.work.key[0] == binding_name for retry in self._retries.values()) - ) - if remaining > 0 or not binding_busy: - automatic_delays.append(max(remaining, 0.001)) - self._next_automatic_wake_at = None if not automatic_delays else loop_time + min(automatic_delays) - - async def _freeze_automatic_waves( - self, - connection: AsyncConnection, - binding_names: Collection[str], - binding_states: Mapping[str, StoredArtifactProcessingBindingState | None], - now: datetime, - ) -> tuple[_AutomaticWave, ...]: - frozen: list[_AutomaticWave] = [] - for binding_name in sorted(binding_names): - binding = self._bindings[binding_name] - interval = binding.automatic_processing_interval - if interval is None or binding_name in self._automatic_waves: - continue - if len(self._automatic_waves) + len(frozen) >= _DISCOVERY_PAGE_SIZE: - break - state = binding_states[binding_name] - if ( - state is not None - and state.last_auto_wave_completed_at is not None - and now < state.last_auto_wave_completed_at + interval - ): - continue - wave = _AutomaticWave( - wave_id=str(uuid4()), - binding_name=binding_name, - targets={}, - ) - await self._auto_wave_targets.freeze_pending(connection, wave.wave_id, binding_name) - frozen.append(wave) - return tuple(frozen) - - def _enqueue_automatic_discovery(self, binding_name: str) -> None: - wave = self._automatic_waves.get(binding_name) - if ( - wave is not None - and not wave.targets - and not wave.discovery_complete - and binding_name not in self._automatic_discovery_queued - ): - self._automatic_discovery_queue.append(binding_name) - self._automatic_discovery_queued.add(binding_name) - self._wake.set() + for row in rows: + state.requested_after = row.pending_sequence + if row.scope_id not in state.running and row.scope_id not in state.retries: + self._enqueue(state, row.scope_id) + if len(rows) < min(capacity, _DISCOVERY_PAGE_SIZE): + state.requested_after = 0 + state.discovery_pending = state.notification_at_start != self._notifications + else: + state.discovery_pending = True + state.next_discovery_at = asyncio.get_running_loop().time() + _DISCOVERY_PAGE_DELAY_SECONDS - def _register_work( - self, - pending: StoredArtifactProcessingPending, - wave_kind: ArtifactProcessingWaveKind, - ) -> None: - key = (pending.binding_name, pending.scope_id) - if key in self._work or key in self._retries: + async def _discover_automatic(self, state: _FamilyState) -> None: # noqa: C901 - bounded admission state + binding = state.binding + capacity = self._fresh_capacity(state) + if capacity <= 0: return - self._work[key] = _WaveWork( - key=key, - wave_kind=wave_kind, - wave_target=pending.source_through, - claimed_flush_generation=pending.flush_generation, - ) - self._enqueue(key) + # Publish RAM progress only after the transaction commits. Advancing a + # page cursor before admit/finish/commit succeeds would skip rolled-back + # rows on the next discovery pass of this same persisted generation. + scan_after = state.scan_after + scan_generation = state.scan_generation + scan_in_progress = False + next_schedule_at = state.next_schedule_at + next_discovery_at = state.next_discovery_at + admitted: list[str] = [] + async with self._database.transaction() as connection: + await self._leases.require_fence(connection, self._require_current_fence()) + persisted = await self._binding_states.load(connection, binding.binding_name, for_update=True) + enabled = binding.automatic_processing_interval is not None or binding.cron is not None + if not enabled: + if persisted is not None and persisted.scan_in_progress: + await self._binding_states.finish_scan(connection, binding.binding_name) + next_schedule_at = None + scan_after = 0 + else: + now = await database_utc_now(connection) + if persisted is None or not persisted.scan_in_progress: + checkpoint = None if persisted is None else persisted.last_schedule_checkpoint_at + due, next_time = _schedule_deadline(binding, checkpoint, now) + next_schedule_at = asyncio.get_running_loop().time() + max(0, (next_time - now).total_seconds()) + if due is not None: + persisted = await self._binding_states.start_scan(connection, binding.binding_name, due) + scan_after = 0 + if persisted is not None and persisted.scan_in_progress: + scan_in_progress = True + if scan_generation != persisted.scan_generation: + scan_generation = persisted.scan_generation + scan_after = 0 + rows = await self._intents.scan( + connection, + binding.binding_name, + after_sequence=scan_after, + limit=min(capacity, _DISCOVERY_PAGE_SIZE), + dirty_only=True, + upper_sequence=persisted.scan_upper_pending_sequence, + ) + candidates = tuple( + row.scope_id + for row in rows + if row.scope_id not in state.queued + and row.scope_id not in state.running + and row.scope_id not in state.retries + and row.last_auto_scan_generation != persisted.scan_generation + ) + eligible = frozenset(candidates) + if candidates and binding.automatic_scope_filter is not None: + eligible &= await binding.automatic_scope_filter(connection, candidates) + for row in rows: + # A full page of ineligible rows still advances discovery; + # keep their dirty Source and request counters untouched. + scan_after = row.pending_sequence + if row.scope_id not in eligible: + continue + await self._intents.admit( + connection, row.scope_id, binding.binding_name, persisted.scan_generation + ) + admitted.append(row.scope_id) + scan_in_progress = len(rows) == min(capacity, _DISCOVERY_PAGE_SIZE) + if not scan_in_progress: + await self._binding_states.finish_scan(connection, binding.binding_name) + scan_after = 0 + # Starting a scan established its checkpoint, so a + # completed page must not restart the interval here. + _, next_time = _schedule_deadline(binding, persisted.last_schedule_checkpoint_at, now) + next_schedule_at = asyncio.get_running_loop().time() + max(0, (next_time - now).total_seconds()) + else: + next_discovery_at = asyncio.get_running_loop().time() + _DISCOVERY_PAGE_DELAY_SECONDS + state.scan_after = scan_after + state.scan_generation = scan_generation + state.scan_in_progress = scan_in_progress + state.next_schedule_at = next_schedule_at + state.next_discovery_at = next_discovery_at + for scope in admitted: + self._enqueue(state, scope) - def _register_automatic_work( - self, - binding_name: str, - scope_id: str, - source_through: int, - *, - wave_id: str, - ) -> None: - key = (binding_name, scope_id) - if key in self._work or key in self._retries: - return - self._work[key] = _WaveWork( - key=key, - wave_kind=ArtifactProcessingWaveKind.AUTOMATIC, - wave_target=source_through, - claimed_flush_generation=0, - automatic_wave_id=wave_id, - ) - self._enqueue(key) - - def _register_untracked_automatic_work(self, pending: StoredArtifactProcessingPending) -> None: - key = (pending.binding_name, pending.scope_id) - self._work[key] = _WaveWork( - key=key, - wave_kind=ArtifactProcessingWaveKind.AUTOMATIC, - wave_target=pending.source_through, - claimed_flush_generation=0, + @staticmethod + def _fresh_capacity(state: _FamilyState) -> int: + return min( + _DISCOVERY_PAGE_SIZE - len(state.ready), _CHANNEL_QUEUE_LIMIT - (len(state.ready) - len(state.retry_queued)) ) - self._enqueue(key) - async def _dispatch_workers(self) -> None: - loop = asyncio.get_running_loop() - attempts = len(self._queue) - while self._queue and len(self._launching) + len(self._running) < self._max_workers and attempts > 0: - attempts -= 1 - key = self._queue.popleft() - self._queued.discard(key) - work = self._work.get(key) - if work is None or key in self._launching or key in self._running: - continue - retry = self._retries.get(key) - if retry is not None and retry.next_retry_at > loop.time(): - self._enqueue(key) - continue - try: - assignment = await self._prepare_assignment(work) - except _WindowSelectionError as error: - self._record_failure(work, None, error.failure) - continue - if assignment is None: - await self._finish_covered_work(work) - continue - task = asyncio.create_task( - self._start_worker(self._bindings[work.key[0]].launcher, assignment), - name=f"powercontext-artifact-worker-launch-{assignment.worker_id}", - ) - task.add_done_callback(lambda _task: self._wake.set()) - self._launching[key] = _LaunchingWorker( - work=work, - assignment=assignment, - task=task, + async def _activate_retries(self, state: _FamilyState) -> None: + now = asyncio.get_running_loop().time() + # Each channel reserves half the bounded queue. Rotate due keys so a + # repeatedly failing prefix cannot refill every free slot indefinitely. + allowance = min(_DISCOVERY_PAGE_SIZE - len(state.ready), _CHANNEL_QUEUE_LIMIT - len(state.retry_queued)) + for scope, retry in tuple(state.retries.items()): + if allowance <= 0: + break + if retry.deadline <= now and scope not in state.running and scope not in state.queued: + self._enqueue(state, scope, retry=True) + state.retries.pop(scope) + state.retries[scope] = retry + allowance -= 1 + + def _enqueue(self, state: _FamilyState, scope: str, *, retry: bool = False) -> None: + if scope not in state.queued and scope not in state.running: + state.ready.append(scope) + state.queued.add(scope) + if retry: + state.retry_queued.add(scope) + + def _defer(self, state: _FamilyState, scope: str, failures: int, deadline: float) -> None: + if scope not in state.retries and len(state.retries) >= _RETRY_STATE_LIMIT: + now = asyncio.get_running_loop().time() + expired = next( + ( + key + for key, value in state.retries.items() + if value.deadline <= now and key not in state.queued and key not in state.running + ), + None, ) - - async def _start_worker( - self, - launcher: ArtifactProcessingWorkerLauncher, - assignment: ArtifactProcessingWorkAssignment, - ) -> ArtifactProcessingWorkerHandle: - try: - async with asyncio.timeout(self._worker_timeout_seconds): - return await launcher.start(assignment) - except TimeoutError as error: - raise _WorkerExecutionError( - ArtifactProcessingWorkerFailure( - stage="worker_start", - error_code="worker_start_timeout", - exception_type=type(error).__name__, - traceback="", - ) - ) from None - - async def _drain_launches(self) -> None: - for key, launching in tuple(self._launching.items()): - if not launching.task.done(): - continue - del self._launching[key] - try: - handle = launching.task.result() - except asyncio.CancelledError: - raise - except _WorkerExecutionError as error: - self._record_failure(launching.work, launching.assignment, error.failure) + if expired is not None: + # Like the previous bounded retry cache, eviction forgets + # volatile history. Only expired backoff can be evicted. + state.retries.pop(expired) + else: + # Durable requested > handled retains the omitted key. Pause + # new discovery until every overflow failure's cooldown has + # elapsed; flush cannot bypass this bounded-capacity gate. + # Already-ready work drains, so only a finite cohort can extend it. + state.overflow_not_before = max(state.overflow_not_before, deadline) + self.wake(state.binding.binding_name) + return + state.retries[scope] = _RetryState(failures, deadline) + + async def _dispatch(self, state: _FamilyState) -> None: + while state.ready and len(state.running) < state.binding.max_workers: + scope = state.ready.popleft() + state.queued.discard(scope) + state.retry_queued.discard(scope) + retry = state.retries.get(scope) + if retry is not None and retry.deadline > asyncio.get_running_loop().time(): continue - except Exception as error: - self._record_failure( - launching.work, - launching.assignment, - ArtifactProcessingWorkerFailure( - stage="worker_start", - error_code="worker_start_failed", - exception_type=type(error).__name__, - traceback=_safe_traceback(error), - ), - ) + async with self._database.transaction() as connection: + fence = self._require_current_fence() + await self._leases.require_fence(connection, fence) + row = await self._intents.load(connection, scope, state.binding.binding_name, for_update=True) + if row is None or row.requested_generation <= row.handled_generation: + state.retries.pop(scope, None) continue - task = asyncio.create_task( - self._wait_for_worker(handle), - name=f"powercontext-artifact-worker-wait-{launching.assignment.worker_id}", + assignment = ArtifactProcessingWorkAssignment( + binding_name=state.binding.binding_name, + scope_id=scope, + artifact_family=state.binding.artifact_family, + claimed_request_generation=row.requested_generation, + fence=fence, + worker_id=str(uuid4()), ) - task.add_done_callback(lambda _task: self._wake.set()) - self._running[key] = _RunningWorker( - work=launching.work, - assignment=launching.assignment, - handle=handle, - task=task, + task = asyncio.create_task( + self._execute(state.binding, assignment), name=f"artifact-worker-{assignment.worker_id}" ) + task.add_done_callback(lambda _: self._wake.set()) + state.running[scope] = _RunningWorker(assignment, task, asyncio.get_running_loop().time()) - async def _prepare_assignment( - self, - work: _WaveWork, - ) -> ArtifactProcessingWorkAssignment | None: - binding_name, scope_id = work.key - async with self._database.transaction() as connection: - await self._leases.require_fence(connection, self._require_current_fence()) - cursor = await self._cursors.load(connection, scope_id, binding_name) - source_after = 0 if cursor is None else cursor.cursor.sequence - if source_after >= work.wave_target: - return None - source_ceiling = min( - source_after + self._bindings[binding_name].source_window_limit, - work.wave_target, - ) - selector = self._bindings[binding_name].window_selector - try: - source_through = ( - source_ceiling if selector is None else await selector.select(scope_id, source_after, source_ceiling) + async def _execute( + self, binding: ArtifactProcessingBinding, assignment: ArtifactProcessingWorkAssignment + ) -> ArtifactProcessingWorkerCompletion: + attributes = {"powercontext.artifact_processing.family": binding.artifact_family} + background = ( + nullcontext() + if self._tracing is None + else self._tracing.background( + "artifact_processing.worker", operation="process_artifact_scope", attributes=attributes ) - if ( - not isinstance(source_through, int) - or isinstance(source_through, bool) - or not source_after < source_through <= source_ceiling - ): - # Classify invalid return values exactly like selector errors. - raise ValueError("artifact processing selector returned an invalid Source boundary") # noqa: TRY003, TRY301 - except ArtifactProcessingLeadershipLostError: - raise - except Exception as error: - # A bad Source/adapter is local to this key. Retain its Pending and - # Cursor and use the same bounded retry frontier as Worker failures. - # Cancellation and fence loss still propagate to the control loop. - raise _WindowSelectionError( - ArtifactProcessingWorkerFailure( - stage="source_window_selection", - error_code="source_window_selection_failed", - exception_type=type(error).__name__, - traceback=_safe_traceback(error), - ) - ) from None - return ArtifactProcessingWorkAssignment( - binding_name=binding_name, - scope_id=scope_id, - source_after=source_after, - source_through=source_through, - wave_target=work.wave_target, - claimed_flush_generation=work.claimed_flush_generation, - cursor_generation=None if cursor is None else cursor.generation, - wave_kind=work.wave_kind, - fence=self._require_current_fence(), - worker_id=str(uuid4()), ) + with background as span: + handle: ArtifactProcessingWorkerHandle | None = None + try: + async with asyncio.timeout(binding.worker_timeout_seconds): + with ( + nullcontext() + if self._tracing is None + else self._tracing.stage("artifact_processing.worker.start", attributes=attributes) + ): + handle = await binding.launcher.start(assignment) + with ( + nullcontext() + if self._tracing is None + else self._tracing.stage("artifact_processing.worker.wait", attributes=attributes) + ): + completion = await handle.wait() + if completion.outcome is ArtifactProcessingWorkerOutcome.LEADERSHIP_LOST: + raise ArtifactProcessingLeadershipLostError( # noqa: TRY301 + self._supervisor_group, self.holder_id, 0 + ) + if completion.outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED: + # A successful process exit is not a successful invocation. + # Check the durable acknowledgement before finishing the trace; + # the reaper still checks the current fence before dispatching a successor. + with ( + nullcontext() + if self._tracing is None + else self._tracing.stage("artifact_processing.worker.acknowledge", attributes=attributes) + ): + await self._verify_acknowledgement(assignment) + elif span is not None: + span.set_outcome(completion.outcome.value) + return completion + except BaseException as error: + if span is not None: + span.set_attributes({"powercontext.artifact_processing.failure": _worker_failure_category(error)}) + if handle is not None: + cleanup = asyncio.create_task(self._terminate_worker(handle)) + await _complete_spawn_cleanup(cleanup) + raise - async def _wait_for_worker( - self, - handle: ArtifactProcessingWorkerHandle, - ) -> ArtifactProcessingWorkerCompletion: - try: - async with asyncio.timeout(self._worker_timeout_seconds): - return await handle.wait() - except TimeoutError as error: - await asyncio.shield(self._terminate_worker(handle)) + async def _verify_acknowledgement(self, assignment: ArtifactProcessingWorkAssignment) -> None: + async with self._database.transaction() as connection: + await self._leases.require_fence(connection, assignment.fence) + row = await self._intents.load(connection, assignment.scope_id, assignment.binding_name) + if row is None or row.handled_generation < assignment.claimed_request_generation: raise _WorkerExecutionError( - ArtifactProcessingWorkerFailure( - stage="worker_process", - error_code="worker_timeout", - exception_type=type(error).__name__, - traceback="", - ) - ) from None - except asyncio.CancelledError: - await asyncio.shield(self._terminate_worker(handle)) - raise + ArtifactProcessingWorkerFailure("completion", "missing_durable_acknowledgement", "RuntimeError", "") + ) async def _terminate_worker(self, handle: ArtifactProcessingWorkerHandle) -> None: try: async with asyncio.timeout(_WORKER_SHUTDOWN_TIMEOUT_SECONDS): await handle.terminate() - except TimeoutError: - log_safely( - logger, - logging.ERROR, - "Artifact processing Worker termination timed out", - extra={ - "event": "artifact_processing.worker.termination_timeout", - "stage": "worker_termination", - "error_code": "worker_termination_timeout", - "outcome": "failure", - "unit": "artifact_processing", - }, - ) - raise _WorkerTerminationError from None + except BaseException as error: + if isinstance(error, asyncio.CancelledError): + raise + raise _WorkerTerminationError(handle) from error - async def _drain_workers(self) -> None: - for key, running in tuple(self._running.items()): + async def _reap(self, state: _FamilyState) -> None: # noqa: C901 - distinct Worker exit outcomes + for scope, running in tuple(state.running.items()): if not running.task.done(): continue - del self._running[key] + state.invocation_seconds = asyncio.get_running_loop().time() - running.started_at + retain_slot = False try: completion = running.task.result() + if completion.outcome is ArtifactProcessingWorkerOutcome.LEADERSHIP_LOST: + raise ArtifactProcessingLeadershipLostError(self._supervisor_group, self.holder_id, 0) # noqa: TRY301 + if completion.outcome in { + ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT, + ArtifactProcessingWorkerOutcome.HEAD_CONFLICT, + }: + previous = state.retries.get(scope) + self._defer( + state, + scope, + 0 if previous is None else previous.failures, + asyncio.get_running_loop().time() + _CONTROL_CONFLICT_RETRY_SECONDS, + ) + continue + async with self._database.transaction() as connection: + await self._leases.require_fence(connection, self._require_current_fence()) + row = await self._intents.load(connection, scope, state.binding.binding_name) + if row is None or row.handled_generation < running.assignment.claimed_request_generation: + raise _WorkerExecutionError( # noqa: TRY301 + ArtifactProcessingWorkerFailure( + "completion", "missing_durable_acknowledgement", "RuntimeError", "" + ) + ) + state.retries.pop(scope, None) + state.completed += 1 + if row.requested_generation > row.handled_generation: + self.wake(state.binding.binding_name) + except (ArtifactProcessingLeadershipLostError, _WorkerTerminationError): + # Retain the slot until the old term is revoked and all children are reaped. + retain_slot = True + raise except asyncio.CancelledError: raise - except _WorkerTerminationError: - await self._lose_leadership(ArtifactProcessingSupervisorStatus.DEGRADED) - return - except _WorkerExecutionError as error: - self._record_failure(running.work, running.assignment, error.failure) - continue except Exception as error: - self._record_failure( - running.work, - running.assignment, - ArtifactProcessingWorkerFailure( - stage="worker_process", - error_code="worker_wait_failed", - exception_type=type(error).__name__, - traceback=_safe_traceback(error), - ), - ) - continue - if completion.outcome is ArtifactProcessingWorkerOutcome.LEADERSHIP_LOST: - await self._lose_leadership(ArtifactProcessingSupervisorStatus.STANDBY) - return - if completion.outcome in { - ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT, - ArtifactProcessingWorkerOutcome.HEAD_CONFLICT, - }: - self._defer_control_conflict(running.work) - continue - await self._complete_window(running.work) - - async def _complete_window(self, work: _WaveWork) -> None: - self._retries.pop(work.key, None) - try: - assignment = await self._prepare_assignment(work) - except _WindowSelectionError as error: - self._record_failure(work, None, error.failure) - return - if assignment is None: - await self._finish_completed_work(work) - else: - self._enqueue(work.key) - - async def _finish_covered_work(self, work: _WaveWork) -> None: - if work.wave_kind is ArtifactProcessingWaveKind.EXPLICIT: - binding_name, scope_id = work.key - async with self._database.transaction() as connection: - await self._leases.require_fence(connection, self._require_current_fence()) - cursor = await self._cursors.load(connection, scope_id, binding_name) - cursor_position = 0 if cursor is None else cursor.cursor.sequence - if cursor_position < work.wave_target: - raise ArtifactProcessingWaveIncompleteError( - binding_name, - scope_id, - work.wave_target, - cursor_position, - ) - await self._pending.mark_flush_handled( - connection, - scope_id, - binding_name, - work.claimed_flush_generation, - ) - await self._pending.delete_if_covered( - connection, - scope_id, - binding_name, - cursor=cursor_position, - source_through_limit=work.wave_target, - ) - await self._finish_completed_work(work) - - async def _finish_completed_work(self, work: _WaveWork) -> None: - binding_wave = self._automatic_waves.get(work.key[0]) - wave = binding_wave if work.automatic_wave_id is not None else None - if work.wave_kind is ArtifactProcessingWaveKind.AUTOMATIC: - if work.automatic_wave_id is not None and ( - wave is None or wave.wave_id != work.automatic_wave_id or work.key not in wave.targets - ): - raise _AutomaticWaveStateError("unknown", "completed target is not active") - binding_name, scope_id = work.key - async with self._database.transaction() as connection: - await self._leases.require_fence(connection, self._require_current_fence()) - cursor = await self._cursors.load(connection, scope_id, binding_name) - cursor_position = 0 if cursor is None else cursor.cursor.sequence - if cursor_position < work.wave_target: - raise ArtifactProcessingWaveIncompleteError( - binding_name, - scope_id, - work.wave_target, - cursor_position, - ) - if wave is not None: - marked = await self._auto_wave_targets.mark_completed( - connection, - wave.wave_id, - scope_id, + previous = state.retries.get(scope) + failures = 1 if previous is None else previous.failures + 1 + delay = min(self._retry_cap, self._retry_base * 2 ** min(failures - 1, 20) * self._jitter()) + self._defer(state, scope, failures, asyncio.get_running_loop().time() + delay) + state.failed += 1 + if isinstance(error, TimeoutError): + state.timeouts += 1 + self._log_failure(state, running.assignment, error, "worker", failures, delay) + finally: + if not retain_slot: + state.running.pop(scope, None) + self.wake(state.binding.binding_name) + + async def _lose_leadership(self) -> None: + fence, self._fence = self._fence, None + self._status = ArtifactProcessingSupervisorStatus.STANDBY + self._lease_lost = False + if self._renew_task is not None: + self._renew_task.cancel() + with suppress(asyncio.CancelledError): + await self._renew_task + self._renew_task = None + # Revoke the term before cancellation can leave an unobservable child. + if fence is not None: + try: + async with self._database.transaction() as connection: + await self._leases.require_fence(connection, fence) + await connection.execute( + update(ARTIFACT_PROCESSING_LEASES_TABLE) + .where(ARTIFACT_PROCESSING_LEASES_TABLE.c.supervisor_group == fence.supervisor_group) + .values( + holder_id=str(uuid4()), + supervisor_generation=fence.supervisor_generation + 1, + lease_expires_at=datetime(1970, 1, 1, tzinfo=UTC).replace(tzinfo=None), + ) ) - if not marked: - raise _AutomaticWaveStateError(wave.wave_id, "completed target row is missing") - self._work.pop(work.key, None) - self._queued.discard(work.key) - self._retries.pop(work.key, None) - if wave is not None: - wave.completed.add(work.key) - if wave.completed == set(wave.targets): - self._wake.set() - elif binding_wave is not None: - self._wake.set() + except Exception as error: + self._log_failure(None, None, error, "term_revocation") + tasks = [worker.task for state in self._families.values() for worker in state.running.values()] + for task in tasks: + task.cancel() + if tasks: + results = await asyncio.gather(*tasks, return_exceptions=True) + for result in results: + if isinstance(result, _WorkerTerminationError) and result.handle not in self._unreaped: + self._unreaped.append(result.handle) + await self._reap_unconfirmed_exits() + for state in self._families.values(): + state.running.clear() + state.ready.clear() + state.queued.clear() + state.retry_queued.clear() + state.overflow_not_before = 0.0 + state.retries.clear() + state.requested_after = state.scan_after = state.scan_generation = 0 + state.scan_in_progress = False + state.discovery_pending = True + + async def _reap_unconfirmed_exits(self) -> None: + for handle in tuple(self._unreaped): + try: + await self._terminate_worker(handle) + except _WorkerTerminationError as error: + self._log_failure(None, None, error, "worker_termination") + else: + self._unreaped.remove(handle) - async def _complete_automatic_wave(self, wave: _AutomaticWave) -> None: - async with self._database.transaction() as connection: - await self._leases.require_fence(connection, self._require_current_fence()) - if not await self._auto_wave_targets.all_completed(connection, wave.wave_id): - raise _AutomaticWaveStateError(wave.wave_id, "incomplete target rows remain") - await self._binding_states.mark_auto_wave_completed(connection, wave.binding_name) - await self._auto_wave_targets.delete_covered_pending( - connection, - wave.wave_id, - wave.binding_name, + def _require_current_fence(self) -> ArtifactProcessingFence: + if self._fence is None or self._lease_lost: + raise ArtifactProcessingLeadershipLostError(self._supervisor_group, self.holder_id, 0) + return self._fence + + def _next_wake_seconds(self) -> float | None: + if self._fence is None or self._lease_mode == "oceanbase": + return self._tick + now = asyncio.get_running_loop().time() + deadlines: list[float] = [] + for state in self._families.values(): + if len(state.running) >= state.binding.max_workers: + continue + deadlines.extend( + retry.deadline + for scope, retry in state.retries.items() + if scope not in state.running and scope not in state.queued ) - await self._auto_wave_targets.clear_wave(connection, wave.wave_id) - self._automatic_waves.pop(wave.binding_name, None) - self._automatic_discovery_queued.discard(wave.binding_name) + if state.overflow_not_before > now: + deadlines.append(state.overflow_not_before) + continue + if state.next_schedule_at is not None: + deadlines.append(state.next_schedule_at) + if state.discovery_pending or state.scan_in_progress or not state.reconcile_complete or state.degraded: + deadlines.append(max(now, state.next_discovery_at)) + return None if not deadlines else max(0.001, min(deadlines) - now) - def _record_failure( + def _log_failure( self, - work: _WaveWork, + state: _FamilyState | None, assignment: ArtifactProcessingWorkAssignment | None, - failure: ArtifactProcessingWorkerFailure, + error: BaseException, + stage: str, + failures: int = 0, + delay: float = 0, ) -> None: - loop = asyncio.get_running_loop() - previous = self._retries.get(work.key) - failures = 1 if previous is None else previous.consecutive_failures + 1 - base_delay = min(self._retry_base_seconds * (2 ** (failures - 1)), self._retry_cap_seconds) - retry_delay = base_delay * self._retry_jitter() - self._defer_work( - work, - consecutive_failures=failures, - next_retry_at=loop.time() + retry_delay, - ) log_safely( logger, logging.ERROR, - "Artifact processing Worker failed", + "Artifact processing failed", extra={ - "event": "artifact_processing.worker.failed", - "binding_name": work.key[0], - "scope_id": work.key[1], - "source_after": None if assignment is None else assignment.source_after, - "source_through": None if assignment is None else assignment.source_through, - "stage": failure.stage, - "error_code": failure.error_code, - "exception_type": failure.exception_type, - "failure_count": failures, - "retry_delay_seconds": retry_delay, - "supervisor_generation": self._require_current_fence().supervisor_generation, + "event": "artifact_processing.failed", + "stage": stage, + "binding": None if state is None else state.binding.binding_name, + "family": None if state is None else state.binding.artifact_family, + "scope": None if assignment is None else assignment.scope_id, "worker_id": None if assignment is None else assignment.worker_id, - "traceback": failure.traceback, - "outcome": "failure", - "unit": "artifact_processing", + "request_generation": None if assignment is None else assignment.claimed_request_generation, + "supervisor_group": self._supervisor_group, + "supervisor_generation": None if self._fence is None else self._fence.supervisor_generation, + "trigger": "accepted_request" if assignment is not None else "control", + "exception_type": error.failure.exception_type + if isinstance(error, _WorkerExecutionError) + else type(error).__name__, + "traceback": error.failure.traceback if isinstance(error, _WorkerExecutionError) else "", + "retry_count": failures, + "retry_delay_seconds": delay, + "error_code": error.failure.error_code + if isinstance(error, _WorkerExecutionError) + else type(error).__name__, }, ) - def _defer_control_conflict(self, work: _WaveWork) -> None: - previous = self._retries.get(work.key) - self._defer_work( - work, - consecutive_failures=0 if previous is None else previous.consecutive_failures, - next_retry_at=asyncio.get_running_loop().time() + _CONTROL_CONFLICT_RETRY_SECONDS, - ) - def _defer_work( - self, - work: _WaveWork, - *, - consecutive_failures: int, - next_retry_at: float, - ) -> None: - self._work.pop(work.key, None) - self._queued.discard(work.key) - with suppress(ValueError): - self._queue.remove(work.key) - previous = self._retries.get(work.key) - if previous is None and len(self._retries) >= _RETRY_STATE_LIMIT: - evicted = next( - ( - key - for key, retry in self._retries.items() - if retry.work.wave_kind is ArtifactProcessingWaveKind.EXPLICIT and key not in self._work - ), - None, - ) - if evicted is None: - if work.wave_kind is ArtifactProcessingWaveKind.AUTOMATIC: - raise _RetryCapacityError - self._next_discovery_wake_at = next_retry_at - else: - self._retries.pop(evicted) - if previous is not None or len(self._retries) < _RETRY_STATE_LIMIT: - self._retries[work.key] = _RetryState( - work=work, - consecutive_failures=consecutive_failures, - next_retry_at=next_retry_at, - ) - if work.automatic_wave_id is not None: - wave = self._automatic_waves.get(work.key[0]) - if wave is not None and work.key in wave.targets: - wave.deferred_targets[work.key] = wave.targets.pop(work.key) - wave.completed.discard(work.key) - - async def _finish_ready_automatic_waves(self) -> None: - for wave in tuple(self._automatic_waves.values()): - if wave.completed != set(wave.targets): - continue - wave.targets.clear() - wave.completed.clear() - if not wave.discovery_complete: - self._enqueue_automatic_discovery(wave.binding_name) - continue - available = _DISCOVERY_PAGE_SIZE - len(self._work) - for key, source_through in tuple(wave.deferred_targets.items()): - if available <= 0: - break - if key in self._work or key in self._retries: - continue - wave.deferred_targets.pop(key) - wave.targets[key] = source_through - self._register_automatic_work(*key, source_through, wave_id=wave.wave_id) - available -= 1 - if wave.targets or wave.deferred_targets: - continue - await self._complete_automatic_wave(wave) - - async def _lose_leadership(self, status: ArtifactProcessingSupervisorStatus) -> None: - self._fence = None - self._status = status - launching = tuple(self._launching.values()) - self._launching.clear() - running = tuple(self._running.values()) - self._running.clear() - for item in launching: - item.task.cancel() - for item in running: - item.task.cancel() - tasks = tuple(item.task for item in (*launching, *running)) - if tasks: - await asyncio.gather(*tasks, return_exceptions=True) - late_handles: list[ArtifactProcessingWorkerHandle] = [] - for item in launching: - if not item.task.done() or item.task.cancelled(): - continue - with suppress(Exception): - late_handles.append(item.task.result()) - await asyncio.gather(*(self._terminate_worker(handle) for handle in late_handles), return_exceptions=True) - self._queue.clear() - self._queued.clear() - self._work.clear() - self._automatic_waves.clear() - self._automatic_discovery_queue.clear() - self._automatic_discovery_queued.clear() - self._discover_automatic_next = False - self._next_automatic_wake_at = None - self._discovery_after = None - self._next_discovery_wake_at = None - self._retries.clear() - - def _enqueue(self, key: ProcessingKey) -> None: - if key not in self._queued and key not in self._launching and key not in self._running and key in self._work: - self._queue.append(key) - self._queued.add(key) +def _schedule_deadline( + binding: ArtifactProcessingBinding, checkpoint: datetime | None, now: datetime +) -> tuple[datetime | None, datetime]: + if checkpoint is None: + return now, now + if binding.automatic_processing_interval is not None: + next_time = checkpoint + binding.automatic_processing_interval + return (now if now >= next_time else None), next_time + if binding.cron is None: + return None, now + trigger = CronTrigger.from_crontab(binding.cron, timezone=ZoneInfo(binding.timezone)) + first = trigger.get_next_fire_time(None, (checkpoint + timedelta(microseconds=1)).replace(tzinfo=UTC)) + if first is None: + return None, datetime.max.replace(tzinfo=None) + first = first.astimezone(UTC).replace(tzinfo=None) + if first > now: + return None, first + # Binary search avoids replaying an unbounded number of missed cron fires. + lo, hi, latest = first, now + timedelta(microseconds=1), first + for _ in range(48): + if (hi - lo).total_seconds() < 0.000001: + break + mid = lo + (hi - lo) / 2 + candidate = trigger.get_next_fire_time(None, mid.replace(tzinfo=UTC)) + if candidate is not None and candidate.astimezone(UTC).replace(tzinfo=None) <= now: + latest = candidate.astimezone(UTC).replace(tzinfo=None) + lo = mid + else: + hi = mid + following = trigger.get_next_fire_time(None, (latest + timedelta(microseconds=1)).replace(tzinfo=UTC)) + return latest, datetime.max.replace(tzinfo=None) if following is None else following.astimezone(UTC).replace( + tzinfo=None + ) - def _require_current_fence(self) -> ArtifactProcessingFence: - if self._fence is None: - raise ArtifactProcessingLeadershipLostError("global", self.holder_id, 0) - return self._fence - def _next_wake_seconds(self) -> float | None: - if self._status is ArtifactProcessingSupervisorStatus.DEGRADED: - return self._oceanbase_tick_seconds - if self._lease_mode == "oceanbase": - return self._oceanbase_tick_seconds - retry_delays = tuple( - max(0.0, retry.next_retry_at - asyncio.get_running_loop().time()) - for key, retry in self._retries.items() - if key not in self._work - ) - automatic_delays = ( - () - if self._next_automatic_wake_at is None - else (max(0.0, self._next_automatic_wake_at - asyncio.get_running_loop().time()),) - ) - discovery_delays = ( - () - if self._next_discovery_wake_at is None - else (max(0.0, self._next_discovery_wake_at - asyncio.get_running_loop().time()),) - ) - candidates = (*automatic_delays, *discovery_delays, *retry_delays) - return None if not candidates else min(candidates) +class ArtifactProcessingSupervisors: + """Runtime-owned collection; global and dedicated share the same controller.""" + + def __init__(self, supervisors: Sequence[ArtifactProcessingSupervisor]) -> None: + self.supervisors = tuple(supervisors) + + @property + def status(self) -> ArtifactProcessingSupervisorStatus: + states = [item.status for item in self.supervisors] + if ArtifactProcessingSupervisorStatus.DEGRADED in states: + return ArtifactProcessingSupervisorStatus.DEGRADED + if ArtifactProcessingSupervisorStatus.LEADER in states: + return ArtifactProcessingSupervisorStatus.LEADER + return ArtifactProcessingSupervisorStatus.STANDBY if states else ArtifactProcessingSupervisorStatus.DISABLED + + @property + def family_status(self) -> dict[str, dict[str, int | float | str]]: + return {family: status for item in self.supervisors for family, status in item.family_status.items()} + + def wake(self, binding_name: str | None = None) -> None: + for supervisor in self.supervisors: + supervisor.wake(binding_name) + + async def close(self) -> None: + await asyncio.gather(*(item.close() for item in self.supervisors)) def _run_spawned_worker( @@ -1437,6 +1177,19 @@ def _safe_error_attribute(error: BaseException, name: str, fallback: str) -> str return value if isinstance(value, str) and value else fallback +def _worker_failure_category(error: BaseException) -> str: + """Bound span attributes without copying exception messages or arbitrary child codes.""" + if isinstance(error, asyncio.CancelledError): + return "cancelled" + if isinstance(error, TimeoutError): + return "timeout" + if isinstance(error, ArtifactProcessingLeadershipLostError): + return "leadership_lost" + if isinstance(error, _WorkerExecutionError) and error.failure.error_code == "missing_durable_acknowledgement": + return "missing_durable_acknowledgement" + return "worker_failed" + + def _safe_traceback(error: BaseException) -> str: """Format stack locations without exception values that may contain Source/model data.""" @@ -1445,9 +1198,10 @@ def _safe_traceback(error: BaseException) -> str: __all__ = [ "ArtifactProcessingBinding", + "ArtifactProcessingPendingProvider", "ArtifactProcessingSupervisor", "ArtifactProcessingSupervisorStatus", - "ArtifactProcessingWaveKind", + "ArtifactProcessingSupervisors", "ArtifactProcessingWorkAssignment", "ArtifactProcessingWorkerCompletion", "ArtifactProcessingWorkerFailure", diff --git a/src/powercontext/builtin/runtime/composition.py b/src/powercontext/builtin/runtime/composition.py index aea081da37..d00f651b04 100644 --- a/src/powercontext/builtin/runtime/composition.py +++ b/src/powercontext/builtin/runtime/composition.py @@ -16,6 +16,7 @@ from __future__ import annotations +import logging import os from collections.abc import AsyncIterator, Callable, Mapping, Sequence from contextlib import AsyncExitStack, asynccontextmanager @@ -27,6 +28,7 @@ from pydantic import AnyHttpUrl, JsonValue, SecretStr from typing_extensions import override +from powercontext._logging import log_safely from powercontext.builtin.artifacts.experience import ExperienceCandidatePipeline, ExperienceGenerator from powercontext.builtin.artifacts.handoff import ( DefaultHandoffEvidenceProjector, @@ -74,6 +76,10 @@ OceanBaseTopicMemoryFTSIndex, OceanBaseTopicMemoryVectorIndex, ) +from powercontext.builtin.persistence.processing_migration import ( + assert_processing_schema_ready, + bootstrap_processing_schema, +) from powercontext.builtin.persistence.scope_search_schema import ensure_scope_search_schema from powercontext.builtin.persistence.seekdb.profile import SeekDBConfig, SeekDBProfile from powercontext.builtin.persistence.skill_distribution_schema import ensure_skill_distribution_schema @@ -95,10 +101,14 @@ from powercontext.builtin.runtime.artifact_processing import ( ArtifactProcessingBinding, ArtifactProcessingSupervisor, + ArtifactProcessingSupervisors, SpawnArtifactProcessingWorkerLauncher, ) from powercontext.builtin.runtime.config import BuiltinConfig, ExternalSkillsConfig, InferenceConfig, RuntimeConfig +from powercontext.builtin.runtime.family_processing import FAMILY_BINDINGS, FamilyWorkerSpec, run_family_worker from powercontext.builtin.runtime.models import MemorySearchMode, RuntimeCapabilities +from powercontext.builtin.runtime.processing_discovery import SourceProcessingPendingProvider, enabled_profile_scopes +from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest, processing_capabilities from powercontext.builtin.runtime.protocols import RuntimeTracing from powercontext.builtin.runtime.readiness import ( CachedReadinessProbe, @@ -109,7 +119,6 @@ ) from powercontext.builtin.runtime.relational import RelationalContexts from powercontext.builtin.runtime.topic_memory_processing import ( - TopicMemoryWindowSelector, TopicMemoryWorkerSpec, run_topic_memory_worker, validate_topic_memory_provider_settings, @@ -130,6 +139,7 @@ from powercontext.builtin.inference.pydantic_ai import InferenceLimits ValueT = TypeVar("ValueT") +logger = logging.getLogger(__name__) class BuiltinConfigurationError(RuntimeError): @@ -145,6 +155,7 @@ def __init__(self, issue: str) -> None: "memory-reranker": "Memory reranking requires a configured generation or rerank model, or injected reranker", "scheduled-experience-pipeline": "scheduled Experience incubation requires a candidate pipeline", "scheduled-pipeline": "scheduled Source processing requires a candidate pipeline", + "scheduled-profile-generation": "scheduled Profile processing requires reconstructible generation", "topic-memory-child-resources": ( "Topic Memory processing requires child-reconstructible inference resources" ), @@ -152,6 +163,15 @@ def __init__(self, issue: str) -> None: "topic-memory-provider-budget": "Topic Memory workers require OpenAI/Anthropic SDK providers with transport retries disabled and bounded stateless model settings", "topic-memory-generation": "Topic Memory processing requires a configured generation model", "topic-memory-database": "Topic Memory workers require file-backed SQLite; an in-memory database cannot be shared with spawned workers", + "artifact-processing-worker-authorization-provider": ( + "Background processing requires a reconstructible Authorization Provider with transactional ownership and audit" + ), + "artifact-processing-child-resources": "Background processing requires child-reconstructible inference resources", + "artifact-processing-source-registry": ( + "Built-in background workers require the built-in Source definitions; " + "provide custom processing bindings or disable built-in background families for a custom Source registry" + ), + "artifact-processing-families": "Declared background families must have one matching registration and reconstructible models", "database": "unsupported built-in database", } super().__init__(messages[issue]) @@ -215,7 +235,7 @@ async def rerank( @asynccontextmanager -async def open_builtin_runtime( # noqa: C901 +async def open_builtin_runtime( config: BuiltinConfig, *, scheduler_path: str | Path = "powercontext.scheduler.db", @@ -234,6 +254,7 @@ async def open_builtin_runtime( # noqa: C901 topic_memory_search_observer: Callable[[str, bool], None] | None = None, tracing: RuntimeTracing | None = None, artifact_processing_bindings: Sequence[ArtifactProcessingBinding] = (), + worker_security: dict[str, Any] | None = None, scheduled_source_runner: ScheduledSourceRunner | None = None, scheduled_experience_runner: ScheduledExperienceRunner | None = None, scheduled_profile_runner: Any = None, @@ -245,6 +266,7 @@ async def open_builtin_runtime( # noqa: C901 async with AsyncExitStack() as resources: configured_source_registry = source_registry or BUILTIN_SOURCE_REGISTRY + _validate_processing_source_registry(config, artifact_processing_bindings, configured_source_registry) prompt_demonstrators: dict[str, DemonstrationGenerator] = {} ( generated_profile, @@ -290,16 +312,7 @@ async def open_builtin_runtime( # noqa: C901 ("skill.generate", skill_generator, generated_skill), ("handoff.generate", handoff_pipeline, generated_handoff), ) - prompt_registry = PromptRegistry( - builtin_prompt_definitions(config.runtime.memory_extraction_profile), - supported=frozenset( - key for key, injected, generated in components if injected is None and generated is not None - ), - injected=frozenset(key for key, injected, _ in components if injected is not None), - disabled=frozenset({"memory.rerank"}) - if not config.runtime.memory_rerank_enabled and memory_reranker is None - else frozenset(), - ) + prompt_registry = _prompt_registry(config.runtime, components) if configured_reranker is not None and tracing is not None: configured_reranker = _TracingMemoryReranker(configured_reranker, tracing) if embedding_model is None: @@ -317,9 +330,7 @@ async def open_builtin_runtime( # noqa: C901 if isinstance(embedding_model, PydanticAIEmbeddingModel) else embedding_model ) - configured_embedding = ( - None if configured_embedding_source is None else UsageReportingEmbeddingModel(configured_embedding_source) - ) + configured_embedding = _usage_reporting_embedding_model(configured_embedding_source) configured_external_skills = ( _external_skill_provider(config.external_skills) if external_skill_provider is None @@ -369,12 +380,44 @@ async def run_profile(scope_id, high): for name, readiness_probe in inference_readiness: if readiness_probe is not None: readiness_probes[name] = ReadinessProbeDefinition(probe=readiness_probe, blocking=False) - processing_bindings = _topic_memory_processing_bindings( + processing_bindings = _artifact_processing_bindings( config, contexts, artifact_processing_bindings, injected_embedding_model=embedding_model, injected_token_estimator=token_estimator, + injected_pipelines={ + "memory": candidate_pipeline, + "experience": experience_pipeline, + "profile": profile_generator, + }, + worker_security=worker_security, + source_registry=configured_source_registry, + ) + log_safely( + logger, + logging.INFO, + "Artifact processing configuration", + extra={ + "event": "artifact_processing.configured", + "mode": config.runtime.artifact_processing_supervisor_mode, + "role": config.runtime.artifact_processing_role, + "compatibility_aliases": config.runtime._processing_aliases_used, + "families": [ + { + "binding": b.binding_name, + "family": b.artifact_family, + "workers": b.max_workers, + "timeout_seconds": b.worker_timeout_seconds, + "interval_seconds": None + if b.automatic_processing_interval is None + else b.automatic_processing_interval.total_seconds(), + "cron": b.cron, + "timezone": b.timezone, + } + for b in processing_bindings + ], + }, ) topic_memory_processing_available = _topic_memory_processing_available(config, processing_bindings) runtime = await resources.enter_async_context( @@ -434,7 +477,7 @@ async def run_profile(scope_id, high): ) ) runtime.artifact_processing_supervisor = await resources.enter_async_context( - _open_artifact_processing_supervisor(config, contexts, processing_bindings) + _open_artifact_processing_supervisor(config, contexts, processing_bindings, tracing=tracing) ) contexts.profiles.operation_context = runtime._operation if config.handoff_report.enabled: @@ -442,93 +485,130 @@ async def run_profile(scope_id, high): contexts.scopes, RuntimeHandoffReadAdapter(runtime.handoff), ) - if ( - config.runtime.artifact_processing_role == "all" - and config.runtime.schedule_seconds is not None - and configured_pipeline is None - ): - raise BuiltinConfigurationError("scheduled-pipeline") - if ( - config.runtime.artifact_processing_role == "all" - and config.runtime.experience_schedule_seconds is not None - and configured_incubation is None - ): - raise BuiltinConfigurationError("scheduled-experience-pipeline") if config.runtime.memory_rerank_enabled and configured_reranker is None: raise BuiltinConfigurationError("memory-reranker") - if config.runtime.artifact_processing_role == "all" and ( - config.runtime.schedule_seconds is not None - or config.runtime.experience_schedule_seconds is not None - or (config.runtime.profile_schedule_enabled and contexts.profiles.generator is not None) - ): - runtime.start_scheduler( - scheduler_path, - config.runtime.schedule_seconds, - experience_schedule_seconds=config.runtime.experience_schedule_seconds, - profile_cron=config.runtime.profile_cron - if config.runtime.profile_schedule_enabled and contexts.profiles.generator is not None - else None, - profile_timezone=config.runtime.profile_timezone, - profile_max_concurrency=config.runtime.profile_max_concurrency, - ) yield runtime -def _topic_memory_processing_bindings( +def _validate_processing_source_registry( + config: BuiltinConfig, + bindings: Sequence[ArtifactProcessingBinding], + source_registry: SourceDefinitionRegistry, +) -> None: + """Reject unsupported child Sources before database bootstrap commits deployment identity.""" + + if config.runtime.artifact_processing_role == "api": + return + registered = {binding.artifact_family for binding in bindings} + if all(family in registered for family in processing_capabilities(config)): + return + definitions = source_registry.definitions + builtin_definitions = BUILTIN_SOURCE_REGISTRY.definitions + if ( + type(source_registry) is not SourceDefinitionRegistry + or len(definitions) != len(builtin_definitions) + or any( + definition is not expected for definition, expected in zip(definitions, builtin_definitions, strict=True) + ) + ): + raise BuiltinConfigurationError("artifact-processing-source-registry") + + +def _artifact_processing_bindings( # noqa: C901 - validate and assemble one registration per Family config: BuiltinConfig, contexts: RelationalContexts, bindings: Sequence[ArtifactProcessingBinding], *, injected_embedding_model: EmbeddingModel | None = None, injected_token_estimator: TokenEstimator | None = None, + injected_pipelines: Mapping[str, object | None] | None = None, + worker_security: dict[str, Any] | None = None, + source_registry: SourceDefinitionRegistry = BUILTIN_SOURCE_REGISTRY, ) -> tuple[ArtifactProcessingBinding, ...]: - configured = tuple(bindings) + configured = list(bindings) + _validate_processing_registrations(configured) + capabilities = processing_capabilities(config) + canonical = {**FAMILY_BINDINGS, "topic-memory": TOPIC_MEMORY_SOURCE_WINDOW_BINDING} + registered = {binding.artifact_family for binding in configured} + declared = set(capabilities) + if declared - (set(canonical) | registered): + raise BuiltinConfigurationError("artifact-processing-families") + automatic = { + "memory": config.runtime.memory_schedule_seconds, + "topic-memory": config.runtime.topic_memory_schedule_seconds, + "experience": config.runtime.experience_schedule_seconds, + "profile": config.runtime.profile_schedule_enabled or None, + } + for family, schedule in automatic.items(): + if schedule is not None and family not in declared | registered: + issue = { + "memory": "scheduled-pipeline", + "experience": "scheduled-experience-pipeline", + "topic-memory": "topic-memory-generation", + "profile": "scheduled-profile-generation", + }[family] + raise BuiltinConfigurationError(issue) if config.runtime.artifact_processing_role == "api": - return configured - if any(binding.binding_name == TOPIC_MEMORY_SOURCE_WINDOW_BINDING for binding in configured): - return configured - if config.inference.generation_model is None: - if config.runtime.topic_memory_schedule_seconds is not None: - raise BuiltinConfigurationError("topic-memory-generation") - return configured - if injected_embedding_model is not None or injected_token_estimator is not None: - raise BuiltinConfigurationError("topic-memory-child-resources") - if isinstance(config.database, SQLiteConfig) and config.database.is_in_memory: - raise BuiltinConfigurationError("topic-memory-database") - if not _topic_memory_provider_available(config): - # Generic inference settings may be valid for other operations. Do not - # register an unusable Topic worker or reject those unrelated features. - if config.runtime.topic_memory_schedule_seconds is not None: + return tuple(configured) + _validate_processing_source_registry(config, configured, source_registry) + injected_pipelines = injected_pipelines or {} + for family in capabilities: + if family in registered: + continue + if config.inference.generation_model is None: + raise BuiltinConfigurationError("artifact-processing-families") + if ( + injected_embedding_model is not None + or injected_token_estimator is not None + or injected_pipelines.get(family) is not None + ): + raise BuiltinConfigurationError("artifact-processing-child-resources") + if isinstance(config.database, SQLiteConfig) and config.database.is_in_memory: + raise BuiltinConfigurationError("topic-memory-database") + prefix = family.replace("-", "_") + if family == "topic-memory": validate_topic_memory_provider_settings(config.inference) - return configured - try: - budget = topic_memory_stage_budget( - context_window_tokens=config.inference.generation_model_context_window_tokens, - max_requests=config.inference.generation_max_requests, - model_settings=config.inference.generation_model_settings, + try: + budget = topic_memory_stage_budget( + context_window_tokens=config.inference.generation_model_context_window_tokens, + max_requests=config.inference.generation_max_requests, + model_settings=config.inference.generation_model_settings, + ) + validate_topic_memory_stage_capacity(budget, contexts.token_estimator) + except TopicMemoryGenerationError as error: + raise BuiltinConfigurationError("topic-memory-generation-budget") from error + entrypoint = partial( + run_topic_memory_worker, TopicMemoryWorkerSpec(config=config, worker_security=worker_security) + ) + else: + entrypoint = partial(run_family_worker, FamilyWorkerSpec(config=config, worker_security=worker_security)) + interval = None if family == "profile" else automatic[family] + binding = canonical[family] + configured.append( + ArtifactProcessingBinding( + binding_name=binding, + artifact_family=family, + launcher=SpawnArtifactProcessingWorkerLauncher(entrypoint), + max_workers=getattr(config.runtime, f"{prefix}_max_workers"), + worker_timeout_seconds=getattr(config.runtime, f"{prefix}_worker_timeout_seconds"), + automatic_processing_interval=None if interval is None else timedelta(seconds=float(interval)), + cron=config.runtime.profile_cron + if family == "profile" and config.runtime.profile_schedule_enabled + else None, + timezone=config.runtime.profile_timezone if family == "profile" else "Asia/Shanghai", + pending_provider=SourceProcessingPendingProvider(contexts.database, binding, family), + automatic_scope_filter=enabled_profile_scopes if family == "profile" else None, + ) ) - validate_topic_memory_stage_capacity(budget, contexts.token_estimator) - except TopicMemoryGenerationError as error: - raise BuiltinConfigurationError("topic-memory-generation-budget") from error - spec = TopicMemoryWorkerSpec(config=config) - entrypoint = partial(run_topic_memory_worker, spec) - selector = TopicMemoryWindowSelector( - contexts.database, - contexts.repositories.sources, - contexts.token_estimator, - context_window_tokens=config.inference.generation_model_context_window_tokens, - ) - automatic = config.runtime.topic_memory_schedule_seconds - return ( - *configured, - ArtifactProcessingBinding( - binding_name=TOPIC_MEMORY_SOURCE_WINDOW_BINDING, - source_window_limit=config.runtime.topic_memory_source_window_limit, - launcher=SpawnArtifactProcessingWorkerLauncher(entrypoint), - automatic_processing_interval=None if automatic is None else timedelta(seconds=automatic), - window_selector=selector, - ), - ) + _validate_processing_registrations(configured) + return tuple(configured) + + +def _validate_processing_registrations(configured: Sequence[ArtifactProcessingBinding]) -> None: + for attribute in ("binding_name", "artifact_family", "config_prefix"): + identifiers = [getattr(binding, attribute) for binding in configured] + if len(identifiers) != len(set(identifiers)): + raise BuiltinConfigurationError("artifact-processing-families") def _topic_memory_processing_available( @@ -538,9 +618,7 @@ def _topic_memory_processing_available( """Report declared cross-role processing ability without probing worker liveness.""" return any(binding.binding_name == TOPIC_MEMORY_SOURCE_WINDOW_BINDING for binding in bindings) or ( - config.runtime.artifact_processing_role == "api" - and config.inference.generation_model is not None - and _topic_memory_provider_available(config) + config.runtime.artifact_processing_role == "api" and "topic-memory" in processing_capabilities(config) ) @@ -557,22 +635,33 @@ async def _open_artifact_processing_supervisor( config: BuiltinConfig, contexts: RelationalContexts, bindings: Sequence[ArtifactProcessingBinding], -) -> AsyncIterator[ArtifactProcessingSupervisor | None]: - if config.runtime.artifact_processing_role == "api": + *, + tracing: RuntimeTracing | None = None, +) -> AsyncIterator[ArtifactProcessingSupervisors | None]: + if config.runtime.artifact_processing_role == "api" or not bindings: yield None return - async with ArtifactProcessingSupervisor( - database=contexts.database, - bindings=bindings, - lease_mode="oceanbase" if isinstance(config.database, OceanBaseConfig) else "single-process", - max_workers=config.runtime.artifact_processing_max_workers, - worker_timeout_seconds=config.runtime.artifact_processing_worker_timeout_seconds, - pending=contexts.repositories.processing_pending, - cursors=contexts.repositories.cursors, - leases=contexts.repositories.processing_leases, - binding_states=contexts.repositories.processing_binding_states, - ) as supervisor: - yield supervisor + groups = ( + [("global", tuple(bindings))] + if config.runtime.artifact_processing_supervisor_mode == "global" + else [(f"artifact:{binding.artifact_family}", (binding,)) for binding in bindings] + ) + async with AsyncExitStack() as resources: + supervisors = [] + for name, group in groups: + supervisor = await resources.enter_async_context( + ArtifactProcessingSupervisor( + database=contexts.database, + bindings=group, + supervisor_group=name, + lease_mode="oceanbase" if isinstance(config.database, OceanBaseConfig) else "single-process", + leases=contexts.repositories.processing_leases, + binding_states=contexts.repositories.processing_binding_states, + tracing=tracing, + ) + ) + supervisors.append(supervisor) + yield ArtifactProcessingSupervisors(tuple(supervisors)) @asynccontextmanager @@ -615,6 +704,8 @@ async def open_builtin_contexts( load_vector_extension=embedding_model is not None, ) as profile: async with profile.database.transaction() as connection: + await bootstrap_processing_schema(connection, canonical_processing_manifest(config)) + await assert_processing_schema_ready(connection, canonical_processing_manifest(config)) await ensure_skill_distribution_schema(connection) await ensure_scope_search_schema(connection) # A Topic child reuses its parent's schema. It never reads or @@ -669,6 +760,8 @@ async def open_builtin_contexts( raise BuiltinConfigurationError("database") async with profile_context as profile: async with profile.database.transaction() as connection: + await bootstrap_processing_schema(connection, canonical_processing_manifest(config)) + await assert_processing_schema_ready(connection, canonical_processing_manifest(config)) await ensure_skill_distribution_schema(connection) await ensure_scope_search_schema(connection) if not _topic_memory_worker: @@ -1145,6 +1238,33 @@ def _merge_headers(*values: Mapping[str, SecretStr]) -> dict[str, SecretStr]: return merged +def _prompt_registry( + runtime: RuntimeConfig, + components: tuple[tuple[str, object | None, object | None], ...], +) -> PromptRegistry: + """Infer Prompt support from executable generated components in either process.""" + + injected = frozenset(key for key, supplied, _ in components if supplied is not None) + return PromptRegistry( + builtin_prompt_definitions(runtime.memory_extraction_profile), + supported=frozenset( + key for key, supplied, generated in components if supplied is None and generated is not None + ), + injected=injected, + disabled=frozenset({"memory.rerank"}) + if not runtime.memory_rerank_enabled and "memory.rerank" not in injected + else frozenset(), + ) + + +def _usage_reporting_embedding_model(model: EmbeddingModel | None) -> EmbeddingModel | None: + """Attribute operational embeddings once, leaving readiness adapters unwrapped.""" + + if model is None or isinstance(model, UsageReportingEmbeddingModel): + return model + return UsageReportingEmbeddingModel(model) + + async def _embedding_models( settings: InferenceConfig, resources: AsyncExitStack, diff --git a/src/powercontext/builtin/runtime/config.py b/src/powercontext/builtin/runtime/config.py index 3a4a300624..58072dea96 100644 --- a/src/powercontext/builtin/runtime/config.py +++ b/src/powercontext/builtin/runtime/config.py @@ -20,7 +20,17 @@ from collections.abc import Mapping from typing import Any, Literal, Self -from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field, JsonValue, SecretStr, field_validator, model_validator +from pydantic import ( + AnyHttpUrl, + BaseModel, + ConfigDict, + Field, + JsonValue, + PrivateAttr, + SecretStr, + field_validator, + model_validator, +) from powercontext.builtin.artifacts.memory.prompts import MemoryExtractionProfile from powercontext.builtin.artifacts.skill import AgentSkillTarget, CodexSkillRoot @@ -39,9 +49,81 @@ _HTTP_FIELD_NAME_PATTERN = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+") +def _equal_numeric_aliases(left: Any, right: Any) -> bool: + if left is None or right is None or isinstance(left, bool) or isinstance(right, bool): + return False + try: + return float(left) == float(right) + except (ValueError, TypeError, OverflowError): + return False + + class RuntimeConfig(BaseModel): """Built-in runtime policy and scheduler configuration.""" + model_config = ConfigDict(extra="forbid") + _processing_aliases_used: tuple[str, ...] = PrivateAttr(default=()) + + @model_validator(mode="wrap") + @classmethod + def record_processing_aliases(cls, value: Any, handler: Any) -> Any: + result = handler(value) + if isinstance(value, Mapping): + result._processing_aliases_used = tuple( + name + for name in ( + "schedule_seconds", + "profile_max_concurrency", + "artifact_processing_max_workers", + "artifact_processing_worker_timeout_seconds", + ) + if name in value + ) + return result + + @model_validator(mode="before") + @classmethod + def normalize_processing_aliases(cls, value: Any) -> Any: + if not isinstance(value, Mapping): + return value + normalized = dict(value) + for old, new in ( + ("schedule_seconds", "memory_schedule_seconds"), + ("profile_max_concurrency", "profile_max_workers"), + ("artifact_processing_max_workers", "topic_memory_max_workers"), + ("artifact_processing_worker_timeout_seconds", "topic_memory_worker_timeout_seconds"), + ): + if ( + old in normalized + and new in normalized + and ( + normalized[old] != normalized[new] + and str(normalized[old]) != str(normalized[new]) + and not _equal_numeric_aliases(normalized[old], normalized[new]) + ) + ): + raise ValueError(f"conflicting artifact processing settings: {old} and {new}") # noqa: TRY003 + if old in normalized: + normalized[new] = normalized[old] + elif new in normalized: + normalized[old] = normalized[new] + return normalized + + @field_validator( + "memory_max_workers", + "topic_memory_max_workers", + "experience_max_workers", + "profile_max_workers", + "profile_max_concurrency", + "artifact_processing_max_workers", + mode="before", + ) + @classmethod + def reject_boolean_worker_quota(cls, value: Any) -> Any: + if isinstance(value, bool): + raise ValueError("Worker quota must be a positive integer") # noqa: TRY003, TRY004 - Pydantic validation + return value + scope_cache_size: int = Field(default=DEFAULT_SCOPE_CACHE_SIZE, ge=1) source_window_limit: int = Field(default=100, ge=1) memory_extraction_profile: MemoryExtractionProfile = MemoryExtractionProfile.CODING @@ -67,6 +149,7 @@ def validate_profile_schedule(self): return self schedule_seconds: float | None = Field(default=None, gt=0) + memory_schedule_seconds: float | None = Field(default=None, gt=0) experience_schedule_seconds: float | None = Field(default=None, gt=0) topic_memory_schedule_seconds: float | None = Field(default=None, gt=0) topic_memory_source_window_limit: int = Field(default=10, ge=1) @@ -76,6 +159,16 @@ def validate_profile_schedule(self): artifact_processing_max_workers: int = Field(default=10, ge=1) artifact_processing_worker_timeout_seconds: float = Field(default=600, gt=0) artifact_processing_role: Literal["all", "api", "background"] = "all" + artifact_processing_supervisor_mode: Literal["global", "dedicated"] = "global" + artifact_processing_families: tuple[str, ...] | None = None + memory_max_workers: int = Field(default=1, ge=1) + topic_memory_max_workers: int = Field(default=10, ge=1) + experience_max_workers: int = Field(default=1, ge=1) + profile_max_workers: int = Field(default=4, ge=1) + memory_worker_timeout_seconds: float = Field(default=600, gt=0) + topic_memory_worker_timeout_seconds: float = Field(default=600, gt=0) + experience_worker_timeout_seconds: float = Field(default=600, gt=0) + profile_worker_timeout_seconds: float = Field(default=600, gt=0) @model_validator(mode="after") def validate_topic_memory_history_candidates(self) -> RuntimeConfig: @@ -83,14 +176,11 @@ def validate_topic_memory_history_candidates(self) -> RuntimeConfig: raise ValueError( # noqa: TRY003 "topic_memory_history_min_candidates must not exceed topic_memory_history_max_candidates" ) - if self.artifact_processing_role != "all" and ( - self.schedule_seconds is not None - or self.experience_schedule_seconds is not None - or self.profile_schedule_enabled + families = self.artifact_processing_families + if families is not None and ( + len(set(families)) != len(families) or any(not family or family != family.strip() for family in families) ): - raise ValueError( # noqa: TRY003 - "schedule_seconds, experience_schedule_seconds and profile_schedule_enabled require artifact_processing_role='all'" - ) + raise ValueError("artifact_processing_families must contain unique, nonempty Family names") # noqa: TRY003 return self diff --git a/src/powercontext/builtin/runtime/family_processing.py b/src/powercontext/builtin/runtime/family_processing.py new file mode 100644 index 0000000000..0dcd11cd90 --- /dev/null +++ b/src/powercontext/builtin/runtime/family_processing.py @@ -0,0 +1,201 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Scope child processors for Memory, Experience, and Profile.""" + +from __future__ import annotations + +import asyncio +import logging +from contextlib import AsyncExitStack +from datetime import UTC, datetime +from functools import partial +from typing import TYPE_CHECKING, Any + +from pydantic import BaseModel, Field + +from powercontext._logging import log_safely +from powercontext.builtin.artifacts.experience import EXPERIENCE_INCUBATION_CURSOR_NAME +from powercontext.builtin.artifacts.profile.models import PROFILE_SOURCE_WINDOW_BINDING +from powercontext.builtin.inference.models import InferenceUsage +from powercontext.builtin.inference.usage import bind_usage_reporter +from powercontext.builtin.persistence.errors import ArtifactProcessingLeadershipLostError, GenerationConflictError +from powercontext.builtin.runtime.config import BuiltinConfig +from powercontext.builtin.runtime.processing_contracts import ( + ArtifactProcessingWorkAssignment, + ArtifactProcessingWorkerCompletion, + ArtifactProcessingWorkerOutcome, +) +from powercontext.builtin.runtime.processing_execution import InvocationAlreadyHandled, ScopeInvocation +from powercontext.builtin.sources import BUILTIN_SOURCE_REGISTRY +from powercontext.builtin.statistics import ModelUsageOperation, ModelUsagePurpose +from powercontext.builtin.triggers import SOURCE_WINDOW_TRIGGER_NAME +from powercontext.errors import RevisionConflictError + +if TYPE_CHECKING: + from powercontext.builtin.runtime.relational import RelationalContexts + from powercontext.server.processing_security import WorkerSecurity + + +FAMILY_BINDINGS = { + "memory": SOURCE_WINDOW_TRIGGER_NAME, + "experience": EXPERIENCE_INCUBATION_CURSOR_NAME, + "profile": PROFILE_SOURCE_WINDOW_BINDING, +} +logger = logging.getLogger(__name__) + + +class FamilyWorkerSpec(BaseModel): + """Serializable child configuration; never expose credentials through repr.""" + + config: BuiltinConfig = Field(repr=False) + worker_security: dict[str, Any] | None = Field(default=None, repr=False) + + +def run_family_worker( + spec: FamilyWorkerSpec, assignment: ArtifactProcessingWorkAssignment, / +) -> ArtifactProcessingWorkerCompletion: + return asyncio.run(_run_family_worker(spec, assignment)) + + +async def _run_family_worker( + spec: FamilyWorkerSpec, assignment: ArtifactProcessingWorkAssignment +) -> ArtifactProcessingWorkerCompletion: + from powercontext.builtin.runtime.composition import ( + _embedding_models, + _generation_pipelines, + _prompt_registry, + _usage_reporting_embedding_model, + open_builtin_contexts, + ) + + config = spec.config + async with AsyncExitStack() as resources: + pipelines = await _generation_pipelines( + config.inference, config.runtime, resources, None, BUILTIN_SOURCE_REGISTRY + ) + embedding, _ = await _embedding_models(config.inference, resources, None) + contexts = await resources.enter_async_context( + open_builtin_contexts( + config, + candidate_pipeline=pipelines[1], + experience_pipeline=pipelines[2], + embedding_model=_usage_reporting_embedding_model(embedding), + prompt_registry=_prompt_registry( + config.runtime, + ( + ("memory.extract", None, pipelines[1]), + ("experience.incubate", None, pipelines[2]), + ), + ), + _topic_memory_worker=True, + ) + ) + contexts.profiles.generator = pipelines[0] + contexts.profiles.max_sources = config.runtime.profile_max_sources_per_window + security = None + if spec.worker_security is not None: + # The optional Server adapter stays outside Runtime-only SDK composition. + from powercontext.server.processing_security import open_worker_security + + security = await resources.enter_async_context( + open_worker_security(spec.worker_security, contexts.database) + ) + return await process_family_invocation(contexts, assignment, config=config, security=security) + + +async def process_family_invocation( + contexts: RelationalContexts, + assignment: ArtifactProcessingWorkAssignment, + *, + config: BuiltinConfig, + security: WorkerSecurity | None = None, +) -> ArtifactProcessingWorkerCompletion: + """Run one bounded domain window, preserving its own Review/Cursor rules.""" + + async def report(purpose: ModelUsagePurpose, operation: ModelUsageOperation, usage: InferenceUsage) -> None: + try: + await contexts.statistics(assignment.scope_id).record(purpose, operation, usage, datetime.now(UTC).date()) + except Exception as error: + # Usage attribution keeps the same best-effort behavior as the SDK facade. + log_safely( + logger, + logging.WARNING, + "Artifact processing usage recording failed", + extra={"event": "artifact_processing.usage_failed", "exception_type": type(error).__name__}, + ) + + generation_purpose = { + "memory": ModelUsagePurpose.MEMORY_EXTRACTION, + "experience": ModelUsagePurpose.EXPERIENCE_GENERATION, + }.get(assignment.artifact_family) + with bind_usage_reporter( + report, + generation_purpose=generation_purpose, + embedding_purpose=ModelUsagePurpose.MEMORY_INDEXING if assignment.artifact_family == "memory" else None, + ): + return await _process_family_invocation(contexts, assignment, config=config, security=security) + + +async def _process_family_invocation( + contexts: RelationalContexts, + assignment: ArtifactProcessingWorkAssignment, + *, + config: BuiltinConfig, + security: WorkerSecurity | None, +) -> ArtifactProcessingWorkerCompletion: + if FAMILY_BINDINGS.get(assignment.artifact_family) != assignment.binding_name: + raise ValueError("processor Family and binding do not match") # noqa: TRY003 + scope = assignment.scope_id + invocation = ScopeInvocation( + assignment, + authorize_transaction=None if security is None else partial(security.authorize_transaction, scope_id=scope), + ) + try: + if assignment.artifact_family == "memory": + await contexts.process_memory( + scope, + config.runtime.source_window_limit, + processing=invocation, + authorize_snapshot=None if security is None else partial(security.authorize_memory, scope), + on_commit=None if security is None else partial(security.memory_commit, scope_id=scope), + ) + elif assignment.artifact_family == "experience": + await contexts.incubate_experience( + scope, + config.runtime.source_window_limit, + processing=invocation, + on_commit=None if security is None else partial(security.experience_commit, scope_id=scope), + ) + else: + result = await contexts.profiles.flush( + scope, + processing=invocation, + authorize_snapshot=None if security is None else partial(security.authorize_profile, scope), + authorize_commit=None + if security is None + else partial(security.authorize_profile_commit, scope_id=scope), + on_commit=None if security is None else partial(security.profile_commit, scope_id=scope), + ) + if result.status == "conflict": + return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.HEAD_CONFLICT) + except InvocationAlreadyHandled: + return ArtifactProcessingWorkerCompletion() + except GenerationConflictError: + return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT) + except RevisionConflictError: + return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.HEAD_CONFLICT) + except ArtifactProcessingLeadershipLostError: + return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.LEADERSHIP_LOST) + return ArtifactProcessingWorkerCompletion() diff --git a/src/powercontext/builtin/runtime/processing_contracts.py b/src/powercontext/builtin/runtime/processing_contracts.py new file mode 100644 index 0000000000..18df788958 --- /dev/null +++ b/src/powercontext/builtin/runtime/processing_contracts.py @@ -0,0 +1,90 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Serializable, domain-independent Scope invocation and Worker contracts.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from enum import StrEnum +from typing import Protocol + +from powercontext.builtin.persistence.supervision import ArtifactProcessingFence + + +class ArtifactProcessingWorkerOutcome(StrEnum): + """Terminal control results; domain conflicts are safe to reschedule.""" + + SUCCEEDED = "succeeded" + CURSOR_CONFLICT = "cursor_conflict" + HEAD_CONFLICT = "head_conflict" + LEADERSHIP_LOST = "leadership_lost" + + +@dataclass(frozen=True, slots=True) +class ArtifactProcessingWorkAssignment: + """One accepted Scope invocation, independent of its processor's inputs.""" + + binding_name: str + scope_id: str + artifact_family: str + claimed_request_generation: int + fence: ArtifactProcessingFence + worker_id: str + + +@dataclass(frozen=True, slots=True) +class ArtifactProcessingWorkerFailure: + """Sanitized metadata safe to return across a child process boundary.""" + + stage: str + error_code: str + exception_type: str + traceback: str + + +@dataclass(frozen=True, slots=True) +class ArtifactProcessingWorkerCompletion: + """Control result; success still requires durable acknowledgement.""" + + outcome: ArtifactProcessingWorkerOutcome = ArtifactProcessingWorkerOutcome.SUCCEEDED + + +class ArtifactProcessingWorkerHandle(Protocol): + """One child whose termination completes only after its exit is observed.""" + + async def wait(self) -> ArtifactProcessingWorkerCompletion: ... + + async def terminate(self) -> None: ... + + +class ArtifactProcessingWorkerLauncher(Protocol): + """Launch a child, reclaiming partially started resources on cancellation.""" + + async def start(self, assignment: ArtifactProcessingWorkAssignment) -> ArtifactProcessingWorkerHandle: ... + + +WorkerEntrypoint = Callable[[ArtifactProcessingWorkAssignment], ArtifactProcessingWorkerCompletion | None] + + +__all__ = [ + "ArtifactProcessingWorkAssignment", + "ArtifactProcessingWorkerCompletion", + "ArtifactProcessingWorkerFailure", + "ArtifactProcessingWorkerHandle", + "ArtifactProcessingWorkerLauncher", + "ArtifactProcessingWorkerOutcome", + "WorkerEntrypoint", +] diff --git a/src/powercontext/builtin/runtime/processing_discovery.py b/src/powercontext/builtin/runtime/processing_discovery.py new file mode 100644 index 0000000000..9d4b34cd4f --- /dev/null +++ b/src/powercontext/builtin/runtime/processing_discovery.py @@ -0,0 +1,76 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Bounded reconciliation of Source-driven Family progress at startup.""" + +from __future__ import annotations + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.supervision import ArtifactProcessingFence, ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import PROFILE_POLICIES_TABLE, SOURCE_JOURNAL_HEADS_TABLE + + +async def enabled_profile_scopes(connection: AsyncConnection, scope_ids: tuple[str, ...]) -> frozenset[str]: + """Qualify one bounded automatic page before accepting any invocation. + + Hold enabled Policy rows through admission so concurrent policy changes + serialize with the decision. This reads metadata only, before any Worker + authorization, model construction, or retry state exists for the page. + """ + + if not scope_ids: + return frozenset() + table = PROFILE_POLICIES_TABLE + rows = await connection.scalars( + select(table.c.scope_id) + .where(table.c.scope_id.in_(scope_ids), table.c.generation_enabled.is_(True)) + .with_for_update() + ) + return frozenset(rows) + + +class SourceProcessingPendingProvider: + """Inspect journal metadata, never Source bodies, prompts, or models.""" + + def __init__(self, database: AsyncDatabase, binding_name: str, artifact_family: str) -> None: + self._database = database + self._binding = binding_name + self._family = artifact_family + + async def reconcile(self, after_scope_id: str | None, limit: int, *, fence: ArtifactProcessingFence) -> str | None: + heads = SOURCE_JOURNAL_HEADS_TABLE + statement = select(heads.c.scope_id, heads.c.position).order_by(heads.c.scope_id).limit(limit) + if after_scope_id is not None: + statement = statement.where(heads.c.scope_id > after_scope_id) + if self._family == "profile": + statement = statement.join(PROFILE_POLICIES_TABLE, PROFILE_POLICIES_TABLE.c.scope_id == heads.c.scope_id) + statement = statement.where(PROFILE_POLICIES_TABLE.c.generation_enabled.is_(True)) + async with self._database.transaction() as connection: + await ArtifactProcessingLeaseRepository().require_fence(connection, fence) + rows = (await connection.execute(statement)).all() + intents = ArtifactProcessingIntentRepository() + cursors = SourceCursorRepository() + for scope, high in rows: + cursor = await cursors.load(connection, scope, self._binding) + if int(high) <= (0 if cursor is None else cursor.cursor.sequence): + continue + intent = await intents.load(connection, scope, self._binding, for_update=True) + if intent is None or intent.dirty_generation == intent.clean_generation: + await intents.mark_dirty(connection, scope, self._binding) + return str(rows[-1][0]) if len(rows) == limit else None diff --git a/src/powercontext/builtin/runtime/processing_execution.py b/src/powercontext/builtin/runtime/processing_execution.py new file mode 100644 index 0000000000..3908219b4e --- /dev/null +++ b/src/powercontext/builtin/runtime/processing_execution.py @@ -0,0 +1,82 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Transaction hooks shared by built-in Scope processors. + +The scheduler's request generation acknowledges an invocation, while each +processor remains responsible for deciding whether domain work remains. +""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable + +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.persistence.processing_intents import ( + ArtifactProcessingIntentRepository, + StoredArtifactProcessingIntent, +) +from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.runtime.processing_contracts import ArtifactProcessingWorkAssignment + + +class InvocationAlreadyHandled(Exception): + """A duplicate invocation must finish without selecting any new input.""" + + +class ScopeInvocation: + """Bind every processor transaction to its term and accepted request.""" + + def __init__( + self, + assignment: ArtifactProcessingWorkAssignment, + *, + authorize_transaction: Callable[[AsyncConnection], Awaitable[None]] | None = None, + ) -> None: + if assignment.fence.supervisor_group not in {"global", f"artifact:{assignment.artifact_family}"}: + raise ValueError("processing fence belongs to another Family") # noqa: TRY003 + self.assignment = assignment + self.intents = ArtifactProcessingIntentRepository() + self.leases = ArtifactProcessingLeaseRepository() + self.dirty_generation: int | None = None + self.authorize_transaction = authorize_transaction + + async def guard(self, connection: AsyncConnection) -> StoredArtifactProcessingIntent: + work = self.assignment + await self.leases.require_fence(connection, work.fence) + intent = await self.intents.load(connection, work.scope_id, work.binding_name, for_update=True) + if intent is None or intent.requested_generation < work.claimed_request_generation: + raise ValueError("processor invocation has no accepted request") # noqa: TRY003 + if intent.handled_generation >= work.claimed_request_generation: + raise InvocationAlreadyHandled + if self.authorize_transaction is not None: + await self.authorize_transaction(connection) + return intent + + async def start(self, connection: AsyncConnection) -> None: + intent = await self.guard(connection) + self.dirty_generation = intent.dirty_generation + + async def complete(self, connection: AsyncConnection, *, remaining_work: bool) -> None: + await self.guard(connection) + work = self.assignment + await self.intents.acknowledge( + connection, + work.scope_id, + work.binding_name, + work.claimed_request_generation, + clean_generation=None if remaining_work else self.dirty_generation, + ) + await self.leases.require_fence(connection, work.fence) diff --git a/src/powercontext/builtin/runtime/processing_registry.py b/src/powercontext/builtin/runtime/processing_registry.py new file mode 100644 index 0000000000..56ee5bc627 --- /dev/null +++ b/src/powercontext/builtin/runtime/processing_registry.py @@ -0,0 +1,72 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Stable deployment identity shared by startup and maintenance tooling.""" + +from __future__ import annotations + +from typing import Any + +from powercontext.builtin.artifacts.experience import EXPERIENCE_INCUBATION_CURSOR_NAME +from powercontext.builtin.artifacts.profile.models import PROFILE_SOURCE_WINDOW_BINDING +from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING +from powercontext.builtin.runtime.config import BuiltinConfig +from powercontext.builtin.triggers import SOURCE_WINDOW_TRIGGER_NAME + + +def processing_capabilities(config: BuiltinConfig) -> tuple[str, ...]: + """Use explicit cross-role declarations or infer executable built-ins.""" + + declared = config.runtime.artifact_processing_families + if declared is not None: + return tuple(sorted(declared)) + if config.inference.generation_model is None: + return () + from powercontext.builtin.runtime.composition import BuiltinConfigurationError + from powercontext.builtin.runtime.topic_memory_processing import validate_topic_memory_provider_settings + + families = ["memory", "experience", "profile"] + try: + validate_topic_memory_provider_settings(config.inference) + except BuiltinConfigurationError: + pass + else: + families.append("topic-memory") + return tuple(sorted(families)) + + +def canonical_processing_manifest(config: BuiltinConfig) -> dict[str, Any]: + """Identify ownership configuration without freezing execution-only budgets.""" + + runtime = config.runtime + # Target schedules do not prove that the stopped deployment had no active + # automatic Topic work. Preserve recovery responsibility conservatively. + automatic = [TOPIC_MEMORY_SOURCE_WINDOW_BINDING] + if runtime.schedule_seconds is not None: + automatic.append(SOURCE_WINDOW_TRIGGER_NAME) + if runtime.experience_schedule_seconds is not None: + automatic.append(EXPERIENCE_INCUBATION_CURSOR_NAME) + if runtime.profile_schedule_enabled: + automatic.append(PROFILE_SOURCE_WINDOW_BINDING) + return { + "mode": runtime.artifact_processing_supervisor_mode, + "capabilities": list(processing_capabilities(config)), + "bindings": { + SOURCE_WINDOW_TRIGGER_NAME: "memory", + TOPIC_MEMORY_SOURCE_WINDOW_BINDING: "topic-memory", + EXPERIENCE_INCUBATION_CURSOR_NAME: "experience", + PROFILE_SOURCE_WINDOW_BINDING: "profile", + }, + "legacy_automatic_bindings": sorted(automatic), + } diff --git a/src/powercontext/builtin/runtime/relational.py b/src/powercontext/builtin/runtime/relational.py index 9ae5ef84b2..6711a02fdd 100644 --- a/src/powercontext/builtin/runtime/relational.py +++ b/src/powercontext/builtin/runtime/relational.py @@ -18,9 +18,9 @@ import asyncio import secrets -from collections.abc import Callable, Mapping +from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass, replace -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast from uuid import uuid4 from jsonschema import Draft202012Validator @@ -130,6 +130,7 @@ from powercontext.builtin.persistence.memory import RelationalMemoryBackend from powercontext.builtin.persistence.memory_index import MemoryIndex, NoMemoryIndex from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.records import RelationalRecordService from powercontext.builtin.persistence.skill_packages import SkillPackageRepository from powercontext.builtin.persistence.skill_publications import SkillPublicationRepository @@ -216,6 +217,15 @@ IdFactory = Callable[[str], str] +if TYPE_CHECKING: + from powercontext.builtin.runtime.processing_execution import ScopeInvocation + + +MemorySnapshotAuthorizer = Callable[[Memory | None], Awaitable[None]] +MemoryCommitHook = Callable[[AsyncConnection, Memory | None, Memory | None], Awaitable[None]] +ExperienceCommitHook = Callable[[AsyncConnection, tuple[ArtifactCandidate[ExperienceContent], ...]], Awaitable[None]] + + def _artifact_identity(ref: ArtifactRef) -> tuple[str, str, int]: return ref.family, ref.artifact_id, ref.revision @@ -731,6 +741,10 @@ async def request_topic_memory_flush(self, scope_id: str, /) -> bool: scope, TOPIC_MEMORY_SOURCE_WINDOW_BINDING, ) + if pending is not None: + await ArtifactProcessingIntentRepository().request( + connection, scope, TOPIC_MEMORY_SOURCE_WINDOW_BINDING + ) return pending is not None async def browse_topic_memories( @@ -1127,7 +1141,31 @@ async def handoff_scope_ids(self) -> tuple[str, ...]: ).scalars() return tuple(str(value) for value in values) - async def incubate_experience(self, scope_id: str, limit: int, /) -> ExperienceIncubationResult: + async def process_memory( + self, + scope_id: str, + limit: int, + /, + *, + processing: ScopeInvocation | None = None, + authorize_snapshot: MemorySnapshotAuthorizer | None = None, + on_commit: MemoryCommitHook | None = None, + ) -> MemoryFlushResult: + services = self._services_for(scope_id) + return await _RelationalTriggers( + services=services, + lock=self._activation_locks.setdefault(services.scope_id, asyncio.Lock()), + ).flush(limit=limit, processing=processing, authorize_snapshot=authorize_snapshot, on_commit=on_commit) + + async def incubate_experience( + self, + scope_id: str, + limit: int, + /, + *, + processing: ScopeInvocation | None = None, + on_commit: ExperienceCommitHook | None = None, + ) -> ExperienceIncubationResult: """Process one independent Task Outcome Source window for Review.""" services = self._services_for(scope_id) @@ -1136,7 +1174,7 @@ async def incubate_experience(self, scope_id: str, limit: int, /) -> ExperienceI return await _RelationalExperienceIncubator( services=services, lock=self._experience_locks.setdefault(services.scope_id, asyncio.Lock()), - ).flush(limit=limit) + ).flush(limit=limit, processing=processing, on_commit=on_commit) async def get( self, @@ -1409,9 +1447,18 @@ async def cursor(self) -> SourceCursor: return self._trigger.initial_state() if state is None else state.cursor @prompt_operation("memory.extract") - async def flush(self, *, limit: int) -> MemoryFlushResult: + async def flush( + self, + *, + limit: int, + processing: ScopeInvocation | None = None, + authorize_snapshot: MemorySnapshotAuthorizer | None = None, + on_commit: MemoryCommitHook | None = None, + ) -> MemoryFlushResult: async with self._lock: async with self._services.database.transaction() as connection: + if processing is not None: + await processing.start(connection) state_row = await self._services.repositories.cursors.load( connection, self._services.scope_id, @@ -1425,6 +1472,8 @@ async def flush(self, *, limit: int) -> MemoryFlushResult: signal = SourceHighWatermark(sequence=high_watermark, limit=limit) transition = self._trigger.activate(signal, state) sources = () if not transition.actions else await self._sources(connection, transition.actions[0]) + if not transition.actions and processing is not None: + await processing.complete(connection, remaining_work=False) if not transition.actions: return MemoryFlushResult( previous_cursor=state.sequence, @@ -1437,6 +1486,8 @@ async def flush(self, *, limit: int) -> MemoryFlushResult: action = transition.actions[0] if not sources: async with self._services.database.transaction() as connection: + if processing is not None: + await processing.guard(connection) await self._services.repositories.cursors.save( connection, self._services.scope_id, @@ -1444,6 +1495,8 @@ async def flush(self, *, limit: int) -> MemoryFlushResult: transition.state, expected_generation=None if state_row is None else state_row.generation, ) + if processing is not None: + await processing.complete(connection, remaining_work=action.through < high_watermark) return MemoryFlushResult( previous_cursor=action.after, high_watermark=high_watermark, @@ -1451,8 +1504,10 @@ async def flush(self, *, limit: int) -> MemoryFlushResult: source_count=0, memory_ref=None, ) - prepared = await self._prepare_memory(sources) + prepared = await self._prepare_memory(sources, authorize_snapshot=authorize_snapshot) async with self._services.database.transaction() as connection: + if processing is not None: + await processing.guard(connection) _, source_catalog = self._services.sources(connection) updated = await self._services.memory(source_catalog, connection).apply(prepared) await self._services.repositories.cursors.save( @@ -1462,6 +1517,11 @@ async def flush(self, *, limit: int) -> MemoryFlushResult: transition.state, expected_generation=None if state_row is None else state_row.generation, ) + if on_commit is not None: + before = prepared.result if prepared.commit is None else prepared.commit.base + await on_commit(connection, before, updated) + if processing is not None: + await processing.complete(connection, remaining_work=action.through < high_watermark) return MemoryFlushResult( previous_cursor=action.after, high_watermark=high_watermark, @@ -1485,13 +1545,17 @@ async def _sources( row.value for row in rows if row.journal_position <= action.through and is_generation_eligible(row.value) ) - async def _prepare_memory(self, sources: tuple[Source, ...]) -> MemoryWritePlan: + async def _prepare_memory( + self, sources: tuple[Source, ...], *, authorize_snapshot: MemorySnapshotAuthorizer | None = None + ) -> MemoryWritePlan: _, source_catalog = self._services.sources() service = self._services.memory(source_catalog) try: current = await service.head(self._services.memory_artifact_id) except ArtifactNotFoundError: current = None + if authorize_snapshot is not None: + await authorize_snapshot(current) return await service.plan_remember(memory=current, sources=sources, mode="extract") @@ -1510,9 +1574,17 @@ def __init__( self._trigger = SourceWindowTrigger() @prompt_operation("experience.incubate") - async def flush(self, *, limit: int) -> ExperienceIncubationResult: + async def flush( # noqa: C901 + self, + *, + limit: int, + processing: ScopeInvocation | None = None, + on_commit: ExperienceCommitHook | None = None, + ) -> ExperienceIncubationResult: async with self._lock: async with self._services.database.transaction() as connection: + if processing is not None: + await processing.start(connection) state_row = await self._services.repositories.cursors.load( connection, self._services.scope_id, @@ -1528,6 +1600,8 @@ async def flush(self, *, limit: int) -> ExperienceIncubationResult: state, ) rows = () if not transition.actions else await self._sources(connection, transition.actions[0]) + if not transition.actions and processing is not None: + await processing.complete(connection, remaining_work=False) if not transition.actions: return ExperienceIncubationResult( previous_cursor=state.sequence, @@ -1544,6 +1618,8 @@ async def flush(self, *, limit: int) -> ExperienceIncubationResult: eligible_rows = tuple(row for row in rows if is_generation_eligible(row.value)) if not eligible_rows: async with self._services.database.transaction() as connection: + if processing is not None: + await processing.guard(connection) await self._services.repositories.cursors.save( connection, self._services.scope_id, @@ -1551,6 +1627,8 @@ async def flush(self, *, limit: int) -> ExperienceIncubationResult: transition.state, expected_generation=None if state_row is None else state_row.generation, ) + if processing is not None: + await processing.complete(connection, remaining_work=action.through < high_watermark) return ExperienceIncubationResult( previous_cursor=action.after, high_watermark=high_watermark, @@ -1563,7 +1641,10 @@ async def flush(self, *, limit: int) -> ExperienceIncubationResult: prompt_refs = () if selection is None or selection.artifact is None else (selection.artifact,) _validate_experience_plans(plans, eligible_rows) candidate_ids: list[str] = [] + candidates: list[ArtifactCandidate[ExperienceContent]] = [] async with self._services.database.transaction() as connection: + if processing is not None: + await processing.guard(connection) review = self._services.review(connection) for plan in plans: candidate = await review.propose_experience( @@ -1574,6 +1655,7 @@ async def flush(self, *, limit: int) -> ExperienceIncubationResult: reason=plan.reason, ) candidate_ids.append(candidate.candidate_id) + candidates.append(candidate) await self._services.repositories.cursors.save( connection, self._services.scope_id, @@ -1581,6 +1663,10 @@ async def flush(self, *, limit: int) -> ExperienceIncubationResult: transition.state, expected_generation=None if state_row is None else state_row.generation, ) + if on_commit is not None: + await on_commit(connection, tuple(candidates)) + if processing is not None: + await processing.complete(connection, remaining_work=action.through < high_watermark) return ExperienceIncubationResult( previous_cursor=action.after, high_watermark=high_watermark, diff --git a/src/powercontext/builtin/runtime/topic_memory_processing.py b/src/powercontext/builtin/runtime/topic_memory_processing.py index af81fcc2d3..cb844ae4dd 100644 --- a/src/powercontext/builtin/runtime/topic_memory_processing.py +++ b/src/powercontext/builtin/runtime/topic_memory_processing.py @@ -24,11 +24,13 @@ from contextvars import ContextVar from dataclasses import dataclass, field, replace from datetime import UTC, datetime +from enum import StrEnum from typing import Any, Generic, TypeVar, cast from uuid import uuid4 from pydantic import BaseModel, Field from sqlalchemy import update +from sqlalchemy.ext.asyncio import AsyncConnection from typing_extensions import override from powercontext._logging import log_safely @@ -91,7 +93,7 @@ from powercontext.builtin.persistence.database import AsyncDatabase from powercontext.builtin.persistence.errors import ArtifactProcessingLeadershipLostError, GenerationConflictError from powercontext.builtin.persistence.sources import SourceRepository, StoredSource -from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.supervision import ArtifactProcessingFence, ArtifactProcessingLeaseRepository from powercontext.builtin.persistence.tables import SOURCE_JOURNAL_HEADS_TABLE from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository from powercontext.builtin.persistence.topic_memory_budget import ( @@ -100,12 +102,12 @@ TopicMemoryWorkBudget, require_topic_memory_work_available, ) -from powercontext.builtin.runtime.artifact_processing import ( +from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig +from powercontext.builtin.runtime.processing_contracts import ( ArtifactProcessingWorkAssignment, ArtifactProcessingWorkerCompletion, ArtifactProcessingWorkerOutcome, ) -from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig from powercontext.builtin.source_eligibility import is_generation_eligible from powercontext.builtin.sources import ( CONTENT_SOURCE_NAME, @@ -152,6 +154,35 @@ async def generate(self, value: InputT, /) -> GenerationResult[OutputT]: UsageReporter = Callable[[ModelUsagePurpose, ModelUsageOperation, Any], Awaitable[None]] +class ArtifactProcessingWaveKind(StrEnum): + """Legacy Topic window metadata; generic supervision has no waves.""" + + EXPLICIT = "explicit" + AUTOMATIC = "automatic" + + +@dataclass(frozen=True, slots=True) +class TopicMemoryWindowAssignment: + """A private finite window used only by the Topic domain pipeline.""" + + binding_name: str + scope_id: str + source_after: int + source_through: int + wave_target: int + claimed_flush_generation: int + cursor_generation: int | None + wave_kind: ArtifactProcessingWaveKind + fence: ArtifactProcessingFence + worker_id: str + + +TopicMemoryCommitAuthorizer = Callable[ + [AsyncConnection, str, Sequence["PreparedTopicMemoryOperation"]], Awaitable[None] +] +TopicMemoryCommitHook = Callable[[AsyncConnection], Awaitable[None]] + + @dataclass(frozen=True, slots=True) class TopicMemoryStageSet: """Injected stage ports; arbitrary generator instances remain process-local.""" @@ -188,6 +219,7 @@ class TopicMemoryWorkerSpec(BaseModel): """Picklable child bootstrap configuration with a permanently redacted repr.""" config: BuiltinConfig = Field(repr=False) + worker_security: dict[str, Any] | None = Field(default=None, repr=False) @override def __repr__(self) -> str: @@ -272,21 +304,24 @@ def __init__( *, cursors: SourceCursorRepository | None = None, leases: ArtifactProcessingLeaseRepository | None = None, + commit_authorizer: TopicMemoryCommitAuthorizer | None = None, ) -> None: self._database = database self._sources = sources self._topics = topics self._cursors = SourceCursorRepository() if cursors is None else cursors self._leases = ArtifactProcessingLeaseRepository() if leases is None else leases + self._commit_authorizer = commit_authorizer async def publish( # noqa: C901 self, - assignment: ArtifactProcessingWorkAssignment, + assignment: TopicMemoryWindowAssignment, evidence: Mapping[str, StoredSource], operations: Sequence[PreparedTopicMemoryOperation], /, *, work_budget: TopicMemoryWorkBudget | None = None, + commit_hook: TopicMemoryCommitHook | None = None, ) -> None: if ( assignment.binding_name != TOPIC_MEMORY_SOURCE_WINDOW_BINDING @@ -357,6 +392,8 @@ async def publish( # noqa: C901 cited_sources = {(item.source_type, item.source_id) for item in operation.draft.sources} if not cited_sources or not cited_sources <= allowed_sources: raise TopicMemoryGenerationError("invalid_evidence") + if self._commit_authorizer is not None: + await self._commit_authorizer(connection, assignment.scope_id, operations) if work_budget is not None: await work_budget.complete(connection) await self._cursors.save( @@ -383,6 +420,8 @@ async def publish( # noqa: C901 operation.draft, operation.projection, ) + if commit_hook is not None: + await commit_hook(connection) await self._leases.require_fence(connection, assignment.fence) @@ -432,7 +471,13 @@ def __init__( self._history_min = history_min_candidates self._id_factory = (lambda: str(uuid4())) if id_factory is None else id_factory - async def process(self, assignment: ArtifactProcessingWorkAssignment, /) -> ArtifactProcessingWorkerCompletion: + async def process( + self, + assignment: TopicMemoryWindowAssignment, + /, + *, + commit_hook: TopicMemoryCommitHook | None = None, + ) -> ArtifactProcessingWorkerCompletion: if ( assignment.binding_name != TOPIC_MEMORY_SOURCE_WINDOW_BINDING or not 0 <= assignment.source_after < assignment.source_through <= assignment.wave_target @@ -456,7 +501,9 @@ async def process(self, assignment: ArtifactProcessingWorkAssignment, /) -> Arti projected = await _project_window(stored, self._sources) proposals, candidates = await self._generate(assignment.scope_id, projected) if projected else ((), {}) operations = await self._prepare_operations(assignment.scope_id, proposals, candidates, evidence) - await self._publisher.publish(assignment, evidence, operations, work_budget=budget) + await self._publisher.publish( + assignment, evidence, operations, work_budget=budget, commit_hook=commit_hook + ) except TopicMemoryGenerationError as error: if error.code == "source_complexity_limit": await budget.fail(error.code) @@ -506,7 +553,7 @@ async def _embed(self, texts: tuple[str, ...]): ) return await self._embedding_model.embed(texts) - async def _read_window(self, assignment: ArtifactProcessingWorkAssignment) -> tuple[StoredSource, ...]: + async def _read_window(self, assignment: TopicMemoryWindowAssignment) -> tuple[StoredSource, ...]: if assignment.source_through - assignment.source_after > MAX_TOPIC_MEMORY_WINDOW_SOURCES: raise TopicMemoryGenerationError("source_complexity_limit") count = assignment.source_through - assignment.source_after @@ -1593,14 +1640,28 @@ async def report(purpose: ModelUsagePurpose, operation: ModelUsageOperation, usa datetime.now(UTC).date(), ) + from powercontext.builtin.runtime.topic_memory_scope import TopicMemoryScopeProcessor + + security = None + if spec.worker_security is not None: + # Runtime-only SDK workers do not require the optional Server adapter. + from powercontext.server.processing_security import open_worker_security + + security = await resources.enter_async_context( + open_worker_security(spec.worker_security, contexts.database) + ) + if security is not None: + await security.authorize_scope(scope_id) + commit_authorizer = None if security is None else security.topic_commit publisher = TopicMemoryAtomicPublisher( contexts.database, contexts.repositories.sources, contexts.repositories.topic_memories, cursors=contexts.repositories.cursors, leases=contexts.repositories.processing_leases, + commit_authorizer=commit_authorizer, ) - yield TopicMemoryProcessor( + processor = TopicMemoryProcessor( database=contexts.database, sources=contexts.repositories.sources, topics=contexts.repositories.topic_memories, @@ -1612,6 +1673,20 @@ async def report(purpose: ModelUsagePurpose, operation: ModelUsageOperation, usa history_rrf_threshold=config.runtime.topic_memory_history_rrf_threshold, history_min_candidates=config.runtime.topic_memory_history_min_candidates, ) + yield TopicMemoryScopeProcessor( + contexts.database, + processor, + TopicMemoryWindowSelector( + contexts.database, + contexts.repositories.sources, + contexts.token_estimator, + context_window_tokens=inference.generation_model_context_window_tokens, + ), + cursors=contexts.repositories.cursors, + leases=contexts.repositories.processing_leases, + commit_authorizer=commit_authorizer, + source_window_limit=config.runtime.topic_memory_source_window_limit, + ) __all__ = [ @@ -1619,6 +1694,7 @@ async def report(purpose: ModelUsagePurpose, operation: ModelUsageOperation, usa "TopicMemoryAtomicPublisher", "TopicMemoryProcessor", "TopicMemoryStageSet", + "TopicMemoryWindowAssignment", "TopicMemoryWindowSelector", "TopicMemoryWorkerSpec", "run_topic_memory_worker", diff --git a/src/powercontext/builtin/runtime/topic_memory_scope.py b/src/powercontext/builtin/runtime/topic_memory_scope.py new file mode 100644 index 0000000000..652bc5e38a --- /dev/null +++ b/src/powercontext/builtin/runtime/topic_memory_scope.py @@ -0,0 +1,306 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Topic-owned finite input snapshots behind generic Scope invocations.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from sqlalchemy import delete, insert, select, update +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING +from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryGenerationError +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.errors import ArtifactProcessingLeadershipLostError, GenerationConflictError +from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import SOURCE_JOURNAL_HEADS_TABLE, TOPIC_MEMORY_PROCESSING_TARGETS_TABLE +from powercontext.builtin.runtime.processing_contracts import ( + ArtifactProcessingWorkAssignment, + ArtifactProcessingWorkerCompletion, + ArtifactProcessingWorkerOutcome, +) +from powercontext.builtin.runtime.topic_memory_processing import ( + MAX_TOPIC_MEMORY_WINDOW_SOURCES, + ArtifactProcessingWaveKind, + TopicMemoryCommitAuthorizer, + TopicMemoryProcessor, + TopicMemoryWindowAssignment, + TopicMemoryWindowSelector, +) + + +@dataclass(frozen=True, slots=True) +class TopicMemoryProcessingTarget: + """One immutable target retained through partial commits and crashes.""" + + target_request_generation: int + source_through: int + captured_flush_generation: int + observed_dirty_generation: int + + +class TopicMemoryScopeProcessor: + """Finish an existing target, then at most one newly claimed snapshot. + + Request generation limits acknowledgment, not input reads. A snapshot is + frozen in the Worker, so all sources committed before that transaction may + be included even when a newer invocation was accepted meanwhile. + """ + + def __init__( + self, + database: AsyncDatabase, + processor: TopicMemoryProcessor, + selector: TopicMemoryWindowSelector, + *, + cursors: SourceCursorRepository | None = None, + leases: ArtifactProcessingLeaseRepository | None = None, + intents: ArtifactProcessingIntentRepository | None = None, + pending: ArtifactProcessingPendingRepository | None = None, + commit_authorizer: TopicMemoryCommitAuthorizer | None = None, + source_window_limit: int = MAX_TOPIC_MEMORY_WINDOW_SOURCES, + ) -> None: + if type(source_window_limit) is not int or source_window_limit < 1: + raise TopicMemoryGenerationError("invalid_window") + self._database = database + self._processor = processor + self._selector = selector + self._cursors = SourceCursorRepository() if cursors is None else cursors + self._leases = ArtifactProcessingLeaseRepository() if leases is None else leases + self._intents = ArtifactProcessingIntentRepository() if intents is None else intents + self._pending = ArtifactProcessingPendingRepository() if pending is None else pending + self._commit_authorizer = commit_authorizer + self._source_window_limit = min(source_window_limit, MAX_TOPIC_MEMORY_WINDOW_SOURCES) + + async def process(self, assignment: ArtifactProcessingWorkAssignment, /) -> ArtifactProcessingWorkerCompletion: + if ( + assignment.binding_name != TOPIC_MEMORY_SOURCE_WINDOW_BINDING + or assignment.artifact_family != "topic-memory" + or assignment.claimed_request_generation < 1 + or assignment.fence.supervisor_group not in {"global", "artifact:topic-memory"} + ): + raise TopicMemoryGenerationError("invalid_invocation") + try: + # An old G0 target may survive while the dispatcher now claims G1. + # Retire G0 atomically before freezing G1; never extend an active H. + for _ in range(2): + target = await self._target(assignment) + if target is None: + return ArtifactProcessingWorkerCompletion() + result = await self._process_target(assignment, target) + if result.outcome is not ArtifactProcessingWorkerOutcome.SUCCEEDED: + return result + if target.target_request_generation == assignment.claimed_request_generation: + return result + except ArtifactProcessingLeadershipLostError: + return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.LEADERSHIP_LOST) + except GenerationConflictError: + return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT) + raise TopicMemoryGenerationError("target_did_not_converge") + + async def _target(self, assignment: ArtifactProcessingWorkAssignment) -> TopicMemoryProcessingTarget | None: + async with self._database.transaction() as connection: + await self._leases.require_fence(connection, assignment.fence) + # Lock the Source head before the intent, matching capture's order. + # SQLite's no-op UPDATE also establishes a real write transaction. + await self._lock_source_head(connection, assignment.scope_id) + intent = await self._intents.load(connection, assignment.scope_id, assignment.binding_name, for_update=True) + if intent is None or assignment.claimed_request_generation > intent.requested_generation: + raise TopicMemoryGenerationError("unaccepted_invocation") + # A replay must not create a fresh target or read new input. + if intent.handled_generation >= assignment.claimed_request_generation: + return None + table = TOPIC_MEMORY_PROCESSING_TARGETS_TABLE + row = ( + ( + await connection.execute( + select(table) + .where(table.c.scope_id == assignment.scope_id, table.c.binding_name == assignment.binding_name) + .with_for_update() + ) + ) + .mappings() + .one_or_none() + ) + if row is not None: + target = TopicMemoryProcessingTarget( + target_request_generation=int(row["target_request_generation"]), + source_through=int(row["source_through"]), + captured_flush_generation=int(row["captured_flush_generation"]), + observed_dirty_generation=int(row["observed_dirty_generation"]), + ) + if target.target_request_generation > assignment.claimed_request_generation: + raise GenerationConflictError( + assignment.binding_name, assignment.claimed_request_generation, target.target_request_generation + ) + return target + head = await self._head(connection, assignment.scope_id) + pending = await self._pending.load( + connection, assignment.scope_id, assignment.binding_name, for_update=True + ) + target = TopicMemoryProcessingTarget( + target_request_generation=assignment.claimed_request_generation, + source_through=head, + captured_flush_generation=0 if pending is None else pending.flush_generation, + observed_dirty_generation=intent.dirty_generation, + ) + await connection.execute( + insert(table).values( + scope_id=assignment.scope_id, + binding_name=assignment.binding_name, + target_request_generation=target.target_request_generation, + source_through=target.source_through, + captured_flush_generation=target.captured_flush_generation, + observed_dirty_generation=target.observed_dirty_generation, + ) + ) + return target + + async def _process_target( + self, assignment: ArtifactProcessingWorkAssignment, target: TopicMemoryProcessingTarget + ) -> ArtifactProcessingWorkerCompletion: + while True: + async with self._database.transaction() as connection: + await self._leases.require_fence(connection, assignment.fence) + cursor = await self._cursors.load(connection, assignment.scope_id, assignment.binding_name) + source_after = 0 if cursor is None else cursor.cursor.sequence + if source_after >= target.source_through: + await self._lock_source_head(connection, assignment.scope_id) + if self._commit_authorizer is not None: + await self._commit_authorizer(connection, assignment.scope_id, ()) + await self._finish_target(connection, assignment, target) + await self._leases.require_fence(connection, assignment.fence) + return ArtifactProcessingWorkerCompletion() + ceiling = min(target.source_through, source_after + self._source_window_limit) + through = await self._selector.select(assignment.scope_id, source_after, ceiling) + if not isinstance(through, int) or isinstance(through, bool) or not source_after < through <= ceiling: + raise TopicMemoryGenerationError("invalid_window") + window = TopicMemoryWindowAssignment( + binding_name=assignment.binding_name, + scope_id=assignment.scope_id, + source_after=source_after, + source_through=through, + wave_target=target.source_through, + claimed_flush_generation=target.captured_flush_generation, + cursor_generation=None if cursor is None else cursor.generation, + wave_kind=ArtifactProcessingWaveKind.EXPLICIT, + fence=assignment.fence, + worker_id=assignment.worker_id, + ) + + async def commit(connection: AsyncConnection, final: bool = through == target.source_through) -> None: + if final: + await self._finish_target(connection, assignment, target) + else: + await self._require_target(connection, assignment, target) + + completion = await self._processor.process(window, commit_hook=commit) + if completion.outcome is not ArtifactProcessingWorkerOutcome.SUCCEEDED or through == target.source_through: + return completion + + async def _finish_target( + self, + connection: AsyncConnection, + assignment: ArtifactProcessingWorkAssignment, + target: TopicMemoryProcessingTarget, + ) -> None: + await self._require_target(connection, assignment, target) + cursor = await self._cursors.load(connection, assignment.scope_id, assignment.binding_name, for_update=True) + position = 0 if cursor is None else cursor.cursor.sequence + if position < target.source_through: + raise TopicMemoryGenerationError("incomplete_target") + pending = await self._pending.mark_flush_handled( + connection, assignment.scope_id, assignment.binding_name, target.captured_flush_generation + ) + covered = pending is None or ( + pending.source_through <= target.source_through + and pending.flush_generation <= target.captured_flush_generation + ) + if target.source_through > 0: + await self._pending.delete_if_covered( + connection, + assignment.scope_id, + assignment.binding_name, + cursor=position, + source_through_limit=target.source_through, + ) + await self._intents.acknowledge( + connection, + assignment.scope_id, + assignment.binding_name, + target.target_request_generation, + clean_generation=target.observed_dirty_generation + if covered and await self._head(connection, assignment.scope_id) <= target.source_through + else None, + ) + result = await connection.execute( + delete(TOPIC_MEMORY_PROCESSING_TARGETS_TABLE).where(*self._target_key(assignment, target)) + ) + if result.rowcount != 1: + raise GenerationConflictError(assignment.binding_name, target.target_request_generation, None) + + async def _require_target( + self, + connection: AsyncConnection, + assignment: ArtifactProcessingWorkAssignment, + target: TopicMemoryProcessingTarget, + ) -> None: + current = await connection.scalar( + select(TOPIC_MEMORY_PROCESSING_TARGETS_TABLE.c.target_request_generation) + .where(*self._target_key(assignment, target)) + .with_for_update() + ) + if current is None: + raise GenerationConflictError(assignment.binding_name, target.target_request_generation, None) + + @staticmethod + def _target_key(assignment: ArtifactProcessingWorkAssignment, target: TopicMemoryProcessingTarget): + table = TOPIC_MEMORY_PROCESSING_TARGETS_TABLE + return ( + table.c.binding_name == assignment.binding_name, + table.c.scope_id == assignment.scope_id, + table.c.target_request_generation == target.target_request_generation, + table.c.source_through == target.source_through, + table.c.captured_flush_generation == target.captured_flush_generation, + table.c.observed_dirty_generation == target.observed_dirty_generation, + ) + + @staticmethod + async def _lock_source_head(connection: AsyncConnection, scope_id: str) -> None: + await connection.execute( + update(SOURCE_JOURNAL_HEADS_TABLE) + .where(SOURCE_JOURNAL_HEADS_TABLE.c.scope_id == scope_id) + .values(position=SOURCE_JOURNAL_HEADS_TABLE.c.position) + ) + + @staticmethod + async def _head(connection: AsyncConnection, scope_id: str) -> int: + # A locking read observes commits made before the lock under MySQL's + # repeatable-read isolation as well as SQLite's transaction semantics. + return int( + await connection.scalar( + select(SOURCE_JOURNAL_HEADS_TABLE.c.position) + .where(SOURCE_JOURNAL_HEADS_TABLE.c.scope_id == scope_id) + .with_for_update() + ) + or 0 + ) + + +__all__ = ["TopicMemoryProcessingTarget", "TopicMemoryScopeProcessor"] diff --git a/src/powercontext/server/cli.py b/src/powercontext/server/cli.py index 36a3f59ec5..4ec206f28e 100644 --- a/src/powercontext/server/cli.py +++ b/src/powercontext/server/cli.py @@ -18,20 +18,32 @@ import asyncio import signal -from contextlib import nullcontext +from contextlib import AsyncExitStack, nullcontext from pathlib import Path from typing import Annotated, Any, Literal import typer from pydantic import ValidationError +from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile +from powercontext.builtin.persistence.processing_migration import ( + apply_processing_migration, + plan_processing_migration, + verify_processing_migration, +) +from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.runtime.composition import open_builtin_runtime from powercontext.builtin.runtime.config import BuiltinConfig +from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest from powercontext.cli.env_file import environment_context from powercontext.cli.inference_notice import write_inference_capability_notice +from powercontext.server.authz import PrincipalRef +from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.configuration import ServerConfigurationError, server_settings_context from powercontext.server.factory import create_server_app from powercontext.server.logging import configure_server_logging +from powercontext.server.processing_security import build_worker_security from powercontext.server.settings import ( MissingAuthenticationProviderError, MissingBearerTokenError, @@ -72,6 +84,78 @@ def main() -> None: """Manage the PowerContext service process.""" +@app.command("processing-migrate") +def processing_migrate( + action: Annotated[Literal["plan", "apply", "verify"], typer.Option(help="Offline migration action.")] = "plan", + env_file: Annotated[Path | None, typer.Option(help="Load deployment settings from this environment file.")] = None, + maintenance_confirmed: Annotated[ + bool, + typer.Option(help="Confirm all old background candidates, Workers, writes and explicit triggers are stopped."), + ] = False, + migration_id: Annotated[ + str, typer.Option(help="Stable resume ID; use a new ID for an offline mode switch.") + ] = "rfc1515", + batch_size: Annotated[int, typer.Option(min=1, max=10000, help="Maximum rows committed per migration step.")] = 100, +) -> None: + """Plan, apply or verify the resumable artifact-processing schema migration.""" + + if action == "apply" and not maintenance_confirmed: + raise typer.BadParameter("apply requires --maintenance-confirmed after stopping old workers and writes") # noqa: TRY003 + with server_settings_context(env_file=env_file) as settings: + ready = asyncio.run(_processing_maintenance(settings, action, migration_id=migration_id, batch_size=batch_size)) + if not ready: + raise typer.Exit(code=1) + + +async def _processing_maintenance( + settings: ServerSettings, + action: Literal["plan", "apply", "verify"], + *, + migration_id: str, + batch_size: int, +) -> bool: + config = BuiltinConfig( + runtime=settings.runtime, + database=settings.database, + inference=settings.inference, + handoff_report=settings.handoff_report, + external_skills=settings.external_skills, + ) + manifest = canonical_processing_manifest(config) + database = settings.database + if isinstance(database, SQLiteConfig): + if database.is_in_memory: + raise typer.BadParameter("offline migration requires a persistent database") # noqa: TRY003 + opened = SQLiteProfile.open(database, tables=()) + elif isinstance(database, OceanBaseConfig): + opened = OceanBaseProfile.open(database, tables=()) + elif isinstance(database, SeekDBConfig): + opened = SeekDBProfile.open(database, tables=()) + else: + raise typer.BadParameter("unsupported migration database") # noqa: TRY003 + async with opened as profile: + if action == "plan": + async with profile.database.transaction() as connection: + plan = await plan_processing_migration(connection, config_manifest=manifest) + typer.echo(plan.model_dump_json()) + return True + if action == "apply": + while True: + async with profile.database.transaction() as connection: + progress = await apply_processing_migration( + connection, + config_manifest=manifest, + migration_id=migration_id, + batch_size=batch_size, + ) + if progress.complete: + break + async with profile.database.transaction() as connection: + verification = await verify_processing_migration(connection, config_manifest=manifest) + typer.echo(verification.model_dump_json()) + return verification.ready + + @app.command() def run( host: Annotated[str | None, typer.Option(help="Address to bind.")] = None, @@ -119,16 +203,7 @@ def _run_configured_server(settings: ServerSettings) -> None: embedding_model=settings.inference.embedding_model, ) if settings.runtime.artifact_processing_role == "background": - _run_background( - BuiltinConfig( - runtime=settings.runtime, - database=settings.database, - handoff_report=settings.handoff_report, - inference=settings.inference, - external_skills=settings.external_skills, - ), - tracing, - ) + _run_background(settings, tracing) return application = create_server_app(settings=settings, tracing=tracing) if settings.dashboard.enabled: @@ -173,13 +248,20 @@ def _run_server(application: Any, *, host: str, port: int) -> None: uvicorn.run(application, host=host, port=port, access_log=False, log_config=None) -def _run_background(config: BuiltinConfig, tracing: Any) -> None: +def _run_background(settings: ServerSettings, tracing: Any) -> None: """Run a Supervisor-only process until SIGINT or SIGTERM.""" - asyncio.run(_run_background_async(config, tracing)) + asyncio.run(_run_background_async(settings, tracing)) -async def _run_background_async(config: BuiltinConfig, tracing: Any) -> None: +async def _run_background_async(settings: ServerSettings, tracing: Any) -> None: + config = BuiltinConfig( + runtime=settings.runtime, + database=settings.database, + handoff_report=settings.handoff_report, + inference=settings.inference, + external_skills=settings.external_skills, + ) stopped = asyncio.Event() loop = asyncio.get_running_loop() installed: list[signal.Signals] = [] @@ -190,11 +272,30 @@ async def _run_background_async(config: BuiltinConfig, tracing: Any) -> None: continue installed.append(signum) try: - async with open_builtin_runtime( - config, - instrumentation=tracing.instrumentation, - tracing=tracing, - ): + async with AsyncExitStack() as resources: + principal = ( + PrincipalRef(type="service", id="server-token", description="PowerContext static bearer") + if settings.auth.token is not None + else None + ) + access = None + if settings.access.mode == "enforced": + access = await resources.enter_async_context( + open_builtin_access_control( + settings.database, + bootstrap_administrators=() if principal is None else (principal,), + deployment_id=settings.access.deployment_id, + ) + ) + worker_security = build_worker_security(settings, access, legacy_static_principal=principal) + await resources.enter_async_context( + open_builtin_runtime( + config, + instrumentation=tracing.instrumentation, + tracing=tracing, + worker_security=worker_security, + ) + ) await stopped.wait() finally: for signum in installed: diff --git a/src/powercontext/server/factory.py b/src/powercontext/server/factory.py index 78c74d1fa9..1268471ed9 100644 --- a/src/powercontext/server/factory.py +++ b/src/powercontext/server/factory.py @@ -43,6 +43,7 @@ from powercontext.builtin.runtime.application import ScheduledExperienceRunner, ScheduledSourceRunner from powercontext.builtin.runtime.composition import open_builtin_runtime from powercontext.builtin.runtime.config import BuiltinConfig +from powercontext.builtin.runtime.processing_registry import processing_capabilities from powercontext.builtin.sources import CONTENT_SOURCE_NAME from powercontext.http import ( Capabilities, @@ -74,6 +75,7 @@ from powercontext.server.mcp import mount_mcp from powercontext.server.metrics import CONTENT_TYPE_LATEST, HttpMetricsMiddleware, ServerMetrics from powercontext.server.middleware import AuthenticationMiddleware +from powercontext.server.processing_security import build_worker_security from powercontext.server.settings import MissingAuthenticationProviderError, ServerSettings from powercontext.server.tracing import HttpTracingMiddleware, ServerTracing from powercontext.server.web import mount_web_ui @@ -108,6 +110,9 @@ async def __call__(self, request: Request) -> Response: request_id=current_request_id(), ), ) + runtime = request.app.state.application + supervisor = None if runtime is None else runtime.artifact_processing_supervisor + self._metrics.set_processing_families({} if supervisor is None else supervisor.family_status) return Response(self._metrics.render(), media_type=CONTENT_TYPE_LATEST) @@ -179,6 +184,13 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: active_access_control, legacy_static_principal=static_principal if legacy_static_admin else None, ) + worker_security = build_worker_security( + resolved, + active_access_control, + legacy_static_principal=static_principal if legacy_static_admin else None, + enabled=config.runtime.artifact_processing_role != "api" and bool(processing_capabilities(config)), + injected=configured_access_control is not None, + ) runtime = await resources.enter_async_context( open_builtin_runtime( config, @@ -197,6 +209,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: tracing=resolved_tracing, scheduled_source_runner=scheduled_source_runner, scheduled_experience_runner=scheduled_experience_runner, + worker_security=worker_security, scheduled_profile_runner=_scheduled_profile_runner( resolved, active_access_control, diff --git a/src/powercontext/server/metrics.py b/src/powercontext/server/metrics.py index a870fd0977..d49e3a2d0e 100644 --- a/src/powercontext/server/metrics.py +++ b/src/powercontext/server/metrics.py @@ -17,6 +17,9 @@ from __future__ import annotations import asyncio +import math +import re +from collections.abc import Iterator, Mapping from contextlib import suppress from time import perf_counter from typing import Any @@ -33,11 +36,68 @@ ProcessCollector, generate_latest, ) +from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily, Metric from starlette.types import ASGIApp, Message, Receive, Scope, Send from typing_extensions import override +from powercontext.limits import MAX_ARTIFACT_FAMILY_LENGTH from powercontext.server.context import is_internal_bridge +_PROCESSING_INSTRUMENTS = ( + ("max_workers", "Configured Worker capacity for this Artifact Family.", False), + ("available_workers", "Available Worker slots for this Artifact Family.", False), + ("used_workers", "Worker slots currently in use for this Artifact Family.", False), + ("ready", "Scope invocations in this Artifact Family's bounded ready queue.", False), + ("retry_wait", "Scope invocations retained in this Artifact Family's bounded retry cache.", False), + ( + "unacknowledged_requests", + "Snapshot of Scopes with unacknowledged requests at the latest requested-work discovery pass.", + False, + ), + ("discovery_seconds", "Duration in seconds of this Artifact Family's most recent discovery pass.", False), + ("last_invocation_seconds", "Duration in seconds of this Artifact Family's most recent invocation.", False), + ("completed", "Acknowledged invocations accumulated by the current Supervisor instance; resets on restart.", True), + ("failed", "Failed invocations accumulated by the current Supervisor instance; resets on restart.", True), + ("timeouts", "Timed-out invocations accumulated by the current Supervisor instance; resets on restart.", True), +) + + +class _ProcessingMetricsCollector: + """Render registered Family snapshots without retaining stale label values.""" + + def __init__(self) -> None: + self._snapshot: dict[str, dict[str, float]] = {} + + def replace(self, families: Mapping[str, Mapping[str, int | float | str]]) -> None: + snapshot: dict[str, dict[str, float]] = {} + for family, values in families.items(): + if len(family) > MAX_ARTIFACT_FAMILY_LENGTH or re.fullmatch(r"[a-z][a-z0-9-]*", family) is None: + continue + measurements: dict[str, float] = {} + for field, _, _ in _PROCESSING_INSTRUMENTS: + value = values.get(field) + if isinstance(value, (int, float)) and not isinstance(value, bool): + with suppress(OverflowError): + number = float(value) + if math.isfinite(number) and number >= 0: + measurements[field] = number + snapshot[family] = measurements + # A scrape observes one complete snapshot even when another thread + # replaces the registered Family set during collection. + self._snapshot = snapshot + + def collect(self) -> Iterator[Metric]: + snapshot = self._snapshot + for field, description, counter in _PROCESSING_INSTRUMENTS: + instrument_type = CounterMetricFamily if counter else GaugeMetricFamily + instrument = instrument_type( + f"powercontext_server_artifact_processing_{field}", description, labels=["family"] + ) + for family, measurements in snapshot.items(): + if field in measurements: + instrument.add_metric([family], measurements[field]) + yield instrument + class ServerMetrics: """Own one Server instance's Prometheus registry and instruments.""" @@ -94,6 +154,8 @@ def __init__(self) -> None: ("state",), registry=self.registry, ) + self._processing = _ProcessingMetricsCollector() + self.registry.register(self._processing) self.set_runtime_scopes(0, 0) def start_transport(self, transport: str, operation: str) -> float: @@ -138,6 +200,12 @@ def set_runtime_scopes(self, cached: int, active: int) -> None: with suppress(Exception): self.runtime_scopes.labels(state=state).set(value) + def set_processing_families(self, families: Mapping[str, Mapping[str, int | float | str]]) -> None: + """Refresh bounded scheduler observations using only registered Family labels.""" + + with suppress(Exception): + self._processing.replace(families) + def render(self) -> bytes: return generate_latest(self.registry) diff --git a/src/powercontext/server/processing_security.py b/src/powercontext/server/processing_security.py new file mode 100644 index 0000000000..219821f32b --- /dev/null +++ b/src/powercontext/server/processing_security.py @@ -0,0 +1,235 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Reconstruct Server authorization inside a processing child. + +Runtime-only SDK users do not import or require this adapter. The serialized +identity is resolved from trusted deployment settings, never from model output. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator, Sequence +from contextlib import asynccontextmanager +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.artifacts.memory import Memory +from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.runtime.composition import BuiltinConfigurationError +from powercontext.server.authz import ( + AccessAction, + AccessAuditContext, + AccessControlService, + MemoryEntrySelector, + PrincipalRef, + ResourceRef, +) +from powercontext.server.authz.repository import RelationalAccessRepository +from powercontext.server.authz.service import BuiltinAuthorizationProvider +from powercontext.server.settings import ServerSettings + + +class WorkerSecuritySpec(BaseModel): + model_config = ConfigDict(extra="forbid") + + provider: Literal["builtin"] = "builtin" + principal: PrincipalRef = Field(repr=False) + deployment_id: str + static_preset: bool = False + + +def build_worker_security( + settings: ServerSettings, + access: AccessControlService | None, + *, + legacy_static_principal: PrincipalRef | None = None, + enabled: bool = True, + injected: bool = False, +) -> dict[str, Any] | None: + """Fail before dispatch when an enforced provider cannot be reconstructed.""" + + if not enabled or settings.access.mode == "disabled": + return None + if injected or ( + access is not None + and ( + type(access.provider) is not BuiltinAuthorizationProvider + or type(access.relationships) is not RelationalAccessRepository + or access.audit is not access.relationships + ) + ): + raise BuiltinConfigurationError("artifact-processing-worker-authorization-provider") + if settings.access.background_principal_id is not None: + principal = PrincipalRef( + type="service", + id=settings.access.background_principal_id, + description=settings.access.background_principal_description, + ) + elif legacy_static_principal is not None: + principal = legacy_static_principal + else: + raise ValueError("scheduled processing in enforced mode requires ACCESS_BACKGROUND_PRINCIPAL_ID") # noqa: TRY003 + return WorkerSecuritySpec( + principal=principal, + deployment_id=settings.access.deployment_id, + static_preset=principal == legacy_static_principal, + ).model_dump(mode="json") + + +class WorkerSecurity: + def __init__(self, access: AccessControlService, principal: PrincipalRef) -> None: + self.access = access + self.principal = principal + self.context = AccessAuditContext(transport="background", operation="artifact_processing") + + async def authorize_scope(self, scope_id: str) -> None: + await self._authorize_scope(self.access, scope_id) + + async def _authorize_scope(self, access: AccessControlService, scope_id: str) -> None: + await access.bootstrap_static_scope(self.principal, scope_id, context=self.context) + await access.require( + self.principal, AccessAction.SCOPE_CONTRIBUTE, ResourceRef.scope(scope_id), context=self.context + ) + + async def authorize_transaction(self, connection: AsyncConnection, scope_id: str) -> None: + await self._authorize_scope(self.access.with_connection(connection), scope_id) + + async def authorize_memory(self, scope_id: str, current: Memory | None) -> None: + await self._authorize_memory(self.access, scope_id, current) + + async def _authorize_memory(self, access: AccessControlService, scope_id: str, current: Memory | None) -> None: + if current is None: + return + await access.require_all( + self.principal, + tuple( + (AccessAction.ARTIFACT_WRITE, self._memory_resource(scope_id, current, entry.entry_id)) + for entry in current.content.manifest.entries + ), + context=self.context, + ) + + @staticmethod + def _memory_resource(scope_id: str, memory: Memory, entry_id: str) -> ResourceRef: + return ResourceRef.artifact( + scope_id, family="memory", artifact_id=memory.artifact_id, selector=MemoryEntrySelector(entry_id=entry_id) + ) + + async def memory_commit( + self, connection: AsyncConnection, before: Memory | None, after: Memory | None, *, scope_id: str + ) -> None: + bound = self.access.with_connection(connection) + await self._authorize_memory(bound, scope_id, before) + if after is None: + return + old = set() if before is None else {entry.entry_id for entry in before.content.manifest.entries} + for entry in after.content.manifest.entries: + if entry.entry_id not in old: + await bound.establish_artifact_owner( + self._memory_resource(scope_id, after, entry.entry_id), + self.principal, + idempotency_key=f"background-memory-owner:{scope_id}:{after.artifact_id}:{entry.entry_id}", + context=self.context, + ) + + async def experience_commit(self, connection: AsyncConnection, candidates: Sequence[Any], *, scope_id: str) -> None: + bound = self.access.with_connection(connection) + for candidate in candidates: + await bound.attest_candidate_owner( + scope_id=scope_id, + candidate_id=candidate.candidate_id, + family="experience", + proposed_owner=self.principal, + target=None, + idempotency_key=f"background-candidate-owner:{scope_id}:{candidate.candidate_id}", + ) + + async def authorize_profile(self, scope_id: str, current: Any) -> None: + if current is not None: + await self.access.require( + self.principal, + AccessAction.ARTIFACT_WRITE, + ResourceRef.artifact(scope_id, family="profile", artifact_id="profile"), + context=self.context, + ) + + async def authorize_profile_commit(self, connection: AsyncConnection, current: Any, *, scope_id: str) -> None: + if current is not None: + await self.access.with_connection(connection).require( + self.principal, + AccessAction.ARTIFACT_WRITE, + ResourceRef.artifact(scope_id, family="profile", artifact_id="profile"), + context=self.context, + ) + + async def profile_commit( + self, connection: AsyncConnection, artifact: Any, candidate: Any, *, scope_id: str + ) -> None: + bound = self.access.with_connection(connection) + resource = ResourceRef.artifact(scope_id, family="profile", artifact_id="profile") + if artifact is not None: + if await bound.artifact_owner(resource) is None: + await bound.establish_artifact_owner( + resource, self.principal, idempotency_key=f"profile-owner:{scope_id}", context=self.context + ) + else: + await bound.require(self.principal, AccessAction.ARTIFACT_WRITE, resource, context=self.context) + if candidate is not None: + if candidate.target is not None: + await bound.require(self.principal, AccessAction.ARTIFACT_WRITE, resource, context=self.context) + await bound.attest_candidate_owner( + scope_id=scope_id, + candidate_id=candidate.candidate_id, + family="profile", + proposed_owner=self.principal, + target=None if candidate.target is None else resource, + idempotency_key=f"candidate-owner:{scope_id}:{candidate.candidate_id}", + ) + + async def topic_commit(self, connection: AsyncConnection, scope_id: str, operations: Sequence[Any]) -> None: + bound = self.access.with_connection(connection) + await self._authorize_scope(bound, scope_id) + for operation in operations: + resource = ResourceRef.artifact(scope_id, family="topic-memory", artifact_id=operation.artifact_id) + if operation.current is not None: + await bound.require(self.principal, AccessAction.ARTIFACT_WRITE, resource, context=self.context) + else: + await bound.establish_artifact_owner( + resource, + self.principal, + idempotency_key=f"background-topic-owner:{scope_id}:{operation.artifact_id}", + context=self.context, + ) + + +@asynccontextmanager +async def open_worker_security( + security: dict[str, Any] | None, database: AsyncDatabase +) -> AsyncIterator[WorkerSecurity | None]: + if security is None: + yield None + return + spec = WorkerSecuritySpec.model_validate(security) + repository = RelationalAccessRepository(database) + access = AccessControlService( + BuiltinAuthorizationProvider(repository, deployment_id=spec.deployment_id), + relationships=repository, + audit=repository, + deployment_id=spec.deployment_id, + static_scope_principal=spec.principal if spec.static_preset else None, + ) + yield WorkerSecurity(access, spec.principal) diff --git a/tests/builtin/artifacts/profile/test_scheduler.py b/tests/builtin/artifacts/profile/test_scheduler.py index 67dac02c4b..72b4cc241c 100644 --- a/tests/builtin/artifacts/profile/test_scheduler.py +++ b/tests/builtin/artifacts/profile/test_scheduler.py @@ -15,15 +15,23 @@ import asyncio from datetime import datetime +from functools import partial from zoneinfo import ZoneInfo import pytest from apscheduler.triggers.cron import CronTrigger from pydantic import ValidationError +from powercontext.builtin.artifacts.profile.models import PROFILE_SOURCE_WINDOW_BINDING from powercontext.builtin.artifacts.profile.service import ProfileGenerationInput from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import BuiltinConfig, RuntimeConfig, open_builtin_runtime +from powercontext.builtin.runtime.artifact_processing import ( + ArtifactProcessingBinding, + SpawnArtifactProcessingWorkerLauncher, +) +from powercontext.builtin.runtime.composition import open_builtin_contexts +from powercontext.builtin.runtime.family_processing import process_family_invocation from powercontext.builtin.scope import ScopeDraft @@ -39,35 +47,64 @@ def test_profile_cron_defaults_and_validation(): RuntimeConfig(profile_timezone="Not/A_Zone") -def test_startup_scan_catches_up_profile_evidence(tmp_path): - class Generator: - def __init__(self): - self.called = asyncio.Event() +class _ProfileGenerator: + async def generate(self, value: ProfileGenerationInput): + return "# Caught up" + + +def _profile_worker(config, assignment): + async def run(): + async with open_builtin_contexts(config) as contexts: + contexts.profiles.generator = _ProfileGenerator() + return await process_family_invocation(contexts, assignment, config=config) - async def generate(self, value: ProfileGenerationInput): - self.called.set() - return "# Caught up" + return asyncio.run(run()) + +def test_startup_scan_catches_up_profile_evidence(tmp_path): async def run(): - config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}")) - async with open_builtin_runtime(config, scheduler_path=tmp_path / "jobs.db") as runtime: + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}"), + runtime=RuntimeConfig(artifact_processing_families=("profile",)), + ) + # Register a reconstructible test child, with the production invocation + # and completion protocol. Scope data outlives the initial Runtime. + binding = ArtifactProcessingBinding( + PROFILE_SOURCE_WINDOW_BINDING, + "profile", + SpawnArtifactProcessingWorkerLauncher(partial(_profile_worker, config)), + ) + async with open_builtin_runtime(config, artifact_processing_bindings=(binding,)) as runtime: assert runtime.scopes is not None and runtime.profiles is not None sid = ( await runtime.scopes.create(ScopeDraft(title="User", summary="User", idempotency_key="User")) ).scope_id await runtime.profiles.put_policy(sid, generation_enabled=True, expected_version=0) await runtime.records.for_scope(sid).create_source("content", "Chinese") - generator = Generator() - async with open_builtin_runtime( - config.model_copy(update={"runtime": RuntimeConfig(profile_schedule_enabled=True)}), - profile_generator=generator, - scheduler_path=tmp_path / "jobs.db", - ) as runtime: - await asyncio.wait_for(generator.called.wait(), timeout=5) - # Runtime.close drains in-flight Profile work before disposing persistence. - async with open_builtin_runtime(config, scheduler_path=tmp_path / "jobs.db") as runtime: + scheduled = ArtifactProcessingBinding( + PROFILE_SOURCE_WINDOW_BINDING, + "profile", + binding.launcher, + cron="0 2 * * *", + timezone="Asia/Shanghai", + ) + async with open_builtin_runtime(config, artifact_processing_bindings=(scheduled,)) as runtime: + from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository + from powercontext.builtin.runtime.relational import RelationalContexts + + assert isinstance(runtime._provider, RelationalContexts) + async with asyncio.timeout(30): + while True: + async with runtime._provider.database.transaction() as connection: + intent = await ArtifactProcessingIntentRepository().load( + connection, sid, PROFILE_SOURCE_WINDOW_BINDING + ) + if intent is not None and intent.handled_generation >= 1: + break + await asyncio.sleep(0.02) saved = await runtime.records.for_scope(sid).get_artifact("profile", "profile") assert saved.revision == 1 + assert not (tmp_path / "jobs.db").exists() asyncio.run(run()) diff --git a/tests/builtin/persistence/test_processing_intents.py b/tests/builtin/persistence/test_processing_intents.py new file mode 100644 index 0000000000..a74c62ad63 --- /dev/null +++ b/tests/builtin/persistence/test_processing_intents.py @@ -0,0 +1,197 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +from datetime import UTC, datetime + +import pytest +from sqlalchemy import insert, select +from sqlalchemy.exc import IntegrityError + +from powercontext.builtin.persistence.errors import ( + ArtifactProcessingLeadershipLostError, + InvalidRepositoryArgumentError, +) +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.sources import SOURCE_PROCESSING_BINDINGS, SourceRepository +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.supervision import ( + ArtifactProcessingBindingStateRepository, + ArtifactProcessingLeaseRepository, +) +from powercontext.builtin.persistence.tables import SHARED_TABLES, SOURCE_JOURNAL_HEADS_TABLE +from powercontext.sources import SourceMaterialization +from tests.builtin.persistence.contract import SOURCE_ADAPTERS, NoteSource + +BINDING = "topic-memory-source-window" + + +def test_late_requests_and_dirty_survive_partial_and_duplicate_acknowledgement() -> None: + async def scenario() -> None: + intents = ArtifactProcessingIntentRepository() + async with ( + SQLiteProfile.open(SQLiteConfig(), tables=SHARED_TABLES) as profile, + profile.database.transaction() as connection, + ): + await intents.mark_dirty(connection, "a", BINDING) + first = await intents.request(connection, "a", BINDING) + await intents.mark_dirty(connection, "a", BINDING) + second = await intents.request(connection, "a", BINDING) + acknowledged = await intents.acknowledge( + connection, "a", BINDING, first.requested_generation, clean_generation=1 + ) + assert (acknowledged.requested_generation, acknowledged.handled_generation) == (2, 1) + assert (acknowledged.dirty_generation, acknowledged.clean_generation) == (2, 1) + duplicate = await intents.acknowledge( + connection, "a", BINDING, first.requested_generation, clean_generation=2 + ) + assert duplicate == acknowledged + partial = await intents.acknowledge(connection, "a", BINDING, second.requested_generation) + assert partial.handled_generation == 2 and partial.clean_generation == 1 + with pytest.raises(InvalidRepositoryArgumentError): + await intents.acknowledge(connection, "a", BINDING, 3) + assert partial.pending_sequence == first.pending_sequence + + asyncio.run(scenario()) + + +def test_resumed_scan_deduplicates_completed_front_pages_and_freezes_upper_bound() -> None: + async def scenario() -> None: + intents, states = ArtifactProcessingIntentRepository(), ArtifactProcessingBindingStateRepository() + async with SQLiteProfile.open(SQLiteConfig(), tables=SHARED_TABLES) as profile: + async with profile.database.transaction() as connection: + first = await intents.mark_dirty(connection, "z-first", BINDING) + second = await intents.mark_dirty(connection, "a-second", BINDING) + scan = await states.start_scan(connection, BINDING, datetime(2026, 1, 1, tzinfo=UTC)) + assert scan.scan_upper_pending_sequence == second.pending_sequence + accepted = await intents.admit(connection, "z-first", BINDING, scan.scan_generation) + await intents.acknowledge(connection, "z-first", BINDING, accepted.requested_generation) + # Simulates process restart after front-page work already completed. + async with profile.database.transaction() as connection: + late = await intents.mark_dirty(connection, "late", BINDING) + resumed = await states.start_scan(connection, BINDING, datetime(2026, 2, 1, tzinfo=UTC)) + assert resumed == scan + page = await intents.scan( + connection, BINDING, limit=1, dirty_only=True, upper_sequence=scan.scan_upper_pending_sequence + ) + assert page[0].pending_sequence == first.pending_sequence + repeated = await intents.admit(connection, "z-first", BINDING, scan.scan_generation) + assert repeated.requested_generation == repeated.handled_generation == 1 + with pytest.raises(InvalidRepositoryArgumentError): + await intents.admit(connection, "late", BINDING, scan.scan_generation) + await states.finish_scan(connection, BINDING) + next_scan = await states.start_scan(connection, BINDING, datetime(2026, 2, 1, tzinfo=UTC)) + assert next_scan.scan_generation == scan.scan_generation + 1 + assert next_scan.scan_upper_pending_sequence == late.pending_sequence + + asyncio.run(scenario()) + + +def test_concurrent_first_requests_keep_one_sequence_and_both_requests(tmp_path) -> None: + async def scenario() -> None: + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'intents.db'}", busy_timeout_ms=10_000) + intents = ArtifactProcessingIntentRepository() + async with ( + SQLiteProfile.open(config, tables=SHARED_TABLES) as first, + SQLiteProfile.open(config, tables=SHARED_TABLES) as second, + ): + barrier = asyncio.Barrier(2) + + async def request(profile): + async with profile.database.transaction() as connection: + await barrier.wait() + return await intents.request(connection, "same", BINDING) + + results = await asyncio.gather(request(first), request(second)) + assert results[0].pending_sequence == results[1].pending_sequence + async with first.database.transaction() as connection: + stored = await intents.load(connection, "same", BINDING) + assert stored is not None and stored.requested_generation == 2 + + asyncio.run(scenario()) + + +def test_source_publication_dirties_every_family_once_and_rolls_back_with_intent_failure() -> None: + async def scenario() -> None: + source = NoteSource(name="note", materialization=SourceMaterialization.CAPTURED, body="body") + sources, intents = SourceRepository(SOURCE_ADAPTERS), ArtifactProcessingIntentRepository() + async with SQLiteProfile.open(SQLiteConfig(), tables=SHARED_TABLES) as profile: + async with profile.database.transaction() as connection: + await sources.add(connection, "a", source) + await sources.add(connection, "a", source) + for binding in SOURCE_PROCESSING_BINDINGS: + stored = await intents.load(connection, "a", binding) + assert stored is not None and stored.dirty_generation == 1 and stored.requested_generation == 0 + await connection.exec_driver_sql(""" + CREATE TRIGGER reject_intent BEFORE INSERT ON pc_artifact_processing_intents + WHEN NEW.scope_id = 'b' BEGIN SELECT RAISE(ABORT, 'reject intent'); END + """) + with pytest.raises(IntegrityError, match="reject intent"): + async with profile.database.transaction() as connection: + await sources.add(connection, "b", source) + async with profile.database.transaction() as connection: + assert await sources.list(connection, "b") == () + assert await intents.load(connection, "b", BINDING) is None + + asyncio.run(scenario()) + + +def test_sqlite_fence_lock_serializes_worker_commit_and_term_replacement(tmp_path) -> None: + async def scenario() -> None: + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'fence.db'}", busy_timeout_ms=10_000) + leases = ArtifactProcessingLeaseRepository() + locked, release, replacing = asyncio.Event(), asyncio.Event(), asyncio.Event() + async with SQLiteProfile.open(config, tables=SHARED_TABLES) as worker_profile: + async with worker_profile.database.transaction() as connection: + lease = await leases.start_single_process_term(connection, "same-holder") + async with SQLiteProfile.open(config, tables=SHARED_TABLES) as leader_profile: + + async def worker(): + async with worker_profile.database.transaction() as connection: + await leases.require_fence(connection, lease.fence("single-process")) + locked.set() + await release.wait() + await connection.execute( + insert(SOURCE_JOURNAL_HEADS_TABLE).values(scope_id="commit", position=0) + ) + + async def replace(): + await locked.wait() + replacing.set() + async with leader_profile.database.transaction() as connection: + return await leases.start_single_process_term(connection, "same-holder") + + worker_task, replace_task = asyncio.create_task(worker()), asyncio.create_task(replace()) + await replacing.wait() + # The replacement must wait while the real Worker transaction + # owns its fence. This is production code, not a locking mock. + await asyncio.sleep(0.03) + assert not replace_task.done() + release.set() + await worker_task + new_term = await replace_task + assert new_term.supervisor_generation == lease.supervisor_generation + 1 + with pytest.raises(ArtifactProcessingLeadershipLostError): + async with worker_profile.database.transaction() as connection: + await leases.require_fence(connection, lease.fence("single-process")) + await connection.execute( + insert(SOURCE_JOURNAL_HEADS_TABLE).values(scope_id="stale", position=0) + ) + async with worker_profile.database.transaction() as connection: + scopes = tuple(await connection.scalars(select(SOURCE_JOURNAL_HEADS_TABLE.c.scope_id))) + assert scopes == ("commit",) + + asyncio.run(scenario()) diff --git a/tests/builtin/persistence/test_processing_migration.py b/tests/builtin/persistence/test_processing_migration.py new file mode 100644 index 0000000000..24d6b59d0d --- /dev/null +++ b/tests/builtin/persistence/test_processing_migration.py @@ -0,0 +1,249 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +from datetime import UTC, datetime + +import pytest +from sqlalchemy import func, insert, select +from sqlalchemy.exc import IntegrityError + +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.errors import ArtifactProcessingLeadershipLostError +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.processing_migration import ( + ProcessingSchemaNotReadyError, + apply_processing_migration, + assert_processing_schema_ready, + bootstrap_processing_schema, + plan_processing_migration, + verify_processing_migration, +) +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.supervision import ( + ArtifactProcessingBindingStateRepository, + ArtifactProcessingLeaseRepository, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_AUTO_WAVE_TARGETS_TABLE as WAVES, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_BINDING_STATES_TABLE as STATES, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_INTENTS_TABLE as INTENTS, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_MIGRATION_RECEIPTS_TABLE as RECEIPTS, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_PENDING_TABLE as PENDING, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_SCHEMA_TABLE as SCHEMA, +) +from powercontext.builtin.persistence.tables import ( + SHARED_TABLES, +) +from powercontext.builtin.persistence.tables import ( + SOURCE_JOURNAL_HEADS_TABLE as HEADS, +) +from powercontext.builtin.persistence.tables import ( + TOPIC_MEMORY_PROCESSING_TARGETS_TABLE as TARGETS, +) +from powercontext.builtin.sources import SourceCursor + +BINDING = "topic-memory-source-window" +MANIFEST = {"mode": "global", "bindings": {BINDING: "topic-memory"}, "legacy_automatic_bindings": [BINDING]} +CHECKPOINT = datetime(2026, 1, 1, 12, 0, tzinfo=UTC).replace(tzinfo=None) + + +async def _legacy(profile): + async with profile.database.transaction() as connection: + await connection.exec_driver_sql("DROP TABLE pc_artifact_processing_binding_states") + await connection.exec_driver_sql( + "CREATE TABLE pc_artifact_processing_binding_states (binding_name VARCHAR(128) PRIMARY KEY NOT NULL, last_auto_wave_completed_at DATETIME)" + ) + await connection.exec_driver_sql( + "INSERT INTO pc_artifact_processing_binding_states VALUES (?, ?)", (BINDING, CHECKPOINT.isoformat(" ")) + ) + lease = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "old-holder") + for scope in ("flush", "untracked", "frozen", "completed", "missing-pending"): + await connection.execute(insert(HEADS).values(scope_id=scope, position=5)) + await SourceCursorRepository().save( + connection, scope, BINDING, SourceCursor(sequence=1), expected_generation=None + ) + if scope != "missing-pending": + await connection.execute( + insert(PENDING).values( + binding_name=BINDING, scope_id=scope, source_through=5, flush_generation=int(scope == "flush") + ) + ) + for scope in ("frozen", "completed"): + await connection.execute( + insert(WAVES).values( + wave_id="00000000-0000-4000-8000-000000000001", + binding_name=BINDING, + scope_id=scope, + source_through=1 if scope == "completed" else 3, + completed=scope == "completed", + ) + ) + return lease + + +async def _finish(profile, manifest=MANIFEST, migration_id="rfc1515"): + for _ in range(50): + async with profile.database.transaction() as connection: + result = await apply_processing_migration( + connection, config_manifest=manifest, migration_id=migration_id, batch_size=1 + ) + if result.complete: + return + pytest.fail("migration did not finish within its bounded fixture") + + +def test_legacy_migration_preserves_targets_untracked_calls_cursor_and_remaining_interval(tmp_path) -> None: + async def scenario() -> None: + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'migration.db'}") + async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: + old = await _legacy(profile) + async with profile.database.transaction() as connection: + plan = await plan_processing_migration(connection, config_manifest=MANIFEST) + assert plan.required and len(plan.missing_state_columns) == 4 + with pytest.raises(ProcessingSchemaNotReadyError): + await bootstrap_processing_schema(connection, MANIFEST) + await _finish(profile) + async with profile.database.transaction() as connection: + await assert_processing_schema_ready(connection, MANIFEST) + assert (await verify_processing_migration(connection, config_manifest=MANIFEST)).ready + intents = { + row.scope_id: row for row in await ArtifactProcessingIntentRepository().scan(connection, BINDING) + } + assert intents["flush"].requested_generation == 1 + assert intents["untracked"].requested_generation == 1 + assert intents["frozen"].requested_generation == 1 + assert intents["completed"].requested_generation == 0 + assert intents["missing-pending"].requested_generation == 0 + targets = {row["scope_id"]: row for row in (await connection.execute(select(TARGETS))).mappings()} + assert targets["frozen"]["source_through"] == 3 + assert targets["untracked"]["source_through"] == 5 + assert targets["flush"]["captured_flush_generation"] == 1 + state = await ArtifactProcessingBindingStateRepository().load(connection, BINDING) + assert state is not None and state.last_schedule_checkpoint_at == CHECKPOINT + assert await connection.scalar(select(func.count()).select_from(WAVES)) == 0 + cursor = await SourceCursorRepository().load(connection, "frozen", BINDING) + assert cursor is not None and cursor.cursor.sequence == cursor.generation == 1 + with pytest.raises(ArtifactProcessingLeadershipLostError): + await ArtifactProcessingLeaseRepository().require_fence(connection, old.fence("single-process")) + # Reopen the database and apply again: no requested++ and no sequence reuse. + async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: + await _finish(profile) + async with profile.database.transaction() as connection: + after = { + row.scope_id: row for row in await ArtifactProcessingIntentRepository().scan(connection, BINDING) + } + assert after == intents + + asyncio.run(scenario()) + + +def test_receipt_failure_rolls_back_request_and_target_before_resuming(tmp_path) -> None: + async def scenario() -> None: + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'receipt.db'}") + async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: + await _legacy(profile) + while True: + async with profile.database.transaction() as connection: + step = await apply_processing_migration(connection, config_manifest=MANIFEST) + if step.phase == "backfill": + break + async with profile.database.transaction() as connection: + await connection.exec_driver_sql( + "CREATE TRIGGER reject_receipt BEFORE INSERT ON pc_artifact_processing_migration_receipts BEGIN SELECT RAISE(ABORT, 'receipt failed'); END" + ) + with pytest.raises(IntegrityError, match="receipt failed"): + async with profile.database.transaction() as connection: + await apply_processing_migration(connection, config_manifest=MANIFEST, batch_size=10) + async with profile.database.transaction() as connection: + assert await connection.scalar(select(func.count()).select_from(INTENTS)) == 0 + assert await connection.scalar(select(func.count()).select_from(TARGETS)) == 0 + assert await connection.scalar(select(func.count()).select_from(RECEIPTS)) == 0 + assert await connection.scalar(select(func.count()).select_from(WAVES)) == 2 + with pytest.raises(ProcessingSchemaNotReadyError): + await assert_processing_schema_ready(connection, MANIFEST) + await connection.exec_driver_sql("DROP TRIGGER reject_receipt") + # Commit one page, then resume from the receipt anti-join. + async with profile.database.transaction() as connection: + await apply_processing_migration(connection, config_manifest=MANIFEST, batch_size=1) + await _finish(profile) + async with profile.database.transaction() as connection: + intent = await ArtifactProcessingIntentRepository().load(connection, "flush", BINDING) + assert intent is not None and intent.requested_generation == 1 + assert await connection.scalar(select(func.count()).select_from(RECEIPTS)) == 5 + + asyncio.run(scenario()) + + +def test_mode_switch_invalidates_old_permanent_lease_without_reimporting_work() -> None: + async def scenario() -> None: + async with SQLiteProfile.open(SQLiteConfig(), tables=SHARED_TABLES) as profile: + async with profile.database.transaction() as connection: + await bootstrap_processing_schema(connection, MANIFEST) + lease = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "same-holder") + before = await ArtifactProcessingIntentRepository().request(connection, "a", BINDING) + dedicated = {**MANIFEST, "mode": "dedicated"} + await _finish(profile, dedicated, "switch-dedicated") + async with profile.database.transaction() as connection: + with pytest.raises(ArtifactProcessingLeadershipLostError): + await ArtifactProcessingLeaseRepository().require_fence(connection, lease.fence("single-process")) + assert await ArtifactProcessingIntentRepository().load(connection, "a", BINDING) == before + with pytest.raises(ProcessingSchemaNotReadyError): + await assert_processing_schema_ready(connection, MANIFEST) + await assert_processing_schema_ready(connection, {**dedicated, "legacy_automatic_bindings": []}) + term = await ArtifactProcessingLeaseRepository().start_single_process_term( + connection, "new-holder", supervisor_group="artifact:topic-memory" + ) + await _finish(profile, MANIFEST, "switch-global") + async with profile.database.transaction() as connection: + with pytest.raises(ArtifactProcessingLeadershipLostError): + await ArtifactProcessingLeaseRepository().require_fence(connection, term.fence("single-process")) + assert await ArtifactProcessingIntentRepository().load(connection, "a", BINDING) == before + assert (await verify_processing_migration(connection, config_manifest=MANIFEST)).ready + + asyncio.run(scenario()) + + +def test_partial_schema_column_addition_is_resumed_before_data_backfill() -> None: + async def scenario() -> None: + async with SQLiteProfile.open(SQLiteConfig(), tables=SHARED_TABLES) as profile: + await _legacy(profile) + async with profile.database.transaction() as connection: + await apply_processing_migration(connection, config_manifest=MANIFEST) + # Mimic MySQL's durable DDL followed by a process crash before its + # next stage update: column exists, but no data has been migrated. + async with profile.database.transaction() as connection: + await connection.exec_driver_sql( + "ALTER TABLE pc_artifact_processing_binding_states ADD COLUMN last_schedule_checkpoint_at DATETIME NULL" + ) + await _finish(profile) + async with profile.database.transaction() as connection: + assert (await verify_processing_migration(connection, config_manifest=MANIFEST)).ready + checkpoint = await connection.scalar(select(STATES.c.last_schedule_checkpoint_at)) + assert checkpoint == CHECKPOINT + assert await connection.scalar(select(SCHEMA.c.phase)) == "complete" + + asyncio.run(scenario()) diff --git a/tests/builtin/persistence/test_processing_storage_backends.py b/tests/builtin/persistence/test_processing_storage_backends.py new file mode 100644 index 0000000000..c0cf0e71bb --- /dev/null +++ b/tests/builtin/persistence/test_processing_storage_backends.py @@ -0,0 +1,211 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Live backend contracts; each run owns a separate database/runtime path.""" + +from __future__ import annotations + +import asyncio +import os +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from datetime import UTC, datetime +from pathlib import Path +from tempfile import TemporaryDirectory +from uuid import uuid4 + +import pytest +from pydantic import SecretStr +from sqlalchemy import Column, DateTime, MetaData, Table, func, insert, select +from sqlalchemy.engine import make_url +from sqlalchemy.ext.asyncio import create_async_engine + +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.errors import ArtifactProcessingLeadershipLostError +from powercontext.builtin.persistence.oceanbase.profile import ( + OceanBaseConfig, + OceanBaseProfile, + _register_official_dialect, +) +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.processing_migration import ( + apply_processing_migration, + assert_processing_schema_ready, + plan_processing_migration, + verify_processing_migration, +) +from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile +from powercontext.builtin.persistence.supervision import ( + ArtifactProcessingBindingStateRepository, + ArtifactProcessingLeaseRepository, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_BINDING_STATES_TABLE as STATES, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_INTENTS_TABLE as INTENTS, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_MIGRATION_RECEIPTS_TABLE as RECEIPTS, +) +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_PENDING_TABLE as PENDING, +) +from powercontext.builtin.persistence.tables import ( + SCOPE_TABLES, + SHARED_TABLES, + identity_string, +) +from powercontext.builtin.persistence.tables import ( + SOURCE_JOURNAL_HEADS_TABLE as HEADS, +) +from powercontext.builtin.sources import SourceCursor +from powercontext.limits import MAX_BINDING_NAME_LENGTH + +BINDING = "topic-memory-source-window" +MANIFEST = {"mode": "global", "bindings": {BINDING: "topic-memory"}} + + +class _SimulatedCrash(Exception): + pass + + +@asynccontextmanager +async def _storage_profile(backend: str, path: Path) -> AsyncIterator[OceanBaseProfile | SeekDBProfile]: + legacy_state = Table( + STATES.name, + MetaData(), + Column("binding_name", identity_string(MAX_BINDING_NAME_LENGTH), primary_key=True), + Column("last_auto_wave_completed_at", DateTime(timezone=False)), + ) + tables = (*SCOPE_TABLES, *tuple(table for table in SHARED_TABLES if table is not STATES), legacy_state) + if backend == "seekdb": + pytest.importorskip("pylibseekdb") + # The embedded engine's Unix socket must fit sockaddr_un. A deeply + # nested pytest base path can exceed that limit even for a short suffix. + with TemporaryDirectory(prefix="pc-storage-", dir="/tmp") as directory: + async with SeekDBProfile.open(SeekDBConfig(path=Path(directory) / "db"), tables=tables) as profile: + yield profile + return + value = os.environ.get("POWERCONTEXT_PROCESSING_STORAGE_URL") + if not value: + pytest.skip("POWERCONTEXT_PROCESSING_STORAGE_URL is needed for the isolated live OceanBase contract") + base = make_url(value).update_query_dict({"charset": "utf8mb4"}) + database = "pc_storage_" + uuid4().hex[:12] + _register_official_dialect() + engine = create_async_engine(base, connect_args={"init_command": "SET autocommit = 0"}, hide_parameters=True) + try: + async with engine.begin() as connection: + await connection.exec_driver_sql(f"CREATE DATABASE {database} CHARACTER SET utf8mb4 COLLATE utf8mb4_bin") + config = OceanBaseConfig(url=SecretStr(base.set(database=database).render_as_string(hide_password=False))) + async with OceanBaseProfile.open(config, tables=tables) as profile: + yield profile + finally: + # Only the uniquely named database created by this fixture is removed. + async with engine.begin() as connection: + await connection.exec_driver_sql(f"DROP DATABASE IF EXISTS {database}") + await engine.dispose() + + +@pytest.mark.parametrize("backend", ("oceanbase", "seekdb")) +def test_live_intents_fencing_and_resumable_legacy_migration(backend: str, tmp_path: Path) -> None: + async def scenario() -> None: + async with _storage_profile(backend, tmp_path) as profile: + leases, intents = ArtifactProcessingLeaseRepository(), ArtifactProcessingIntentRepository() + checkpoint = datetime(2026, 1, 1, tzinfo=UTC).replace(tzinfo=None) + async with profile.database.transaction() as connection: + old = await leases.start_single_process_term(connection, "old-holder") + await connection.execute(insert(HEADS).values(scope_id="untracked", position=3)) + await SourceCursorRepository().save( + connection, "untracked", BINDING, SourceCursor(sequence=1), expected_generation=None + ) + await connection.execute( + insert(PENDING).values(binding_name=BINDING, scope_id="untracked", source_through=3) + ) + # The metadata includes new columns; use only old-column SQL + # against this deliberately pre-migration table. + await connection.execute( + insert(STATES).values(binding_name=BINDING, last_auto_wave_completed_at=checkpoint) + ) + plan = await plan_processing_migration(connection, config_manifest=MANIFEST) + assert len(plan.missing_state_columns) == 4 + while True: + async with profile.database.transaction() as connection: + step = await apply_processing_migration(connection, config_manifest=MANIFEST) + if step.phase == "backfill": + break + with pytest.raises(_SimulatedCrash): + async with profile.database.transaction() as connection: + await apply_processing_migration(connection, config_manifest=MANIFEST, batch_size=1) + raise _SimulatedCrash + async with profile.database.transaction() as connection: + assert await connection.scalar(select(func.count()).select_from(INTENTS)) == 0 + assert await connection.scalar(select(func.count()).select_from(RECEIPTS)) == 0 + for _ in range(20): + async with profile.database.transaction() as connection: + step = await apply_processing_migration(connection, config_manifest=MANIFEST, batch_size=1) + if step.complete: + break + assert step.complete + async with profile.database.transaction() as connection: + await assert_processing_schema_ready(connection, MANIFEST) + assert (await verify_processing_migration(connection, config_manifest=MANIFEST)).ready + recovered = await intents.load(connection, "untracked", BINDING) + assert recovered is not None and recovered.requested_generation == 1 + state = await ArtifactProcessingBindingStateRepository().load(connection, BINDING) + assert state is not None and state.last_schedule_checkpoint_at == checkpoint + if backend == "oceanbase": + lease = await leases.try_acquire(connection, "new-holder", 60) + else: + lease = await leases.start_single_process_term(connection, "new-holder") + assert lease is not None and lease.supervisor_generation > old.supervisor_generation + mode = "oceanbase" if backend == "oceanbase" else "single-process" + with pytest.raises(ArtifactProcessingLeadershipLostError): + async with profile.database.transaction() as connection: + await leases.require_fence(connection, old.fence("single-process")) + await intents.request(connection, "stale", BINDING) + async with profile.database.transaction() as connection: + await leases.require_fence(connection, lease.fence(mode)) + await intents.acknowledge(connection, "untracked", BINDING, recovered.requested_generation) + assert await intents.load(connection, "stale", BINDING) is None + barrier = asyncio.Barrier(2) + + async def request(): + async with profile.database.transaction() as connection: + await barrier.wait() + return await intents.request(connection, "concurrent", BINDING) + + first, second = await asyncio.gather(request(), request()) + assert first.pending_sequence == second.pending_sequence + async with profile.database.transaction() as connection: + current = await intents.load(connection, "concurrent", BINDING) + assert current is not None and current.requested_generation == 2 + await intents.mark_dirty(connection, "concurrent", BINDING) + await intents.mark_dirty(connection, "concurrent", BINDING) + await leases.require_fence(connection, lease.fence(mode)) + acknowledged = await intents.acknowledge(connection, "concurrent", BINDING, 1, clean_generation=1) + assert (acknowledged.requested_generation, acknowledged.handled_generation) == (2, 1) + assert (acknowledged.dirty_generation, acknowledged.clean_generation) == (2, 1) + states = ArtifactProcessingBindingStateRepository() + scan = await states.start_scan(connection, BINDING) + admitted = await intents.admit(connection, "concurrent", BINDING, scan.scan_generation) + assert admitted.requested_generation == 2 + await intents.acknowledge(connection, "concurrent", BINDING, 2, clean_generation=2) + duplicate = await intents.admit(connection, "concurrent", BINDING, scan.scan_generation) + assert duplicate.requested_generation == duplicate.handled_generation == 2 + await states.finish_scan(connection, BINDING) + finished = await states.load(connection, BINDING) + assert finished is not None and not finished.scan_in_progress + + asyncio.run(scenario()) diff --git a/tests/builtin/persistence/test_topic_memory_integrity.py b/tests/builtin/persistence/test_topic_memory_integrity.py index 01af24cf0a..cbe5500e28 100644 --- a/tests/builtin/persistence/test_topic_memory_integrity.py +++ b/tests/builtin/persistence/test_topic_memory_integrity.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Statement-consistent integrity checks on real SQLite and opt-in OceanBase.""" +"""Statement-consistent integrity checks on SQLite and opt-in OceanBase/seekDB.""" from __future__ import annotations @@ -22,6 +22,7 @@ from contextlib import AsyncExitStack, asynccontextmanager from dataclasses import dataclass from pathlib import Path +from tempfile import TemporaryDirectory from typing import Any, cast from uuid import uuid4 @@ -45,6 +46,7 @@ OceanBaseTopicMemoryFTSIndex, OceanBaseTopicMemoryVectorIndex, ) +from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.persistence.sqlite.topic_memory_index import ( SQLiteTopicMemoryFTSIndex, @@ -56,6 +58,12 @@ _LIVE_URL = os.environ.get("POWERCONTEXT_TEST_OCEANBASE_URL") _OB = pytest.param("oceanbase", marks=pytest.mark.skipif(not _LIVE_URL, reason="requires test OceanBase URL")) +_SEEKDB = pytest.param( + "seekdb", + marks=pytest.mark.skipif( + os.environ.get("POWERCONTEXT_TEST_SEEKDB") != "1", reason="requires POWERCONTEXT_TEST_SEEKDB=1" + ), +) _PROFILE = EmbeddingProfile(profile_id="integrity", model="test", dimension=3, distance="l2", normalization="unit") _VECTOR = (1.0, 0.0, 0.0) @@ -67,6 +75,7 @@ class _Store: repository: TopicMemoryRepository first: TopicMemory index: CompositeTopicMemoryIndex + seekdb_config: SeekDBConfig | None = None async def publish(self, connection: AsyncConnection, previous: TopicMemory | None, scope: str) -> TopicMemory: content = TopicMemoryContent(title="Recovery", summary="Durable evidence", detail="Evidence " * 400) @@ -89,6 +98,7 @@ async def publish(self, connection: AsyncConnection, previous: TopicMemory | Non @asynccontextmanager async def _open_store(tmp_path: Path, backend: str, *, vector: bool) -> AsyncIterator[_Store]: async with AsyncExitStack() as stack: + seekdb_config = None if backend == "sqlite": index = CompositeTopicMemoryIndex( SQLiteTopicMemoryFTSIndex(), *((SQLiteTopicMemoryVectorIndex(_PROFILE),) if vector else ()) @@ -100,6 +110,21 @@ async def _open_store(tmp_path: Path, backend: str, *, vector: bool) -> AsyncIte reader = await stack.enter_async_context( SQLiteProfile.open(config, tables=BUILTIN_TABLES + index.tables, load_vector_extension=vector) ) + elif backend == "seekdb": + pytest.importorskip("pylibseekdb") + # Unix socket paths must fit sockaddr_un even in deeply nested CI + # workspaces. Both profiles own separate engines and native handles. + directory = stack.enter_context(TemporaryDirectory(prefix="pc-integrity-", dir="/tmp")) + seekdb_config = SeekDBConfig(path=Path(directory) / "db") + index = CompositeTopicMemoryIndex( + OceanBaseTopicMemoryFTSIndex(), *((OceanBaseTopicMemoryVectorIndex(_PROFILE),) if vector else ()) + ) + profile = await stack.enter_async_context( + SeekDBProfile.open(seekdb_config, tables=BUILTIN_TABLES + index.tables) + ) + reader = await stack.enter_async_context( + SeekDBProfile.open(seekdb_config, tables=BUILTIN_TABLES + index.tables) + ) else: assert _LIVE_URL is not None server = await stack.enter_async_context( @@ -126,7 +151,8 @@ async def drop_database() -> None: OceanBaseProfile.open(ob_config, tables=BUILTIN_TABLES + index.tables) ) repository = TopicMemoryRepository(index=index) - store = _Store(profile.database, reader.database, repository, cast(TopicMemory, None), index) + assert profile.database.engine is not reader.database.engine + store = _Store(profile.database, reader.database, repository, cast(TopicMemory, None), index, seekdb_config) async with profile.database.transaction() as connection: await repository.initialize(connection) async with profile.database.transaction() as connection: @@ -204,7 +230,7 @@ async def check() -> None: assert [item.artifact_ref.revision for item in b] == [1] -@pytest.mark.parametrize("backend", ["sqlite", _OB]) +@pytest.mark.parametrize("backend", ["sqlite", _OB, _SEEKDB]) @pytest.mark.parametrize("timing", ["before", "after"]) def test_worker_integrity_accepts_another_scopes_concurrent_revision(tmp_path: Path, backend: str, timing: str) -> None: async def scenario() -> None: @@ -214,7 +240,7 @@ async def scenario() -> None: asyncio.run(scenario()) -@pytest.mark.parametrize("backend", ["sqlite", _OB]) +@pytest.mark.parametrize("backend", ["sqlite", _OB, _SEEKDB]) @pytest.mark.parametrize("timing", ["before", "after"]) def test_current_vector_integrity_uses_one_revision(tmp_path: Path, backend: str, timing: str) -> None: async def scenario() -> None: @@ -234,7 +260,7 @@ async def scenario() -> None: asyncio.run(scenario()) -@pytest.mark.parametrize("backend", ["sqlite", _OB]) +@pytest.mark.parametrize("backend", ["sqlite", _OB, _SEEKDB]) def test_worker_integrity_still_rejects_missing_active_chunks(tmp_path: Path, backend: str) -> None: async def scenario() -> None: async with _open_store(tmp_path, backend, vector=False) as store: @@ -251,7 +277,7 @@ async def scenario() -> None: asyncio.run(scenario()) -@pytest.mark.parametrize("backend", ["sqlite", _OB]) +@pytest.mark.parametrize("backend", ["sqlite", _OB, _SEEKDB]) @pytest.mark.parametrize( "corruption", ["topic-missing", "chunk-missing", "extra", "ordinal", "topic-profile", "chunk-profile", "extra-profile"], diff --git a/tests/builtin/runtime/test_artifact_processing.py b/tests/builtin/runtime/test_artifact_processing.py index 8a88adcd83..ea87f3858f 100644 --- a/tests/builtin/runtime/test_artifact_processing.py +++ b/tests/builtin/runtime/test_artifact_processing.py @@ -19,232 +19,34 @@ import signal import threading import time -from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any, cast import pytest -from sqlalchemy import update -from sqlalchemy.ext.asyncio import AsyncConnection -from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryGenerationError -from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.database import AsyncDatabase from powercontext.builtin.persistence.errors import ArtifactProcessingLeadershipLostError -from powercontext.builtin.persistence.processing import ( - ArtifactProcessingAutoWaveTargetRepository, - ArtifactProcessingPendingRepository, - StoredArtifactProcessingPending, -) -from powercontext.builtin.persistence.sources import SourceRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.builtin.persistence.supervision import ( - ArtifactProcessingBindingStateRepository, - ArtifactProcessingFence, - ArtifactProcessingLeaseRepository, - StoredArtifactProcessingLease, -) -from powercontext.builtin.persistence.tables import ARTIFACT_PROCESSING_BINDING_STATES_TABLE, SHARED_TABLES +from powercontext.builtin.persistence.supervision import ArtifactProcessingFence, ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import SHARED_TABLES from powercontext.builtin.runtime import artifact_processing as artifact_processing_module from powercontext.builtin.runtime.artifact_processing import ( ArtifactProcessingBinding, ArtifactProcessingSupervisor, - ArtifactProcessingSupervisorStatus, - ArtifactProcessingWaveKind, ArtifactProcessingWorkAssignment, ArtifactProcessingWorkerCompletion, ArtifactProcessingWorkerOutcome, SpawnArtifactProcessingWorkerLauncher, ) -from powercontext.builtin.sources import SourceCursor -from powercontext.sources import SourceMaterialization -from tests.builtin.persistence.contract import SOURCE_ADAPTERS, NoteSource BINDING = "topic-memory-source-window" SPAWN_TEST_TIMEOUT_SECONDS = 10.0 -class _PublishingLauncher: - def __init__( - self, - database: AsyncDatabase, - *, - inject_new_source: bool = False, - inject_successor_flush: bool = False, - fail_scopes: set[str] | None = None, - control_conflicts: dict[str, ArtifactProcessingWorkerOutcome] | None = None, - wait_for: asyncio.Event | None = None, - inject_wave_snapshot_changes: bool = False, - ) -> None: - self.database = database - self.inject_new_source = inject_new_source - self.inject_successor_flush = inject_successor_flush - self.fail_scopes = set() if fail_scopes is None else fail_scopes - self.control_conflicts = {} if control_conflicts is None else control_conflicts - self.wait_for = wait_for - self.inject_wave_snapshot_changes = inject_wave_snapshot_changes - self.injected = False - self.assignments: list[ArtifactProcessingWorkAssignment] = [] - self.active: set[tuple[str, str]] = set() - - async def start(self, assignment: ArtifactProcessingWorkAssignment): - key = (assignment.binding_name, assignment.scope_id) - self.assignments.append(assignment) - if assignment.scope_id in self.fail_scopes: - raise RuntimeError - assert key not in self.active - self.active.add(key) - return _PublishingHandle(self, assignment) - - -class _PublishingHandle: - def __init__(self, launcher: _PublishingLauncher, assignment: ArtifactProcessingWorkAssignment) -> None: - self.launcher = launcher - self.assignment = assignment - - async def wait(self) -> ArtifactProcessingWorkerCompletion: - if self.launcher.wait_for is not None: - await self.launcher.wait_for.wait() - await asyncio.sleep(0) - assignment = self.assignment - key = (assignment.binding_name, assignment.scope_id) - conflict = self.launcher.control_conflicts.get(assignment.scope_id) - if conflict is not None: - self.launcher.active.remove(key) - return ArtifactProcessingWorkerCompletion(outcome=conflict) - leases = ArtifactProcessingLeaseRepository() - cursors = SourceCursorRepository() - pending = ArtifactProcessingPendingRepository() - if self.launcher.inject_successor_flush and not self.launcher.injected: - sources = SourceRepository(SOURCE_ADAPTERS) - async with self.launcher.database.transaction() as connection: - stored = await sources.add( - connection, - assignment.scope_id, - NoteSource( - name="successor", - materialization=SourceMaterialization.CAPTURED, - body="successor", - ), - ) - await pending.raise_source( - connection, - assignment.scope_id, - assignment.binding_name, - stored.journal_position, - ) - assert ( - await pending.request_flush( - connection, - assignment.scope_id, - assignment.binding_name, - ) - is not None - ) - self.launcher.injected = True - async with self.launcher.database.transaction() as connection: - await leases.require_fence(connection, assignment.fence) - await cursors.save( - connection, - assignment.scope_id, - assignment.binding_name, - SourceCursor(sequence=assignment.source_through), - expected_generation=assignment.cursor_generation, - ) - if ( - self.launcher.inject_new_source - and not self.launcher.injected - and assignment.wave_kind is ArtifactProcessingWaveKind.AUTOMATIC - ): - await pending.raise_source( - connection, - assignment.scope_id, - assignment.binding_name, - assignment.wave_target + 1, - ) - self.launcher.injected = True - if ( - self.launcher.inject_wave_snapshot_changes - and not self.launcher.injected - and assignment.wave_kind is ArtifactProcessingWaveKind.AUTOMATIC - ): - await pending.raise_source(connection, "scope-b", assignment.binding_name, 1) - await pending.raise_source(connection, "scope-c", assignment.binding_name, 2) - self.launcher.injected = True - if ( - assignment.wave_kind is ArtifactProcessingWaveKind.EXPLICIT - and assignment.source_through == assignment.wave_target - ): - await pending.mark_flush_handled( - connection, - assignment.scope_id, - assignment.binding_name, - assignment.claimed_flush_generation, - ) - await pending.delete_if_covered( - connection, - assignment.scope_id, - assignment.binding_name, - cursor=assignment.source_through, - source_through_limit=assignment.wave_target, - ) - self.launcher.active.remove(key) - return ArtifactProcessingWorkerCompletion() - - async def terminate(self) -> None: - self.launcher.active.discard((self.assignment.binding_name, self.assignment.scope_id)) - - -class _HangingLauncher: - def __init__(self) -> None: - self.started = asyncio.Event() - self.terminated = asyncio.Event() - - async def start(self, assignment: ArtifactProcessingWorkAssignment): - del assignment - self.started.set() - return _HangingHandle(self.terminated) - - -class _HangingHandle: - def __init__(self, terminated: asyncio.Event) -> None: - self.terminated = terminated - - async def wait(self) -> ArtifactProcessingWorkerCompletion: - await asyncio.Event().wait() - raise AssertionError("unreachable") - - async def terminate(self) -> None: - self.terminated.set() - - -class _HangingStartLauncher: - def __init__(self) -> None: - self.started = asyncio.Event() - self.cancelled = asyncio.Event() - self.attempts = 0 - - async def start(self, assignment: ArtifactProcessingWorkAssignment): - del assignment - self.attempts += 1 - self.started.set() - try: - await asyncio.Event().wait() - finally: - self.cancelled.set() - raise AssertionError("unreachable") - - -class _FailingStartLauncher: - def __init__(self) -> None: - self.attempts = 0 - self.attempted = asyncio.Event() - - async def start(self, assignment: ArtifactProcessingWorkAssignment): - del assignment - self.attempts += 1 - self.attempted.set() - raise RuntimeError +async def _request(database: AsyncDatabase, scope_id: str) -> None: + async with database.transaction() as connection: + await ArtifactProcessingIntentRepository().request(connection, scope_id, BINDING) class _CapturingSpawnLauncher: @@ -262,110 +64,6 @@ async def start(self, assignment: ArtifactProcessingWorkAssignment): return handle -class _TrackingPendingRepository(ArtifactProcessingPendingRepository): - def __init__(self) -> None: - self.scan_calls = 0 - self.scan_limits: list[int | None] = [] - - async def scan( - self, - connection: AsyncConnection, - /, - *, - binding_name: str | None = None, - after: tuple[str, str] | None = None, - limit: int | None = None, - for_update: bool = False, - ) -> tuple[StoredArtifactProcessingPending, ...]: - self.scan_calls += 1 - self.scan_limits.append(limit) - return await super().scan( - connection, - binding_name=binding_name, - after=after, - limit=limit, - for_update=for_update, - ) - - -class _FailingPendingRepository(ArtifactProcessingPendingRepository): - async def scan( - self, - connection: AsyncConnection, - /, - *, - binding_name: str | None = None, - after: tuple[str, str] | None = None, - limit: int | None = None, - for_update: bool = False, - ) -> tuple[StoredArtifactProcessingPending, ...]: - del connection, binding_name, after, limit, for_update - raise RuntimeError - - -class _RenewingLeaseRepository(ArtifactProcessingLeaseRepository): - def __init__(self) -> None: - self.lease = StoredArtifactProcessingLease( - supervisor_group="global", - holder_id="holder-a", - supervisor_generation=1, - lease_expires_at=datetime(3000, 1, 1, tzinfo=UTC).replace(tzinfo=None), - ) - self.acquired = False - self.renew_count = 0 - self.renewed = asyncio.Event() - - async def try_acquire( - self, - connection: AsyncConnection, - holder_id: str, - lease_seconds: float, - /, - *, - supervisor_group: str = "global", - ) -> StoredArtifactProcessingLease | None: - del connection, lease_seconds, supervisor_group - assert holder_id == self.lease.holder_id - if self.acquired: - return None - self.acquired = True - return self.lease - - async def renew( - self, - connection: AsyncConnection, - fence: ArtifactProcessingFence, - lease_seconds: float, - /, - ) -> StoredArtifactProcessingLease: - del connection, lease_seconds - assert fence == self.lease.fence("oceanbase") - self.renew_count += 1 - if self.renew_count >= 2: - self.renewed.set() - return self.lease - - async def require_fence( - self, - connection: AsyncConnection, - fence: ArtifactProcessingFence, - /, - ) -> StoredArtifactProcessingLease: - del connection - assert fence == self.lease.fence("oceanbase") - return self.lease - - -class _CycleCountingSupervisor(ArtifactProcessingSupervisor): - def __init__(self, *args, **kwargs) -> None: - super().__init__(*args, **kwargs) - self.cycle_count = 0 - - async def _cycle(self) -> None: - self.cycle_count += 1 - await super()._cycle() - - def _spawn_success(_assignment: ArtifactProcessingWorkAssignment) -> ArtifactProcessingWorkerCompletion: return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.SUCCEEDED) @@ -383,1053 +81,13 @@ async def _wait_until(predicate, *, timeout_seconds: float = 3.0) -> None: await asyncio.sleep(0.01) -async def _raise_and_flush( - database: AsyncDatabase, - pending: ArtifactProcessingPendingRepository, - scope_id: str, - source_count: int, -) -> None: - sources = SourceRepository(SOURCE_ADAPTERS) - async with database.transaction() as connection: - for position in range(1, source_count + 1): - stored = await sources.add( - connection, - scope_id, - NoteSource( - name=f"note-{position}", - materialization=SourceMaterialization.CAPTURED, - body=f"body-{position}", - ), - ) - await pending.raise_source(connection, scope_id, BINDING, stored.journal_position) - assert await pending.request_flush(connection, scope_id, BINDING) is not None - - -def test_explicit_windows_are_single_flight_and_requeue_fairly(tmp_path) -> None: - async def scenario() -> None: - pending = ArtifactProcessingPendingRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'fair.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - for scope_id in ("scope-a", "scope-b"): - await _raise_and_flush(profile.database, pending, scope_id, 3) - launcher = _PublishingLauncher(profile.database) - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, launcher),), - lease_mode="single-process", - max_workers=2, - worker_timeout_seconds=1, - ) as supervisor: - - async def completed() -> bool: - async with profile.database.transaction() as connection: - return not await pending.scan(connection) - - await _wait_until(completed, timeout_seconds=SPAWN_TEST_TIMEOUT_SECONDS) - assert supervisor.status is ArtifactProcessingSupervisorStatus.LEADER - - keys = [(item.binding_name, item.scope_id) for item in launcher.assignments] - assert set(keys[:2]) == {(BINDING, "scope-a"), (BINDING, "scope-b")} - assert keys.count((BINDING, "scope-a")) == 3 - assert keys.count((BINDING, "scope-b")) == 3 - assert not launcher.active - - asyncio.run(scenario()) - - -def test_automatic_wave_commits_binding_time_but_preserves_newer_sources(tmp_path) -> None: - async def scenario() -> None: - pending = ArtifactProcessingPendingRepository() - states = ArtifactProcessingBindingStateRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'automatic.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - async with profile.database.transaction() as connection: - await pending.raise_source(connection, "scope-a", BINDING, 2) - launcher = _PublishingLauncher(profile.database, inject_new_source=True) - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=60), - ), - ), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - ): - - async def wave_completed() -> bool: - async with profile.database.transaction() as connection: - return await states.load(connection, BINDING) is not None - - await _wait_until(wave_completed) - - async with profile.database.transaction() as connection: - stored = await pending.load(connection, "scope-a", BINDING) - state = await states.load(connection, BINDING) - assert stored is not None - assert stored.source_through == 3 - assert state is not None - assert state.last_auto_wave_completed_at is not None - assert [item.wave_target for item in launcher.assignments] == [2, 2] - - asyncio.run(scenario()) - - -def test_automatic_wave_spans_pages_before_committing_binding_time(tmp_path, monkeypatch) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 2) - pending = ArtifactProcessingPendingRepository() - states = ArtifactProcessingBindingStateRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'automatic-pages.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - async with profile.database.transaction() as connection: - for scope_id in ("scope-a", "scope-b", "scope-c"): - await pending.raise_source(connection, scope_id, BINDING, 1) - launcher = _PublishingLauncher(profile.database) - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=60), - ), - ), - lease_mode="single-process", - max_workers=2, - worker_timeout_seconds=1, - ): - - async def wave_completed() -> bool: - async with profile.database.transaction() as connection: - return await states.load(connection, BINDING) is not None - - await _wait_until(wave_completed) - - assert [assignment.scope_id for assignment in launcher.assignments] == [ - "scope-a", - "scope-b", - "scope-c", - ] - async with profile.database.transaction() as connection: - assert await pending.scan(connection, binding_name=BINDING) == () - for scope_id in ("scope-a", "scope-b", "scope-c"): - cursor = await SourceCursorRepository().load(connection, scope_id, BINDING) - assert cursor is not None - assert cursor.cursor.sequence == 1 - - asyncio.run(scenario()) - - -def test_automatic_wave_pages_only_the_wave_start_snapshot(tmp_path, monkeypatch) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 1) - pending = ArtifactProcessingPendingRepository() - states = ArtifactProcessingBindingStateRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'automatic-snapshot.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - async with profile.database.transaction() as connection: - await pending.raise_source(connection, "scope-a", BINDING, 1) - await pending.raise_source(connection, "scope-c", BINDING, 1) - launcher = _PublishingLauncher( - profile.database, - inject_wave_snapshot_changes=True, - ) - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=60), - ), - ), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - ): - - async def wave_completed() -> bool: - async with profile.database.transaction() as connection: - return await states.load(connection, BINDING) is not None - - await _wait_until(wave_completed) - - assert [(item.scope_id, item.wave_target) for item in launcher.assignments] == [ - ("scope-a", 1), - ("scope-c", 1), - ] - async with profile.database.transaction() as connection: - remaining = await pending.scan(connection, binding_name=BINDING) - cursor = await SourceCursorRepository().load(connection, "scope-c", BINDING) - assert [(row.scope_id, row.source_through) for row in remaining] == [ - ("scope-b", 1), - ("scope-c", 2), - ] - assert cursor is not None - assert cursor.cursor.sequence == 1 - - asyncio.run(scenario()) - - -def test_due_automatic_binding_without_pending_waits_for_the_next_interval(tmp_path) -> None: - async def scenario() -> None: - states = ArtifactProcessingBindingStateRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'automatic-idle.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - async with profile.database.transaction() as connection: - await states.mark_auto_wave_completed(connection, BINDING) - await connection.execute( - update(ARTIFACT_PROCESSING_BINDING_STATES_TABLE) - .where(ARTIFACT_PROCESSING_BINDING_STATES_TABLE.c.binding_name == BINDING) - .values(last_auto_wave_completed_at=datetime(2000, 1, 1, tzinfo=UTC).replace(tzinfo=None)) - ) - launcher = _PublishingLauncher(profile.database) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=10), - ), - ), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - ) - await supervisor.start() - - assert supervisor.status is ArtifactProcessingSupervisorStatus.LEADER - next_wake_seconds = supervisor._next_wake_seconds() - assert next_wake_seconds is not None - assert next_wake_seconds > 9 - assert not launcher.assignments - await supervisor.close() - - asyncio.run(scenario()) - - -def test_flush_during_a_wave_creates_one_successor_from_the_new_snapshot(tmp_path) -> None: - async def scenario() -> None: - pending = ArtifactProcessingPendingRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'successor.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, "scope-a", 2) - launcher = _PublishingLauncher(profile.database, inject_successor_flush=True) - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 2, launcher),), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - ): - - async def completed() -> bool: - async with profile.database.transaction() as connection: - return await pending.load(connection, "scope-a", BINDING) is None - - await _wait_until(completed) - - assert [item.wave_target for item in launcher.assignments] == [2, 3] - assert [item.claimed_flush_generation for item in launcher.assignments] == [1, 2] - assert [item.source_after for item in launcher.assignments] == [0, 2] - - asyncio.run(scenario()) - - -def test_worker_timeout_terminates_child_and_keeps_durable_work(tmp_path) -> None: - async def scenario() -> None: - pending = ArtifactProcessingPendingRepository() - launcher = _HangingLauncher() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'timeout.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, "scope-a", 1) - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, launcher),), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=0.01, - retry_base_seconds=60, - retry_jitter=lambda: 1, - ): - await asyncio.wait_for(launcher.terminated.wait(), timeout=1) - async with profile.database.transaction() as connection: - assert await pending.load(connection, "scope-a", BINDING) is not None - assert await SourceCursorRepository().load(connection, "scope-a", BINDING) is None - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("automatic", [False, True]) -@pytest.mark.parametrize("invalid_boundary", [False, True]) -def test_selector_failure_defers_only_its_scope_and_preserves_leadership( - tmp_path, monkeypatch, automatic, invalid_boundary -): - class FailingSelector: - def __init__(self) -> None: - self.failed_attempts = 0 - - async def select(self, scope_id: str, source_after: int, source_ceiling: int) -> int: - if scope_id == "scope-a": - self.failed_attempts += 1 - if invalid_boundary: - return source_after - raise TopicMemoryGenerationError("unsupported_evidence") - return source_ceiling - - async def scenario() -> None: - monkeypatch.setattr(artifact_processing_module, "_DISCOVERY_PAGE_SIZE", 1) - pending = ArtifactProcessingPendingRepository() - selector = FailingSelector() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'selection-isolation.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - async with profile.database.transaction() as connection: - for scope in ("scope-a", "scope-b"): - await SourceRepository(SOURCE_ADAPTERS).add( - connection, - scope, - NoteSource(name="note", materialization=SourceMaterialization.CAPTURED, body="evidence"), - ) - await pending.raise_source(connection, scope, BINDING, 1) - if not automatic: - assert await pending.request_flush(connection, scope, BINDING) is not None - launcher = _PublishingLauncher(profile.database) - binding = ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(hours=1) if automatic else None, - window_selector=selector, - ) - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=(binding,), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - retry_base_seconds=60, - retry_jitter=lambda: 1, - ) as supervisor: - fence = supervisor.fence - assert fence is not None - - async def healthy_scope_completed() -> bool: - async with profile.database.transaction() as connection: - cursor = await SourceCursorRepository().load(connection, "scope-b", BINDING) - return cursor is not None and cursor.cursor.sequence == 1 - - await _wait_until(healthy_scope_completed) - assert supervisor.status is ArtifactProcessingSupervisorStatus.LEADER - assert supervisor.fence == fence - assert selector.failed_attempts == 1 - assert [item.scope_id for item in launcher.assignments] == ["scope-b"] - async with profile.database.transaction() as connection: - assert await SourceCursorRepository().load(connection, "scope-a", BINDING) is None - assert await pending.load(connection, "scope-a", BINDING) is not None - await ArtifactProcessingLeaseRepository().require_fence(connection, fence) - state = await ArtifactProcessingBindingStateRepository().load(connection, BINDING) - assert state is None or state.last_auto_wave_completed_at is None - - asyncio.run(scenario()) - - -def test_successor_selection_failure_preserves_an_inflight_peer(tmp_path) -> None: - class SuccessorSelector: - def __init__(self) -> None: - self.failed = asyncio.Event() - - async def select(self, scope_id: str, source_after: int, source_ceiling: int) -> int: - if scope_id == "scope-a" and source_after == 1: - self.failed.set() - raise TopicMemoryGenerationError("unsupported_evidence") - return source_ceiling - - async def scenario() -> None: - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'successor-selection.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - pending = ArtifactProcessingPendingRepository() - async with profile.database.transaction() as connection: - for scope in ("scope-a", "scope-b"): - for position in range(2): - await SourceRepository(SOURCE_ADAPTERS).add( - connection, - scope, - NoteSource( - name=f"note-{position}", materialization=SourceMaterialization.CAPTURED, body="evidence" - ), - ) - await pending.raise_source(connection, scope, BINDING, 2) - await pending.request_flush(connection, scope, BINDING) - peer = _HangingLauncher() - publisher = _PublishingLauncher(profile.database, wait_for=peer.started) - - class Launcher: - async def start(self, assignment): - return await (peer if assignment.scope_id == "scope-b" else publisher).start(assignment) - - selector = SuccessorSelector() - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, Launcher(), window_selector=selector),), - lease_mode="single-process", - max_workers=2, - worker_timeout_seconds=10, - retry_base_seconds=60, - retry_jitter=lambda: 1, - ) as supervisor: - fence = supervisor.fence - await asyncio.wait_for(selector.failed.wait(), timeout=3) - await asyncio.sleep(0.05) - assert supervisor.status is ArtifactProcessingSupervisorStatus.LEADER - assert supervisor.fence == fence - assert not peer.terminated.is_set() - async with profile.database.transaction() as connection: - cursor = await SourceCursorRepository().load(connection, "scope-a", BINDING) - assert cursor is not None and cursor.cursor.sequence == 1 - assert await pending.load(connection, "scope-a", BINDING) is not None - - asyncio.run(scenario()) - - -def test_flush_wake_rescans_a_scope_behind_the_pending_frontier(tmp_path, monkeypatch) -> None: - async def scenario() -> None: - # Freeze the next page's timer so the flush wake is the only trigger - # after the first 100 rows. No sleeps or a second wake drive dispatch. - monkeypatch.setattr(artifact_processing_module, "_DISCOVERY_PAGE_DELAY_SECONDS", 60) - pending = _TrackingPendingRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'flush-frontier.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - async with profile.database.transaction() as connection: - for index in range(101): - await SourceRepository(SOURCE_ADAPTERS).add( - connection, - f"scope-{index:03d}", - NoteSource(name="note", materialization=SourceMaterialization.CAPTURED, body="evidence"), - ) - await pending.raise_source(connection, f"scope-{index:03d}", BINDING, 1) - launcher = _PublishingLauncher(profile.database) - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, launcher),), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - pending=pending, - ) as supervisor: - assert pending.scan_calls == 1 - assert not launcher.assignments - async with profile.database.transaction() as connection: - assert await pending.request_flush(connection, "scope-000", BINDING) is not None - # Subsequent pages can run on their bounded timer, but the - # already-armed first-page delay cannot rescue a lost wake. - monkeypatch.setattr(artifact_processing_module, "_DISCOVERY_PAGE_DELAY_SECONDS", 0.01) - supervisor.wake() - - async def flush_completed() -> bool: - async with profile.database.transaction() as connection: - return await pending.load(connection, "scope-000", BINDING) is None - - await _wait_until(flush_completed) - assert [item.scope_id for item in launcher.assignments] == ["scope-000"] - assert all(limit is not None and limit <= 100 for limit in pending.scan_limits) - - asyncio.run(scenario()) - - -def test_retry_deadline_is_quiet_and_dispatches_once_when_due(tmp_path) -> None: - async def scenario() -> None: - pending = _TrackingPendingRepository() - launcher = _FailingStartLauncher() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'retry-deadline.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, "scope-a", 1) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, launcher),), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - pending=pending, - retry_base_seconds=0.2, - retry_cap_seconds=0.2, - retry_jitter=lambda: 1, - ) - await supervisor.start() - - async def failure_recorded() -> bool: - return bool(supervisor._retries) - - await _wait_until(failure_recorded) - await asyncio.sleep(0.01) - scans_before_deadline = pending.scan_calls - launcher.attempted.clear() - await asyncio.sleep(0.05) - assert launcher.attempts == 1 - assert pending.scan_calls == scans_before_deadline - - await asyncio.wait_for(launcher.attempted.wait(), timeout=0.5) - assert launcher.attempts == 2 - await supervisor.close() - - asyncio.run(scenario()) - - -def test_covered_explicit_retry_wakes_its_deferred_automatic_target(tmp_path, monkeypatch) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 1) - pending = ArtifactProcessingPendingRepository() - states = ArtifactProcessingBindingStateRepository() - cursors = SourceCursorRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'covered-retry.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, "scope-a", 1) - launcher = _PublishingLauncher(profile.database, fail_scopes={"scope-a"}) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=60), - ), - ), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - retry_base_seconds=0.1, - retry_cap_seconds=0.1, - retry_jitter=lambda: 1, - ) - await supervisor.start() - - async def target_is_deferred() -> bool: - wave = supervisor._automatic_waves.get(BINDING) - return ( - wave is not None - and wave.discovery_complete - and (BINDING, "scope-a") in wave.deferred_targets - and (BINDING, "scope-a") in supervisor._retries - ) - - await _wait_until(target_is_deferred) - async with profile.database.transaction() as connection: - await cursors.save( - connection, - "scope-a", - BINDING, - SourceCursor(sequence=1), - expected_generation=None, - ) - - async def wave_completed() -> bool: - async with profile.database.transaction() as connection: - return ( - await states.load(connection, BINDING) is not None - and await pending.load(connection, "scope-a", BINDING) is None - ) - - await _wait_until(wave_completed) - await supervisor.close() - assert {(item.scope_id, item.wave_kind) for item in launcher.assignments} == { - ("scope-a", ArtifactProcessingWaveKind.EXPLICIT) - } - - asyncio.run(scenario()) - - -def test_backoff_key_releases_discovery_budget_for_the_next_key(tmp_path, monkeypatch) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 1) - pending = ArtifactProcessingPendingRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'retry-fairness.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - for scope_id in ("scope-a", "scope-b"): - await _raise_and_flush(profile.database, pending, scope_id, 1) - launcher = _PublishingLauncher(profile.database, fail_scopes={"scope-a"}) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, launcher),), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - retry_base_seconds=0.05, - retry_cap_seconds=0.05, - retry_jitter=lambda: 1, - ) - await supervisor.start() - - async def second_key_completed() -> bool: - async with profile.database.transaction() as connection: - return await pending.load(connection, "scope-b", BINDING) is None - - await _wait_until(second_key_completed) - - async def first_key_failed_multiple_times() -> bool: - return sum(assignment.scope_id == "scope-a" for assignment in launcher.assignments) >= 3 - - await _wait_until(first_key_failed_multiple_times) - await supervisor.close() - - assert [assignment.scope_id for assignment in launcher.assignments[:2]] == [ - "scope-a", - "scope-b", - ] - async with profile.database.transaction() as connection: - assert await pending.load(connection, "scope-a", BINDING) is not None - assert await pending.load(connection, "scope-b", BINDING) is None - - asyncio.run(scenario()) - - -def test_failed_explicit_scope_does_not_starve_automatic_peer(tmp_path, monkeypatch) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 1) - pending = ArtifactProcessingPendingRepository() - states = ArtifactProcessingBindingStateRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'explicit-auto-fairness.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, "scope-a", 1) - async with profile.database.transaction() as connection: - await pending.raise_source(connection, "scope-b", BINDING, 1) - launcher = _PublishingLauncher(profile.database, fail_scopes={"scope-a"}) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=60), - ), - ), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - retry_base_seconds=60, - retry_jitter=lambda: 1, - ) - await supervisor.start() - - async def peer_completed() -> bool: - async with profile.database.transaction() as connection: - cursor = await SourceCursorRepository().load(connection, "scope-b", BINDING) - return cursor is not None and cursor.cursor.sequence == 1 - - await _wait_until(peer_completed) - await supervisor.close() - - assert [(item.scope_id, item.wave_kind) for item in launcher.assignments] == [ - ("scope-a", ArtifactProcessingWaveKind.EXPLICIT), - ("scope-b", ArtifactProcessingWaveKind.AUTOMATIC), - ] - async with profile.database.transaction() as connection: - assert await pending.load(connection, "scope-a", BINDING) is not None - assert await pending.load(connection, "scope-b", BINDING) is not None - assert await states.load(connection, BINDING) is None - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("request_explicit", (False, True), ids=("ordinary", "explicit")) -def test_active_failed_wave_does_not_starve_new_peer(tmp_path, monkeypatch, request_explicit) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 1) - pending = ArtifactProcessingPendingRepository() - states = ArtifactProcessingBindingStateRepository() - targets = ArtifactProcessingAutoWaveTargetRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / f'new-peer-{request_explicit}.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, "scope-a", 1) - launcher = _PublishingLauncher(profile.database, fail_scopes={"scope-a"}) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=60), - ), - ), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - retry_base_seconds=60, - retry_jitter=lambda: 1, - ) - await supervisor.start() - - async def old_wave_is_backing_off() -> bool: - wave = supervisor._automatic_waves.get(BINDING) - return wave is not None and (BINDING, "scope-a") in supervisor._retries - - await _wait_until(old_wave_is_backing_off) - old_wave_id = supervisor._automatic_waves[BINDING].wave_id - async with profile.database.transaction() as connection: - stored = await SourceRepository(SOURCE_ADAPTERS).add( - connection, - "scope-b", - NoteSource( - name="late-peer", - materialization=SourceMaterialization.CAPTURED, - body="late peer", - ), - ) - await pending.raise_source(connection, "scope-b", BINDING, stored.journal_position) - if request_explicit: - assert await pending.request_flush(connection, "scope-b", BINDING) is not None - supervisor.wake() - - async def new_peer_completed() -> bool: - async with profile.database.transaction() as connection: - if request_explicit: - return await pending.load(connection, "scope-b", BINDING) is None - cursor = await SourceCursorRepository().load(connection, "scope-b", BINDING) - return cursor is not None and cursor.cursor.sequence == 1 - - await _wait_until(new_peer_completed) - await supervisor.close() - - assert [(item.scope_id, item.wave_kind) for item in launcher.assignments] == [ - ("scope-a", ArtifactProcessingWaveKind.EXPLICIT), - ( - "scope-b", - ArtifactProcessingWaveKind.EXPLICIT if request_explicit else ArtifactProcessingWaveKind.AUTOMATIC, - ), - ] - async with profile.database.transaction() as connection: - frozen = await targets.scan(connection, old_wave_id, BINDING, limit=10) - scope_b_pending = await pending.load(connection, "scope-b", BINDING) - assert await states.load(connection, BINDING) is None - assert [(target.scope_id, target.source_through) for target in frozen] == [("scope-a", 1)] - assert (scope_b_pending is None) is request_explicit - - asyncio.run(scenario()) - - -def test_failed_automatic_scope_does_not_starve_frozen_suffix(tmp_path, monkeypatch) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 1) - pending = ArtifactProcessingPendingRepository() - states = ArtifactProcessingBindingStateRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'automatic-fairness.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - async with profile.database.transaction() as connection: - await pending.raise_source(connection, "scope-a", BINDING, 1) - await pending.raise_source(connection, "scope-b", BINDING, 1) - launcher = _PublishingLauncher(profile.database, fail_scopes={"scope-a"}) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=60), - ), - ), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - retry_base_seconds=60, - retry_jitter=lambda: 1, - ) - await supervisor.start() - - async def suffix_completed() -> bool: - async with profile.database.transaction() as connection: - cursor = await SourceCursorRepository().load(connection, "scope-b", BINDING) - return cursor is not None and cursor.cursor.sequence == 1 - - await _wait_until(suffix_completed) - await supervisor.close() - - assert [(item.scope_id, item.wave_kind) for item in launcher.assignments] == [ - ("scope-a", ArtifactProcessingWaveKind.AUTOMATIC), - ("scope-b", ArtifactProcessingWaveKind.AUTOMATIC), - ] - async with profile.database.transaction() as connection: - assert await pending.load(connection, "scope-a", BINDING) is not None - assert await pending.load(connection, "scope-b", BINDING) is not None - assert await states.load(connection, BINDING) is None - - asyncio.run(scenario()) - - -@pytest.mark.parametrize( - "outcome", - ( - ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT, - ArtifactProcessingWorkerOutcome.HEAD_CONFLICT, - ), -) -def test_automatic_control_conflict_is_quiet_and_does_not_starve_frozen_suffix( - tmp_path, - monkeypatch, - outcome, -) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 1) - monkeypatch.setattr( - "powercontext.builtin.runtime.artifact_processing._CONTROL_CONFLICT_RETRY_SECONDS", - 1.0, - ) - pending = ArtifactProcessingPendingRepository() - states = ArtifactProcessingBindingStateRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / f'automatic-{outcome}.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - async with profile.database.transaction() as connection: - await pending.raise_source(connection, "scope-a", BINDING, 1) - await pending.raise_source(connection, "scope-b", BINDING, 1) - launcher = _PublishingLauncher( - profile.database, - control_conflicts={"scope-a": outcome}, - ) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=60), - ), - ), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - ) - await supervisor.start() - - async def suffix_completed() -> bool: - async with profile.database.transaction() as connection: - cursor = await SourceCursorRepository().load(connection, "scope-b", BINDING) - return cursor is not None and cursor.cursor.sequence == 1 - - await _wait_until(suffix_completed) - first_key_attempts = sum(item.scope_id == "scope-a" for item in launcher.assignments) - await asyncio.sleep(0.05) - assert first_key_attempts == 1 - assert sum(item.scope_id == "scope-a" for item in launcher.assignments) == first_key_attempts - retry = supervisor._retries[(BINDING, "scope-a")] - assert retry.next_retry_at > asyncio.get_running_loop().time() - assert retry.consecutive_failures == 0 - await supervisor.close() - - assert [(item.scope_id, item.wave_kind) for item in launcher.assignments] == [ - ("scope-a", ArtifactProcessingWaveKind.AUTOMATIC), - ("scope-b", ArtifactProcessingWaveKind.AUTOMATIC), - ] - async with profile.database.transaction() as connection: - assert await pending.load(connection, "scope-a", BINDING) is not None - assert await pending.load(connection, "scope-b", BINDING) is not None - assert await states.load(connection, BINDING) is None - - asyncio.run(scenario()) - - -def test_hanging_launch_preserves_short_lease_and_bounds_discovery(tmp_path, monkeypatch) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 4) - pending = _TrackingPendingRepository() - launcher = _HangingStartLauncher() - leases = _RenewingLeaseRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'bounded-discovery.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - async with profile.database.transaction() as connection: - for index in range(12): - await pending.raise_source(connection, f"scope-{index:02d}", BINDING, 1) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=( - ArtifactProcessingBinding( - BINDING, - 1, - launcher, - automatic_processing_interval=timedelta(seconds=60), - ), - ), - lease_mode="oceanbase", - max_workers=1, - worker_timeout_seconds=0.08, - pending=pending, - leases=leases, - holder_id="holder-a", - oceanbase_tick_seconds=0.002, - oceanbase_lease_seconds=0.03, - retry_base_seconds=60, - retry_jitter=lambda: 1, - ) - await supervisor.start() - await asyncio.wait_for(launcher.started.wait(), timeout=1) - await asyncio.wait_for(leases.renewed.wait(), timeout=1) - await asyncio.wait_for(launcher.cancelled.wait(), timeout=1) - - async def launch_failure_recorded() -> bool: - return bool(supervisor._retries) - - await _wait_until(launch_failure_recorded) - assert leases.renew_count >= 2 - assert pending.scan_limits and all(limit is not None and limit <= 4 for limit in pending.scan_limits) - assert len(supervisor._work) <= 4 - assert len(supervisor._queue) <= 4 - wave = supervisor._automatic_waves[BINDING] - assert len(wave.targets) + len(wave.deferred_targets) == 4 - await asyncio.wait_for(supervisor.close(), timeout=0.2) - - asyncio.run(scenario()) - - -def test_full_discovery_budget_waits_for_worker_callback_without_spinning(tmp_path, monkeypatch) -> None: - async def scenario() -> None: - monkeypatch.setattr("powercontext.builtin.runtime.artifact_processing._DISCOVERY_PAGE_SIZE", 2) - release = asyncio.Event() - pending = ArtifactProcessingPendingRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'full-budget.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - for scope_id in ("scope-a", "scope-b"): - await _raise_and_flush(profile.database, pending, scope_id, 1) - launcher = _PublishingLauncher(profile.database, wait_for=release) - supervisor = _CycleCountingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, launcher),), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=60, - ) - await supervisor.start() - - async def first_worker_started() -> bool: - return len(launcher.assignments) == 1 - - await _wait_until(first_worker_started) - await asyncio.sleep(0.03) - settled_cycle_count = supervisor.cycle_count - await asyncio.sleep(0.03) - - assert supervisor.cycle_count - settled_cycle_count <= 1 - assert supervisor._next_discovery_wake_at is None - assert supervisor._next_wake_seconds() is None - release.set() - - async def all_work_completed() -> bool: - async with profile.database.transaction() as connection: - return await pending.scan(connection, binding_name=BINDING) == () - - await _wait_until(all_work_completed) - assert supervisor.cycle_count > settled_cycle_count - await supervisor.close() - - asyncio.run(scenario()) - - -def test_close_cancels_a_worker_launch_with_a_bounded_wait(tmp_path) -> None: - async def scenario() -> None: - pending = ArtifactProcessingPendingRepository() - launcher = _HangingStartLauncher() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'cancel-launch.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, "scope-a", 1) - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, launcher),), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=60, - ) - await supervisor.start() - await asyncio.wait_for(launcher.started.wait(), timeout=1) - await asyncio.wait_for(supervisor.close(), timeout=0.2) - assert launcher.cancelled.is_set() - - asyncio.run(scenario()) - - -def test_degraded_status_is_sticky_until_a_successful_control_cycle(tmp_path) -> None: - async def scenario() -> None: - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'sticky-degraded.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - supervisor = ArtifactProcessingSupervisor( - database=profile.database, - bindings=(), - lease_mode="oceanbase", - max_workers=1, - worker_timeout_seconds=1, - pending=_FailingPendingRepository(), - holder_id="holder-a", - oceanbase_tick_seconds=0.005, - oceanbase_lease_seconds=60, - ) - await supervisor.start() - assert supervisor.status is ArtifactProcessingSupervisorStatus.DEGRADED - await asyncio.sleep(0.03) - assert supervisor.status is ArtifactProcessingSupervisorStatus.DEGRADED - await supervisor.close() - - asyncio.run(scenario()) - - -def test_restart_increments_the_term_and_recovers_only_from_durable_state(tmp_path) -> None: - async def scenario() -> None: - pending = ArtifactProcessingPendingRepository() - config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'recovery.db'}") - async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, "scope-a", 1) - orphan = _HangingLauncher() - first = ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, orphan),), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=60, - ) - await first.start() - await asyncio.wait_for(orphan.started.wait(), timeout=1) - first_generation = first.fence.supervisor_generation if first.fence is not None else 0 - await first.close() - - recovered = _PublishingLauncher(profile.database) - async with ArtifactProcessingSupervisor( - database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, recovered),), - lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, - ) as second: - - async def completed() -> bool: - async with profile.database.transaction() as connection: - return await pending.load(connection, "scope-a", BINDING) is None - - await _wait_until(completed) - assert second.fence is not None - assert second.fence.supervisor_generation == first_generation + 1 - assert recovered.assignments[0].source_after == 0 - - asyncio.run(scenario()) - - def test_spawn_launcher_runs_a_real_child_process() -> None: async def scenario() -> None: assignment = ArtifactProcessingWorkAssignment( binding_name=BINDING, scope_id="scope-a", - source_after=0, - source_through=1, - wave_target=1, - claimed_flush_generation=1, - cursor_generation=None, - wave_kind=ArtifactProcessingWaveKind.EXPLICIT, + artifact_family="topic-memory", + claimed_request_generation=1, fence=ArtifactProcessingFence( supervisor_group="global", holder_id="holder-a", @@ -1453,17 +111,18 @@ async def scenario() -> None: def test_supervisor_close_kills_spawned_worker_and_stales_its_fence(tmp_path) -> None: async def scenario() -> None: ready = tmp_path / "worker-ready" - pending = ArtifactProcessingPendingRepository() config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'spawn-close.db'}") async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, str(ready), 1) + await _request(profile.database, str(ready)) launcher = _CapturingSpawnLauncher() supervisor = ArtifactProcessingSupervisor( database=profile.database, - bindings=(ArtifactProcessingBinding(BINDING, 1, launcher),), + bindings=( + ArtifactProcessingBinding( + BINDING, "topic-memory", launcher, max_workers=1, worker_timeout_seconds=60 + ), + ), lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=60, holder_id="holder-a", ) await supervisor.start() @@ -1490,12 +149,10 @@ async def child_is_ready() -> bool: database=profile.database, bindings=(), lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, holder_id="holder-b", ) as successor: assert successor.fence is not None - assert successor.fence.supervisor_generation == old_fence.supervisor_generation + 1 + assert successor.fence.supervisor_generation > old_fence.supervisor_generation async with profile.database.transaction() as connection: stale_fence_rejected = False try: @@ -1509,7 +166,6 @@ async def child_is_ready() -> bool: def test_supervisor_close_owns_cancelled_post_spawn_cleanup(tmp_path, monkeypatch) -> None: async def scenario() -> None: - pending = ArtifactProcessingPendingRepository() config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'spawn-cancel-close.db'}") spawned = threading.Event() release_start = threading.Event() @@ -1525,19 +181,19 @@ def stalled_launch(popen, process): monkeypatch.setattr(artifact_processing_module._OwnedSpawnPopen, "_launch", stalled_launch) async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, "scope-a", 1) + await _request(profile.database, str(tmp_path / "worker-ready")) supervisor = ArtifactProcessingSupervisor( database=profile.database, bindings=( ArtifactProcessingBinding( BINDING, - 1, + "topic-memory", SpawnArtifactProcessingWorkerLauncher(_ignore_sigterm), + max_workers=1, + worker_timeout_seconds=60, ), ), lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=60, holder_id="holder-a", ) await supervisor.start() @@ -1564,12 +220,10 @@ def stalled_launch(popen, process): database=profile.database, bindings=(), lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, holder_id="holder-b", ) as successor: assert successor.fence is not None - assert successor.fence.supervisor_generation == old_fence.supervisor_generation + 1 + assert successor.fence.supervisor_generation > old_fence.supervisor_generation async with profile.database.transaction() as connection: with pytest.raises(ArtifactProcessingLeadershipLostError): await ArtifactProcessingLeaseRepository().require_fence(connection, old_fence) @@ -1579,7 +233,6 @@ def stalled_launch(popen, process): def test_supervisor_close_waits_for_cleanup_after_worker_start_timeout(tmp_path, monkeypatch) -> None: async def scenario() -> None: - pending = ArtifactProcessingPendingRepository() config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'spawn-timeout-close.db'}") ready = tmp_path / "worker-ready" spawned = threading.Event() @@ -1609,19 +262,19 @@ def stalled_launch(popen, process): monkeypatch.setattr(type(spawn_context), "Pipe", tracking_pipe) monkeypatch.setattr(artifact_processing_module._OwnedSpawnPopen, "_launch", stalled_launch) async with SQLiteProfile.open(config, tables=SHARED_TABLES) as profile: - await _raise_and_flush(profile.database, pending, str(ready), 1) + await _request(profile.database, str(ready)) supervisor = ArtifactProcessingSupervisor( database=profile.database, bindings=( ArtifactProcessingBinding( BINDING, - 1, + "topic-memory", SpawnArtifactProcessingWorkerLauncher(_ignore_sigterm), + max_workers=1, + worker_timeout_seconds=0.05, ), ), lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=0.05, holder_id="holder-a", ) await supervisor.start() @@ -1662,12 +315,10 @@ async def cleanup_started() -> bool: database=profile.database, bindings=(), lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=1, holder_id="holder-b", ) as successor: assert successor.fence is not None - assert successor.fence.supervisor_generation == old_fence.supervisor_generation + 1 + assert successor.fence.supervisor_generation > old_fence.supervisor_generation async with profile.database.transaction() as connection: with pytest.raises(ArtifactProcessingLeadershipLostError): await ArtifactProcessingLeaseRepository().require_fence(connection, old_fence) @@ -1701,12 +352,8 @@ def failing_launch(popen, process): assignment = ArtifactProcessingWorkAssignment( binding_name=BINDING, scope_id=str(ready), - source_after=0, - source_through=1, - wave_target=1, - claimed_flush_generation=1, - cursor_generation=None, - wave_kind=ArtifactProcessingWaveKind.EXPLICIT, + artifact_family="topic-memory", + claimed_request_generation=1, fence=ArtifactProcessingFence( supervisor_group="global", holder_id="holder-a", diff --git a/tests/builtin/runtime/test_artifact_processing_config.py b/tests/builtin/runtime/test_artifact_processing_config.py index 6f862052b2..07f4d16a77 100644 --- a/tests/builtin/runtime/test_artifact_processing_config.py +++ b/tests/builtin/runtime/test_artifact_processing_config.py @@ -104,12 +104,12 @@ def test_artifact_processing_configuration_rejects_invalid_bounds() -> None: ), ], ) -def test_split_roles_reject_legacy_scheduler_intervals(runtime_values: dict[str, object]) -> None: - with pytest.raises(ValidationError, match="require artifact_processing_role='all'"): - RuntimeConfig.model_validate(runtime_values) +def test_split_roles_accept_migrated_family_schedules(runtime_values: dict[str, object]) -> None: + runtime = RuntimeConfig.model_validate(runtime_values) + assert runtime.artifact_processing_role == runtime_values["artifact_processing_role"] -def test_all_role_remains_the_legacy_scheduler_owner() -> None: +def test_all_role_preserves_schedule_alias_values() -> None: runtime = RuntimeConfig( artifact_processing_role="all", schedule_seconds=30, @@ -193,7 +193,7 @@ def test_server_cli_routes_background_role_without_starting_http(monkeypatch) -> tracing.shutdown.assert_called_once() -def test_server_cli_rejects_split_role_with_a_legacy_scheduler(monkeypatch) -> None: +def test_server_cli_routes_split_role_with_a_migrated_schedule(monkeypatch) -> None: for name in tuple(os.environ): if name.startswith("POWERCONTEXT_SERVER_"): monkeypatch.delenv(name, raising=False) @@ -201,8 +201,49 @@ def test_server_cli_rejects_split_role_with_a_legacy_scheduler(monkeypatch) -> N monkeypatch.setenv("POWERCONTEXT_SERVER_DATABASE_URL", OCEANBASE_URL) monkeypatch.setenv("POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS", "30") + run_background = Mock() + monkeypatch.setattr("powercontext.server.cli._run_background", run_background) result = CliRunner().invoke(create_cli([server_app]), ["server", "run", "--role", "background"]) - assert result.exit_code == 2 - assert "schedule_seconds" in result.output - assert "artifact_processing_role" in result.output + assert result.exit_code == 0, result.output + assert run_background.call_args.args[0].runtime.memory_schedule_seconds == 30 + + +@pytest.mark.parametrize( + "old,new", + [ + ("schedule_seconds", "memory_schedule_seconds"), + ("profile_max_concurrency", "profile_max_workers"), + ("artifact_processing_max_workers", "topic_memory_max_workers"), + ("artifact_processing_worker_timeout_seconds", "topic_memory_worker_timeout_seconds"), + ], +) +def test_processing_aliases_accept_equivalent_values_and_reject_conflicts(old, new): + assert getattr(RuntimeConfig.model_validate({old: "12", new: 12.0}), new) == 12 + assert getattr(RuntimeConfig.model_validate({new: 12}), old) == 12 + with pytest.raises(ValidationError, match="conflicting artifact processing"): + RuntimeConfig.model_validate({old: 12, new: 13}) + + +@pytest.mark.parametrize( + "field", ["memory_max_workers", "topic_memory_max_workers", "experience_max_workers", "profile_max_workers"] +) +@pytest.mark.parametrize("value", [0, -1, 1.5, True]) +def test_each_family_requires_positive_integer_quota(field, value): + with pytest.raises(ValidationError): + RuntimeConfig.model_validate({field: value}) + + +def test_api_can_declare_topic_processing_without_inference_credentials(): + config = BuiltinConfig( + database=OceanBaseConfig(url=SecretStr(OCEANBASE_URL)), + runtime=RuntimeConfig(artifact_processing_role="api", artifact_processing_families=("topic-memory",)), + ) + assert _topic_memory_processing_available(config, ()) + + +def test_unknown_processing_mode_and_unregistered_schedule_fields_rejected(): + with pytest.raises(ValidationError): + RuntimeConfig.model_validate({"artifact_processing_supervisor_mode": "custom"}) + with pytest.raises(ValidationError): + RuntimeConfig.model_validate({"skill_schedule_seconds": 10}) diff --git a/tests/builtin/runtime/test_family_processing.py b/tests/builtin/runtime/test_family_processing.py new file mode 100644 index 0000000000..d0f6a30ab1 --- /dev/null +++ b/tests/builtin/runtime/test_family_processing.py @@ -0,0 +1,353 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Scope completion must agree with domain progress and Server ownership.""" + +from __future__ import annotations + +import asyncio +from dataclasses import replace +from functools import partial + +import pytest +from sqlalchemy import func, select + +from powercontext.builtin.artifacts.experience import ExperienceCandidateInput, ExperienceContent +from powercontext.builtin.artifacts.memory import MemoryEntryInput +from powercontext.builtin.inference.models import GenerationResult, InferenceUsage +from powercontext.builtin.inference.usage import UsageReportingStructuredGenerator +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.processing_migration import bootstrap_processing_schema +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import ( + ARTIFACT_CANDIDATE_HEADS_TABLE, + ARTIFACT_HEADS_TABLE, + BUILTIN_TABLES, + MODEL_USAGE_DAILY_TABLE, +) +from powercontext.builtin.runtime.artifact_processing import SpawnArtifactProcessingWorkerLauncher +from powercontext.builtin.runtime.composition import open_builtin_contexts +from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig, RuntimeConfig +from powercontext.builtin.runtime.family_processing import ( + FAMILY_BINDINGS, + FamilyWorkerSpec, + process_family_invocation, + run_family_worker, +) +from powercontext.builtin.runtime.processing_contracts import ( + ArtifactProcessingWorkAssignment, + ArtifactProcessingWorkerOutcome, +) +from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest +from powercontext.builtin.runtime.relational import RelationalContexts +from powercontext.builtin.scope import ScopeDraft +from powercontext.builtin.sources import SourceCursor +from powercontext.server.authz import AccessDeniedError, PrincipalRef +from powercontext.server.authz.repository import ACCESS_OWNERS_TABLE, ACCESS_TABLES +from powercontext.server.processing_security import WorkerSecuritySpec, open_worker_security +from powercontext.sources import SourceRef + + +def _open_sqlite(config: BuiltinConfig, *, tables): + assert isinstance(config.database, SQLiteConfig) + return SQLiteProfile.open(config.database, tables=tables) + + +class MemoryPipeline: + async def extract(self, request): + return tuple( + MemoryEntryInput(kind="fact", text=source.content, sources=(source,)) for source in request.sources + ) + + +class ExperiencePipeline: + async def incubate(self, sources): + return tuple( + ExperienceCandidateInput( + proposal=ExperienceContent( + situation="Configuration", action="Test", outcome=source.content, lesson="Verify" + ), + sources=(SourceRef(source_type="content", source_id=source.name),), + ) + for source in sources + ) + + +class ProfileGenerator: + async def generate(self, value): + return "# Preferences\n\nVerify every change." + + +async def prepare(profile, family): + contexts = RelationalContexts( + database=profile.database, candidate_pipeline=MemoryPipeline(), experience_pipeline=ExperiencePipeline() + ) + contexts.profiles.generator = ProfileGenerator() + scope = ( + await contexts.scopes.create(ScopeDraft(title="Worker", summary="Worker", idempotency_key="worker")) + ).scope_id + await contexts.records.create_source(scope, "content", "Run the configuration tests.") + if family == "profile": + await contexts.profiles.put_policy(scope, generation_enabled=True, expected_version=0) + async with profile.database.transaction() as connection: + lease = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "worker-test") + intent = await ArtifactProcessingIntentRepository().request(connection, scope, FAMILY_BINDINGS[family]) + assignment = ArtifactProcessingWorkAssignment( + binding_name=FAMILY_BINDINGS[family], + scope_id=scope, + artifact_family=family, + claimed_request_generation=intent.requested_generation, + fence=lease.fence("single-process"), + worker_id="worker-1", + ) + return contexts, assignment + + +def security_spec(*, allowed=True): + return WorkerSecuritySpec( + principal=PrincipalRef(type="service", id="worker-test"), + deployment_id="test", + static_preset=allowed, + ).model_dump(mode="json") + + +@pytest.mark.parametrize("family", ["memory", "experience", "profile"]) +def test_owner_failure_rolls_back_domain_cursor_and_ack_then_retry_owns_result(tmp_path, family): + async def scenario(): + config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'atomic.db'}")) + async with _open_sqlite(config, tables=(*BUILTIN_TABLES, *ACCESS_TABLES)) as profile: + contexts, assignment = await prepare(profile, family) + async with open_worker_security(security_spec(), profile.database) as security: + assert security is not None + hook_name = f"{family}_commit" + original = getattr(security, hook_name) + + async def failed_commit(*args, **kwargs): + await original(*args, **kwargs) + raise OSError("injected ownership failure") # noqa: TRY003 + + setattr(security, hook_name, failed_commit) + with pytest.raises(OSError, match="ownership failure"): + await process_family_invocation(contexts, assignment, config=config, security=security) + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load( + connection, assignment.scope_id, assignment.binding_name + ) + intent = await ArtifactProcessingIntentRepository().load( + connection, assignment.scope_id, assignment.binding_name + ) + assert cursor is None + assert intent is not None and intent.handled_generation == 0 + for table in (ARTIFACT_HEADS_TABLE, ARTIFACT_CANDIDATE_HEADS_TABLE, ACCESS_OWNERS_TABLE): + assert await connection.scalar(select(func.count()).select_from(table)) == 0 + setattr(security, hook_name, original) + result = await process_family_invocation(contexts, assignment, config=config, security=security) + assert result.outcome == ArtifactProcessingWorkerOutcome.SUCCEEDED + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load( + connection, assignment.scope_id, assignment.binding_name + ) + intent = await ArtifactProcessingIntentRepository().load( + connection, assignment.scope_id, assignment.binding_name + ) + assert cursor is not None and cursor.cursor.sequence == 1 + assert intent is not None and intent.handled_generation == assignment.claimed_request_generation + assert await connection.scalar(select(func.count()).select_from(ACCESS_OWNERS_TABLE)) == 1 + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("family", ["memory", "experience", "profile"]) +def test_denied_scope_preserves_request_and_source_progress(tmp_path, family): + async def scenario(): + config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'denied.db'}")) + async with _open_sqlite(config, tables=(*BUILTIN_TABLES, *ACCESS_TABLES)) as profile: + contexts, assignment = await prepare(profile, family) + async with open_worker_security(security_spec(allowed=False), profile.database) as security: + with pytest.raises(AccessDeniedError): + await process_family_invocation(contexts, assignment, config=config, security=security) + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, assignment.scope_id, assignment.binding_name) + intent = await ArtifactProcessingIntentRepository().load( + connection, assignment.scope_id, assignment.binding_name + ) + assert cursor is None + assert intent is not None and intent.handled_generation == 0 + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("family", ["memory", "experience"]) +def test_worker_records_existing_model_usage_purposes_and_replay_does_not_infer(tmp_path, monkeypatch, family): + class Generator: + async def generate(self, _value): + return GenerationResult(output=None, usage=InferenceUsage(requests=1, input_tokens=3, output_tokens=2)) + + pipeline = MemoryPipeline if family == "memory" else ExperiencePipeline + method = "extract" if family == "memory" else "incubate" + original = getattr(pipeline, method) + + async def generated(self, value): + await UsageReportingStructuredGenerator(Generator()).generate(None) + return await original(self, value) + + monkeypatch.setattr(pipeline, method, generated) + + async def scenario(): + config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'usage.db'}")) + async with _open_sqlite(config, tables=BUILTIN_TABLES) as profile: + contexts, assignment = await prepare(profile, family) + await process_family_invocation(contexts, assignment, config=config) + await process_family_invocation(contexts, assignment, config=config) + async with profile.database.transaction() as connection: + row = (await connection.execute(select(MODEL_USAGE_DAILY_TABLE))).mappings().one() + assert row["scope_id"] == assignment.scope_id + assert row["purpose"] == ("memory_extraction" if family == "memory" else "experience_generation") + assert row["operation"] == "generation" + assert row["requests"] == 1 + + asyncio.run(scenario()) + + +def test_completed_memory_generation_does_not_consume_new_input_and_new_trigger_remains(tmp_path): + async def scenario(): + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'replay.db'}"), + runtime=RuntimeConfig(source_window_limit=1), + ) + async with _open_sqlite(config, tables=BUILTIN_TABLES) as profile: + contexts, assignment = await prepare(profile, "memory") + await contexts.records.create_source(assignment.scope_id, "content", "Second input.") + await process_family_invocation(contexts, assignment, config=config) + await process_family_invocation(contexts, assignment, config=config) + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, assignment.scope_id, assignment.binding_name) + intent = await ArtifactProcessingIntentRepository().load( + connection, assignment.scope_id, assignment.binding_name + ) + assert cursor is not None and cursor.cursor.sequence == 1 + assert intent is not None and intent.dirty_generation > intent.clean_generation + request = await ArtifactProcessingIntentRepository().request( + connection, assignment.scope_id, assignment.binding_name + ) + await process_family_invocation( + contexts, replace(assignment, claimed_request_generation=request.requested_generation), config=config + ) + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, assignment.scope_id, assignment.binding_name) + assert cursor is not None and cursor.cursor.sequence == 2 + + asyncio.run(scenario()) + + +def test_profile_candidate_success_and_pending_noop_never_advance_review_cursor(tmp_path): + async def scenario(): + config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'profile.db'}")) + async with _open_sqlite(config, tables=BUILTIN_TABLES) as profile: + contexts, assignment = await prepare(profile, "profile") + policy = await contexts.profiles.get_policy(assignment.scope_id) + await contexts.profiles.put_policy( + assignment.scope_id, + generation_enabled=True, + activation_mode="review_required", + expected_version=policy.version, + ) + assert (await process_family_invocation(contexts, assignment, config=config)).outcome == "succeeded" + pending = (await contexts.profiles.get_policy(assignment.scope_id)).pending_candidate_id + assert pending is not None + async with profile.database.transaction() as connection: + request = await ArtifactProcessingIntentRepository().request( + connection, assignment.scope_id, assignment.binding_name + ) + successor = replace(assignment, claimed_request_generation=request.requested_generation) + assert (await process_family_invocation(contexts, successor, config=config)).outcome == "succeeded" + assert (await contexts.profiles.get_policy(assignment.scope_id)).pending_candidate_id == pending + async with profile.database.transaction() as connection: + assert ( + await SourceCursorRepository().load(connection, assignment.scope_id, assignment.binding_name) + is None + ) + intent = await ArtifactProcessingIntentRepository().load( + connection, assignment.scope_id, assignment.binding_name + ) + assert intent is not None and intent.handled_generation == successor.claimed_request_generation + assert intent.dirty_generation > intent.clean_generation + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("family", ["memory", "experience", "profile"]) +def test_spawned_family_restores_trusted_identity_and_persists_noop_ack(tmp_path, family): + async def scenario(): + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'spawn.db'}"), + inference=InferenceConfig(generation_model="test"), + ) + async with open_builtin_contexts(config): + pass + async with _open_sqlite(config, tables=(*BUILTIN_TABLES, *ACCESS_TABLES)) as profile: + async with profile.database.transaction() as connection: + await bootstrap_processing_schema(connection, canonical_processing_manifest(config)) + _, assignment = await prepare(profile, family) + async with profile.database.transaction() as connection: + await SourceCursorRepository().save( + connection, + assignment.scope_id, + assignment.binding_name, + SourceCursor(sequence=1), + expected_generation=None, + ) + spec = FamilyWorkerSpec(config=config, worker_security=security_spec()) + launcher = SpawnArtifactProcessingWorkerLauncher(partial(run_family_worker, spec)) + worker = await launcher.start(assignment) + try: + result = await asyncio.wait_for(worker.wait(), timeout=30) + assert result.outcome == "succeeded" + finally: + await worker.terminate() + async with profile.database.transaction() as connection: + intent = await ArtifactProcessingIntentRepository().load( + connection, assignment.scope_id, assignment.binding_name + ) + assert intent is not None and intent.handled_generation == assignment.claimed_request_generation + assert intent.clean_generation == intent.dirty_generation + + asyncio.run(scenario()) + + +def test_dedicated_fence_cannot_commit_another_family(tmp_path): + async def scenario(): + config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'wrong-family.db'}")) + async with _open_sqlite(config, tables=BUILTIN_TABLES) as profile: + contexts, assignment = await prepare(profile, "memory") + async with profile.database.transaction() as connection: + lease = await ArtifactProcessingLeaseRepository().start_single_process_term( + connection, "profile-worker", supervisor_group="artifact:profile" + ) + wrong = replace(assignment, fence=lease.fence("single-process")) + with pytest.raises(ValueError, match="another Family"): + await process_family_invocation(contexts, wrong, config=config) + async with profile.database.transaction() as connection: + assert ( + await SourceCursorRepository().load(connection, assignment.scope_id, assignment.binding_name) + is None + ) + intent = await ArtifactProcessingIntentRepository().load( + connection, assignment.scope_id, assignment.binding_name + ) + assert intent is not None and intent.handled_generation == 0 + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_processing_composition.py b/tests/builtin/runtime/test_processing_composition.py new file mode 100644 index 0000000000..6d4199a7d9 --- /dev/null +++ b/tests/builtin/runtime/test_processing_composition.py @@ -0,0 +1,277 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +from contextlib import asynccontextmanager +from pathlib import Path +from types import SimpleNamespace +from typing import Literal, cast +from unittest.mock import AsyncMock + +import pytest +from pydantic import SecretStr +from sqlalchemy import insert, select + +from powercontext.builtin.persistence.oceanbase import OceanBaseConfig +from powercontext.builtin.persistence.processing_migration import ( + ProcessingSchemaNotReadyError, + apply_processing_migration, +) +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.supervision import ArtifactProcessingFence +from powercontext.builtin.persistence.tables import ( + ARTIFACT_PROCESSING_PENDING_TABLE, + ARTIFACT_PROCESSING_SCHEMA_TABLE, + SHARED_TABLES, + SOURCE_JOURNAL_HEADS_TABLE, +) +from powercontext.builtin.runtime import BuiltinConfig, InferenceConfig, RuntimeConfig, composition +from powercontext.builtin.runtime.artifact_processing import ( + ArtifactProcessingBinding, + ArtifactProcessingSupervisorStatus, +) +from powercontext.builtin.runtime.composition import ( + BuiltinConfigurationError, + open_builtin_contexts, + open_builtin_runtime, +) +from powercontext.builtin.runtime.family_processing import FamilyWorkerSpec, run_family_worker +from powercontext.builtin.runtime.processing_contracts import ArtifactProcessingWorkAssignment +from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest +from powercontext.builtin.runtime.relational import RelationalContexts +from powercontext.builtin.runtime.topic_memory_processing import TopicMemoryWorkerSpec, run_topic_memory_worker + +_FAMILIES = {"memory", "topic-memory", "experience", "profile"} +_BINDING = "topic-memory-source-window" +_OCEANBASE = OceanBaseConfig( + url=SecretStr("mysql+aoceanbase://root%40test@127.0.0.1:2881/composition_unused?charset=utf8mb4") +) + + +def _sqlite(path: Path) -> SQLiteConfig: + return SQLiteConfig(url=f"sqlite+aiosqlite:///{path}") + + +async def _seed_partial_migration(config: BuiltinConfig) -> None: + assert isinstance(config.database, SQLiteConfig) + async with ( + SQLiteProfile.open(config.database, tables=SHARED_TABLES) as profile, + profile.database.transaction() as connection, + ): + progress = await apply_processing_migration(connection, config_manifest=canonical_processing_manifest(config)) + assert not progress.complete + + +def _assignment(family: str) -> ArtifactProcessingWorkAssignment: + bindings = canonical_processing_manifest(BuiltinConfig())["bindings"] + return ArtifactProcessingWorkAssignment( + binding_name=next(binding for binding, value in bindings.items() if value == family), + scope_id="project", + artifact_family=family, + claimed_request_generation=1, + fence=ArtifactProcessingFence( + supervisor_group="global", holder_id="stopped-parent", supervisor_generation=1, lease_mode="single-process" + ), + worker_id="composition-worker", + ) + + +def test_fresh_sqlite_bootstraps_and_reopens_after_business_data_is_written(tmp_path: Path) -> None: + async def scenario() -> None: + config = BuiltinConfig(database=_sqlite(tmp_path / "fresh.db")) + async with open_builtin_contexts(config) as contexts, contexts.database.transaction() as connection: + marker = (await connection.execute(select(ARTIFACT_PROCESSING_SCHEMA_TABLE))).mappings().one() + assert marker["phase"] == "complete" + assert marker["migration_id"] == "fresh" + await connection.execute(insert(SOURCE_JOURNAL_HEADS_TABLE).values(scope_id="project", position=1)) + async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + assert runtime.artifact_processing_supervisor is None + + asyncio.run(scenario()) + + +def test_nonempty_legacy_sqlite_is_rejected_without_importing_or_discarding_work(tmp_path: Path) -> None: + async def scenario() -> None: + database = _sqlite(tmp_path / "legacy.db") + async with ( + SQLiteProfile.open(database, tables=SHARED_TABLES) as profile, + profile.database.transaction() as connection, + ): + await connection.execute(insert(SOURCE_JOURNAL_HEADS_TABLE).values(scope_id="project", position=2)) + await connection.execute( + insert(ARTIFACT_PROCESSING_PENDING_TABLE).values( + binding_name=_BINDING, scope_id="project", source_through=2, flush_generation=1 + ) + ) + with pytest.raises(ProcessingSchemaNotReadyError, match="offline processing migration"): + async with open_builtin_runtime(BuiltinConfig(database=database), scheduler_path=tmp_path / "scheduler.db"): + pytest.fail("legacy work must not be accepted as a fresh database") + async with ( + SQLiteProfile.open(database, tables=SHARED_TABLES) as profile, + profile.database.transaction() as connection, + ): + assert await connection.scalar(select(ARTIFACT_PROCESSING_SCHEMA_TABLE.c.singleton)) is None + pending = (await connection.execute(select(ARTIFACT_PROCESSING_PENDING_TABLE))).mappings().one() + assert pending["source_through"] == 2 + assert pending["flush_generation"] == 1 + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("role", ["api", "background"]) +def test_partial_migration_refuses_split_role_startup( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, role: Literal["api", "background"] +) -> None: + async def scenario() -> None: + database = _sqlite(tmp_path / "partial.db") + await _seed_partial_migration(BuiltinConfig(database=database)) + + # Exercise the OceanBase role's real startup gate against a real SQLite + # transaction. A failed gate must run before dialect-specific indexes. + @asynccontextmanager + async def local_profile(_config, *, tables): + async with SQLiteProfile.open(database, tables=tables) as profile: + yield profile + + monkeypatch.setattr(composition.OceanBaseProfile, "open", local_profile) + config = BuiltinConfig(database=_OCEANBASE, runtime=RuntimeConfig(artifact_processing_role=role)) + with pytest.raises(ProcessingSchemaNotReadyError, match="not ready"): + async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db"): + pytest.fail("split-role startup must reject a partial migration") + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("family", sorted(_FAMILIES)) +def test_partial_migration_refuses_each_worker_entrypoint(tmp_path: Path, family: str) -> None: + config = BuiltinConfig( + database=_sqlite(tmp_path / "partial-worker.db"), inference=InferenceConfig(generation_model="test") + ) + asyncio.run(_seed_partial_migration(config)) + with pytest.raises(ProcessingSchemaNotReadyError, match="not ready"): + if family == "topic-memory": + run_topic_memory_worker(TopicMemoryWorkerSpec(config=config), _assignment(family)) + else: + run_family_worker(FamilyWorkerSpec(config=config), _assignment(family)) + + +@pytest.mark.parametrize("change", ["mode", "capabilities"]) +def test_startup_rejects_a_different_completed_deployment_manifest(tmp_path: Path, change: str) -> None: + async def scenario() -> None: + config = BuiltinConfig( + database=_sqlite(tmp_path / "identity.db"), inference=InferenceConfig(generation_model="test") + ) + async with open_builtin_contexts(config): + pass + settings = ( + RuntimeConfig(artifact_processing_supervisor_mode="dedicated") + if change == "mode" + else RuntimeConfig(artifact_processing_families=("memory",)) + ) + changed = config.model_copy(update={"runtime": settings}) + with pytest.raises(ProcessingSchemaNotReadyError, match="completed maintenance manifest"): + async with open_builtin_runtime(changed, scheduler_path=tmp_path / "scheduler.db"): + pytest.fail("ownership identity changes require explicit maintenance") + + asyncio.run(scenario()) + + +def test_schedule_and_worker_budgets_can_change_without_maintenance(tmp_path: Path) -> None: + async def scenario() -> None: + config = BuiltinConfig( + database=_sqlite(tmp_path / "budget.db"), inference=InferenceConfig(generation_model="test") + ) + async with open_builtin_contexts(config): + pass + changed = config.model_copy( + update={ + "runtime": RuntimeConfig( + memory_schedule_seconds=90, memory_max_workers=2, memory_worker_timeout_seconds=120 + ) + } + ) + async with open_builtin_contexts(changed): + pass + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("role", ["all", "api"]) +@pytest.mark.parametrize("duplicate", ["binding_name", "artifact_family", "config_prefix"]) +def test_duplicate_custom_registration_is_rejected_for_every_role(role: Literal["all", "api"], duplicate: str) -> None: + first = ArtifactProcessingBinding( + binding_name="custom-first", artifact_family="custom-first", config_prefix="CUSTOM_FIRST", launcher=AsyncMock() + ) + second = ArtifactProcessingBinding( + binding_name=first.binding_name if duplicate == "binding_name" else "custom-second", + artifact_family=first.artifact_family if duplicate == "artifact_family" else "custom-second", + config_prefix=first.config_prefix if duplicate == "config_prefix" else "CUSTOM_SECOND", + launcher=AsyncMock(), + ) + config = BuiltinConfig(database=_OCEANBASE, runtime=RuntimeConfig(artifact_processing_role=role)) + with pytest.raises(BuiltinConfigurationError, match="one matching registration"): + composition._artifact_processing_bindings(config, cast(RelationalContexts, SimpleNamespace()), (first, second)) + + +def test_api_can_declare_topic_processing_without_constructing_models_or_controllers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def scenario() -> None: + model_opener = AsyncMock(side_effect=AssertionError("API attempted to construct an inference model")) + monkeypatch.setattr(composition, "_open_pydantic_ai_model", model_opener) + config = BuiltinConfig( + database=_OCEANBASE, + runtime=RuntimeConfig(artifact_processing_role="api", artifact_processing_families=("topic-memory",)), + ) + contexts = cast(RelationalContexts, SimpleNamespace()) + await composition.preflight_builtin_runtime(config) + bindings = composition._artifact_processing_bindings(config, contexts, ()) + assert not bindings + assert composition._topic_memory_processing_available(config, bindings) + async with composition._open_artifact_processing_supervisor(config, contexts, bindings) as controllers: + assert controllers is None + model_opener.assert_not_called() + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("mode", ["global", "dedicated"]) +def test_composition_opens_one_global_or_four_dedicated_controllers( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: Literal["global", "dedicated"] +) -> None: + async def scenario() -> None: + launch = AsyncMock(side_effect=AssertionError("an empty deployment must not start a worker")) + monkeypatch.setattr(composition.SpawnArtifactProcessingWorkerLauncher, "start", launch) + config = BuiltinConfig( + database=_sqlite(tmp_path / "controllers.db"), + inference=InferenceConfig(generation_model="test"), + runtime=RuntimeConfig(artifact_processing_supervisor_mode=mode), + ) + async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + group = runtime.artifact_processing_supervisor + assert group is not None + assert group.status == ArtifactProcessingSupervisorStatus.LEADER + assert set(group.family_status) == _FAMILIES + assert len(group.supervisors) == (1 if mode == "global" else 4) + fences = [controller.fence for controller in group.supervisors] + assert all(fence is not None for fence in fences) + assert {fence.supervisor_group for fence in fences if fence is not None} == ( + {"global"} if mode == "global" else {f"artifact:{family}" for family in _FAMILIES} + ) + assert all(status["used_workers"] == 0 for status in group.family_status.values()) + launch.assert_not_called() + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_processing_scan_rollback.py b/tests/builtin/runtime/test_processing_scan_rollback.py new file mode 100644 index 0000000000..35e69ff0eb --- /dev/null +++ b/tests/builtin/runtime/test_processing_scan_rollback.py @@ -0,0 +1,211 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +from datetime import timedelta + +import pytest +from sqlalchemy import event + +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.supervision import ArtifactProcessingBindingStateRepository +from powercontext.builtin.runtime import artifact_processing as processing +from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingBinding, ArtifactProcessingSupervisor +from tests.builtin.runtime.test_processing_scheduler import _intent, _Launcher, _profile, _request + + +class _InjectedRollback(Exception): + pass + + +class _FailingIntents(ArtifactProcessingIntentRepository): + boundary: str | None = None + + async def admit(self, connection, scope_id, binding_name, scan_generation, /): + result = await super().admit(connection, scope_id, binding_name, scan_generation) + if self.boundary is not None and scope_id in {"b", "d"}: + boundary, self.boundary = self.boundary, None + if boundary == "cancel": + raise asyncio.CancelledError + raise _InjectedRollback + return result + + +class _FailingBindingStates(ArtifactProcessingBindingStateRepository): + fail_finish = False + + async def finish_scan(self, connection, binding_name, /): + await super().finish_scan(connection, binding_name) + if self.fail_finish: + self.fail_finish = False + raise _InjectedRollback + + +@pytest.mark.parametrize("boundary", ["start", "eligibility", "admit", "finish", "commit", "cancel"]) +def test_automatic_page_rollback_retains_frontier_and_resumes_same_scan(tmp_path, monkeypatch, boundary): # noqa: C901 + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 2) + + async def scenario(): # noqa: C901 - exercise transaction failure boundaries + async with _profile(tmp_path, "scan-rollback") as profile: + scopes = ("a", "b", "c", "d", "e") + for scope in scopes: + await _request(profile.database, "memory-binding", scope, requested=False) + intents = _FailingIntents() + states = _FailingBindingStates() + launcher = _Launcher(profile.database) + fail_eligibility = False + + async def eligible_scopes(connection, scopes): + nonlocal fail_eligibility + if fail_eligibility: + fail_eligibility = False + raise _InjectedRollback + return frozenset(scopes) + + supervisor = ArtifactProcessingSupervisor( + database=profile.database, + bindings=( + ArtifactProcessingBinding( + "memory-binding", + "memory", + launcher, + max_workers=2, + automatic_processing_interval=timedelta(days=30), + automatic_scope_filter=eligible_scopes, + ), + ), + lease_mode="single-process", + intents=intents, + binding_states=states, + ) + await supervisor._acquire() + state = supervisor._families["memory-binding"] + + async def persisted(): + async with profile.database.transaction() as connection: + return await states.load(connection, "memory-binding") + + async def page_and_dispatch(): + await supervisor._discover_automatic(state) + await supervisor._dispatch(state) + await asyncio.gather(*(running.task for running in state.running.values())) + await supervisor._reap(state) + + def frontier(): + return ( + state.scan_after, + state.scan_generation, + state.scan_in_progress, + state.next_schedule_at, + state.next_discovery_at, + tuple(state.ready), + frozenset(state.queued), + ) + + try: + # Leave a durable in-progress generation with a successfully + # committed prefix. The final-page case fails while finishing it. + for _ in range(0 if boundary == "start" else 2 if boundary == "finish" else 1): + await page_and_dispatch() + before = frontier() + persisted_before = await persisted() + rows_before = [await _intent(profile.database, "memory-binding", scope) for scope in scopes] + if boundary in {"start", "admit", "cancel"}: + intents.boundary = boundary + elif boundary == "eligibility": + fail_eligibility = True + elif boundary == "finish": + states.fail_finish = True + + def fail_commit(_connection): + raise _InjectedRollback + + if boundary == "commit": + event.listen(profile.database.engine.sync_engine, "commit", fail_commit, once=True) + try: + with pytest.raises(asyncio.CancelledError if boundary == "cancel" else _InjectedRollback): + await supervisor._discover_automatic(state) + finally: + if boundary == "commit": + event.remove(profile.database.engine.sync_engine, "commit", fail_commit) + assert frontier() == before + assert await persisted() == persisted_before + assert [await _intent(profile.database, "memory-binding", scope) for scope in scopes] == rows_before + + # A later registration cannot extend a scan whose finite upper + # bound already committed before the failed page. + if persisted_before is not None: + await _request(profile.database, "memory-binding", "late", requested=False) + for _ in range(4): + await page_and_dispatch() + saved = await persisted() + if saved is not None and not saved.scan_in_progress: + break + assert saved is not None and not saved.scan_in_progress and saved.scan_generation == 1 + if persisted_before is not None: + assert saved.last_schedule_checkpoint_at == persisted_before.last_schedule_checkpoint_at + assert (await _intent(profile.database, "memory-binding", "late")).requested_generation == 0 + assert supervisor.family_status["memory"]["completed"] == len(scopes) + assert [work.scope_id for work in launcher.assignments] == list(scopes) + for scope in scopes: + row = await _intent(profile.database, "memory-binding", scope) + assert row.requested_generation == row.handled_generation == row.last_auto_scan_generation == 1 + assert state.next_schedule_at is not None + assert state.next_schedule_at > asyncio.get_running_loop().time() + 29 * 86400 + finally: + await supervisor._lose_leadership() + + asyncio.run(scenario()) + + +def test_failed_admission_recovers_in_running_supervisor_without_waiting_for_next_interval(tmp_path, monkeypatch): + from tests.builtin.runtime.test_processing_scheduler import _wait, _wait_scan_finished + + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 2) + + async def scenario(): + async with _profile(tmp_path, "live-scan-rollback") as profile: + for scope in ("a", "b", "c", "d", "e"): + await _request(profile.database, "memory-binding", scope, requested=False) + states = ArtifactProcessingBindingStateRepository() + async with profile.database.transaction() as connection: + started = await states.start_scan(connection, "memory-binding") + intents = _FailingIntents() + intents.boundary = "admit" + launcher = _Launcher(profile.database) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=( + ArtifactProcessingBinding( + "memory-binding", + "memory", + launcher, + max_workers=2, + automatic_processing_interval=timedelta(days=30), + ), + ), + lease_mode="single-process", + intents=intents, + oceanbase_tick_seconds=0.01, + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 5) + assert [work.scope_id for work in launcher.assignments] == ["a", "b", "c", "d", "e"] + completed = await _wait_scan_finished(profile.database, "memory-binding") + assert completed is not None and not completed.scan_in_progress + assert completed.scan_generation == started.scan_generation + assert completed.last_schedule_checkpoint_at == started.last_schedule_checkpoint_at + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_processing_scheduler.py b/tests/builtin/runtime/test_processing_scheduler.py new file mode 100644 index 0000000000..7d5fc32b3e --- /dev/null +++ b/tests/builtin/runtime/test_processing_scheduler.py @@ -0,0 +1,631 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +import logging +from collections import Counter +from datetime import timedelta + +import pytest + +from powercontext.builtin.persistence.errors import ArtifactProcessingLeadershipLostError +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.supervision import ( + ArtifactProcessingBindingStateRepository, + ArtifactProcessingLeaseRepository, +) +from powercontext.builtin.persistence.tables import SHARED_TABLES +from powercontext.builtin.runtime import artifact_processing as processing +from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingBinding, ArtifactProcessingSupervisor +from powercontext.builtin.runtime.processing_contracts import ( + ArtifactProcessingWorkerCompletion, + ArtifactProcessingWorkerOutcome, +) + + +async def _wait(predicate, timeout_seconds=5): + async with asyncio.timeout(timeout_seconds): + while not predicate(): # noqa: ASYNC110 - bounded observation of worker events + await asyncio.sleep(0.005) + + +async def _wait_scan_finished(database, binding): + # Workers can finish before discovery commits its final empty page. + async with asyncio.timeout(5): + while True: + async with database.transaction() as connection: + state = await ArtifactProcessingBindingStateRepository().load(connection, binding) + if state is not None and not state.scan_in_progress: + return state + await asyncio.sleep(0.005) + + +async def _request(database, binding, scope, *, dirty=True, requested=True): + intents = ArtifactProcessingIntentRepository() + async with database.transaction() as connection: + if dirty: + await intents.mark_dirty(connection, scope, binding) + if requested: + return await intents.request(connection, scope, binding) + return await intents.load(connection, scope, binding) + + +async def _intent(database, binding, scope): + async with database.transaction() as connection: + return await ArtifactProcessingIntentRepository().load(connection, scope, binding) + + +class _Launcher: + def __init__(self, database, *, on_work=None, gates=None): + self.database = database + self.on_work = on_work + self.gates = {} if gates is None else gates + self.assignments = [] + self.active = set() + self.maximum_active = 0 + self.terminated = [] + + async def start(self, assignment): + key = (assignment.binding_name, assignment.scope_id) + assert key not in self.active + self.assignments.append(assignment) + self.active.add(key) + self.maximum_active = max(self.maximum_active, len(self.active)) + return _Handle(self, assignment) + + +class _Handle: + def __init__(self, launcher, assignment): + self.launcher = launcher + self.assignment = assignment + + async def wait(self): + work = self.assignment + try: + gate = self.launcher.gates.get(work.scope_id) + if gate is not None: + await gate.wait() + if self.launcher.on_work is not None: + completion = await self.launcher.on_work(work) + if completion is not None: + return completion + async with self.launcher.database.transaction() as connection: + await ArtifactProcessingLeaseRepository().require_fence(connection, work.fence) + intents = ArtifactProcessingIntentRepository() + row = await intents.load(connection, work.scope_id, work.binding_name, for_update=True) + assert row is not None + await intents.acknowledge( + connection, + work.scope_id, + work.binding_name, + work.claimed_request_generation, + clean_generation=row.dirty_generation, + ) + return ArtifactProcessingWorkerCompletion() + finally: + self.launcher.active.discard((work.binding_name, work.scope_id)) + + async def terminate(self): + self.launcher.terminated.append(self.assignment.scope_id) + self.launcher.active.discard((self.assignment.binding_name, self.assignment.scope_id)) + + +class _ObservedIntents(ArtifactProcessingIntentRepository): + def __init__(self): + self.scans = [] + + async def scan(self, connection, binding_name, /, **kwargs): + self.scans.append((binding_name, dict(kwargs))) + return await super().scan(connection, binding_name, **kwargs) + + +class _CycleSupervisor(ArtifactProcessingSupervisor): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.cycles = 0 + self.max_resident = 0 + + async def __aenter__(self): + await self.start() + return self + + async def _cycle(self): + self.cycles += 1 + await super()._cycle() + for state in self.family_status.values(): + resident = int(state["retry_wait"]) + int(state["ready"]) + int(state["used_workers"]) + self.max_resident = max(self.max_resident, resident) + + +def _profile(tmp_path, name): + return SQLiteProfile.open( + SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / (name + '.db')}"), tables=SHARED_TABLES + ) + + +def test_each_family_has_independent_capacity_and_a_scope_is_single_flight(tmp_path): + async def scenario(): + async with _profile(tmp_path, "family-capacity") as profile: + blocked = asyncio.Event() + memory = _Launcher(profile.database, gates={"a": blocked, "b": blocked, "c": blocked}) + topic = _Launcher(profile.database) + for scope in ("a", "b", "c"): + await _request(profile.database, "memory-binding", scope) + await _request(profile.database, "topic-binding", "peer") + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=( + ArtifactProcessingBinding("memory-binding", "memory", memory, max_workers=2), + ArtifactProcessingBinding("topic-binding", "topic-memory", topic, max_workers=1), + ), + lease_mode="single-process", + ) as supervisor: + await _wait(lambda: supervisor.family_status["topic-memory"]["completed"] == 1) + assert len(memory.assignments) == 2 and memory.maximum_active == 2 + assert supervisor.family_status["memory"]["used_workers"] == 2 + assert (await _intent(profile.database, "topic-binding", "peer")).handled_generation == 1 + # A second accepted request coalesces behind the active Scope. + await _request(profile.database, "memory-binding", "a", dirty=False) + supervisor.wake("memory-binding") + await asyncio.sleep(0.03) + assert [work.scope_id for work in memory.assignments].count("a") == 1 + blocked.set() + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 4) + assert memory.maximum_active == 2 + assert (await _intent(profile.database, "memory-binding", "a")).handled_generation == 2 + + asyncio.run(scenario()) + + +def test_success_without_durable_acknowledgement_is_a_failure_and_retries(tmp_path): + async def scenario(): + async with _profile(tmp_path, "no-ack") as profile: + await _request(profile.database, "memory-binding", "scope") + attempts = 0 + + async def forget_once(_work): + nonlocal attempts + attempts += 1 + return ArtifactProcessingWorkerCompletion() if attempts == 1 else None + + launcher = _Launcher(profile.database, on_work=forget_once) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("memory-binding", "memory", launcher),), + lease_mode="single-process", + retry_base_seconds=0.15, + retry_cap_seconds=0.15, + retry_jitter=lambda: 1, + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["failed"] == 1) + assert (await _intent(profile.database, "memory-binding", "scope")).handled_generation == 0 + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 1) + assert attempts == 2 + assert (await _intent(profile.database, "memory-binding", "scope")).handled_generation == 1 + + asyncio.run(scenario()) + + +def test_retry_backoff_is_quiet_and_failure_does_not_starve_other_scopes(tmp_path, monkeypatch): + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 2) + + async def scenario(): + async with _profile(tmp_path, "fair-retry") as profile: + for scope in ("bad", "a", "b", "c", "d", "e"): + await _request(profile.database, "memory-binding", scope) + + async def fail_bad(work): + if work.scope_id == "bad": + raise RuntimeError + + launcher = _Launcher(profile.database, on_work=fail_bad) + async with _CycleSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("memory-binding", "memory", launcher),), + lease_mode="single-process", + retry_base_seconds=1, + retry_cap_seconds=1, + retry_jitter=lambda: 1, + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 5) + assert Counter(work.scope_id for work in launcher.assignments)["bad"] == 1 + before = supervisor.cycles + await asyncio.sleep(0.1) + assert supervisor.cycles - before <= 2 + assert (await _intent(profile.database, "memory-binding", "bad")).handled_generation == 0 + + asyncio.run(scenario()) + + +def test_notification_during_requested_scan_revisits_a_scope_behind_frontier(tmp_path, monkeypatch): + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 2) + + async def scenario(): + async with _profile(tmp_path, "notification") as profile: + await _request(profile.database, "memory-binding", "first", requested=False) + for scope in ("b", "c", "d", "e"): + await _request(profile.database, "memory-binding", scope) + gate = asyncio.Event() + launcher = _Launcher(profile.database, gates={"b": gate}) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("memory-binding", "memory", launcher),), + lease_mode="single-process", + ) as supervisor: + await _wait(lambda: len(launcher.assignments) == 1) + await _request(profile.database, "memory-binding", "first", dirty=False) + supervisor.wake("memory-binding") + gate.set() + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 5) + assert (await _intent(profile.database, "memory-binding", "first")).handled_generation == 1 + + asyncio.run(scenario()) + + +def test_automatic_scan_is_bounded_and_excludes_new_registration_until_next_schedule(tmp_path, monkeypatch): + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 2) + + async def scenario(): + async with _profile(tmp_path, "automatic") as profile: + for scope in ("a", "b", "c", "d", "e"): + await _request(profile.database, "memory-binding", scope, requested=False) + gate = asyncio.Event() + launcher = _Launcher(profile.database, gates={"a": gate}) + observed = _ObservedIntents() + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=( + ArtifactProcessingBinding( + "memory-binding", "memory", launcher, automatic_processing_interval=timedelta(hours=1) + ), + ), + lease_mode="single-process", + intents=observed, + ) as supervisor: + await _wait(lambda: bool(launcher.assignments)) + async with profile.database.transaction() as connection: + state = await ArtifactProcessingBindingStateRepository().load(connection, "memory-binding") + assert state is not None + initial_checkpoint = state.last_schedule_checkpoint_at + assert state.scan_in_progress + await _request(profile.database, "memory-binding", "late", requested=False) + supervisor.wake("memory-binding") + gate.set() + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 5) + state = await _wait_scan_finished(profile.database, "memory-binding") + assert state is not None + assert not state.scan_in_progress and state.last_schedule_checkpoint_at == initial_checkpoint + assert {work.scope_id for work in launcher.assignments} == {"a", "b", "c", "d", "e"} + assert (await _intent(profile.database, "memory-binding", "late")).requested_generation == 0 + assert all(options["limit"] <= 2 for _, options in observed.scans) + + asyncio.run(scenario()) + + +def test_worker_timeout_reclaims_slot_and_preserves_durable_intent(tmp_path): + async def scenario(): + async with _profile(tmp_path, "timeout") as profile: + await _request(profile.database, "memory-binding", "hang") + launcher = _Launcher(profile.database, gates={"hang": asyncio.Event()}) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=( + ArtifactProcessingBinding("memory-binding", "memory", launcher, worker_timeout_seconds=0.05), + ), + lease_mode="single-process", + retry_base_seconds=10, + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["timeouts"] == 1) + assert launcher.terminated == ["hang"] + assert supervisor.family_status["memory"]["used_workers"] == 0 + assert (await _intent(profile.database, "memory-binding", "hang")).handled_generation == 0 + + asyncio.run(scenario()) + + +def test_restart_uses_durable_requests_and_close_revokes_the_previous_fence(tmp_path): + async def scenario(): + async with _profile(tmp_path, "restart") as profile: + await _request(profile.database, "memory-binding", "scope") + blocked = _Launcher(profile.database, gates={"scope": asyncio.Event()}) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("memory-binding", "memory", blocked),), + lease_mode="single-process", + ) as supervisor: + await _wait(lambda: bool(blocked.assignments)) + old_fence = supervisor.fence + assert old_fence is not None + assert blocked.terminated == ["scope"] + async with profile.database.transaction() as connection: + with pytest.raises(ArtifactProcessingLeadershipLostError): + await ArtifactProcessingLeaseRepository().require_fence(connection, old_fence) + replacement = _Launcher(profile.database) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("memory-binding", "memory", replacement),), + lease_mode="single-process", + ) as successor: + await _wait(lambda: successor.family_status["memory"]["completed"] == 1) + assert successor.fence is not None + assert successor.fence.supervisor_generation > old_fence.supervisor_generation + assert (await _intent(profile.database, "memory-binding", "scope")).handled_generation == 1 + + asyncio.run(scenario()) + + +def test_domain_control_conflict_retries_without_counting_a_provider_failure(tmp_path): + async def scenario(): + async with _profile(tmp_path, "conflict") as profile: + await _request(profile.database, "memory-binding", "scope") + attempts = 0 + + async def conflict_once(_work): + nonlocal attempts + attempts += 1 + return ( + ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT) + if attempts == 1 + else None + ) + + launcher = _Launcher(profile.database, on_work=conflict_once) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("memory-binding", "memory", launcher),), + lease_mode="single-process", + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 1) + assert attempts == 2 and supervisor.family_status["memory"]["failed"] == 0 + + asyncio.run(scenario()) + + +def test_discovery_failure_is_confined_to_its_family(tmp_path): + class BrokenDiscovery: + async def reconcile(self, after_scope_id, limit, *, fence): + raise RuntimeError + + async def scenario(): + async with _profile(tmp_path, "discovery-failure") as profile: + await _request(profile.database, "topic-binding", "healthy") + memory = _Launcher(profile.database) + topic = _Launcher(profile.database) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=( + ArtifactProcessingBinding("memory-binding", "memory", memory, pending_provider=BrokenDiscovery()), + ArtifactProcessingBinding("topic-binding", "topic-memory", topic), + ), + lease_mode="single-process", + ) as supervisor: + await _wait(lambda: supervisor.family_status["topic-memory"]["completed"] == 1) + assert supervisor.family_status["memory"]["status"] == "degraded" + assert supervisor.family_status["topic-memory"]["status"] == "leader" + assert (await _intent(profile.database, "topic-binding", "healthy")).handled_generation == 1 + + asyncio.run(scenario()) + + +def test_automatic_scan_restart_reuses_frozen_members_without_double_admission(tmp_path, monkeypatch): + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 2) + + async def scenario(): + async with _profile(tmp_path, "scan-restart") as profile: + for scope in ("a", "b", "c", "d", "e"): + await _request(profile.database, "memory-binding", scope, requested=False) + blocked = _Launcher(profile.database, gates={"a": asyncio.Event()}) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=( + ArtifactProcessingBinding( + "memory-binding", "memory", blocked, automatic_processing_interval=timedelta(hours=1) + ), + ), + lease_mode="single-process", + ): + await _wait(lambda: bool(blocked.assignments)) + async with profile.database.transaction() as connection: + before = await ArtifactProcessingBindingStateRepository().load(connection, "memory-binding") + assert before is not None + assert before.scan_in_progress + await _request(profile.database, "memory-binding", "late", requested=False) + recovered = _Launcher(profile.database) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=( + ArtifactProcessingBinding( + "memory-binding", "memory", recovered, automatic_processing_interval=timedelta(hours=1) + ), + ), + lease_mode="single-process", + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 5) + after = await _wait_scan_finished(profile.database, "memory-binding") + assert after is not None + assert after.scan_generation == before.scan_generation and not after.scan_in_progress + assert after.last_schedule_checkpoint_at == before.last_schedule_checkpoint_at + for scope in ("a", "b", "c", "d", "e"): + row = await _intent(profile.database, "memory-binding", scope) + assert row.requested_generation == row.handled_generation == 1 + assert (await _intent(profile.database, "memory-binding", "late")).requested_generation == 0 + + asyncio.run(scenario()) + + +def test_new_requests_preserve_failure_count_until_success(tmp_path, caplog): + async def scenario(): + async with _profile(tmp_path, "retry-generations") as profile: + await _request(profile.database, "memory-binding", "scope") + attempts = 0 + + async def intermittent_failure(_work): + nonlocal attempts + attempts += 1 + if attempts in (1, 2, 4): + raise RuntimeError + + launcher = _Launcher(profile.database, on_work=intermittent_failure) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("memory-binding", "memory", launcher),), + lease_mode="single-process", + retry_base_seconds=0.1, + retry_cap_seconds=0.2, + retry_jitter=lambda: 1, + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["failed"] == 1) + await _request(profile.database, "memory-binding", "scope", dirty=False) + supervisor.wake("memory-binding") + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 1) + await _request(profile.database, "memory-binding", "scope", dirty=False) + supervisor.wake("memory-binding") + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 2) + retry_counts = [ + record.retry_count + for record in caplog.records + if getattr(record, "scope", None) == "scope" and getattr(record, "stage", None) == "worker" + ] + assert retry_counts == [1, 2, 1] + + asyncio.run(scenario()) + + +def test_retry_residency_budget_serves_healthy_suffix_after_large_failure_population(tmp_path, caplog): + """Keep the inherited 1512 cache budget while requiring progress past it.""" + caplog.set_level(logging.CRITICAL, logger=processing.__name__) + retry_budget = 1000 + ready_budget = 100 + workers = 16 + + async def scenario(): + async with _profile(tmp_path, "retry-budget") as profile: + intents = ArtifactProcessingIntentRepository() + async with profile.database.transaction() as connection: + for number in range(1200): + await intents.request(connection, f"failed-{number:04}", "memory-binding") + await intents.request(connection, "healthy-tail", "memory-binding") + + async def permanent_failure(work): + if work.scope_id != "healthy-tail": + raise RuntimeError + + launcher = _Launcher(profile.database, on_work=permanent_failure) + async with _CycleSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("memory-binding", "memory", launcher, max_workers=workers),), + lease_mode="single-process", + retry_base_seconds=0.5, + retry_cap_seconds=0.5, + retry_jitter=lambda: 1, + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 1, timeout_seconds=60) + assert (await _intent(profile.database, "memory-binding", "healthy-tail")).handled_generation == 1 + # Public residency counters measure the background memory + # contract without depending on dict layout or eviction order. + assert supervisor.max_resident <= retry_budget + ready_budget + workers + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("admission", ["requested", "automatic"]) +def test_continuously_due_retries_do_not_starve_fresh_discovery(tmp_path, monkeypatch, caplog, admission): + caplog.set_level(logging.CRITICAL, logger=processing.__name__) + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 4) + monkeypatch.setattr(processing, "_CHANNEL_QUEUE_LIMIT", 2) + + async def scenario(): + async with _profile(tmp_path, "continuously-due") as profile: + for number in range(12): + await _request(profile.database, "memory-binding", f"bad-{number:02}") + await _request(profile.database, "memory-binding", "healthy-tail", requested=admission == "requested") + + async def always_bad(work): + if work.scope_id != "healthy-tail": + raise RuntimeError + + launcher = _Launcher(profile.database, on_work=always_bad) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=( + ArtifactProcessingBinding( + "memory-binding", + "memory", + launcher, + max_workers=2, + automatic_processing_interval=timedelta(hours=1) if admission == "automatic" else None, + ), + ), + lease_mode="single-process", + retry_base_seconds=0.001, + retry_cap_seconds=0.001, + retry_jitter=lambda: 1, + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 1, timeout_seconds=3) + assert (await _intent(profile.database, "memory-binding", "healthy-tail")).handled_generation == 1 + + asyncio.run(scenario()) + + +def test_overflow_flush_cannot_advance_retry_and_cached_failures_cannot_extend_gate(tmp_path, monkeypatch, caplog): + caplog.set_level(logging.CRITICAL, logger=processing.__name__) + monkeypatch.setattr(processing, "_RETRY_STATE_LIMIT", 1) + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 4) + monkeypatch.setattr(processing, "_CHANNEL_QUEUE_LIMIT", 2) + monkeypatch.setattr(processing, "_CONTROL_CONFLICT_RETRY_SECONDS", 0.2) + + async def scenario(): + async with _profile(tmp_path, "overflow-pressure") as profile: + await _request(profile.database, "memory-binding", "cached") + await _request(profile.database, "memory-binding", "overflow") + attempts = {"cached": [], "overflow": [], "healthy-tail": []} + + async def pressure(work): + attempts[work.scope_id].append(asyncio.get_running_loop().time()) + if work.scope_id == "cached": + return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT) + if work.scope_id == "overflow": + raise RuntimeError + + launcher = _Launcher(profile.database, on_work=pressure) + async with _CycleSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("memory-binding", "memory", launcher),), + lease_mode="single-process", + retry_base_seconds=0.8, + retry_cap_seconds=0.8, + retry_jitter=lambda: 1, + ) as supervisor: + await _wait(lambda: supervisor.family_status["memory"]["failed"] == 1) + assert supervisor.family_status["memory"]["retry_wait"] == 1 + await _request(profile.database, "memory-binding", "overflow", dirty=False) + await _request(profile.database, "memory-binding", "healthy-tail") + # Repeated API wakes must respect the omitted key's cooldown. + for _ in range(4): + supervisor.wake("memory-binding") + await asyncio.sleep(0.04) + assert len(attempts["overflow"]) == 1 + # Cached retries keep failing, but cannot keep shifting the + # finite overflow cohort's gate beyond the original deadline. + await _wait(lambda: supervisor.family_status["memory"]["completed"] == 1, timeout_seconds=1.5) + assert len(attempts["cached"]) >= 3 + await _wait(lambda: len(attempts["overflow"]) >= 2, timeout_seconds=1.5) + assert attempts["overflow"][1] - attempts["overflow"][0] >= 0.78 + assert supervisor.max_resident <= 1 + 4 + 1 + assert (await _intent(profile.database, "memory-binding", "healthy-tail")).handled_generation == 1 + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_processing_source_registry.py b/tests/builtin/runtime/test_processing_source_registry.py new file mode 100644 index 0000000000..7468f52343 --- /dev/null +++ b/tests/builtin/runtime/test_processing_source_registry.py @@ -0,0 +1,157 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Reject Source capabilities that built-in child processes cannot reconstruct.""" + +from __future__ import annotations + +import asyncio +from dataclasses import replace +from types import SimpleNamespace +from typing import cast +from unittest.mock import Mock + +import pytest + +from powercontext import AdapterSourceDefinition, SourceDefinitionRegistry +from powercontext.builtin.inference import character_token_estimator +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.runtime import BuiltinConfig, InferenceConfig, RuntimeConfig, composition +from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingBinding +from powercontext.builtin.runtime.composition import BuiltinConfigurationError, open_builtin_runtime +from powercontext.builtin.runtime.relational import RelationalContexts +from powercontext.builtin.sources import BUILTIN_SOURCE_REGISTRY, CONTENT_SOURCE_DEFINITION +from tests.builtin.persistence.test_provider import CustomCapture, CustomSource, CustomSourceAdapter +from tests.builtin.runtime.test_processing_composition import _OCEANBASE + +_FAMILIES = ("memory", "topic-memory", "experience", "profile") + + +def _custom_registry(): + return SourceDefinitionRegistry(( + *BUILTIN_SOURCE_REGISTRY.definitions, + AdapterSourceDefinition(CustomSourceAdapter()), + )) + + +@pytest.mark.parametrize("family", _FAMILIES) +@pytest.mark.parametrize("mode", ["global", "dedicated"]) +def test_runtime_rejects_custom_sources_before_bootstrap_and_allows_corrected_restart( + tmp_path, monkeypatch, family, mode +): + async def scenario(): + launcher = Mock(side_effect=AssertionError("unsupported Source registry reached a child launcher")) + monkeypatch.setattr(composition, "SpawnArtifactProcessingWorkerLauncher", launcher) + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'unsupported.db'}"), + inference=InferenceConfig(generation_model="test"), + runtime=RuntimeConfig(artifact_processing_families=(family,), artifact_processing_supervisor_mode=mode), + ) + # Schedules are disabled, but explicit requests would still spawn children. + with pytest.raises(BuiltinConfigurationError, match="built-in Source definitions"): + async with open_builtin_runtime( + config, source_registry=_custom_registry(), scheduler_path=tmp_path / "scheduler.db" + ): + pytest.fail("unsupported child Source capabilities must fail before accepting work") + launcher.assert_not_called() + # A configuration rejection must not freeze a completed deployment + # manifest that prevents the suggested correction on the same database. + assert not (tmp_path / "unsupported.db").exists() + corrected = config.model_copy( + update={"runtime": RuntimeConfig(artifact_processing_families=(), artifact_processing_supervisor_mode=mode)} + ) + async with open_builtin_runtime( + corrected, source_registry=_custom_registry(), scheduler_path=tmp_path / "scheduler.db" + ) as runtime: + context = await runtime._provider.get("project") + resolved = await context.sources.resolve(CustomCapture(source_id="custom", value="corrected startup")) + stored = await context.sources.add(resolved) + assert isinstance(stored, CustomSource) + assert await context.sources.read(stored) == "corrected startup" + assert runtime.artifact_processing_supervisor is None + launcher.assert_not_called() + + asyncio.run(scenario()) + + +def test_runtime_preserves_custom_source_persistence_with_builtin_families_disabled(tmp_path): + async def scenario(): + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'synchronous.db'}"), + inference=InferenceConfig(generation_model="test"), + runtime=RuntimeConfig(artifact_processing_families=()), + ) + registry = _custom_registry() + async with open_builtin_runtime( + config, source_registry=registry, scheduler_path=tmp_path / "scheduler.db" + ) as runtime: + context = await runtime._provider.get("project") + resolved = await context.sources.resolve(CustomCapture(source_id="custom", value="retained typed value")) + stored = await context.sources.add(resolved) + assert isinstance(stored, CustomSource) + assert await context.sources.read(stored) == "retained typed value" + assert await context.sources.list() == (stored,) + assert runtime.artifact_processing_supervisor is None + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("role", ["all", "background"]) +def test_custom_bindings_must_cover_every_enabled_family_with_custom_sources(role): + config = BuiltinConfig( + database=_OCEANBASE, + inference=InferenceConfig(generation_model="test"), + runtime=RuntimeConfig(artifact_processing_role=role, artifact_processing_families=_FAMILIES), + ) + bindings = tuple( + ArtifactProcessingBinding(binding_name=f"custom-{family}", artifact_family=family, launcher=Mock()) + for family in _FAMILIES + ) + contexts = cast(RelationalContexts, SimpleNamespace()) + assert ( + composition._artifact_processing_bindings(config, contexts, bindings, source_registry=_custom_registry()) + == bindings + ) + with pytest.raises(BuiltinConfigurationError, match="built-in Source definitions"): + composition._artifact_processing_bindings(config, contexts, bindings[:-1], source_registry=_custom_registry()) + + +def test_api_role_preserves_custom_registry_without_creating_builtin_children(): + config = BuiltinConfig( + database=_OCEANBASE, + runtime=RuntimeConfig(artifact_processing_role="api", artifact_processing_families=_FAMILIES), + ) + assert ( + composition._artifact_processing_bindings( + config, cast(RelationalContexts, SimpleNamespace()), (), source_registry=_custom_registry() + ) + == () + ) + + +def test_copied_builtin_registry_is_accepted_but_replaced_definitions_are_rejected(tmp_path): + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'builtin.db'}"), + inference=InferenceConfig(generation_model="test"), + runtime=RuntimeConfig(artifact_processing_families=("memory",)), + ) + contexts = cast(RelationalContexts, SimpleNamespace(database=Mock(), token_estimator=character_token_estimator())) + copied = SourceDefinitionRegistry(BUILTIN_SOURCE_REGISTRY.definitions) + assert len(composition._artifact_processing_bindings(config, contexts, (), source_registry=copied)) == 1 + + definitions = BUILTIN_SOURCE_REGISTRY.definitions + # Identical name/version does not guarantee identical adapter/projection behavior. + changed = SourceDefinitionRegistry((replace(CONTENT_SOURCE_DEFINITION, projections=()), *definitions[1:])) + with pytest.raises(BuiltinConfigurationError, match="built-in Source definitions"): + composition._artifact_processing_bindings(config, contexts, (), source_registry=changed) diff --git a/tests/builtin/runtime/test_profile_automatic_admission.py b/tests/builtin/runtime/test_profile_automatic_admission.py new file mode 100644 index 0000000000..2f0b8a438d --- /dev/null +++ b/tests/builtin/runtime/test_profile_automatic_admission.py @@ -0,0 +1,328 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Cron qualification must precede admission without changing explicit requests.""" + +from __future__ import annotations + +import asyncio +from collections import Counter +from dataclasses import replace +from datetime import UTC, datetime, timedelta + +import pytest + +from powercontext.builtin.artifacts.profile.models import PROFILE_SOURCE_WINDOW_BINDING as BINDING +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.supervision import ArtifactProcessingBindingStateRepository +from powercontext.builtin.persistence.tables import BUILTIN_TABLES +from powercontext.builtin.runtime import artifact_processing as processing +from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingSupervisor +from powercontext.builtin.runtime.composition import _artifact_processing_bindings +from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig, RuntimeConfig +from powercontext.builtin.runtime.family_processing import process_family_invocation +from powercontext.builtin.runtime.relational import RelationalContexts +from powercontext.builtin.scope import ScopeDraft +from powercontext.server.authz import AccessDeniedError +from powercontext.server.authz.repository import ACCESS_TABLES +from powercontext.server.processing_security import open_worker_security +from tests.builtin.runtime.test_family_processing import security_spec +from tests.builtin.runtime.test_processing_scheduler import _intent, _Launcher + + +class _Clock: + def __init__(self): + self.now = datetime(2026, 9, 9, tzinfo=UTC).replace(tzinfo=None) + + async def read(self, _connection): + return self.now + + def fire(self): + self.now += timedelta(minutes=1) + + +class _ObservedIntents(ArtifactProcessingIntentRepository): + def __init__(self): + self.pages = [] + self.admissions = [] + + async def scan(self, connection, binding_name, /, **kwargs): + rows = await super().scan(connection, binding_name, **kwargs) + if kwargs.get("dirty_only"): + self.pages.append(tuple(row.scope_id for row in rows)) + return rows + + async def admit(self, connection, scope_id, binding_name, scan_generation, /): + self.admissions.append((scope_id, scan_generation)) + return await super().admit(connection, scope_id, binding_name, scan_generation) + + +class _Generator: + def __init__(self): + self.inputs = [] + + async def generate(self, value): + self.inputs.append(value) + return "# Preferences\n\nRetain the original Source until generation is enabled." + + +def _config(tmp_path): + return BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'profile-admission.db'}"), + inference=InferenceConfig(generation_model="test"), + runtime=RuntimeConfig( + artifact_processing_families=("profile",), + profile_schedule_enabled=True, + profile_cron="* * * * *", + profile_timezone="UTC", + profile_max_workers=1, + ), + ) + + +async def _scope(contexts, name, *, enabled=None): + scope = (await contexts.scopes.create(ScopeDraft(title=name, summary=name, idempotency_key=name))).scope_id + await contexts.records.create_source(scope, "content", f"Original evidence for {name}.") + if enabled is not None: + await contexts.profiles.put_policy(scope, generation_enabled=enabled, expected_version=0) + return scope + + +async def _dispatch(supervisor, state): + await supervisor._dispatch(state) + results = await asyncio.gather(*(worker.task for worker in state.running.values()), return_exceptions=True) + await supervisor._reap(state) + return results + + +async def _scan(supervisor, state): + for _ in range(10): + await supervisor._discover_automatic(state) + await _dispatch(supervisor, state) + async with supervisor._database.transaction() as connection: + persisted = await ArtifactProcessingBindingStateRepository().load(connection, BINDING) + if persisted is not None and not persisted.scan_in_progress: + return persisted + pytest.fail("finite automatic scan did not finish") + + +async def _unconsumed(contexts, scope): + async with contexts.database.transaction() as connection: + assert await SourceCursorRepository().load(connection, scope, BINDING) is None + sources = await contexts.profiles.sources.list(connection, scope, after=0, limit=10) + assert len(sources) == 1 and sources[0].journal_position == 1 + return sources[0].value + + +def test_profile_cron_skips_ineligible_prefix_across_fires_and_later_consumes_original_sources(tmp_path, monkeypatch): + clock = _Clock() + monkeypatch.setattr(processing, "database_utc_now", clock.read) + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 2) + + async def scenario(): + config = _config(tmp_path) + assert isinstance(config.database, SQLiteConfig) + async with SQLiteProfile.open(config.database, tables=BUILTIN_TABLES) as profile: + contexts = RelationalContexts(database=profile.database) + generator = _Generator() + contexts.profiles.generator = generator + missing = await _scope(contexts, "missing") + disabled = await _scope(contexts, "disabled", enabled=False) + enabled = await _scope(contexts, "enabled", enabled=True) + original = {scope: await _unconsumed(contexts, scope) for scope in (missing, disabled)} + observed = _ObservedIntents() + + async def work(assignment): + return await process_family_invocation(contexts, assignment, config=config) + + launcher = _Launcher(profile.database, on_work=work) + # Use the production registration, including its qualification hook. + binding = replace(_artifact_processing_bindings(config, contexts, ())[0], launcher=launcher) + supervisor = ArtifactProcessingSupervisor( + database=profile.database, bindings=(binding,), lease_mode="single-process", intents=observed + ) + await supervisor._acquire() + state = supervisor._families[BINDING] + try: + for generation in (1, 2): + saved = await _scan(supervisor, state) + assert saved.scan_generation == generation + assert saved.last_schedule_checkpoint_at == clock.now + assert state.retries == {} + for scope in (missing, disabled): + intent = await _intent(profile.database, BINDING, scope) + assert intent.requested_generation == intent.handled_generation == 0 + assert intent.last_auto_scan_generation == 0 + assert intent.dirty_generation > intent.clean_generation + assert await _unconsumed(contexts, scope) == original[scope] + clock.fire() + assert observed.pages[0] == (missing, disabled) + assert all(len(page) <= 2 for page in observed.pages) + assert observed.admissions == [(enabled, 1)] + assert [work.scope_id for work in launcher.assignments] == [enabled] + assert len(generator.inputs) == 1 + + # Policy writes wake existing dirty work; no new Source is added. + await contexts.profiles.put_policy(missing, generation_enabled=True, expected_version=0) + await contexts.profiles.put_policy(disabled, generation_enabled=True, expected_version=1) + assert (await _scan(supervisor, state)).scan_generation == 3 + assert Counter(work.scope_id for work in launcher.assignments) == Counter({ + missing: 1, + disabled: 1, + enabled: 1, + }) + for scope in (missing, disabled): + intent = await _intent(profile.database, BINDING, scope) + assert intent.requested_generation == intent.handled_generation == 1 + assert intent.last_auto_scan_generation == 3 + assert intent.clean_generation == intent.dirty_generation + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, scope, BINDING) + artifact = await contexts.profiles.latest(connection, scope) + assert cursor is not None and cursor.cursor.sequence == 1 + assert artifact is not None + assert artifact.content.generation.source_window is not None + assert artifact.content.generation.source_window.through == 1 + assert any(original[scope].model_dump_json() in request.sources for request in generator.inputs) + assert state.retries == {} + finally: + await supervisor._lose_leadership() + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("enabled", [None, False]) +def test_explicit_profile_request_without_enabled_policy_is_acknowledged_and_remains_dirty(tmp_path, enabled): + async def scenario(): + config = _config(tmp_path) + assert isinstance(config.database, SQLiteConfig) + async with SQLiteProfile.open(config.database, tables=BUILTIN_TABLES) as profile: + contexts = RelationalContexts(database=profile.database) + scope = await _scope(contexts, "explicit", enabled=enabled) + original = await _unconsumed(contexts, scope) + generator = _Generator() + contexts.profiles.generator = generator + + async def work(assignment): + return await process_family_invocation(contexts, assignment, config=config) + + launcher = _Launcher(profile.database, on_work=work) + binding = replace(_artifact_processing_bindings(config, contexts, ())[0], launcher=launcher) + supervisor = ArtifactProcessingSupervisor( + database=profile.database, bindings=(binding,), lease_mode="single-process" + ) + await supervisor._acquire() + state = supervisor._families[BINDING] + try: + async with profile.database.transaction() as connection: + await ArtifactProcessingIntentRepository().request(connection, scope, BINDING) + await supervisor._discover_requested(state) + assert await _dispatch(supervisor, state) + intent = await _intent(profile.database, BINDING, scope) + assert intent.requested_generation == intent.handled_generation == 1 + assert intent.last_auto_scan_generation == 0 + assert intent.dirty_generation > intent.clean_generation + assert [work.scope_id for work in launcher.assignments] == [scope] + assert state.retries == {} and generator.inputs == [] + assert await _unconsumed(contexts, scope) == original + finally: + await supervisor._lose_leadership() + + asyncio.run(scenario()) + + +def test_enforced_cron_qualifies_before_authorization_but_keeps_explicit_and_enabled_denials(tmp_path, monkeypatch): + clock = _Clock() + monkeypatch.setattr(processing, "database_utc_now", clock.read) + monkeypatch.setattr(processing, "_DISCOVERY_PAGE_SIZE", 2) + + async def scenario(): + config = _config(tmp_path) + assert isinstance(config.database, SQLiteConfig) + async with SQLiteProfile.open(config.database, tables=(*BUILTIN_TABLES, *ACCESS_TABLES)) as profile: + contexts = RelationalContexts(database=profile.database) + missing = await _scope(contexts, "missing") + disabled = await _scope(contexts, "disabled", enabled=False) + enabled = await _scope(contexts, "enabled", enabled=True) + observed = _ObservedIntents() + authorizations = [] + policy_reads = [] + async with open_worker_security(security_spec(allowed=False), profile.database) as security: + assert security is not None + authorize = security.authorize_transaction + read_policy = contexts.profiles.policies.get + + async def observed_authorize(connection, scope_id): + authorizations.append(scope_id) + await authorize(connection, scope_id) + + async def observed_policy(*args, **kwargs): + policy_reads.append(args[1]) + return await read_policy(*args, **kwargs) + + monkeypatch.setattr(security, "authorize_transaction", observed_authorize) + monkeypatch.setattr(contexts.profiles.policies, "get", observed_policy) + + async def work(assignment): + return await process_family_invocation(contexts, assignment, config=config, security=security) + + launcher = _Launcher(profile.database, on_work=work) + binding = replace(_artifact_processing_bindings(config, contexts, ())[0], launcher=launcher) + supervisor = ArtifactProcessingSupervisor( + database=profile.database, + bindings=(binding,), + lease_mode="single-process", + intents=observed, + retry_base_seconds=3600, + retry_cap_seconds=3600, + ) + await supervisor._acquire() + state = supervisor._families[BINDING] + try: + for generation in (1, 2): + assert (await _scan(supervisor, state)).scan_generation == generation + assert set(state.retries) == {enabled} + for scope in (missing, disabled): + intent = await _intent(profile.database, BINDING, scope) + assert intent.requested_generation == intent.handled_generation == 0 + assert intent.last_auto_scan_generation == 0 + clock.fire() + assert observed.admissions == [(enabled, 1)] + assert authorizations == [enabled] + assert policy_reads == [] # Worker denial still precedes business Policy/Source reads. + assert [work.scope_id for work in launcher.assignments] == [enabled] + assert state.failed == 1 + + # Explicit work stays accepted and protected even for disabled Policies. + for scope in (missing, disabled): + async with profile.database.transaction() as connection: + await ArtifactProcessingIntentRepository().request(connection, scope, BINDING) + for _ in range(3): + await supervisor._discover_requested(state) + results = await _dispatch(supervisor, state) + assert all(isinstance(result, AccessDeniedError) for result in results) + assert Counter(authorizations) == Counter({missing: 1, disabled: 1, enabled: 1}) + assert set(state.retries) == {missing, disabled, enabled} + assert policy_reads == [] + for scope in (missing, disabled, enabled): + intent = await _intent(profile.database, BINDING, scope) + assert intent.requested_generation == 1 and intent.handled_generation == 0 + assert intent.dirty_generation > intent.clean_generation + await _unconsumed(contexts, scope) + finally: + await supervisor._lose_leadership() + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_readiness.py b/tests/builtin/runtime/test_readiness.py index a7759a997f..222bc24128 100644 --- a/tests/builtin/runtime/test_readiness.py +++ b/tests/builtin/runtime/test_readiness.py @@ -43,10 +43,9 @@ async def scenario() -> None: assert readiness.checks == { "runtime": ReadinessCheckStatus.READY, "database": ReadinessCheckStatus.READY, - "artifact_processing_supervisor": "leader", + "artifact_processing_supervisor": "disabled", } - assert supervisor is not None - assert supervisor.status.value == "standby" + assert supervisor is None asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_topic_memory_processing.py b/tests/builtin/runtime/test_topic_memory_processing.py index 09a95ccbea..7ce5fe2c86 100644 --- a/tests/builtin/runtime/test_topic_memory_processing.py +++ b/tests/builtin/runtime/test_topic_memory_processing.py @@ -77,6 +77,7 @@ from powercontext.builtin.inference.usage import UsageReportingEmbeddingModel, UsageReportingStructuredGenerator from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.sources import SourceRepository from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.persistence.sqlite.topic_memory_index import SQLiteTopicMemoryFTSIndex @@ -94,20 +95,20 @@ from powercontext.builtin.runtime.artifact_processing import ( ArtifactProcessingBinding, ArtifactProcessingSupervisor, - ArtifactProcessingWaveKind, - ArtifactProcessingWorkAssignment, ArtifactProcessingWorkerCompletion, ArtifactProcessingWorkerOutcome, SpawnArtifactProcessingWorkerLauncher, ) from powercontext.builtin.runtime.composition import ( BuiltinConfigurationError, - _topic_memory_processing_bindings, + _artifact_processing_bindings, open_builtin_contexts, open_builtin_runtime, ) from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig, RuntimeConfig +from powercontext.builtin.runtime.processing_contracts import ArtifactProcessingWorkAssignment as ScopeAssignment from powercontext.builtin.runtime.topic_memory_processing import ( + ArtifactProcessingWaveKind, PreparedTopicMemoryOperation, TopicMemoryAtomicPublisher, TopicMemoryProcessor, @@ -116,6 +117,10 @@ TopicMemoryWorkerSpec, run_topic_memory_worker, ) +from powercontext.builtin.runtime.topic_memory_processing import ( + TopicMemoryWindowAssignment as ArtifactProcessingWorkAssignment, +) +from powercontext.builtin.runtime.topic_memory_scope import TopicMemoryScopeProcessor from powercontext.builtin.sources import ( CONTENT_SOURCE_ADAPTER, EXTERNAL_SKILL_SNAPSHOT_SOURCE_ADAPTER, @@ -195,15 +200,15 @@ async def publish_create(self, connection, scope_id, artifact_id, draft, project class _ProcessorLauncher: - def __init__(self, processor: TopicMemoryProcessor) -> None: + def __init__(self, processor: TopicMemoryScopeProcessor) -> None: self.processor = processor - async def start(self, assignment: ArtifactProcessingWorkAssignment): + async def start(self, assignment: ScopeAssignment): return _ProcessorHandle(self.processor, assignment) class _ProcessorHandle: - def __init__(self, processor: TopicMemoryProcessor, assignment: ArtifactProcessingWorkAssignment) -> None: + def __init__(self, processor: TopicMemoryScopeProcessor, assignment: ScopeAssignment) -> None: self.processor = processor self.assignment = assignment @@ -2079,6 +2084,9 @@ async def scenario() -> None: connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING, source.journal_position ) await pending.request_flush(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + await ArtifactProcessingIntentRepository().request( + connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING + ) processor = TopicMemoryProcessor( database=profile.database, sources=sources, @@ -2094,22 +2102,26 @@ async def scenario() -> None: ) binding = ArtifactProcessingBinding( binding_name=TOPIC_MEMORY_SOURCE_WINDOW_BINDING, - source_window_limit=10, - launcher=_ProcessorLauncher(processor), - window_selector=TopicMemoryWindowSelector( - profile.database, - sources, - character_token_estimator(), - context_window_tokens=10_000, + artifact_family="topic-memory", + max_workers=1, + worker_timeout_seconds=5, + launcher=_ProcessorLauncher( + TopicMemoryScopeProcessor( + profile.database, + processor, + TopicMemoryWindowSelector( + profile.database, + sources, + character_token_estimator(), + context_window_tokens=10_000, + ), + ) ), ) async with ArtifactProcessingSupervisor( database=profile.database, bindings=(binding,), lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=5, - pending=pending, retry_base_seconds=0.01, retry_cap_seconds=0.01, retry_jitter=lambda: 1.0, @@ -2183,7 +2195,17 @@ async def scenario() -> None: await scope.sources.capture(ContentCapture(source_id="spawn", content=secret)) async with contexts.database.transaction() as connection: term = await contexts.repositories.processing_leases.start_single_process_term(connection, "holder") - assignment = _assignment(term.fence("single-process"), through=1) + await ArtifactProcessingIntentRepository().request( + connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING + ) + assignment = ScopeAssignment( + binding_name=TOPIC_MEMORY_SOURCE_WINDOW_BINDING, + scope_id="scope-a", + artifact_family="topic-memory", + claimed_request_generation=1, + fence=term.fence("single-process"), + worker_id="worker-a", + ) launcher = SpawnArtifactProcessingWorkerLauncher( partial(_run_worker_without_general_fts_writes, TopicMemoryWorkerSpec(config=config)) ) @@ -2241,7 +2263,16 @@ async def scenario() -> None: async with current.database.transaction() as connection: assert tuple((await connection.execute(shape_query)).one()) == expected_shape launcher = SpawnArtifactProcessingWorkerLauncher(partial(run_topic_memory_worker, spec)) - handle = await launcher.start(_assignment(term.fence("single-process"), through=1)) + handle = await launcher.start( + ScopeAssignment( + binding_name=TOPIC_MEMORY_SOURCE_WINDOW_BINDING, + scope_id="scope-a", + artifact_family="topic-memory", + claimed_request_generation=1, + fence=term.fence("single-process"), + worker_id="worker-a", + ) + ) try: with pytest.raises(RuntimeError) as error: await asyncio.wait_for(handle.wait(), timeout=30) @@ -2343,30 +2374,100 @@ async def scenario() -> None: inference=InferenceConfig(generation_model="test"), ) async with open_builtin_contexts(config) as contexts: - bindings = _topic_memory_processing_bindings(config, contexts, ()) + bindings = _artifact_processing_bindings(config, contexts, ()) with pytest.raises(BuiltinConfigurationError, match="child-reconstructible"): - _topic_memory_processing_bindings( + _artifact_processing_bindings( config, contexts, (), injected_token_estimator=character_token_estimator(), ) - assert len(bindings) == 1 - assert bindings[0].binding_name == TOPIC_MEMORY_SOURCE_WINDOW_BINDING - assert bindings[0].window_selector is not None + topic_bindings = tuple(binding for binding in bindings if binding.artifact_family == "topic-memory") + assert len(topic_bindings) == 1 + assert topic_bindings[0].binding_name == TOPIC_MEMORY_SOURCE_WINDOW_BINDING incomplete = BuiltinConfig( runtime=RuntimeConfig(topic_memory_schedule_seconds=30), ) async with open_builtin_contexts(incomplete) as contexts: - with pytest.raises(BuiltinConfigurationError, match="generation model"): - _topic_memory_processing_bindings(incomplete, contexts, ()) + with pytest.raises(BuiltinConfigurationError, match="configured generation model"): + _artifact_processing_bindings(incomplete, contexts, ()) invalid_budget = config.model_copy( update={"inference": config.inference.model_copy(update={"generation_model_context_window_tokens": 1_000})} ) async with open_builtin_contexts(invalid_budget) as contexts: with pytest.raises(BuiltinConfigurationError, match="budget"): - _topic_memory_processing_bindings(invalid_budget, contexts, ()) + _artifact_processing_bindings(invalid_budget, contexts, ()) + + asyncio.run(scenario()) + + +def _run_topic_worker_without_server_imports(spec, assignment): + # Install inside the actual child; blocking imports in the parent does not + # constrain a spawned interpreter. Intercept cached modules as well. + import builtins + + original_import = builtins.__import__ + + def reject_server_import(name, *args, **kwargs): + if name == "powercontext.server" or name.startswith("powercontext.server."): + raise ModuleNotFoundError("Server dependencies are unavailable in the builtin SDK", name=name) # noqa: TRY003 + return original_import(name, *args, **kwargs) + + with pytest.MonkeyPatch.context() as patch: + patch.setattr(builtins, "__import__", reject_server_import) + return run_topic_memory_worker(spec, assignment) + + +def test_topic_worker_without_server_dependencies_acknowledges_and_replays_in_spawn_child(tmp_path) -> None: + async def scenario() -> None: + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'builtin-worker.db'}"), + inference=InferenceConfig(generation_model="test"), + ) + async with open_builtin_contexts(config) as contexts: + scope = await contexts.get("scope-a") + intents = ArtifactProcessingIntentRepository() + async with contexts.database.transaction() as connection: + term = await contexts.repositories.processing_leases.start_single_process_term(connection, "holder") + accepted = await intents.request(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + assignment = ScopeAssignment( + binding_name=TOPIC_MEMORY_SOURCE_WINDOW_BINDING, + scope_id="scope-a", + artifact_family="topic-memory", + claimed_request_generation=accepted.requested_generation, + fence=term.fence("single-process"), + worker_id="builtin-worker", + ) + launcher = SpawnArtifactProcessingWorkerLauncher( + partial(_run_topic_worker_without_server_imports, TopicMemoryWorkerSpec(config=config)) + ) + + async def invoke() -> None: + handle = await launcher.start(assignment) + try: + completion = await asyncio.wait_for(handle.wait(), timeout=30) + finally: + await handle.terminate() + assert completion.outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + + await invoke() + async with contexts.database.transaction() as connection: + acknowledged = await intents.load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + assert acknowledged is not None + assert acknowledged.requested_generation == acknowledged.handled_generation == 1 + assert acknowledged.dirty_generation == acknowledged.clean_generation == 0 + + # A replay of confirmed G1 must not consume newly captured input. + await scope.sources.capture(ContentCapture(source_id="later", content="Keep for the next request")) + await invoke() + async with contexts.database.transaction() as connection: + replayed = await intents.load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + cursor = await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + assert replayed is not None + assert replayed.requested_generation == replayed.handled_generation == 1 + assert replayed.dirty_generation > replayed.clean_generation + assert cursor is None asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_topic_memory_scope.py b/tests/builtin/runtime/test_topic_memory_scope.py new file mode 100644 index 0000000000..7440c33c0f --- /dev/null +++ b/tests/builtin/runtime/test_topic_memory_scope.py @@ -0,0 +1,337 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +from dataclasses import replace + +import pytest +from sqlalchemy import select, update + +from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING +from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryProbeOutput +from powercontext.builtin.inference import GenerationResult, character_token_estimator +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import ( + TOPIC_MEMORY_PROCESSING_TARGETS_TABLE, + TOPIC_MEMORY_WORK_BUDGETS_TABLE, +) +from powercontext.builtin.runtime.processing_contracts import ( + ArtifactProcessingWorkAssignment, + ArtifactProcessingWorkerOutcome, +) +from powercontext.builtin.runtime.topic_memory_processing import ( + TopicMemoryAtomicPublisher, + TopicMemoryProcessor, + TopicMemoryStageSet, + TopicMemoryWindowSelector, +) +from powercontext.builtin.runtime.topic_memory_scope import TopicMemoryScopeProcessor +from powercontext.sources import SourceMaterialization +from tests.builtin.persistence.contract import NoteSource +from tests.builtin.runtime.test_topic_memory_processing import _repositories + +BINDING = TOPIC_MEMORY_SOURCE_WINDOW_BINDING + + +class _Probe: + def __init__(self, before=None): + self.before = before + self.inputs = [] + + async def generate(self, value, /): + self.inputs.append(value) + if self.before is not None: + await self.before(len(self.inputs)) + return GenerationResult(output=TopicMemoryProbeOutput(probes=())) + + +class _OneSourceSelector(TopicMemoryWindowSelector): + async def select(self, scope_id, source_after, source_ceiling, /): + return await super().select(scope_id, source_after, min(source_after + 1, source_ceiling)) + + +def _processor(profile, sources, topics, probe, *, commit_authorizer=None, intents=None): + stages = TopicMemoryStageSet( + probe=probe, + global_evolver=probe, + planner=probe, + evolver=probe, + temporary=probe, + reconciler=probe, + estimator=character_token_estimator(), + input_tokens_limit=100_000, + ) + domain = TopicMemoryProcessor( + database=profile.database, + sources=sources, + topics=topics, + stages=stages, + publisher=TopicMemoryAtomicPublisher(profile.database, sources, topics, commit_authorizer=commit_authorizer), + ) + return TopicMemoryScopeProcessor( + profile.database, + domain, + _OneSourceSelector(profile.database, sources, character_token_estimator(), context_window_tokens=100_000), + commit_authorizer=commit_authorizer, + intents=intents, + ) + + +async def _capture(profile, sources, number, *, flush=True): + intents = ArtifactProcessingIntentRepository() + async with profile.database.transaction() as connection: + source = await sources.add( + connection, + "scope-a", + NoteSource(name=f"note-{number}", materialization=SourceMaterialization.CAPTURED, body=f"source {number}"), + ) + pending = ArtifactProcessingPendingRepository() + await pending.raise_source(connection, "scope-a", BINDING, source.journal_position) + if flush: + await pending.request_flush(connection, "scope-a", BINDING) + return await intents.request(connection, "scope-a", BINDING) + return await intents.load(connection, "scope-a", BINDING) + + +async def _assignment(profile, generation=1): + async with profile.database.transaction() as connection: + term = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "holder") + return ArtifactProcessingWorkAssignment( + binding_name=BINDING, + scope_id="scope-a", + artifact_family="topic-memory", + claimed_request_generation=generation, + fence=term.fence("single-process"), + worker_id="worker-a", + ) + + +async def _state(profile): + async with profile.database.transaction() as connection: + intent = await ArtifactProcessingIntentRepository().load(connection, "scope-a", BINDING) + cursor = await SourceCursorRepository().load(connection, "scope-a", BINDING) + pending = await ArtifactProcessingPendingRepository().load(connection, "scope-a", BINDING) + targets = (await connection.execute(select(TOPIC_MEMORY_PROCESSING_TARGETS_TABLE))).mappings().all() + return intent, 0 if cursor is None else cursor.cursor.sequence, pending, targets + + +def test_snapshot_reads_current_input_but_acknowledges_only_claimed_generation(): + async def scenario(): + manager, profile, sources, topics = await _repositories() + try: + await _capture(profile, sources, 1) + assignment = await _assignment(profile) + await _capture(profile, sources, 2) + probe = _Probe() + processor = _processor(profile, sources, topics, probe) + result = await processor.process(assignment) + assert result.outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + intent, cursor, pending, targets = await _state(profile) + assert intent.requested_generation == 2 + assert intent.handled_generation == 1 + assert intent.clean_generation == intent.dirty_generation == 2 + assert cursor == 2 and pending is None and not targets + + await _capture(profile, sources, 3) + await processor.process(assignment) + assert len(probe.inputs) == 2 + assert (await _state(profile))[1] == 2 + await processor.process(replace(assignment, claimed_request_generation=2)) + intent, cursor, _, targets = await _state(profile) + assert cursor == 3 and intent.handled_generation == 2 and intent.requested_generation == 3 + assert not targets + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +def test_crash_after_partial_commit_retains_old_target_before_new_invocation(): + async def scenario(): + manager, profile, sources, topics = await _repositories() + try: + await _capture(profile, sources, 1, flush=False) + await _capture(profile, sources, 2) + assignment = await _assignment(profile) + + async def crash_second(count): + if count == 2: + raise RuntimeError("worker crashed") # noqa: TRY003 + + with pytest.raises(RuntimeError, match="worker crashed"): + await _processor(profile, sources, topics, _Probe(crash_second)).process(assignment) + intent, cursor, pending, targets = await _state(profile) + assert cursor == 1 and intent.handled_generation == 0 + assert pending.handled_flush_generation == 0 + assert targets[0]["source_through"] == 2 and targets[0]["target_request_generation"] == 1 + await _capture(profile, sources, 3) + observed = [] + + async def observe(_count): + observed.append(await _state(profile)) + + result = await _processor(profile, sources, topics, _Probe(observe)).process( + replace(assignment, claimed_request_generation=2) + ) + assert result.outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + assert observed[0][3][0]["source_through"] == 2 + assert observed[1][0].handled_generation == 1 + assert observed[1][3][0]["source_through"] == 3 + assert observed[1][3][0]["target_request_generation"] == 2 + intent, cursor, pending, targets = await _state(profile) + assert cursor == 3 and intent.handled_generation == intent.requested_generation == 2 + assert pending is None and not targets + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +def test_late_source_and_flush_are_not_consumed_by_active_target(): + async def scenario(): + manager, profile, sources, topics = await _repositories() + try: + await _capture(profile, sources, 1) + assignment = await _assignment(profile) + + async def append_during_generation(_count): + await _capture(profile, sources, 2) + + probe = _Probe(append_during_generation) + result = await _processor(profile, sources, topics, probe).process(assignment) + assert result.outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + intent, cursor, pending, targets = await _state(profile) + assert cursor == 1 and intent.handled_generation == 1 and intent.requested_generation == 2 + assert pending.flush_generation == 2 and pending.handled_flush_generation == 1 + assert intent.dirty_generation > intent.clean_generation and not targets + replay = _Probe() + await _processor(profile, sources, topics, replay).process(assignment) + assert not replay.inputs + await _processor(profile, sources, topics, replay).process( + replace(assignment, claimed_request_generation=2) + ) + assert (await _state(profile))[1] == 2 + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +def test_target_compare_and_swap_failure_rolls_back_cursor_and_acknowledgement(): + async def scenario(): + manager, profile, sources, topics = await _repositories() + try: + await _capture(profile, sources, 1) + assignment = await _assignment(profile) + + async def replace_target(_count): + async with profile.database.transaction() as connection: + await ArtifactProcessingIntentRepository().request(connection, "scope-a", BINDING) + await connection.execute( + update(TOPIC_MEMORY_PROCESSING_TARGETS_TABLE).values(target_request_generation=2) + ) + + result = await _processor(profile, sources, topics, _Probe(replace_target)).process(assignment) + assert result.outcome is ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT + intent, cursor, pending, targets = await _state(profile) + assert cursor == 0 and intent.handled_generation == 0 and pending.handled_flush_generation == 0 + assert targets[0]["target_request_generation"] == 2 + async with profile.database.transaction() as connection: + budgets = (await connection.execute(select(TOPIC_MEMORY_WORK_BUDGETS_TABLE))).mappings().all() + # Provider reservations remain charged after publication rollback. + assert len(budgets) == 1 and budgets[0]["requests"] > 0 + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +def test_source_capture_waits_for_frozen_worker_snapshot(tmp_path): + async def scenario(): + manager, profile, sources, topics = await _repositories( + SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'freeze-race.db'}") + ) + freeze_started = asyncio.Event() + finish_freeze = asyncio.Event() + capture_started = asyncio.Event() + + class PausedIntents(ArtifactProcessingIntentRepository): + async def load(self, connection, scope_id, binding_name, /, *, for_update=False): + result = await super().load(connection, scope_id, binding_name, for_update=for_update) + if for_update and not freeze_started.is_set(): + freeze_started.set() + await finish_freeze.wait() + return result + + try: + await _capture(profile, sources, 1) + assignment = await _assignment(profile) + + async def capture(): + capture_started.set() + await _capture(profile, sources, 2) + + async def wait_for_capture(_count): + await capture_task + + probe = _Probe(wait_for_capture) + processor = _processor(profile, sources, topics, probe, intents=PausedIntents()) + worker = asyncio.create_task(processor.process(assignment)) + await asyncio.wait_for(freeze_started.wait(), 5) + capture_task = asyncio.create_task(capture()) + await asyncio.wait_for(capture_started.wait(), 5) + finish_freeze.set() + result = await asyncio.wait_for(worker, 10) + await capture_task + assert result.outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + intent, cursor, pending, targets = await _state(profile) + assert len(probe.inputs) == 1 and cursor == 1 + assert intent.handled_generation == 1 and intent.requested_generation == 2 + assert pending.handled_flush_generation == 1 and pending.flush_generation == 2 and not targets + finally: + finish_freeze.set() + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("empty", [False, True]) +def test_authorization_failure_preserves_target_and_unacknowledged_work(empty): + async def scenario(): + manager, profile, sources, topics = await _repositories() + try: + if empty: + async with profile.database.transaction() as connection: + await ArtifactProcessingIntentRepository().request(connection, "scope-a", BINDING) + else: + await _capture(profile, sources, 1) + assignment = await _assignment(profile) + + async def deny(_connection, _scope_id, _operations): + raise PermissionError("access revoked") # noqa: TRY003 + + with pytest.raises(PermissionError, match="access revoked"): + await _processor(profile, sources, topics, _Probe(), commit_authorizer=deny).process(assignment) + intent, cursor, _, targets = await _state(profile) + assert cursor == 0 and intent.handled_generation == 0 and targets + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_topic_memory_security.py b/tests/builtin/runtime/test_topic_memory_security.py new file mode 100644 index 0000000000..bd624283cb --- /dev/null +++ b/tests/builtin/runtime/test_topic_memory_security.py @@ -0,0 +1,229 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Topic publication, Server ownership, and accepted request completion are atomic.""" + +from __future__ import annotations + +import asyncio + +import pytest +from sqlalchemy import func, select + +from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING, TopicMemoryContent +from powercontext.builtin.artifacts.topic_memory.generation import ( + TopicMemoryGlobalOutput, + TopicMemoryProbe, + TopicMemoryProbeOutput, + TopicMemoryProposal, +) +from powercontext.builtin.inference import character_token_estimator +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.sources import SourceRepository +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.sqlite.topic_memory_index import SQLiteTopicMemoryFTSIndex +from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import ( + ARTIFACT_HEADS_TABLE, + BUILTIN_TABLES, + TOPIC_MEMORY_ACTIVE_TOPICS_TABLE, + TOPIC_MEMORY_PROCESSING_TARGETS_TABLE, + TOPIC_MEMORY_REVISION_PUBLICATIONS_TABLE, + TOPIC_MEMORY_WORK_BUDGETS_TABLE, +) +from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository +from powercontext.builtin.persistence.topic_memory_index import CompositeTopicMemoryIndex +from powercontext.builtin.runtime.processing_contracts import ( + ArtifactProcessingWorkAssignment, + ArtifactProcessingWorkerOutcome, +) +from powercontext.builtin.runtime.topic_memory_processing import ( + TopicMemoryAtomicPublisher, + TopicMemoryProcessor, + TopicMemoryWindowSelector, +) +from powercontext.builtin.runtime.topic_memory_scope import TopicMemoryScopeProcessor +from powercontext.server.authz import PrincipalRef +from powercontext.server.authz.repository import ACCESS_AUDIT_EVENTS_TABLE, ACCESS_OWNERS_TABLE, ACCESS_TABLES +from powercontext.server.processing_security import WorkerSecuritySpec, open_worker_security +from powercontext.sources import SourceMaterialization +from tests.builtin.persistence.contract import SOURCE_ADAPTERS, NoteSource +from tests.builtin.runtime.test_topic_memory_processing import _stages + +BINDING = TOPIC_MEMORY_SOURCE_WINDOW_BINDING +SCOPE = "topic-security-scope" +TOPIC_ID = "owned-topic" + + +@pytest.mark.parametrize("failure_boundary", ["owner", "acknowledgement"]) +def test_real_topic_owner_and_publication_roll_back_then_same_generation_retry_succeeds(tmp_path, failure_boundary): + async def scenario(): + index = CompositeTopicMemoryIndex(SQLiteTopicMemoryFTSIndex()) + topics = TopicMemoryRepository(index=index) + sources = SourceRepository(SOURCE_ADAPTERS) + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'topic-security.db'}") + async with SQLiteProfile.open(config, tables=(*BUILTIN_TABLES, *ACCESS_TABLES, *index.tables)) as profile: + async with profile.database.transaction() as connection: + await topics.initialize(connection) + source = await sources.add( + connection, + SCOPE, + NoteSource( + name="ownership-source", materialization=SourceMaterialization.CAPTURED, body="Verified topic" + ), + ) + pending = ArtifactProcessingPendingRepository() + await pending.raise_source(connection, SCOPE, BINDING, source.journal_position) + await pending.request_flush(connection, SCOPE, BINDING) + intent = await ArtifactProcessingIntentRepository().request(connection, SCOPE, BINDING) + term = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "topic-owner") + assignment = ArtifactProcessingWorkAssignment( + BINDING, SCOPE, "topic-memory", intent.requested_generation, term.fence("single-process"), "worker-1" + ) + + def processor(commit_authorizer): + stages = _stages( + probe=TopicMemoryProbeOutput( + probes=(TopicMemoryProbe(query="verified", evidence_ids=("evidence-0001",)),) + ), + global_output=TopicMemoryGlobalOutput( + proposals=( + TopicMemoryProposal( + content=TopicMemoryContent( + title="Verified", summary="Durable topic", detail="Evidence" + ), + evidence_ids=("evidence-0001",), + ), + ) + ), + ) + return TopicMemoryScopeProcessor( + profile.database, + TopicMemoryProcessor( + database=profile.database, + sources=sources, + topics=topics, + stages=stages, + publisher=TopicMemoryAtomicPublisher( + profile.database, sources, topics, commit_authorizer=commit_authorizer + ), + id_factory=lambda: TOPIC_ID, + ), + TopicMemoryWindowSelector( + profile.database, sources, character_token_estimator(), context_window_tokens=100_000 + ), + commit_authorizer=commit_authorizer, + ) + + spec = WorkerSecuritySpec( + principal=PrincipalRef(type="service", id="topic-worker"), deployment_id="test", static_preset=True + ).model_dump(mode="json") + async with open_worker_security(spec, profile.database) as security: + assert security is not None + owner_hook_calls = 0 + + async def owner_commit(connection, scope_id, operations): + nonlocal owner_hook_calls + await security.topic_commit(connection, scope_id, operations) + owner_hook_calls += 1 + assert len(operations) == 1 and operations[0].artifact_id == TOPIC_ID + assert await connection.scalar(select(func.count()).select_from(ACCESS_OWNERS_TABLE)) == 1 + assert ( + await connection.scalar( + select(func.count()) + .select_from(ACCESS_AUDIT_EVENTS_TABLE) + .where(ACCESS_AUDIT_EVENTS_TABLE.c.reason_code == "artifact-owner-established") + ) + == 1 + ) + if failure_boundary == "owner": + raise OSError("injected after real Topic owner hook") # noqa: TRY003 + + first = processor(owner_commit) + finish_target = first._finish_target + + async def fail_after_ack(connection, work, target): + await finish_target(connection, work, target) + acknowledged = await ArtifactProcessingIntentRepository().load(connection, SCOPE, BINDING) + cursor = await SourceCursorRepository().load(connection, SCOPE, BINDING) + assert acknowledged is not None and cursor is not None + assert acknowledged.handled_generation == assignment.claimed_request_generation + assert cursor.cursor.sequence == source.journal_position + assert await connection.scalar(select(func.count()).select_from(ARTIFACT_HEADS_TABLE)) == 1 + assert await connection.scalar(select(func.count()).select_from(ACCESS_OWNERS_TABLE)) == 1 + raise OSError("injected after real Topic owner hook and acknowledgement") # noqa: TRY003 + + if failure_boundary == "acknowledgement": + first._finish_target = fail_after_ack + with pytest.raises(OSError, match="after real Topic owner hook"): + await first.process(assignment) + assert owner_hook_calls == 1 + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, SCOPE, BINDING) + intent = await ArtifactProcessingIntentRepository().load(connection, SCOPE, BINDING) + pending = await ArtifactProcessingPendingRepository().load(connection, SCOPE, BINDING) + assert cursor is None + assert intent is not None and pending is not None + assert intent.handled_generation == 0 and intent.clean_generation == 0 + assert pending.handled_flush_generation == 0 and pending.flush_generation == 1 + target = (await connection.execute(select(TOPIC_MEMORY_PROCESSING_TARGETS_TABLE))).mappings().one() + assert target["target_request_generation"] == assignment.claimed_request_generation + assert target["source_through"] == source.journal_position + for table in ( + ARTIFACT_HEADS_TABLE, + TOPIC_MEMORY_ACTIVE_TOPICS_TABLE, + TOPIC_MEMORY_REVISION_PUBLICATIONS_TABLE, + ACCESS_OWNERS_TABLE, + ACCESS_AUDIT_EVENTS_TABLE, + ): + assert await connection.scalar(select(func.count()).select_from(table)) == 0 + budget_before = (await connection.execute(select(TOPIC_MEMORY_WORK_BUDGETS_TABLE))).mappings().one() + assert budget_before["attempts"] == 1 and budget_before["requests"] > 0 + + async def retry_commit(connection, scope_id, operations): + await security.topic_commit(connection, scope_id, operations) + budget = (await connection.execute(select(TOPIC_MEMORY_WORK_BUDGETS_TABLE))).mappings().one() + assert budget["attempts"] == 2 and budget["requests"] > budget_before["requests"] + + retry = processor(retry_commit) + assert (await retry.process(assignment)).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + # Replaying the same acknowledged G must not invoke the exhausted deterministic generators. + assert (await retry.process(assignment)).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, SCOPE, BINDING) + intent = await ArtifactProcessingIntentRepository().load(connection, SCOPE, BINDING) + assert cursor is not None and intent is not None + assert cursor.cursor.sequence == source.journal_position + assert intent.handled_generation == assignment.claimed_request_generation + assert intent.clean_generation == intent.dirty_generation + assert await ArtifactProcessingPendingRepository().load(connection, SCOPE, BINDING) is None + assert ( + await connection.scalar(select(func.count()).select_from(TOPIC_MEMORY_PROCESSING_TARGETS_TABLE)) + == 0 + ) + owner = (await connection.execute(select(ACCESS_OWNERS_TABLE))).mappings().one() + assert (owner["owner_kind"], owner["family"], owner["artifact_id"]) == ( + "artifact", + "topic-memory", + TOPIC_ID, + ) + assert (owner["owner_type"], owner["owner_id"]) == ("service", "topic-worker") + assert await connection.scalar(select(func.count()).select_from(ARTIFACT_HEADS_TABLE)) == 1 + assert ( + await connection.scalar(select(func.count()).select_from(TOPIC_MEMORY_WORK_BUDGETS_TABLE)) == 0 + ) + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_topic_memory_work_budget.py b/tests/builtin/runtime/test_topic_memory_work_budget.py index 371ad50a3b..5c812ce1a4 100644 --- a/tests/builtin/runtime/test_topic_memory_work_budget.py +++ b/tests/builtin/runtime/test_topic_memory_work_budget.py @@ -21,6 +21,7 @@ import sys from contextlib import AsyncExitStack from dataclasses import replace +from types import SimpleNamespace from typing import Any, cast import httpx @@ -45,9 +46,9 @@ from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingWorkerOutcome from powercontext.builtin.runtime.composition import ( BuiltinConfigurationError, + _artifact_processing_bindings, _provider_factory, _topic_memory_processing_available, - _topic_memory_processing_bindings, ) from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig, RuntimeConfig from powercontext.builtin.runtime.topic_memory_processing import ( @@ -407,13 +408,14 @@ async def scenario(): database=SQLiteConfig(url="sqlite+aiosqlite:///not-opened.sqlite3"), inference=InferenceConfig.model_validate(settings), ) - assert _topic_memory_processing_bindings(config, cast(Any, None), ()) == () + bindings = _artifact_processing_bindings(config, cast(Any, SimpleNamespace(database=None)), ()) + assert all(binding.artifact_family != "topic-memory" for binding in bindings) assert not _topic_memory_processing_available(config, ()) api = config.model_copy(update={"runtime": RuntimeConfig(artifact_processing_role="api")}) assert not _topic_memory_processing_available(api, ()) scheduled = config.model_copy(update={"runtime": RuntimeConfig(topic_memory_schedule_seconds=60)}) with pytest.raises(BuiltinConfigurationError): - _topic_memory_processing_bindings(scheduled, cast(Any, None), ()) + _artifact_processing_bindings(scheduled, cast(Any, None), ()) spec = TopicMemoryWorkerSpec(config=config) with pytest.raises(BuiltinConfigurationError): async with _open_topic_memory_processor(spec, "scope-a"): @@ -516,10 +518,10 @@ def test_unsupported_worker_provider_fails_when_binding_is_assembled(): config = BuiltinConfig( database=SQLiteConfig(url="sqlite+aiosqlite:///not-opened.sqlite3"), inference=InferenceConfig(generation_model="google:test"), - runtime=RuntimeConfig(topic_memory_schedule_seconds=60), + runtime=RuntimeConfig(topic_memory_schedule_seconds=60, artifact_processing_families=("topic-memory",)), ) with pytest.raises(BuiltinConfigurationError, match="bounded stateless"): - _topic_memory_processing_bindings(config, cast(Any, None), ()) + _artifact_processing_bindings(config, cast(Any, None), ()) def test_embedding_shares_exhausted_generation_budget_and_other_scope_can_progress(monkeypatch): diff --git a/tests/builtin/runtime/test_worker_prompt_usage.py b/tests/builtin/runtime/test_worker_prompt_usage.py new file mode 100644 index 0000000000..9d8f6b70a5 --- /dev/null +++ b/tests/builtin/runtime/test_worker_prompt_usage.py @@ -0,0 +1,328 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Configured spawned Workers honor persisted Prompts and count inference once.""" + +from __future__ import annotations + +import asyncio +import json +import threading +from functools import partial +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any, cast + +import pytest +from pydantic import AnyHttpUrl +from sqlalchemy import func, select + +from powercontext.builtin.artifacts.memory import EmbeddingProfile +from powercontext.builtin.artifacts.memory.prompts import MemoryExtractionProfile +from powercontext.builtin.artifacts.prompt import PromptError +from powercontext.builtin.inference import EmbeddingResult +from powercontext.builtin.inference.models import InferenceUsage +from powercontext.builtin.inference.usage import UsageReportingEmbeddingModel, bind_usage_reporter +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import ( + ARTIFACT_CANDIDATE_HEADS_TABLE, + ARTIFACT_HEADS_TABLE, + BUILTIN_TABLES, + MODEL_USAGE_DAILY_TABLE, +) +from powercontext.builtin.records import ArtifactWrite +from powercontext.builtin.runtime import CaptureSource +from powercontext.builtin.runtime.artifact_processing import SpawnArtifactProcessingWorkerLauncher +from powercontext.builtin.runtime.composition import _usage_reporting_embedding_model, open_builtin_runtime +from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig, RuntimeConfig +from powercontext.builtin.runtime.family_processing import FAMILY_BINDINGS, FamilyWorkerSpec, run_family_worker +from powercontext.builtin.runtime.processing_contracts import ArtifactProcessingWorkAssignment +from powercontext.builtin.scope import ScopeDraft +from powercontext.builtin.statistics import ModelUsagePurpose +from powercontext.server.authz import PrincipalRef +from powercontext.server.authz.repository import ACCESS_OWNERS_TABLE, ACCESS_TABLES +from powercontext.server.processing_security import WorkerSecuritySpec + + +class _InferenceServer(ThreadingHTTPServer): + requests: list[tuple[str, dict[str, Any]]] + family: str + + +class _InferenceHandler(BaseHTTPRequestHandler): + def do_POST(self) -> None: + payload = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + server = cast(_InferenceServer, self.server) + server.requests.append((self.path, payload)) + if self.path == "/v1/embeddings": + inputs = payload["input"] + body = { + "object": "list", + "model": "test-embedding", + "data": [ + {"object": "embedding", "index": index, "embedding": [1.0, 0.0]} for index in range(len(inputs)) + ], + "usage": {"prompt_tokens": 7, "total_tokens": 7}, + } + else: + if server.family == "memory": + candidate = { + "intent": "add", + "kind": "preference", + "text": "The user requires spawned Worker validation.", + "evidence_ids": ["source:0"], + } + else: + candidate = { + "proposal": { + "situation": "A configured Worker runs in another process.", + "action": "Restore its supported Prompt registry.", + "outcome": "The persisted guidance is honored.", + "lesson": "Validate reconstructed capabilities in a spawned process.", + }, + "evidence_ids": ["source:content/evidence"], + } + body = { + "id": "worker-prompt-test", + "object": "chat.completion", + "created": 0, + "model": "gpt-4o-mini", + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": json.dumps({"candidates": [candidate]})}, + "finish_reason": "stop", + } + ], + "usage": {"prompt_tokens": 11, "completion_tokens": 13, "total_tokens": 24}, + } + encoded = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 - stdlib parameter + pass + + +@pytest.mark.parametrize("family", ["memory", "experience"]) +def test_spawned_worker_restores_custom_prompt_and_counts_actual_requests_once(tmp_path, monkeypatch, family): + # A configured loopback provider crosses the real spawn/serialization boundary: + # no injected pipeline, model monkeypatch, or preconstructed PromptRegistry reaches the child. + monkeypatch.setenv("OPENAI_API_KEY", "hermetic-worker-key") + server = _InferenceServer(("127.0.0.1", 0), _InferenceHandler) + server.requests = [] + server.family = family + thread = threading.Thread(target=server.serve_forever) + thread.start() + + async def scenario(): + endpoint = AnyHttpUrl(f"http://127.0.0.1:{server.server_port}/v1") + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'worker.db'}"), + inference=InferenceConfig( + generation_model="openai-chat:gpt-4o-mini", + generation_base_url=endpoint, + embedding_model="openai:test-embedding" if family == "memory" else None, + embedding_base_url=endpoint if family == "memory" else None, + embedding_dimension=2 if family == "memory" else None, + embedding_profile_id="worker-test" if family == "memory" else None, + ), + runtime=RuntimeConfig( + artifact_processing_families=(family,), + memory_extraction_profile=MemoryExtractionProfile.CONVERSATION, + ), + ) + prompt_key = "memory.extract" if family == "memory" else "experience.incubate" + marker = f"PERSISTED_CUSTOM_{family.upper()}_GUIDANCE" + async with open_builtin_runtime(config) as runtime: + assert runtime.scopes is not None + scope = ( + await runtime.scopes.create(ScopeDraft(title="Worker", summary="Worker", idempotency_key="worker")) + ).scope_id + await runtime.records.for_scope(scope).create_artifact( + "prompt", + ArtifactWrite( + prompt_key=prompt_key, + content={ + "schema_version": "powercontext.prompt.v1", + "mode": "custom", + "instructions": f"{marker}: Preserve the supplied evidence and return one bounded candidate.", + "demonstrations": [], + }, + ), + ) + receipt = await runtime.sources.for_scope(scope).capture( + CaptureSource( + source_id="evidence", + content="The user requires spawned Worker tests. Restoring the Prompt registry made one pass.", + metadata={"kind": "task-outcome"}, + ) + ) + assert server.requests == [] + assert isinstance(config.database, SQLiteConfig) + async with SQLiteProfile.open(config.database, tables=(*BUILTIN_TABLES, *ACCESS_TABLES)) as profile: + async with profile.database.transaction() as connection: + lease = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "worker") + intent = await ArtifactProcessingIntentRepository().request(connection, scope, FAMILY_BINDINGS[family]) + assignment = ArtifactProcessingWorkAssignment( + binding_name=FAMILY_BINDINGS[family], + scope_id=scope, + artifact_family=family, + claimed_request_generation=intent.requested_generation, + fence=lease.fence("single-process"), + worker_id="worker-prompt-test", + ) + security = WorkerSecuritySpec( + principal=PrincipalRef(type="service", id="worker-test"), + deployment_id="test", + static_preset=True, + ).model_dump(mode="json") + launcher = SpawnArtifactProcessingWorkerLauncher( + partial(run_family_worker, FamilyWorkerSpec(config=config, worker_security=security)) + ) + for _ in range(2): + worker = await launcher.start(assignment) + try: + result = await asyncio.wait_for(worker.wait(), timeout=45) + assert result.outcome == "succeeded", result + finally: + await worker.terminate() + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, scope, assignment.binding_name) + completed = await ArtifactProcessingIntentRepository().load( + connection, scope, assignment.binding_name + ) + assert cursor is not None and cursor.cursor.sequence == receipt.sequence + assert ( + completed is not None and completed.handled_generation == assignment.claimed_request_generation + ) + assert completed.clean_generation == completed.dirty_generation + generated = ARTIFACT_HEADS_TABLE if family == "memory" else ARTIFACT_CANDIDATE_HEADS_TABLE + assert ( + await connection.scalar( + select(func.count()).select_from(generated).where(generated.c.family == family) + ) + == 1 + ) + assert await connection.scalar(select(func.count()).select_from(ACCESS_OWNERS_TABLE)) == 1 + usage = (await connection.execute(select(MODEL_USAGE_DAILY_TABLE))).mappings().all() + generation = [row for row in usage if row["operation"] == "generation"] + assert len(generation) == 1 + assert generation[0]["scope_id"] == scope + assert generation[0]["purpose"] == ( + "memory_extraction" if family == "memory" else "experience_generation" + ) + assert generation[0]["requests"] == 1 + assert generation[0]["input_tokens"] == 11 + assert generation[0]["output_tokens"] == 13 + embedding = [row for row in usage if row["operation"] == "embedding"] + if family == "memory": + assert len(embedding) == 1 + assert embedding[0]["scope_id"] == scope + assert embedding[0]["purpose"] == "memory_indexing" + assert embedding[0]["requests"] == 1 + assert embedding[0]["input_tokens"] == 7 + else: + assert embedding == [] + calls = [payload for path, payload in server.requests if path == "/v1/chat/completions"] + assert len(calls) == 1 + assert marker in json.dumps(calls[0]) + assert len([path for path, _ in server.requests if path == "/v1/embeddings"]) == ( + 1 if family == "memory" else 0 + ) + + try: + asyncio.run(scenario()) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + assert not thread.is_alive() + + +def test_operational_embedding_composition_does_not_double_count_an_existing_usage_adapter(): + class Embedding: + profile = EmbeddingProfile(profile_id="test", model="test", dimension=2, distance="l2", normalization="unit") + + async def embed(self, texts): + return EmbeddingResult(vectors=((1.0, 0.0),) * len(texts), usage=InferenceUsage(requests=1, input_tokens=3)) + + async def scenario(): + reports = [] + + async def report(purpose, operation, usage): + reports.append((purpose, operation, usage)) + + model = _usage_reporting_embedding_model(UsageReportingEmbeddingModel(Embedding())) + assert model is not None + with bind_usage_reporter(report, embedding_purpose=ModelUsagePurpose.MEMORY_INDEXING): + await model.embed(("One document",)) + assert len(reports) == 1 + assert reports[0][2].requests == 1 + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("family", ["memory", "experience"]) +@pytest.mark.parametrize("injected", [False, True]) +def test_shared_prompt_composition_preserves_missing_provider_and_injected_rejection(family, injected): + class Pipeline: + async def extract(self, request): + return () + + async def incubate(self, sources): + return () + + async def scenario(): + config = BuiltinConfig( + inference=InferenceConfig(generation_model="test" if injected else None), + runtime=RuntimeConfig(artifact_processing_families=()), + ) + pipeline = Pipeline() + async with open_builtin_runtime( + config, + candidate_pipeline=pipeline if injected and family == "memory" else None, + experience_pipeline=pipeline if injected and family == "experience" else None, + ) as runtime: + assert runtime.scopes is not None + scope = ( + await runtime.scopes.create(ScopeDraft(title="Prompt", summary="Prompt", idempotency_key="prompt")) + ).scope_id + key = "memory.extract" if family == "memory" else "experience.incubate" + capability = await runtime.prompts.for_scope(scope).read_configuration(key) + assert capability.status == ("unsupported" if injected else "disabled") + assert capability.reason == ("injected_component" if injected else "provider_not_configured") + disabled = await runtime.prompts.for_scope(scope).read_configuration("memory.rerank") + assert disabled.status == "disabled" and disabled.reason == "operation_disabled" + with pytest.raises(PromptError) as rejected: + await runtime.records.for_scope(scope).create_artifact( + "prompt", + ArtifactWrite( + prompt_key=key, + content={ + "schema_version": "powercontext.prompt.v1", + "mode": "custom", + "instructions": "This component cannot honor customized instructions.", + "demonstrations": [], + }, + ), + ) + assert rejected.value.code == "prompt_customization_unavailable" + + asyncio.run(scenario()) diff --git a/tests/e2e/artifact_supervisor_real.py b/tests/e2e/artifact_supervisor_real.py new file mode 100644 index 0000000000..d227149044 --- /dev/null +++ b/tests/e2e/artifact_supervisor_real.py @@ -0,0 +1,684 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Opt-in real-provider acceptance for the four Scope processors. + +Run each database in its own disposable location. The JSON report contains +counts and control state only; provider settings, inputs, and outputs stay out +of the artifact. This module is not collected by ordinary pytest. +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import tempfile +import time +from pathlib import Path +from typing import Any, Literal, cast +from uuid import uuid4 + +from pydantic import SecretStr +from sqlalchemy import func, select, text + +from powercontext.builtin.artifacts.profile.models import PROFILE_SOURCE_WINDOW_BINDING +from powercontext.builtin.artifacts.prompt import PromptKey +from powercontext.builtin.artifacts.prompt.builtin import builtin_prompt_definitions +from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository +from powercontext.builtin.persistence.processing_migration import bootstrap_processing_schema +from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.tables import ( + ARTIFACT_CANDIDATE_HEADS_TABLE, + ARTIFACT_CANDIDATE_VERSIONS_TABLE, + ARTIFACT_HEADS_TABLE, + ARTIFACT_PROCESSING_BINDING_STATES_TABLE, + BUILTIN_TABLES, + MEMORY_ENTRY_VERSIONS_TABLE, + MODEL_USAGE_DAILY_TABLE, + SCOPES_TABLE, + SOURCE_JOURNAL_HEADS_TABLE, +) +from powercontext.builtin.records import ArtifactWrite +from powercontext.builtin.runtime.composition import open_builtin_runtime +from powercontext.builtin.runtime.config import BuiltinConfig, RuntimeConfig +from powercontext.builtin.runtime.family_processing import FAMILY_BINDINGS +from powercontext.builtin.runtime.models import SearchTopicMemoryRequest +from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest +from powercontext.builtin.runtime.relational import RelationalContexts +from powercontext.builtin.scope import ScopeDraft +from powercontext.server.authz import PrincipalRef +from powercontext.server.authz.repository import ACCESS_OWNERS_TABLE, ACCESS_TABLES +from powercontext.server.configuration import server_settings_context +from powercontext.server.processing_security import WorkerSecuritySpec +from powercontext.server.settings import ServerSettings + +BINDINGS = {**FAMILY_BINDINGS, "topic-memory": TOPIC_MEMORY_SOURCE_WINDOW_BINDING} +PROFILE_CONTROL_TITLES = { + "absent": "Supervisor Profile absent-policy control", + "disabled": "Supervisor Profile disabled-policy control", +} +CUSTOM_PROMPT_MARKERS: dict[PromptKey, str] = { + "memory.extract": "ScopePromptMemoryAccepted", + "experience.incubate": "ScopePromptExperienceAccepted", +} + + +class AcceptanceFailure(RuntimeError): + def __init__(self, code: str) -> None: + super().__init__(code) + self.details: dict[str, Any] = {} + + +class FailureCapture(logging.Handler): + def __init__(self): + super().__init__() + self.failures: list[dict[str, str]] = [] + + def emit(self, record): + if record.levelno >= logging.ERROR and "artifact_processing" in record.name: + self.failures.append({ + "event": str(getattr(record, "event", "worker-error")), + "error_code": str(getattr(record, "error_code", "unknown")), + "exception_type": str(getattr(record, "exception_type", "unknown")), + "traceback": str(getattr(record, "traceback", "")), + "stage": str(getattr(record, "stage", "unknown")), + "family": str(getattr(record, "family", "unknown")), + }) + + +def _database(config): + if isinstance(config, SQLiteConfig): + return SQLiteProfile.open(config, tables=(*BUILTIN_TABLES, *ACCESS_TABLES)) + if isinstance(config, SeekDBConfig): + return SeekDBProfile.open(config, tables=(*BUILTIN_TABLES, *ACCESS_TABLES)) + return OceanBaseProfile.open(config, tables=(*BUILTIN_TABLES, *ACCESS_TABLES)) + + +def _seekdb_path(directory: Path) -> Path: + # Embedded SeekDB uses a Unix socket beneath its data path (108-byte limit). + link = directory / "seekdb" + if link.is_symlink() and not link.exists(): + raise AcceptanceFailure("seekdb-acceptance-database-no-longer-exists") + if not link.exists(): + # Runtime-owned TMPDIR can disappear between invocations. Preserve the + # dedicated data directory so a later --resume actually reopens it. + link.symlink_to(tempfile.mkdtemp(prefix="pc-rfc1515-", dir="/tmp"), target_is_directory=True) + return link.resolve() + + +async def _case_state(connection, database, scope: str) -> dict[str, Any]: + version_sql = "SELECT sqlite_version()" if isinstance(database, SQLiteConfig) else "SELECT version()" + version = str(await connection.scalar(text(version_sql))) + rows = ( + await connection.execute( + select( + MODEL_USAGE_DAILY_TABLE.c.purpose, + MODEL_USAGE_DAILY_TABLE.c.operation, + func.sum(MODEL_USAGE_DAILY_TABLE.c.requests), + ) + .where(MODEL_USAGE_DAILY_TABLE.c.scope_id == scope) + .group_by(MODEL_USAGE_DAILY_TABLE.c.purpose, MODEL_USAGE_DAILY_TABLE.c.operation) + ) + ).all() + intents = [ + await ArtifactProcessingIntentRepository().load(connection, scope, binding) for binding in BINDINGS.values() + ] + return { + "backend_version": version, + "profile_scan_generation": int( + await connection.scalar( + select(ARTIFACT_PROCESSING_BINDING_STATES_TABLE.c.scan_generation).where( + ARTIFACT_PROCESSING_BINDING_STATES_TABLE.c.binding_name == PROFILE_SOURCE_WINDOW_BINDING + ) + ) + or 0 + ), + "model_requests": {f"{row[0]}/{row[1]}": int(row[2]) for row in rows}, + "source_journal_position": int( + await connection.scalar( + select(SOURCE_JOURNAL_HEADS_TABLE.c.position).where(SOURCE_JOURNAL_HEADS_TABLE.c.scope_id == scope) + ) + or 0 + ), + "all_requests_handled": all( + row is not None and row.requested_generation > 0 and row.handled_generation >= row.requested_generation + for row in intents + ), + } + + +async def _prepare_scope( + database, config: BuiltinConfig, *, resume: bool, custom_prompts: bool, automatic_profile: bool +) -> tuple[str, dict[str, Any]]: + async with _database(database) as profile, profile.database.transaction() as connection: + count = await connection.scalar(select(func.count()).select_from(SCOPES_TABLE)) + if count and not resume: + raise AcceptanceFailure("acceptance-requires-empty-database") + if resume: + scopes = ( + ( + await connection.execute( + select(SCOPES_TABLE.c.scope_id).where( + SCOPES_TABLE.c.title == "Supervisor acceptance", + SCOPES_TABLE.c.summary == "Synthetic acceptance work", + ) + ) + ) + .scalars() + .all() + ) + if len(scopes) != 1: + raise AcceptanceFailure("resume-requires-one-acceptance-scope") + return scopes[0], await _case_state(connection, database, scopes[0]) + await bootstrap_processing_schema(connection, canonical_processing_manifest(config)) + # Compose the public Runtime so Prompt capabilities follow the same real + # adapters as production. Automatic admission is disabled in this fixture; + # accepted work is published only after this setup Runtime has closed. + setup_config = config.model_copy( + update={"runtime": config.runtime.model_copy(update={"profile_schedule_enabled": False})} + ) + async with open_builtin_runtime(setup_config) as setup_runtime: + contexts = cast(RelationalContexts, setup_runtime._provider) + scope = ( + await contexts.scopes.create( + ScopeDraft( + title="Supervisor acceptance", + summary="Synthetic acceptance work", + idempotency_key=uuid4().hex, + ) + ) + ).scope_id + if custom_prompts: + definitions = { + item.key: item for item in builtin_prompt_definitions(config.runtime.memory_extraction_profile) + } + for key, marker in CUSTOM_PROMPT_MARKERS.items(): + field = "text" if key == "memory.extract" else "lesson" + await contexts.records.create_artifact( + scope, + "prompt", + ArtifactWrite( + prompt_key=key, + content={ + "schema_version": "powercontext.prompt.v1", + "mode": "custom", + "instructions": definitions[key].default_instructions + + f"\nFor this Scope, prefix every candidate {field} with [{marker}] " + "as a formatting label, then include the supported factual content.", + "demonstrations": [], + }, + ), + ) + await contexts.profiles.put_policy( + scope, generation_enabled=True, activation_mode="review_required", expected_version=0 + ) + await contexts.records.capture_source( + scope, + "content", + "supervisor-real-task-outcome", + "Completed engineering task: a release failed because configuration changes bypassed validation. " + "I added a strict configuration check before deployment; the check then passed and the release succeeded. " + "Reusable lesson: always run the strict configuration test after changing configuration.", + {"kind": "task-outcome", "synthetic": True}, + ) + await contexts.records.capture_source( + scope, + "content", + "supervisor-real-user-profile", + "I am the single user of this Scope. I have worked as a Python backend engineer since 2020. " + "Simplified Chinese has been my preferred language for engineering discussions since 2024. " + "I use pytest for Python regression tests and require executable test evidence before accepting changes. " + "I prefer narrowly scoped code changes. These are my enduring personal work preferences, " + "consistently confirmed across multiple years and projects, independent of the current release task.", + {"kind": "profile-evidence", "role": "user", "synthetic": True}, + ) + if automatic_profile: + await _prepare_profile_controls(contexts) + async with ( + _database(database) as profile, + profile.database.transaction() as connection, + ): + for binding in BINDINGS.values(): + if not automatic_profile or binding != PROFILE_SOURCE_WINDOW_BINDING: + await ArtifactProcessingIntentRepository().request(connection, scope, binding) + return scope, await _case_state(connection, database, scope) + + +async def _prepare_profile_controls(contexts: RelationalContexts) -> None: + for policy, title in PROFILE_CONTROL_TITLES.items(): + control = ( + await contexts.scopes.create( + ScopeDraft(title=title, summary="Synthetic eligibility control", idempotency_key=uuid4().hex) + ) + ).scope_id + if policy == "disabled": + await contexts.profiles.put_policy( + control, generation_enabled=False, activation_mode="review_required", expected_version=0 + ) + await contexts.records.capture_source( + control, + "content", + f"supervisor-profile-{policy}-policy", + "I prefer executable Python regression evidence before accepting engineering changes.", + {"kind": "profile-evidence", "role": "user", "synthetic": True}, + ) + + +async def _automatic_profile_state(contexts: RelationalContexts, supervisor) -> dict[str, Any]: + """Observe durable cron progress and reject any admission of ineligible Scopes.""" + + controls = {} + async with contexts.database.transaction() as connection: + for policy, title in PROFILE_CONTROL_TITLES.items(): + scope = await connection.scalar(select(SCOPES_TABLE.c.scope_id).where(SCOPES_TABLE.c.title == title)) + if scope is None: + raise AcceptanceFailure("automatic-profile-control-scope-missing") + intent = await ArtifactProcessingIntentRepository().load(connection, scope, PROFILE_SOURCE_WINDOW_BINDING) + if intent is None or intent.dirty_generation <= intent.clean_generation: + raise AcceptanceFailure("automatic-profile-control-dirty-input-lost") + if intent.requested_generation or intent.handled_generation or intent.last_auto_scan_generation: + raise AcceptanceFailure("automatic-profile-ineligible-scope-admitted") + controllers = getattr(supervisor, "supervisors", (supervisor,)) + for controller in controllers: + state = controller._families.get(PROFILE_SOURCE_WINDOW_BINDING) + if state is not None and any(scope in items for items in (state.running, state.queued, state.retries)): + raise AcceptanceFailure("automatic-profile-ineligible-worker-or-retry") + controls[policy] = { + "requested_generation": intent.requested_generation, + "handled_generation": intent.handled_generation, + "last_auto_scan_generation": intent.last_auto_scan_generation, + "dirty_generation": intent.dirty_generation, + "clean_generation": intent.clean_generation, + "observed_running_queued_or_retry": False, + } + table = ARTIFACT_PROCESSING_BINDING_STATES_TABLE + scan = ( + (await connection.execute(select(table).where(table.c.binding_name == PROFILE_SOURCE_WINDOW_BINDING))) + .mappings() + .one_or_none() + ) + return { + "controls": controls, + "scan_generation": 0 if scan is None else int(scan["scan_generation"]), + "scan_in_progress": False if scan is None else bool(scan["scan_in_progress"]), + "checkpoint": None if scan is None else str(scan["last_schedule_checkpoint_at"]), + } + + +async def _custom_prompt_evidence(contexts: RelationalContexts, scope: str) -> dict[str, Any]: + async with contexts.database.transaction() as connection: + memory_texts = ( + ( + await connection.execute( + select(MEMORY_ENTRY_VERSIONS_TABLE.c.text).where(MEMORY_ENTRY_VERSIONS_TABLE.c.scope_id == scope) + ) + ) + .scalars() + .all() + ) + experience_proposals = ( + ( + await connection.execute( + select(ARTIFACT_CANDIDATE_VERSIONS_TABLE.c.proposal).where( + ARTIFACT_CANDIDATE_VERSIONS_TABLE.c.scope_id == scope, + ARTIFACT_CANDIDATE_VERSIONS_TABLE.c.family == "experience", + ) + ) + ) + .scalars() + .all() + ) + observed = { + "memory.extract": any(CUSTOM_PROMPT_MARKERS["memory.extract"] in str(value) for value in memory_texts), + "experience.incubate": any( + CUSTOM_PROMPT_MARKERS["experience.incubate"] in str(value) for value in experience_proposals + ), + } + evidence = {} + for key in CUSTOM_PROMPT_MARKERS: + selected = await contexts.prompts.resolve(scope, key) + if selected is None or selected.selection != "artifact" or not observed[key]: + raise AcceptanceFailure("custom-prompt-not-executed-by-worker") + evidence[key] = { + "selection": selected.selection, + "revision": selected.selected_version, + "compiled_digest": selected.compiled_digest, + "persisted_output_contains_custom_formatting_label": observed[key], + } + return evidence + + +async def run_acceptance( # noqa: C901 - one bounded end-to-end acceptance lifecycle + settings: ServerSettings, + *, + backend: str, + directory: Path, + mode: Literal["global", "dedicated"], + resume: bool = False, + custom_prompts: bool = False, + automatic_profile: bool = False, +) -> dict[str, Any]: + """Recover accepted work after reopening, then acknowledge a fresh NOOP.""" + + await asyncio.to_thread(directory.mkdir, parents=True, exist_ok=True) + inference = settings.inference + if inference.generation_model is None or inference.generation_model == "test": + raise AcceptanceFailure("real-generation-required") + if inference.embedding_model is None or inference.embedding_model == "test": + raise AcceptanceFailure("real-embedding-required") + if backend == "sqlite": + database = SQLiteConfig(url=f"sqlite+aiosqlite:///{(directory / 'runtime.db').resolve()}") + elif backend == "seekdb": + database = SeekDBConfig(path=await asyncio.to_thread(_seekdb_path, directory)) + else: + if not isinstance(settings.database, OceanBaseConfig): + raise AcceptanceFailure("dedicated-oceanbase-configuration-required") + database = settings.database + runtime_config = RuntimeConfig( + artifact_processing_supervisor_mode=mode, + artifact_processing_families=tuple(BINDINGS), + source_window_limit=4, + topic_memory_source_window_limit=4, + memory_max_workers=1, + experience_max_workers=1, + profile_max_workers=1, + profile_schedule_enabled=automatic_profile, + profile_cron="* * * * *", + topic_memory_max_workers=1, + ) + config = BuiltinConfig(database=database, runtime=runtime_config, inference=inference) + security = WorkerSecuritySpec( + principal=PrincipalRef(type="service", id="supervisor-real-acceptance"), + deployment_id="supervisor-real-acceptance", + static_preset=True, + ).model_dump(mode="json") + scope, initial_state = await _prepare_scope( + database, config, resume=resume, custom_prompts=custom_prompts, automatic_profile=automatic_profile + ) + captured = FailureCapture() + logger = logging.getLogger("powercontext.builtin.runtime.artifact_processing") + logger.addHandler(captured) + started = time.monotonic() + intent_states: dict[str, dict[str, int]] = {} + automatic_evidence: dict[str, Any] = {} + completed_scans: dict[int, str] = {} + required_scan_generation = initial_state["profile_scan_generation"] + (2 if resume else 3) + + def failed(code: str) -> AcceptanceFailure: + error = AcceptanceFailure(code) + error.details = { + "worker_failures": captured.failures, + "intent_generations": intent_states, + "automatic_profile": automatic_evidence, + "elapsed_seconds": round(time.monotonic() - started, 2), + } + return error + + try: + async with open_builtin_runtime(config, worker_security=security) as runtime: + contexts = cast(RelationalContexts, runtime._provider) + supervisor = runtime.artifact_processing_supervisor + if supervisor is None: + raise failed("supervisor-not-registered") + deadline = asyncio.get_running_loop().time() + 660 + while True: + async with contexts.database.transaction() as connection: + rows = [ + await ArtifactProcessingIntentRepository().load(connection, scope, binding) + for binding in BINDINGS.values() + ] + intent_states = { + family: { + "requested": row.requested_generation, + "handled": row.handled_generation, + "dirty": row.dirty_generation, + "clean": row.clean_generation, + } + for family, row in zip(BINDINGS, rows, strict=True) + if row is not None + } + scans_complete = True + if automatic_profile: + automatic_evidence = await _automatic_profile_state(contexts, supervisor) + if not automatic_evidence["scan_in_progress"] and automatic_evidence["scan_generation"]: + completed_scans[automatic_evidence["scan_generation"]] = automatic_evidence["checkpoint"] + scans_complete = ( + automatic_evidence["scan_generation"] >= required_scan_generation + and not automatic_evidence["scan_in_progress"] + ) + if all(row is not None and row.handled_generation >= 1 for row in rows) and scans_complete: + break + if asyncio.get_running_loop().time() >= deadline: + raise failed("accepted-work-timeout") + await asyncio.sleep(0.25) + async with contexts.database.transaction() as connection: + artifact_rows = ( + await connection.execute( + select(ARTIFACT_HEADS_TABLE.c.family, func.count()) + .where(ARTIFACT_HEADS_TABLE.c.scope_id == scope) + .group_by(ARTIFACT_HEADS_TABLE.c.family) + ) + ).all() + candidate_rows = ( + await connection.execute( + select(ARTIFACT_CANDIDATE_HEADS_TABLE.c.family, func.count()) + .where(ARTIFACT_CANDIDATE_HEADS_TABLE.c.scope_id == scope) + .group_by(ARTIFACT_CANDIDATE_HEADS_TABLE.c.family) + ) + ).all() + ownership_rows = ( + await connection.execute( + select(ACCESS_OWNERS_TABLE.c.family, func.count()) + .where(ACCESS_OWNERS_TABLE.c.scope_id == scope) + .group_by(ACCESS_OWNERS_TABLE.c.family) + ) + ).all() + ownership = {str(row[0]): int(row[1]) for row in ownership_rows} + artifacts = {str(row[0]): int(row[1]) for row in artifact_rows} + candidates = {str(row[0]): int(row[1]) for row in candidate_rows} + cursors = {} + for family, binding in BINDINGS.items(): + cursor = await SourceCursorRepository().load(connection, scope, binding) + cursors[family] = 0 if cursor is None else cursor.cursor.sequence + if artifacts.get("memory", 0) < 1 or artifacts.get("topic-memory", 0) < 1: + raise failed("real-generation-produced-no-published-memory") + if candidates.get("experience", 0) < 1 or candidates.get("profile", 0) != 1: + raise failed("real-generation-did-not-preserve-review-candidates") + if any(ownership.get(family, 0) < 1 for family in BINDINGS): + raise failed("atomic-owner-attestation-contract-failed") + if cursors["profile"] != 0 or any( + cursors[family] != initial_state["source_journal_position"] + for family in ("memory", "experience", "topic-memory") + ): + raise failed("domain-cursor-contract-failed") + # Already pending Profile review is a successful invocation without + # generating another Candidate or consuming its Source window. + async with contexts.database.transaction() as connection: + request = await ArtifactProcessingIntentRepository().request( + connection, scope, PROFILE_SOURCE_WINDOW_BINDING + ) + supervisor.wake(PROFILE_SOURCE_WINDOW_BINDING) + while True: + async with contexts.database.transaction() as connection: + pending = await ArtifactProcessingIntentRepository().load( + connection, scope, PROFILE_SOURCE_WINDOW_BINDING + ) + if pending is not None and pending.handled_generation >= request.requested_generation: + break + if asyncio.get_running_loop().time() >= deadline: + raise failed("pending-review-noop-failed") + await asyncio.sleep(0.25) + async with contexts.database.transaction() as connection: + review_count = await connection.scalar( + select(func.count()) + .select_from(ARTIFACT_CANDIDATE_HEADS_TABLE) + .where( + ARTIFACT_CANDIDATE_HEADS_TABLE.c.scope_id == scope, + ARTIFACT_CANDIDATE_HEADS_TABLE.c.family == "profile", + ) + ) + review_cursor = await SourceCursorRepository().load(connection, scope, PROFILE_SOURCE_WINDOW_BINDING) + final_state = await _case_state(connection, database, scope) + expected_ids = set( + ( + await connection.execute( + select(ARTIFACT_HEADS_TABLE.c.artifact_id).where( + ARTIFACT_HEADS_TABLE.c.scope_id == scope, + ARTIFACT_HEADS_TABLE.c.family == "topic-memory", + ) + ) + ).scalars() + ) + if review_count != 1 or (review_cursor is not None and review_cursor.cursor.sequence != 0): + raise failed("pending-review-noop-consumed-domain-input") + if automatic_profile: + automatic_evidence = await _automatic_profile_state(contexts, supervisor) + automatic_evidence.update({ + "initial_scan_generation": initial_state["profile_scan_generation"], + "required_scan_generation": required_scan_generation, + "observed_completed_scans": completed_scans, + "cron": "* * * * *", + "two_cron_fires_completed": True, + "initial_profile_explicit_request": False, + }) + replay_without_model_calls = resume and initial_state["all_requests_handled"] + if replay_without_model_calls and initial_state["model_requests"] != final_state["model_requests"]: + raise failed("completed-request-replay-made-model-calls") + for usage_key in ( + "memory_extraction/generation", + "memory_indexing/embedding", + "experience_generation/generation", + "topic_memory_generation/generation", + "topic_memory_indexing/embedding", + ): + if final_state["model_requests"].get(usage_key, 0) < 1: + raise failed("real-model-usage-evidence-missing") + prompt_evidence = await _custom_prompt_evidence(contexts, scope) if custom_prompts else {} + search = await runtime.topic_memory.for_scope(scope).search( + SearchTopicMemoryRequest(query="strict configuration validation release engineering", limit=10) + ) + vector_hits = sum(any("vector" in channel for channel in hit.matched_by) for hit in search.hits) + if ( + search.mode != "hybrid" + or not vector_hits + or any(hit.artifact_ref.artifact_id not in expected_ids for hit in search.hits) + ): + raise failed("real-hybrid-vector-retrieval-failed") + return { + "status": "PASS", + "backend": backend, + "mode": mode, + "backend_version": final_state["backend_version"], + "generation_model": config.inference.generation_model, + "embedding_model": config.inference.embedding_model, + "model_requests": final_state["model_requests"], + "custom_prompts": prompt_evidence, + "automatic_profile": automatic_evidence, + "source_journal_position": initial_state["source_journal_position"], + "all_requests_handled": final_state["all_requests_handled"], + "resume_without_processing_model_calls": replay_without_model_calls, + "retrieval": { + "mode": search.mode, + "hit_count": len(search.hits), + "vector_hit_count": vector_hits, + "all_hits_belong_to_expected_scope": True, + }, + "real_generation": True, + "real_embedding": True, + "generation_timeout_seconds": config.inference.generation_timeout_seconds, + "scope_timeout_seconds": 600, + "accepted_work_recovered_after_reopen": True, + "profile_pending_review_noop": True, + "artifact_counts": artifacts, + "candidate_counts": candidates, + "cursors": cursors, + "ownership_counts": ownership, + "family_status": supervisor.family_status, + "worker_failures": captured.failures, + "recovered_worker_failures": len(captured.failures), + "elapsed_seconds": round(time.monotonic() - started, 2), + } + finally: + logger.removeHandler(captured) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--backend", choices=("sqlite", "seekdb", "oceanbase"), required=True) + parser.add_argument("--env-file", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument( + "--report-file", type=Path, help="Write evidence separately while reusing an existing database." + ) + parser.add_argument("--mode", choices=("global", "dedicated"), default="global") + parser.add_argument("--resume", action="store_true", help="Recover the existing synthetic acceptance database.") + parser.add_argument( + "--custom-prompts", action="store_true", help="Verify Scope-owned Memory and Experience custom Prompts." + ) + parser.add_argument( + "--automatic-profile", action="store_true", help="Verify Profile Policy filtering across two real cron fires." + ) + parser.add_argument("--generation-timeout-seconds", type=float) + parser.add_argument("--oceanbase-url-env", default="POWERCONTEXT_TEST_OCEANBASE_URL") + args = parser.parse_args() + report: dict[str, Any] + try: + with server_settings_context(env_file=args.env_file) as settings: + if args.generation_timeout_seconds is not None: + inference = type(settings.inference).model_validate({ + **settings.inference.model_dump(), + "generation_timeout_seconds": args.generation_timeout_seconds, + }) + settings = settings.model_copy(update={"inference": inference}) + if args.backend == "oceanbase": + import os + + url = os.environ.get(args.oceanbase_url_env) + if not url: + raise AcceptanceFailure("dedicated-oceanbase-url-required") # noqa: TRY301 + settings = settings.model_copy(update={"database": OceanBaseConfig(url=SecretStr(url))}) + report = asyncio.run( + run_acceptance( + settings, + backend=args.backend, + directory=args.output, + mode=args.mode, + resume=args.resume, + custom_prompts=args.custom_prompts, + automatic_profile=args.automatic_profile, + ) + ) + except Exception as error: + report = {"status": "FAIL", "backend": args.backend, "error_type": type(error).__name__} + if isinstance(error, AcceptanceFailure): + report["error_code"] = str(error) + report.update(error.details) + if report["status"] == "PASS": + report["runtime_closed"] = True + args.output.mkdir(parents=True, exist_ok=True) + report_file = args.report_file or args.output / "report.json" + report_file.parent.mkdir(parents=True, exist_ok=True) + report_file.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, ensure_ascii=False)) + return 0 if report["status"] == "PASS" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/e2e/test_access_control_http.py b/tests/e2e/test_access_control_http.py index e89cd87ec0..7db2cfc90d 100644 --- a/tests/e2e/test_access_control_http.py +++ b/tests/e2e/test_access_control_http.py @@ -26,7 +26,7 @@ from powercontext.builtin.artifacts.handoff import HandoffDraft, HandoffGenerationRequest, HandoffStatement from powercontext.builtin.artifacts.memory import MemoryCandidateRequest, MemoryEntryInput from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.runtime.config import RuntimeConfig +from powercontext.builtin.runtime.config import InferenceConfig, RuntimeConfig from powercontext.builtin.sources import ContentSource from powercontext.client import ForbiddenResponseError, PowerContextClient, UnavailableResponseError from powercontext.http import ( @@ -422,13 +422,33 @@ async def scenario() -> None: asyncio.run(scenario()) -def test_scheduled_memory_processing_uses_the_static_service_principal_as_owner(tmp_path: Path) -> None: +def _scheduled_content_memory_worker(spec, assignment): + from powercontext.builtin.runtime.composition import open_builtin_contexts + from powercontext.builtin.runtime.family_processing import process_family_invocation + from powercontext.server.processing_security import open_worker_security + + async def run(): + async with ( + open_builtin_contexts(spec.config, candidate_pipeline=_ContentMemoryPipeline()) as contexts, + open_worker_security(spec.worker_security, contexts.database) as security, + ): + return await process_family_invocation(contexts, assignment, config=spec.config, security=security) + + return asyncio.run(run()) + + +def test_scheduled_memory_processing_uses_the_static_service_principal_as_owner(tmp_path: Path, monkeypatch) -> None: + # Only the model adapter is deterministic. Server identity reconstruction, + # spawned child, transaction hooks and public access checks are real. + monkeypatch.setattr("powercontext.builtin.runtime.composition.run_family_worker", _scheduled_content_memory_worker) + async def scenario() -> None: token = "scheduled-static-token" # noqa: S105 - test credential. app = create_server_app( settings=ServerSettings( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'scheduled-runtime.db'}"), - runtime=RuntimeConfig(schedule_seconds=0.02), + runtime=RuntimeConfig(memory_schedule_seconds=0.02, artifact_processing_families=("memory",)), + inference=InferenceConfig(generation_model="test"), access=AccessControlConfig( mode="enforced", deployment_id="scheduled-access-e2e", @@ -439,7 +459,6 @@ async def scenario() -> None: mcp=McpConfig(enabled=False), ), scheduler_path=tmp_path / "scheduled-access.db", - candidate_pipeline=_ContentMemoryPipeline(), ) async with _client(app, token) as client: scope = await client.create_scope( @@ -457,7 +476,7 @@ async def scenario() -> None: ) ) entries = None - for _ in range(100): + for _ in range(1500): try: entries = await client.list_memory_entries(ListMemoryEntriesRequest(scope_id=scope.scope_id)) except UnavailableResponseError as error: diff --git a/tests/e2e/test_access_control_regressions.py b/tests/e2e/test_access_control_regressions.py index dcea1f7103..8b7a4fbfdc 100644 --- a/tests/e2e/test_access_control_regressions.py +++ b/tests/e2e/test_access_control_regressions.py @@ -25,7 +25,7 @@ import pytest from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.runtime import InferenceConfig +from powercontext.builtin.runtime import InferenceConfig, RuntimeConfig from powercontext.server.authentication import AuthenticationResult, ProviderReadiness from powercontext.server.authz import AccessUnavailableError, PrincipalRef from powercontext.server.authz.composition import open_builtin_access_control, open_casbin_access_control @@ -53,6 +53,7 @@ async def _server(tmp_path: Path, backend="builtin", *, inference: InferenceConf settings=ServerSettings( database=database, inference=inference or InferenceConfig(), + runtime=RuntimeConfig(artifact_processing_families=()), access=AccessControlConfig(mode="enforced", deployment_id="regressions"), mcp=McpConfig(enabled=False), metrics=MetricsConfig(enabled=False), diff --git a/tests/e2e/test_artifact_processing_persistence.py b/tests/e2e/test_artifact_processing_persistence.py index 6e93d083a7..43bf5037dc 100644 --- a/tests/e2e/test_artifact_processing_persistence.py +++ b/tests/e2e/test_artifact_processing_persistence.py @@ -25,6 +25,7 @@ from powercontext.builtin.persistence import GenerationConflictError from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.sources import SourceRepository from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.persistence.tables import SHARED_TABLES @@ -50,7 +51,7 @@ async def start(self, assignment: ArtifactProcessingWorkAssignment) -> NoReturn: def _processing_binding() -> ArtifactProcessingBinding: - return ArtifactProcessingBinding(BINDING, 1, _BlockedLauncher()) + return ArtifactProcessingBinding(BINDING, "topic-memory", _BlockedLauncher()) async def _create_scope(runtime: BuiltinRuntime, idempotency_key: str) -> str: @@ -94,9 +95,14 @@ async def scenario() -> None: scope_b_sources = await sources.list(connection, scope_b) scope_a_pending = await pending.load(connection, scope_a, BINDING) scope_b_pending = await pending.load(connection, scope_b, BINDING) + scope_a_intent = await ArtifactProcessingIntentRepository().load(connection, scope_a, BINDING) + scope_b_intent = await ArtifactProcessingIntentRepository().load(connection, scope_b, BINDING) assert tuple(source.journal_position for source in scope_a_sources) == (1, 2) assert tuple(source.journal_position for source in scope_b_sources) == (1,) + assert scope_a_intent is not None and scope_b_intent is not None + assert (scope_a_intent.dirty_generation, scope_b_intent.dirty_generation) == (2, 1) + assert scope_a_intent.requested_generation == scope_b_intent.requested_generation == 0 assert scope_a_pending is not None assert ( scope_a_pending.source_through, @@ -146,9 +152,11 @@ async def scenario() -> None: ): stored_sources = await sources.list(connection, scope_id) stored_pending = await pending.load(connection, scope_id, BINDING) + stored_intent = await ArtifactProcessingIntentRepository().load(connection, scope_id, BINDING) assert stored_sources == () assert stored_pending is None + assert stored_intent is None asyncio.run(scenario()) diff --git a/tests/e2e/test_observability.py b/tests/e2e/test_observability.py index c59f867333..c8fec549ab 100644 --- a/tests/e2e/test_observability.py +++ b/tests/e2e/test_observability.py @@ -18,6 +18,8 @@ import json import logging import sqlite3 +from datetime import timedelta +from functools import partial from pathlib import Path from time import monotonic, sleep @@ -50,7 +52,16 @@ from powercontext.builtin.inference.pydantic_ai import PydanticAIEmbeddingModel from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import BuiltinConfig, RememberMemoryRequest, open_builtin_runtime +from powercontext.builtin.runtime.artifact_processing import ( + ArtifactProcessingBinding, + SpawnArtifactProcessingWorkerLauncher, +) from powercontext.builtin.runtime.config import InferenceConfig, RuntimeConfig +from powercontext.builtin.runtime.family_processing import FamilyWorkerSpec, process_family_invocation +from powercontext.builtin.runtime.processing_contracts import ( + ArtifactProcessingWorkAssignment, + ArtifactProcessingWorkerCompletion, +) from powercontext.builtin.scope import ScopeDraft from powercontext.errors import RevisionConflictError from powercontext.server.factory import create_server_app @@ -131,18 +142,23 @@ "powercontext.experience.incubation.source_count", "powercontext.experience.incubation.candidate_count", }, - "scheduled.process_source_window": { + "artifact_processing.worker": { "powercontext.operation.name", "powercontext.operation.unit", "powercontext.operation.outcome", - "powercontext.background.source_count", + "powercontext.artifact_processing.family", + "powercontext.artifact_processing.failure", + "error.type", }, - "scheduled.incubate_experience_candidates": { - "powercontext.operation.name", - "powercontext.operation.unit", - "powercontext.operation.outcome", - "powercontext.background.source_count", - "powercontext.background.candidate_count", + **{ + f"artifact_processing.worker.{stage}": { + "powercontext.operation.name", + "powercontext.operation.unit", + "powercontext.operation.outcome", + "powercontext.artifact_processing.family", + "error.type", + } + for stage in ("start", "wait", "acknowledge") }, } @@ -747,18 +763,116 @@ async def incubate(self, sources: tuple[object, ...], /) -> tuple[()]: return () -def test_scheduled_source_window_starts_an_independent_trace_root(tmp_path) -> None: +def _traced_family_worker( + spec: FamilyWorkerSpec, assignment: ArtifactProcessingWorkAssignment, / +) -> ArtifactProcessingWorkerCompletion: + """Rebuild deterministic processors inside a real spawn child.""" + from powercontext.builtin.runtime.composition import open_builtin_contexts + + async def run() -> ArtifactProcessingWorkerCompletion: + async with open_builtin_contexts( + spec.config, + candidate_pipeline=_EmptyCandidatePipeline(), + experience_pipeline=_EmptyExperiencePipeline(), + _topic_memory_worker=True, + ) as contexts: + return await process_family_invocation(contexts, assignment, config=spec.config) + + return asyncio.run(run()) + + +def _unacknowledged_worker( + spec: FamilyWorkerSpec, assignment: ArtifactProcessingWorkAssignment, / +) -> ArtifactProcessingWorkerCompletion: + del spec, assignment + return ArtifactProcessingWorkerCompletion() + + +def _failed_worker( + spec: FamilyWorkerSpec, assignment: ArtifactProcessingWorkAssignment, / +) -> ArtifactProcessingWorkerCompletion: + del spec, assignment + raise RuntimeError("private child failure evidence") # noqa: TRY003 + + +def _protocol_acknowledging_worker( + config: BuiltinConfig, assignment: ArtifactProcessingWorkAssignment, / +) -> ArtifactProcessingWorkerCompletion: + """Exercise the Family-neutral control protocol, without simulating domain work.""" + from powercontext.builtin.runtime.composition import open_builtin_contexts + from powercontext.builtin.runtime.processing_execution import ScopeInvocation + + async def run() -> ArtifactProcessingWorkerCompletion: + async with ( + open_builtin_contexts(config, _topic_memory_worker=True) as contexts, + contexts.database.transaction() as connection, + ): + invocation = ScopeInvocation(assignment) + await invocation.start(connection) + await invocation.complete(connection, remaining_work=False) + return ArtifactProcessingWorkerCompletion() + + return asyncio.run(run()) + + +@pytest.mark.parametrize("family", ["topic-memory", "profile"]) +def test_scope_worker_lifecycle_trace_is_family_neutral_and_detaches_ambient_http(tmp_path, family) -> None: + exporter = InMemorySpanExporter() + provider = TracerProvider(shutdown_on_exit=False) + provider.add_span_processor(SimpleSpanProcessor(exporter)) + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'protocol-tracing.db'}"), + runtime=RuntimeConfig.model_validate({"artifact_processing_families": (family,)}), + ) + binding = ArtifactProcessingBinding( + f"{family}-source-window", + family, + SpawnArtifactProcessingWorkerLauncher(partial(_protocol_acknowledging_worker, config)), + automatic_processing_interval=timedelta(seconds=0.02), + ) + content = "private source excluded from protocol traces" + + async def run() -> tuple[str, ReadableSpan]: + # Starting the controller under an ambient HTTP span catches accidental + # context inheritance by its async scheduling task and child stages. + with provider.get_tracer(__name__).start_as_current_span("HTTP capture"): + async with open_builtin_runtime( + config, artifact_processing_bindings=(binding,), tracing=ServerTracing(provider) + ) as runtime: + assert runtime.scopes is not None + scope = await runtime.scopes.create( + ScopeDraft(title="Trace", summary="Protocol trace", idempotency_key="protocol-trace") + ) + await runtime.records.for_scope(scope.scope_id).create_source("content", content) + root = await asyncio.to_thread( + _wait_for_named_span, exporter, "artifact_processing.worker", outcome="success", timeout=30 + ) + return scope.scope_id, root + + scope_id, root = asyncio.run(run()) + spans = list(exporter.get_finished_spans()) + assert (root.attributes or {})["powercontext.artifact_processing.family"] == family + for stage_name in ("start", "wait", "acknowledge"): + stage = _only_child(spans, root, f"artifact_processing.worker.{stage_name}") + _assert_scheduled_background_trace(root, stage, spans, scope_id=scope_id, content=content) + + +@pytest.mark.parametrize("family", ["memory", "experience"]) +def test_scheduled_family_worker_starts_an_independent_trace_root(monkeypatch, tmp_path, family) -> None: + monkeypatch.setattr("powercontext.builtin.runtime.composition.run_family_worker", _traced_family_worker) exporter = InMemorySpanExporter() provider = TracerProvider(shutdown_on_exit=False) provider.add_span_processor(SimpleSpanProcessor(exporter)) app = create_server_app( settings=ServerSettings( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'scheduled-tracing.db'}"), - runtime=RuntimeConfig(schedule_seconds=0.02), + runtime=RuntimeConfig.model_validate({ + "artifact_processing_families": (family,), + f"{family}_schedule_seconds": 0.02, + }), + inference=InferenceConfig(generation_model="test"), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", - candidate_pipeline=_EmptyCandidatePipeline(), tracing=ServerTracing(provider), ) content = "private scheduled evidence" @@ -770,29 +884,40 @@ def test_scheduled_source_window_starts_an_independent_trace_root(tmp_path) -> N json={"scope_id": scope_id, "source_id": "task-1", "content": content}, ) assert captured.status_code == 202 - root = _wait_for_named_span(exporter, "scheduled.process_source_window", outcome="success") + root = _wait_for_named_span(exporter, "artifact_processing.worker", outcome="success", timeout=30) spans = list(exporter.get_finished_spans()) - flush = _only_child(spans, root, "memory.flush") - _assert_scheduled_background_trace(root, flush, spans, scope_id=scope_id, content=content) - assert (root.attributes or {})["powercontext.background.source_count"] == 1 - assert (flush.attributes or {})["powercontext.memory.flush.source_count"] == 1 + assert (root.attributes or {})["powercontext.artifact_processing.family"] == family + for stage_name in ("start", "wait", "acknowledge"): + stage = _only_child(spans, root, f"artifact_processing.worker.{stage_name}") + _assert_scheduled_background_trace(root, stage, spans, scope_id=scope_id, content=content) + assert (stage.attributes or {})["powercontext.artifact_processing.family"] == family -def test_scheduled_experience_starts_an_independent_trace_root(tmp_path) -> None: +@pytest.mark.parametrize("failure", ["missing_durable_acknowledgement", "worker_failed", "timeout"]) +def test_scheduled_worker_failure_trace_requires_acknowledgement_and_excludes_payloads( + monkeypatch, tmp_path, failure +) -> None: + monkeypatch.setattr( + "powercontext.builtin.runtime.composition.run_family_worker", + _failed_worker if failure == "worker_failed" else _unacknowledged_worker, + ) exporter = InMemorySpanExporter() provider = TracerProvider(shutdown_on_exit=False) provider.add_span_processor(SimpleSpanProcessor(exporter)) app = create_server_app( settings=ServerSettings( - database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'scheduled-experience-tracing.db'}"), - runtime=RuntimeConfig(experience_schedule_seconds=0.02), + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'failed-worker-tracing.db'}"), + runtime=RuntimeConfig( + artifact_processing_families=("memory",), + memory_schedule_seconds=0.02, + memory_worker_timeout_seconds=0.01 if failure == "timeout" else 30, + ), + inference=InferenceConfig(generation_model="test"), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", - experience_pipeline=_EmptyExperiencePipeline(), tracing=ServerTracing(provider), ) - content = "private scheduled incubation evidence" + content = "private child failure evidence" with TestClient(app) as client: scope_id = _get_default_scope_id(client) @@ -801,14 +926,22 @@ def test_scheduled_experience_starts_an_independent_trace_root(tmp_path) -> None json={"scope_id": scope_id, "source_id": "task-1", "content": content}, ) assert captured.status_code == 202 - root = _wait_for_named_span(exporter, "scheduled.incubate_experience_candidates", outcome="success") + root = _wait_for_named_span(exporter, "artifact_processing.worker", outcome="failure", timeout=30) spans = list(exporter.get_finished_spans()) - incubation = _only_child(spans, root, "experience.incubation") - _assert_scheduled_background_trace(root, incubation, spans, scope_id=scope_id, content=content) - assert (root.attributes or {})["powercontext.background.source_count"] == 1 - assert (root.attributes or {})["powercontext.background.candidate_count"] == 0 - assert (incubation.attributes or {})["powercontext.experience.incubation.source_count"] == 1 - assert (incubation.attributes or {})["powercontext.experience.incubation.candidate_count"] == 0 + assert root.parent is None + assert (root.attributes or {})["powercontext.artifact_processing.failure"] == failure + assert root.status.status_code.name == "ERROR" + assert not any( + span.name == "artifact_processing.worker" + and (span.attributes or {}).get("powercontext.operation.outcome") == "success" + for span in spans + ) + for span in spans: + if span.name.startswith("artifact_processing.worker"): + _assert_stage_attribute_keys(span) + exported = _exported_span_data(spans) + assert scope_id not in exported + assert content not in exported def test_vector_search_exports_embedding_under_memory_search_without_recording_text(monkeypatch, tmp_path) -> None: diff --git a/tests/e2e/test_runtime_server.py b/tests/e2e/test_runtime_server.py index a6cfbd6205..ef5bf03940 100644 --- a/tests/e2e/test_runtime_server.py +++ b/tests/e2e/test_runtime_server.py @@ -230,7 +230,7 @@ async def scenario() -> None: assert readiness.checks == { "runtime": "ready", "database": "ready", - "artifact_processing_supervisor": "leader", + "artifact_processing_supervisor": "disabled", **_ACCESS_READINESS_CHECKS, } assert capabilities.source_types == ["content"] @@ -389,7 +389,7 @@ async def scenario() -> None: "runtime": "ready", "database": "ready", "inference.embedding": "misconfigured", - "artifact_processing_supervisor": "leader", + "artifact_processing_supervisor": "disabled", **_ACCESS_READINESS_CHECKS, } assert captured.position == 1 diff --git a/tests/e2e/test_scheduled_experience_incubation.py b/tests/e2e/test_scheduled_experience_incubation.py index 6014222d74..ec9ebe621b 100644 --- a/tests/e2e/test_scheduled_experience_incubation.py +++ b/tests/e2e/test_scheduled_experience_incubation.py @@ -19,10 +19,19 @@ from time import monotonic import httpx +import pytest -from powercontext.builtin.artifacts.experience import ExperienceCandidateInput, ExperienceContent +from powercontext.builtin.artifacts.experience import ( + EXPERIENCE_INCUBATION_CURSOR_NAME, + ExperienceCandidateInput, + ExperienceContent, +) +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.runtime import RuntimeConfig +from powercontext.builtin.runtime import InferenceConfig, RuntimeConfig +from powercontext.builtin.runtime.composition import open_builtin_contexts +from powercontext.builtin.runtime.family_processing import process_family_invocation +from powercontext.builtin.runtime.relational import RelationalContexts from powercontext.builtin.sources import ContentSource from powercontext.client import PowerContextClient from powercontext.http import ( @@ -32,6 +41,7 @@ PrepareContextRequest, ) from powercontext.server.factory import create_server_app +from powercontext.server.processing_security import open_worker_security from powercontext.server.settings import McpConfig, ServerSettings from powercontext.sources import Source, SourceRef @@ -53,20 +63,31 @@ async def incubate(self, sources: tuple[Source, ...], /) -> tuple[ExperienceCand ) +def _experience_worker(spec, assignment): + async def run(): + async with ( + open_builtin_contexts(spec.config, experience_pipeline=_TaskOutcomePipeline()) as contexts, + open_worker_security(spec.worker_security, contexts.database) as security, + ): + return await process_family_invocation(contexts, assignment, config=spec.config, security=security) + + return asyncio.run(run()) + + def _app(database: Path, scheduler: Path): return create_server_app( settings=ServerSettings( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{database}"), - runtime=RuntimeConfig(experience_schedule_seconds=0.02), + runtime=RuntimeConfig(experience_schedule_seconds=0.02, artifact_processing_families=("experience",)), + inference=InferenceConfig(generation_model="test"), mcp=McpConfig(enabled=False), ), scheduler_path=scheduler, - experience_pipeline=_TaskOutcomePipeline(), ) async def _pending_experience(client: PowerContextClient, scope_id: str): - deadline = monotonic() + 3 + deadline = monotonic() + 30 while monotonic() < deadline: page = await client.list_artifact_candidates( ListArtifactCandidatesRequest( @@ -80,7 +101,32 @@ async def _pending_experience(client: PowerContextClient, scope_id: str): raise AssertionError("scheduled Experience Candidate did not reach the Review Inbox") # noqa: TRY003 -def test_scheduler_incubates_task_outcome_once_and_preserves_review_gating(tmp_path: Path) -> None: +async def _wait_for_handled(app, scope_id: str, minimum_generation: int) -> int: + contexts = app.state.application._provider + assert isinstance(contexts, RelationalContexts) + async with asyncio.timeout(30): + while True: + async with contexts.database.transaction() as connection: + intent = await ArtifactProcessingIntentRepository().load( + connection, scope_id, EXPERIENCE_INCUBATION_CURSOR_NAME + ) + if ( + intent is not None + and intent.handled_generation >= minimum_generation + and intent.handled_generation == intent.requested_generation + and intent.clean_generation == intent.dirty_generation + ): + return intent.handled_generation + await asyncio.sleep(0.02) + + +def test_scheduler_incubates_task_outcome_once_and_preserves_review_gating( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # The deterministic adapter is rebuilt in the spawned child. Discovery, + # the Scope invocation transaction, durable acknowledgement and Inbox are real. + monkeypatch.setattr("powercontext.builtin.runtime.composition.run_family_worker", _experience_worker) + async def scenario() -> None: database = tmp_path / "powercontext.db" scheduler = tmp_path / "scheduler.db" @@ -103,6 +149,7 @@ async def scenario() -> None: ) ) candidates = await _pending_experience(client, scope_id) + handled_generation = await _wait_for_handled(app, scope_id, 1) prepared = await client.prepare_context( PrepareContextRequest( scope_id=scope_id, @@ -124,8 +171,16 @@ async def scenario() -> None: ) as transport, ): client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True) - await asyncio.sleep(0.08) + await client.capture_content_source( + CaptureContentSourceRequest( + scope_id=scope_id, + source_id="follow-up", + content="The recorded outcome remains available after restarting the Server.", + ) + ) + await _wait_for_handled(restored, scope_id, handled_generation + 1) candidates = await _pending_experience(client, scope_id) assert len(candidates) == 1 + assert not scheduler.exists() asyncio.run(scenario()) diff --git a/tests/e2e/test_topic_memory_budget_integrity.py b/tests/e2e/test_topic_memory_budget_integrity.py index d5159f2413..4b37801534 100644 --- a/tests/e2e/test_topic_memory_budget_integrity.py +++ b/tests/e2e/test_topic_memory_budget_integrity.py @@ -28,6 +28,7 @@ from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository +from powercontext.builtin.persistence.seekdb import SeekDBProfile from powercontext.builtin.persistence.sources import SourceRepository from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository @@ -40,7 +41,7 @@ ) from powercontext.builtin.runtime.topic_memory_processing import TopicMemoryAtomicPublisher from powercontext.builtin.sources import CONTENT_SOURCE_ADAPTER, ContentCapture -from tests.builtin.persistence.test_topic_memory_integrity import _OB, _concurrent_revision, _open_store +from tests.builtin.persistence.test_topic_memory_integrity import _OB, _SEEKDB, _concurrent_revision, _open_store from tests.builtin.runtime.test_topic_memory_processing import _assignment @@ -50,7 +51,7 @@ async def save(self, *args, **kwargs): raise RuntimeError("injected publication rollback") # noqa: TRY003 -@pytest.mark.parametrize("backend", ["sqlite", _OB]) +@pytest.mark.parametrize("backend", ["sqlite", _OB, _SEEKDB]) @pytest.mark.parametrize("terminal", [None, "requests", "tokens"]) def test_budget_reopen_supersession_and_publication_with_concurrent_integrity(tmp_path, backend, terminal): async def scenario(): @@ -116,13 +117,17 @@ async def budget_row(database): url = store.reader.engine.url.render_as_string(hide_password=False) await store.reader.close() tables = BUILTIN_TABLES + store.index.tables - reopened = ( - OceanBaseProfile.open(OceanBaseConfig(url=SecretStr(url)), tables=tables) - if backend == "oceanbase" - else SQLiteProfile.open(SQLiteConfig(url=url), tables=tables) - ) + if backend == "seekdb": + assert store.seekdb_config is not None + reopened = SeekDBProfile.open(store.seekdb_config, tables=tables) + elif backend == "oceanbase": + reopened = OceanBaseProfile.open(OceanBaseConfig(url=SecretStr(url)), tables=tables) + else: + reopened = SQLiteProfile.open(SQLiteConfig(url=url), tables=tables) async with reopened as profile: database = profile.database + assert database.engine is not store.reader.engine + assert database.engine is not store.database.engine async with database.transaction() as connection: await store.repository.initialize(connection, configure_retrieval_shape=False) current = budget(database) diff --git a/tests/e2e/test_topic_memory_processing.py b/tests/e2e/test_topic_memory_processing.py index d347951d00..defc98f889 100644 --- a/tests/e2e/test_topic_memory_processing.py +++ b/tests/e2e/test_topic_memory_processing.py @@ -32,6 +32,7 @@ ) from powercontext.builtin.inference import GenerationResult from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime.artifact_processing import ( ArtifactProcessingBinding, @@ -47,6 +48,7 @@ TopicMemoryStageSet, TopicMemoryWindowSelector, ) +from powercontext.builtin.runtime.topic_memory_scope import TopicMemoryScopeProcessor from powercontext.builtin.sources import ContentCapture @@ -60,8 +62,13 @@ async def generate(self, _value, /): return GenerationResult(output=self.outputs.popleft()) +class _OneSourceSelector(TopicMemoryWindowSelector): + async def select(self, scope_id, source_after, source_ceiling, /): + return await super().select(scope_id, source_after, min(source_after + 1, source_ceiling)) + + class _Launcher: - def __init__(self, processor: TopicMemoryProcessor) -> None: + def __init__(self, processor: TopicMemoryScopeProcessor) -> None: self.processor = processor async def start(self, assignment: ArtifactProcessingWorkAssignment): @@ -69,7 +76,7 @@ async def start(self, assignment: ArtifactProcessingWorkAssignment): class _Handle: - def __init__(self, processor: TopicMemoryProcessor, assignment: ArtifactProcessingWorkAssignment) -> None: + def __init__(self, processor: TopicMemoryScopeProcessor, assignment: ArtifactProcessingWorkAssignment) -> None: self.processor = processor self.assignment = assignment @@ -100,6 +107,9 @@ async def scenario() -> None: pending = contexts.repositories.processing_pending async with contexts.database.transaction() as connection: await pending.request_flush(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + await ArtifactProcessingIntentRepository().request( + connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING + ) unexpected = _QueueGenerator() stages = TopicMemoryStageSet( @@ -145,23 +155,26 @@ async def scenario() -> None: ) binding = ArtifactProcessingBinding( binding_name=TOPIC_MEMORY_SOURCE_WINDOW_BINDING, - source_window_limit=1, - launcher=_Launcher(processor), - window_selector=TopicMemoryWindowSelector( - contexts.database, - contexts.repositories.sources, - contexts.token_estimator, - context_window_tokens=10_000, + artifact_family="topic-memory", + max_workers=1, + worker_timeout_seconds=5, + launcher=_Launcher( + TopicMemoryScopeProcessor( + contexts.database, + processor, + _OneSourceSelector( + contexts.database, + contexts.repositories.sources, + contexts.token_estimator, + context_window_tokens=10_000, + ), + ) ), ) async with ArtifactProcessingSupervisor( database=contexts.database, bindings=(binding,), lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=5, - pending=pending, - cursors=contexts.repositories.cursors, leases=contexts.repositories.processing_leases, binding_states=contexts.repositories.processing_binding_states, retry_base_seconds=0.01, @@ -229,6 +242,9 @@ async def scenario() -> None: pending = contexts.repositories.processing_pending async with contexts.database.transaction() as connection: await pending.request_flush(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + await ArtifactProcessingIntentRepository().request( + connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING + ) provisional = TopicMemoryProposal(content=old_content, evidence_ids=("evidence-0001",)) reconciled = provisional.model_copy( @@ -265,23 +281,26 @@ async def scenario() -> None: ) binding = ArtifactProcessingBinding( binding_name=TOPIC_MEMORY_SOURCE_WINDOW_BINDING, - source_window_limit=1, - launcher=_Launcher(processor), - window_selector=TopicMemoryWindowSelector( - contexts.database, - contexts.repositories.sources, - contexts.token_estimator, - context_window_tokens=10_000, + artifact_family="topic-memory", + max_workers=1, + worker_timeout_seconds=5, + launcher=_Launcher( + TopicMemoryScopeProcessor( + contexts.database, + processor, + _OneSourceSelector( + contexts.database, + contexts.repositories.sources, + contexts.token_estimator, + context_window_tokens=10_000, + ), + ) ), ) async with ArtifactProcessingSupervisor( database=contexts.database, bindings=(binding,), lease_mode="single-process", - max_workers=1, - worker_timeout_seconds=5, - pending=pending, - cursors=contexts.repositories.cursors, leases=contexts.repositories.processing_leases, binding_states=contexts.repositories.processing_binding_states, retry_base_seconds=0.01, diff --git a/tests/e2e/topic_memory_product/harness.py b/tests/e2e/topic_memory_product/harness.py index c08e799a3a..8296864cbd 100644 --- a/tests/e2e/topic_memory_product/harness.py +++ b/tests/e2e/topic_memory_product/harness.py @@ -46,7 +46,6 @@ from sqlalchemy.engine import make_url from starlette.middleware import Middleware -from powercontext.builtin.artifacts.memory import EmbeddingProfile from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING from powercontext.builtin.artifacts.topic_memory.generation import ( TopicMemoryEvolveOutput, @@ -56,7 +55,6 @@ TopicMemoryReconcileOutput, TopicMemoryTemporaryOutput, ) -from powercontext.builtin.inference import EmbeddingResult, InferenceUnavailableError from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository @@ -166,19 +164,16 @@ class _CodexMcpCall: status: str -class _FallbackEmbedding: - """Deterministically inject one unavailable query embedding for E2.""" +def _unavailable_embedding_app() -> FastAPI: + """Fail at the HTTP provider boundary using the reconstructible adapter.""" - def __init__(self, config: _RealEmbeddingConfig) -> None: - self.profile = EmbeddingProfile( - profile_id=config.profile_id, - model=config.model, - dimension=config.dimension, - normalization=config.normalization, - ) + app = FastAPI() + + @app.post("/v1/embeddings") + async def embeddings() -> None: + raise HTTPException(status_code=503, detail="controlled embedding outage") - async def embed(self, _texts: tuple[str, ...], /) -> EmbeddingResult: - raise InferenceUnavailableError("embed") + return app class _EmbeddingFallbackCapture(logging.Handler): @@ -1186,6 +1181,7 @@ def run_e2( # noqa: C901 timeline = AccessTimeline() server = None fallback_server = None + unavailable_embedding_server = None fallback_capture = _EmbeddingFallbackCapture() search_logger = logging.getLogger("powercontext.builtin.runtime.application") search_logger.addHandler(fallback_capture) @@ -1251,16 +1247,26 @@ def run_e2( # noqa: C901 if not server_closed: raise ProductChainError("E2 hybrid server port remained open") + unavailable_embedding_server = start_loopback_server(_unavailable_embedding_app()) fallback_settings = ServerSettings( auth=BearerAuthConfig(enabled=True, token=SecretStr(_E2_TOKEN)), database=database, - inference=InferenceConfig(), + # The all-role restart retains the deployment's capabilities and + # uses a reconstructible provider adapter for the controlled outage. + runtime=settings.runtime, + inference=settings.inference.model_copy( + update={ + "embedding_base_url": AnyHttpUrl(f"{unavailable_embedding_server.base_url}/v1"), + "embedding_headers": {}, + "embedding_timeout_seconds": 3, + } + ), mcp=McpConfig(enabled=False), dashboard=DashboardConfig(enabled=False), handoff_report=HandoffReportConfig(enabled=False), ) fallback_server = start_loopback_server( - create_server_app(settings=fallback_settings, embedding_model=_FallbackEmbedding(config)), + create_server_app(settings=fallback_settings), startup_timeout=60, ) fallback_search = asyncio.run( @@ -1304,7 +1310,7 @@ def run_e2( # noqa: C901 }, "hybrid_chain": chain.as_dict(), "controlled_fallback": { - "injection": "InferenceUnavailableError at query embedding boundary", + "injection": "HTTP 503 at the configured query embedding provider boundary", "search_mode": "fts", "exact_ref": fallback_ref.as_dict(), "signal": expected_fallback, @@ -1321,6 +1327,8 @@ def run_e2( # noqa: C901 search_logger.removeHandler(fallback_capture) if fallback_server is not None: fallback_server.stop() + if unavailable_embedding_server is not None: + unavailable_embedding_server.stop() if server is not None: server.stop() inference_server.stop() @@ -1332,6 +1340,9 @@ def run_e2( # noqa: C901 result["cleanup"] = { "hybrid_server_port_closed": True, "fallback_server_port_closed": True, + "unavailable_embedding_port_closed": ( + unavailable_embedding_server is not None and unavailable_embedding_server.port_is_closed() + ), "fake_generation_port_closed": inference_server.port_is_closed(), "temporary_runtime_removed": not runtime_directory.exists(), } @@ -1704,6 +1715,7 @@ def run_e4(directory: Path, *, generation_timeout: float) -> dict[str, object]: timeline = AccessTimeline() server = None fts_server = None + unavailable_embedding_server = None temporary_openai_key = False result: dict[str, object] | None = None try: @@ -1769,11 +1781,20 @@ def run_e4(directory: Path, *, generation_timeout: float) -> dict[str, object]: if not hybrid_closed: raise ProductChainError("E4 hybrid server port remained open") + unavailable_embedding_server = start_loopback_server(_unavailable_embedding_app()) fts_settings = ServerSettings( auth=BearerAuthConfig(enabled=True, token=SecretStr(_E4_TOKEN)), database=database, - runtime=RuntimeConfig(artifact_processing_role="all"), - inference=InferenceConfig(), + # Preserve the frozen hybrid retrieval shape and single-host all + # role; unavailable query embeddings exercise the allowed FTS fallback. + runtime=settings.runtime, + inference=settings.inference.model_copy( + update={ + "embedding_base_url": AnyHttpUrl(f"{unavailable_embedding_server.base_url}/v1"), + "embedding_headers": {}, + "embedding_timeout_seconds": 3, + } + ), mcp=McpConfig(enabled=False), dashboard=DashboardConfig(enabled=False), handoff_report=HandoffReportConfig(enabled=False), @@ -1807,6 +1828,7 @@ def run_e4(directory: Path, *, generation_timeout: float) -> dict[str, object]: "dialect_checks": { "hybrid_mode": "hybrid", "fts_mode_after_restart": "fts", + "embedding_outage": "HTTP 503 with the original hybrid profile retained", "same_exact_ref": fts_ref.as_dict(), }, "redaction": { @@ -1818,6 +1840,8 @@ def run_e4(directory: Path, *, generation_timeout: float) -> dict[str, object]: finally: if fts_server is not None: fts_server.stop() + if unavailable_embedding_server is not None: + unavailable_embedding_server.stop() if server is not None: server.stop() inference_server.stop() @@ -1829,6 +1853,9 @@ def run_e4(directory: Path, *, generation_timeout: float) -> dict[str, object]: result["cleanup"] = { "hybrid_server_port_closed": True, "fts_server_port_closed": True, + "unavailable_embedding_port_closed": ( + unavailable_embedding_server is not None and unavailable_embedding_server.port_is_closed() + ), "fake_provider_port_closed": inference_server.port_is_closed(), "temporary_seekdb_removed": not runtime_directory.exists(), } diff --git a/tests/langchain_middleware/test_middleware.py b/tests/langchain_middleware/test_middleware.py index 115d48b613..4c9239c531 100644 --- a/tests/langchain_middleware/test_middleware.py +++ b/tests/langchain_middleware/test_middleware.py @@ -37,7 +37,7 @@ from powercontext.builtin.artifacts.memory import MemoryCandidateRequest, MemoryEntryInput from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.runtime import InferenceConfig +from powercontext.builtin.runtime import InferenceConfig, RuntimeConfig from powercontext.builtin.sources import ContentSource from powercontext.client import PowerContextClient from powercontext.http import ( @@ -117,6 +117,7 @@ def _server_app(tmp_path: Path) -> FastAPI: settings=ServerSettings( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}"), inference=InferenceConfig(generation_model="test"), + runtime=RuntimeConfig(artifact_processing_families=()), mcp=McpConfig(enabled=False), ), candidate_pipeline=_ContentCandidatePipeline(), diff --git a/tests/test_access_http.py b/tests/test_access_http.py index 724fc58dac..9a4302c645 100644 --- a/tests/test_access_http.py +++ b/tests/test_access_http.py @@ -116,7 +116,9 @@ def test_enforced_mode_uses_injected_authentication_and_builtin_access(tmp_path: @pytest.mark.parametrize("scheduled", [False, True]) -def test_generation_model_does_not_require_background_principal_unless_scheduled(tmp_path: Path, scheduled) -> None: +def test_declared_background_processing_requires_identity_even_without_automatic_schedule( + tmp_path: Path, scheduled +) -> None: from powercontext.builtin.runtime.config import InferenceConfig app = create_server_app( @@ -128,12 +130,8 @@ def test_generation_model_does_not_require_background_principal_unless_scheduled ), authentication_provider=_ActingAuthenticationProvider(), ) - if scheduled: - with pytest.raises(ValueError, match="BACKGROUND_PRINCIPAL_ID"), TestClient(app): - pass - else: - with TestClient(app) as client: - assert client.get("/v1/access/me").status_code == 200 + with pytest.raises(ValueError, match="BACKGROUND_PRINCIPAL_ID"), TestClient(app): + pass @pytest.mark.parametrize("background", [False, True]) diff --git a/tests/test_processing_metrics.py b/tests/test_processing_metrics.py new file mode 100644 index 0000000000..92e0fefc94 --- /dev/null +++ b/tests/test_processing_metrics.py @@ -0,0 +1,147 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from fastapi.testclient import TestClient +from prometheus_client.parser import text_string_to_metric_families + +from powercontext.limits import MAX_ARTIFACT_FAMILY_LENGTH +from powercontext.server.factory import create_server_app +from powercontext.server.metrics import ServerMetrics +from tests.test_server_metrics import _settings + +PREFIX = "powercontext_server_artifact_processing_" + + +def _status(**changes): + return { + "status": "leader", + "max_workers": 8, + "available_workers": 5, + "used_workers": 3, + "ready": 7, + "retry_wait": 2, + "unacknowledged_requests": 19, + "discovery_seconds": 0.125, + "last_invocation_seconds": 1.75, + "completed": 12, + "failed": 4, + "timeouts": 1, + **changes, + } + + +def _samples(rendered): + return { + (sample.name, sample.labels["family"]): sample.value + for metric in text_string_to_metric_families(rendered) + for sample in metric.samples + if sample.name.startswith(PREFIX) + } + + +def test_processing_metrics_expose_family_capacity_progress_and_counter_snapshots(): + metrics = ServerMetrics() + snapshot = _status(scope_id="scope-secret", worker_id="worker-secret", binding_name="binding-secret") + metrics.set_processing_families(dict.fromkeys(("memory", "topic-memory", "experience", "profile"), snapshot)) + + rendered = metrics.render().decode() + samples = _samples(rendered) + assert len(samples) == 11 * 4 + for family in ("memory", "topic-memory", "experience", "profile"): + for field in ( + "max_workers", + "available_workers", + "used_workers", + "ready", + "retry_wait", + "unacknowledged_requests", + "discovery_seconds", + "last_invocation_seconds", + "completed", + "failed", + "timeouts", + ): + suffix = "_total" if field in {"completed", "failed", "timeouts"} else "" + assert samples[(PREFIX + field + suffix, family)] == snapshot[field] + instruments = {metric.name: metric for metric in text_string_to_metric_families(rendered)} + assert instruments[PREFIX + "completed"].type == "counter" + assert instruments[PREFIX + "failed"].type == "counter" + assert instruments[PREFIX + "timeouts"].type == "counter" + assert instruments[PREFIX + "unacknowledged_requests"].type == "gauge" + assert "latest requested-work discovery pass" in instruments[PREFIX + "unacknowledged_requests"].documentation + assert "resets on restart" in instruments[PREFIX + "completed"].documentation + assert not any(secret in rendered for secret in ("scope-secret", "worker-secret", "binding-secret")) + assert all( + set(sample.labels) == {"family"} + for instrument in instruments.values() + for sample in instrument.samples + if sample.name.startswith(PREFIX) + ) + + # Scrapes observe cumulative state; they never add it repeatedly. + metrics.set_processing_families({"memory": _status(completed=13)}) + assert _samples(metrics.render().decode())[(PREFIX + "completed_total", "memory")] == 13 + assert _samples(metrics.render().decode())[(PREFIX + "completed_total", "memory")] == 13 + metrics.set_processing_families({"memory": _status(completed=0)}) + assert _samples(metrics.render().decode())[(PREFIX + "completed_total", "memory")] == 0 + + +@pytest.mark.parametrize( + "invalid_family", ["scope/private-secret", 'memory"secret', "Memory", "", "a" * (MAX_ARTIFACT_FAMILY_LENGTH + 1)] +) +def test_processing_metrics_reject_noncanonical_family_labels(invalid_family): + metrics = ServerMetrics() + metrics.set_processing_families({invalid_family: _status(), "custom-family": _status()}) + + samples = _samples(metrics.render().decode()) + assert {family for _, family in samples} == {"custom-family"} + + +def test_processing_metrics_replace_removed_families_and_omit_invalid_numbers(): + metrics = ServerMetrics() + metrics.set_processing_families({"memory": _status()}) + metrics.set_processing_families({"topic-memory": _status()}) + assert {family for _, family in _samples(metrics.render().decode())} == {"topic-memory"} + + metrics.set_processing_families({"memory": {"used_workers": float("nan"), "failed": -1, "ready": "secret"}}) + assert _samples(metrics.render().decode()) == {} + metrics.set_processing_families({}) + assert _samples(metrics.render().decode()) == {} + + +def test_existing_metrics_endpoint_refreshes_current_supervisor_snapshot(tmp_path): + app = create_server_app(settings=_settings(tmp_path / "metrics.db")) + with TestClient(app) as client: + runtime = app.state.application + previous = runtime.artifact_processing_supervisor + supervisor = SimpleNamespace(family_status={"memory": _status()}) + runtime.artifact_processing_supervisor = supervisor + try: + first = client.get("/metrics") + assert first.status_code == 200 + assert _samples(first.text)[(PREFIX + "used_workers", "memory")] == 3 + supervisor.family_status = {"profile": _status(used_workers=1, available_workers=7, completed=30)} + second = client.get("/metrics") + assert second.status_code == 200 + assert _samples(second.text)[(PREFIX + "completed_total", "profile")] == 30 + assert {family for _, family in _samples(second.text)} == {"profile"} + runtime.artifact_processing_supervisor = None + assert _samples(client.get("/metrics").text) == {} + finally: + runtime.artifact_processing_supervisor = previous diff --git a/tests/test_processing_migration_cli.py b/tests/test_processing_migration_cli.py new file mode 100644 index 0000000000..7995253fab --- /dev/null +++ b/tests/test_processing_migration_cli.py @@ -0,0 +1,60 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Offline maintenance commands expose resumable state without settings values.""" + +import asyncio +import json +import os + +from click import unstyle +from typer.testing import CliRunner + +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.tables import BUILTIN_TABLES +from powercontext.cli.app import create_cli +from powercontext.server.cli import app + + +def test_processing_maintenance_plan_apply_verify_require_maintenance_and_reuse_receipt(tmp_path, monkeypatch): + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'maintenance.db'}") + + async def setup(): + async with SQLiteProfile.open(config, tables=BUILTIN_TABLES): + pass + + asyncio.run(setup()) + for key in tuple(os.environ): + if key.startswith("POWERCONTEXT_SERVER_"): + monkeypatch.delenv(key) + monkeypatch.setenv("POWERCONTEXT_SERVER_DATABASE_KIND", "sqlite") + monkeypatch.setenv("POWERCONTEXT_SERVER_DATABASE_URL", config.url) + cli = create_cli([app]) + runner = CliRunner() + command = ["server", "processing-migrate"] + plan = runner.invoke(cli, [*command, "--action", "plan"]) + assert plan.exit_code == 0, plan.output + assert json.loads(plan.output)["required"] is True + denied = runner.invoke(cli, [*command, "--action", "apply"]) + assert denied.exit_code == 2 + assert "maintenance-confirmed" in unstyle(denied.output) + applied = runner.invoke(cli, [*command, "--action", "apply", "--maintenance-confirmed", "--batch-size", "1"]) + assert applied.exit_code == 0, applied.output + assert json.loads(applied.output)["ready"] is True + verified = runner.invoke(cli, [*command, "--action", "verify"]) + assert verified.exit_code == 0, verified.output + assert json.loads(verified.output)["ready"] is True + replay = runner.invoke(cli, [*command, "--action", "apply", "--maintenance-confirmed"]) + assert replay.exit_code == 0, replay.output + assert config.url not in plan.output + applied.output + verified.output + replay.output diff --git a/tests/test_processing_security.py b/tests/test_processing_security.py new file mode 100644 index 0000000000..b3aeb57eb8 --- /dev/null +++ b/tests/test_processing_security.py @@ -0,0 +1,142 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Only deployment-owned authorization can be reconstructed in a child.""" + +import asyncio +import json +from contextlib import asynccontextmanager +from types import SimpleNamespace + +import pytest +from pydantic import SecretStr + +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.runtime.composition import BuiltinConfigurationError +from powercontext.builtin.runtime.config import InferenceConfig +from powercontext.server.authz import AccessControlService, PrincipalRef +from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.server.authz.service import BuiltinAuthorizationProvider +from powercontext.server.cli import _run_background_async +from powercontext.server.factory import create_server_app +from powercontext.server.processing_security import WorkerSecuritySpec, build_worker_security +from powercontext.server.settings import AccessControlConfig, BearerAuthConfig, ServerSettings + + +class CustomAuthorizationProvider(BuiltinAuthorizationProvider): + """An injected subclass may impose rules the standard child cannot rebuild.""" + + +def test_worker_identity_prefers_explicit_background_principal_and_excludes_credentials(): + settings = ServerSettings( + auth=BearerAuthConfig(token=SecretStr("do-not-serialize-this-token")), + access=AccessControlConfig(mode="enforced", background_principal_id="worker", deployment_id="test"), + ) + legacy = PrincipalRef(type="service", id="server-token") + data = build_worker_security(settings, None, legacy_static_principal=legacy) + assert data is not None + spec = WorkerSecuritySpec.model_validate(data) + assert spec.principal.id == "worker" + assert spec.deployment_id == "test" + assert spec.static_preset is False + assert "do-not-serialize-this-token" not in json.dumps(data) + assert "worker" not in repr(spec) + + +def test_injected_authorization_fails_before_background_dispatch_but_not_for_sync_only(): + settings = ServerSettings(access=AccessControlConfig(mode="enforced", background_principal_id="worker")) + with pytest.raises(BuiltinConfigurationError, match="reconstructible Authorization Provider"): + build_worker_security(settings, None, injected=True) + assert build_worker_security(settings, None, injected=True, enabled=False) is None + assert build_worker_security(ServerSettings(), None, injected=True) is None + + +def test_authorization_subclass_is_not_silently_replaced_by_builtin_provider(tmp_path): + async def scenario(): + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'access.db'}") + settings = ServerSettings(access=AccessControlConfig(mode="enforced", background_principal_id="worker")) + async with SQLiteProfile.open(config, tables=ACCESS_TABLES) as profile: + repository = RelationalAccessRepository(profile.database) + access = AccessControlService( + CustomAuthorizationProvider(repository), relationships=repository, audit=repository + ) + with pytest.raises(BuiltinConfigurationError, match="reconstructible Authorization Provider"): + build_worker_security(settings, access) + standard = AccessControlService( + BuiltinAuthorizationProvider(repository), relationships=repository, audit=repository + ) + assert build_worker_security(settings, standard) is not None + + asyncio.run(scenario()) + + +def test_server_rejects_injected_authorization_before_registering_actual_background_workers(tmp_path): + async def scenario(): + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'server.db'}") + settings = ServerSettings( + database=config, + auth=BearerAuthConfig(token=SecretStr("test-token")), + access=AccessControlConfig(mode="enforced", background_principal_id="worker"), + inference=InferenceConfig(generation_model="test"), + ) + async with SQLiteProfile.open(config, tables=ACCESS_TABLES) as profile: + repository = RelationalAccessRepository(profile.database) + access = AccessControlService( + BuiltinAuthorizationProvider(repository), relationships=repository, audit=repository + ) + app = create_server_app(settings=settings, access_control=access) + with pytest.raises(BuiltinConfigurationError, match="reconstructible Authorization Provider"): + async with app.router.lifespan_context(app): + pass + settings = settings.model_copy(update={"inference": InferenceConfig()}) + app = create_server_app(settings=settings, access_control=access) + async with app.router.lifespan_context(app): + assert app.state.application.artifact_processing_supervisor is None + + asyncio.run(scenario()) + + +def test_background_cli_preserves_deployment_identity_when_building_the_worker_spec(monkeypatch): + async def scenario(): + settings = ServerSettings( + access=AccessControlConfig( + mode="enforced", background_principal_id="background-worker", deployment_id="test" + ) + ) + observed = {} + stop_callbacks = [] + loop = asyncio.get_running_loop() + monkeypatch.setattr(loop, "add_signal_handler", lambda _signal, callback: stop_callbacks.append(callback)) + monkeypatch.setattr(loop, "remove_signal_handler", lambda _signal: True) + + @asynccontextmanager + async def access_control(_database, **kwargs): + observed["access"] = kwargs + yield None + + @asynccontextmanager + async def runtime(_config, **kwargs): + observed["runtime"] = kwargs + stop_callbacks[0]() + yield None + + monkeypatch.setattr("powercontext.server.cli.open_builtin_access_control", access_control) + monkeypatch.setattr("powercontext.server.cli.open_builtin_runtime", runtime) + await _run_background_async(settings, SimpleNamespace(instrumentation=None)) + security = observed["runtime"]["worker_security"] + assert security["principal"]["id"] == "background-worker" + assert security["deployment_id"] == observed["access"]["deployment_id"] == "test" + assert security["static_preset"] is False + + asyncio.run(scenario()) diff --git a/tests/test_server.py b/tests/test_server.py index 775c32a4d7..0228b77fce 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -423,19 +423,20 @@ def test_server_settings_reject_custom_embedded_seekdb_database(tmp_path, monkey ServerSettings() -def test_server_scheduler_uses_the_powercontext_data_directory(tmp_path, monkeypatch) -> None: +def test_supervisor_uses_primary_database_without_scheduler_sidecar(tmp_path, monkeypatch) -> None: data_dir = tmp_path / "powercontext-data" monkeypatch.setenv("POWERCONTEXT_HOME", str(data_dir)) app = create_server_app( settings=ServerSettings( runtime=RuntimeConfig(experience_schedule_seconds=3_600), + inference=InferenceConfig(generation_model="test"), mcp=McpConfig(enabled=False), ), - experience_pipeline=_NoopExperiencePipeline(), ) with TestClient(app): - assert (data_dir / "scheduler.db").is_file() + assert (data_dir / "powercontext.db").is_file() + assert not (data_dir / "scheduler.db").exists() def test_scheduled_experience_owns_only_candidates_created_by_its_incubation() -> None: @@ -723,7 +724,7 @@ async def fail_ping(_database: AsyncDatabase) -> None: "checks": { "runtime": "ready", "database": "unavailable", - "artifact_processing_supervisor": "leader", + "artifact_processing_supervisor": "disabled", **_access_readiness_checks(), }, } @@ -768,6 +769,10 @@ def capture_readiness_timeout(operation, *, timeout_seconds=READINESS_PROBE_TIME "database": "ready", "inference.generation": "ready", "artifact_processing_supervisor": "leader", + "artifact_processing.memory": "leader", + "artifact_processing.experience": "leader", + "artifact_processing.profile": "leader", + "artifact_processing.topic-memory": "leader", **_access_readiness_checks(), }, } @@ -832,6 +837,9 @@ async def rate_limited(_messages: list[ModelMessage], _info: AgentInfo) -> Model "database": "ready", "inference.generation": "unavailable", "artifact_processing_supervisor": "leader", + "artifact_processing.memory": "leader", + "artifact_processing.experience": "leader", + "artifact_processing.profile": "leader", **_access_readiness_checks(), }, } @@ -863,7 +871,7 @@ def test_server_factory_caches_and_redacts_degraded_embedding_readiness(caplog, "runtime": "ready", "database": "ready", "inference.embedding": "misconfigured", - "artifact_processing_supervisor": "leader", + "artifact_processing_supervisor": "disabled", **_access_readiness_checks(), }, } @@ -893,7 +901,7 @@ def test_server_factory_reports_a_rejected_embedding_request_with_a_redacted_rea "runtime": "ready", "database": "ready", "inference.embedding": "misconfigured: provider-rejected (HTTP 400)", - "artifact_processing_supervisor": "leader", + "artifact_processing_supervisor": "disabled", **_access_readiness_checks(), }, } @@ -929,7 +937,7 @@ def test_server_factory_reports_transient_embedding_failures_as_degraded( "runtime": "ready", "database": "ready", "inference.embedding": expected_status, - "artifact_processing_supervisor": "leader", + "artifact_processing_supervisor": "disabled", **_access_readiness_checks(), }, } @@ -1035,7 +1043,7 @@ def reject(request: httpx.Request) -> httpx.Response: "runtime": "ready", "database": "ready", "inference.embedding": "misconfigured: provider-rejected (HTTP 404)", - "artifact_processing_supervisor": "leader", + "artifact_processing_supervisor": "disabled", **_access_readiness_checks(), }, } diff --git a/website/docs-redirects.json b/website/docs-redirects.json index 7a0a34d654..e01602388d 100644 --- a/website/docs-redirects.json +++ b/website/docs-redirects.json @@ -2,6 +2,7 @@ "explanation/core-concepts": "get-started/core-concepts", "explanation/experience-and-skill-lifecycle": "workflows/experience-and-skill-lifecycle", "explanation/memory-and-handoff": "workflows/memory-and-handoff", + "how-to/artifact-processing-migration": "operate/artifact-processing-migration", "how-to/configure-agent-plugin": "integrations/agent-plugin", "how-to/configure-agent-skill-targets": "workflows/configure-agent-skill-targets", "how-to/configure-claude-code": "integrations/claude-code",