diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5052555c..7e539b70 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -143,8 +143,13 @@ The provider-operations integration was first tested against Motoro commit subsequently released those changes in `v0.14.0`. The current provider-driven sampling integration pins Motoro release tag `v0.15.1` (`805fa51455642b01c1fb9aff52fabd28ebfbb6b8`), which also fixes native -effort fields for Azure-hosted Claude. For future -integrations, **release Motoro first** and complete this sequence before ASAREE's +effort fields for Azure-hosted Claude. Native resource registration currently +uses temporary integration commit `1d75d9c036ebc35217901d8945b69b4841d17798` +([Motoro PR #26](https://github.com/EpistasisLab/motoro/pull/26)) so manual +creation and experiment imports share registration implementations while imports +can own their transactions and defer connections. Replace this pin with a tested +release tag before production. For future integrations, **release Motoro first** +and complete this sequence before ASAREE's production release: 1. Replace the integration pin with the tested Motoro release tag. Update the diff --git a/README.md b/README.md index 2cee94bf..6872acce 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,36 @@ integration. Motoro ships no HTTP layer, no auth, and no UI; ASAREE adds those, plus the experiment/protocol/dataset model, and depends on Motoro as a pinned library — in-process, not a service call. +## Registered skills + +ASAREE treats registered skills as immutable. Instructions, discovery metadata, +and bundled files live in Motoro's existing `skills` and `skill_files` tables; +canvases keep skill IDs. Register changed content under a new name. ASAREE's +update and Markdown/folder replacement routes return HTTP 409, including for +older SDKs. Motoro v0.15.1 and progressive disclosure remain unchanged. + +ASAREE's `skill_references` table retains IDs for draft canvases, experiment +factor choices, design revisions, published experiment versions, and runs. +Deleting a referenced skill returns HTTP 409 with its retained usages. Removing +a draft node does not release published versions or historical runs. Deletion +also checks Motoro's retained agent configurations and agent-run snapshots; +deleting an experiment alone does not erase those runtime records. Reference +rows disappear with their owning records; no skill content is copied or garbage +collected. Position and unrelated configuration saves do not resolve skill +bundles or update reference rows. + +Apply ASAREE's migrations before running the application. The migration backfills +references without changing historical definitions. After migration, run: + +```sh +uv run python -m asaree.services.skill_references +``` + +The audit prints unavailable references and exits nonzero if any are found. +Missing/deleted sources need explicit repair in the draft and a new publication; +their historical content cannot be inferred. The policy governs ASAREE's own +writes. Direct Motoro calls and database administration remain outside it. + ## Releases and development For installation, reproducible research, and production deployments, use a diff --git a/docs/adr/0001-measurements-have-explicit-producers.md b/docs/adr/0001-measurements-have-explicit-producers.md deleted file mode 100644 index 2676112c..00000000 --- a/docs/adr/0001-measurements-have-explicit-producers.md +++ /dev/null @@ -1,17 +0,0 @@ -# Built-in metrics are evaluated; custom metrics are reported - -ASAREE distinguishes two measurement paths. - -Built-in metrics are owned by ASAREE. Their runtime producer reads the immutable attempt snapshot during finalization, computes supported numeric or Boolean observations, and supplies the values used for aggregation, comparison, and ranking. - -Custom metrics are owned by the experiment author. A custom declaration points to an Agent, or to a Script/MCP tool directly connected to that Agent. ASAREE does not execute that source as a post-run evaluator. It captures the Agent's completed final output or the result of the last matching tool call already recorded in the Agent's execution trace. The last call is used whether it succeeded or failed. - -## Consequences - -- Users are responsible for prompts, scripts, MCP tools, and Agent behavior that produce the value they want to record. -- Custom values are opaque JSON. ASAREE does not coerce, validate, aggregate, rank, or choose a primary custom metric. -- If the Agent never produces the configured output or call, the observation is `unavailable` and its CSV cell is empty. -- Test Runs, per-node Play, production Results, and CSV export all consume the same persisted observation shape. -- Every observation retains producer provenance and a status. A measured JSON `null` remains distinguishable from an unavailable observation through that status and is exported as the literal `null`. -- Script and MCP configuration is validated for source identity, enabled state, and direct Agent wiring. Evaluator input mappings, result paths, deterministic execution, and side-effect acknowledgements are not part of custom measurement. -- Historical `deterministic_evaluator` bindings are normalized at the persistence boundary to reported bindings; no runtime adapter exists for them. diff --git a/docs/adr/0003-immutable-dataset-inputs-and-managed-artifacts.md b/docs/adr/0003-immutable-dataset-inputs-and-managed-artifacts.md deleted file mode 100644 index 4d94a012..00000000 --- a/docs/adr/0003-immutable-dataset-inputs-and-managed-artifacts.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -status: accepted -date: 2026-11-09 ---- - -# Preserve immutable dataset inputs with PostgreSQL records and managed files - -ASAREE must preserve experimental inputs across re-splitting, publication, -execution, storage relocation, and experiment downloads. Keep original CSVs, -exact partition files, and derived datasets in managed filesystem storage; -store their identities, relationships, provenance, and derived row indexes in -the existing ASAREE PostgreSQL database. Motoro retains its existing database; -this work introduces no additional database technology. - -This is the accepted target design, not a claim that the behavior is already -implemented. Implementation is divided between -[immutable splits (#67)](https://github.com/EpistasisLab/ASAREE_Issues/issues/67), -[pinned inputs (#68)](https://github.com/EpistasisLab/ASAREE_Issues/issues/68), -[managed storage (#50)](https://github.com/EpistasisLab/ASAREE_Issues/issues/50), -[PostgreSQL row indexes (#69)](https://github.com/EpistasisLab/ASAREE_Issues/issues/69), -and [experiment packages (#55)](https://github.com/EpistasisLab/ASAREE_Issues/issues/55). - -## Dataset source identity - -The existing registered dataset UUID identifies one immutable original source; -its SHA-256 verifies the original bytes. A separate source table is not required -solely to introduce another identifier. Replacing the original data creates a -new registration. Names and descriptions may change without changing source -identity, and ownership remains attached to the registration. - -Whole-dataset and per-row execution refer to the same source. The derived row -index preserves original row positions, column order, and exact string values. -Its parsing rules are recorded separately: changing a parser does not change -the original source. Build this index when row-oriented functionality requires -it, using bounded-memory ingestion and batched PostgreSQL reads, rather than -requiring every whole-dataset upload to become database rows. - -## Immutable splits and current selection - -Each successful split operation creates a split UUID associated with its -dataset. A split records train/test artifact references and hashes, creation -time, effective target column, and available provenance. Quick splits record -the actual strategy, seed, requested test fraction, and grouping/stratification -behavior. Manual splits record their supplied origin without inventing their -generation procedure or claiming verified source-row membership. - -The dataset has a nullable `current_split_id`. Creating a successful split -makes it current; selecting an older split changes only that pointer. Neither -operation modifies another split's files or provenance. Registration without -a split remains supported. Compatibility response fields such as `train_path` -are resolved from the selected split, not maintained as another authoritative -selection. Publish the new split and update the selection only after successful -artifact preparation, preserving the previous selection on failure. - -## Managed artifact references - -A managed-artifact record in ASAREE PostgreSQL has an artifact UUID, storage -namespace and relative storage key, content hash, byte size, format, and -preparation/availability status. Resolve deployment-specific absolute paths -when files are needed; durable references use stable artifact identities. -For example, a split references a train artifact whose storage key may be -`datasets//splits//train.parquet`. The precise directory -layout remains an implementation decision. - -Original CSVs and exact partition files are authoritative file artifacts. The -row index is derived and is not independently editable. Artifact availability -may change without changing content identity; relocation must preserve bytes -and references. Referenced artifacts are protected from cleanup. Identical -hashes do not imply permission to share content across owners; automatic global -deduplication is not required. - -Issue #67 introduces only the artifact handling its sources and splits need. -Issue #50 extends the same contract to other managed files and migrates existing -path references. Avoid implementing a general storage framework upfront. - -## Publication and attempt inputs - -A published experiment version freezes dataset sources and split selections -required by its graph and factor alternatives. Publication resolves a current -split selection to a specific split UUID. Each attempt records the resulting -inputs for its cell and Agent bindings. Preserve binding order and ownership -checks. - -For example: publishing with split A pins A. Creating split B changes the -dataset's default, but executing or resuming the older publication still uses -A. A newly published draft may select B. An unsplit binding explicitly selects -the original source: creating a split later must not change that binding. -Per-row inputs retain their original row positions and projections. - -Workspace reuse validates pinned input identities. Identical bytes do not -automatically authorize sharing workspaces across publications or attempts. -Issue #68 settles the detailed sharing rules; #67 supplies the identities. -Missing or mismatched pinned inputs must not fall back to the current selection. - -## Migration and historical evidence - -Verify available legacy files and metadata and represent them as initial -source/split/artifact records without regenerating or changing their bytes. -When a missing hash is computed during migration, it establishes the observed -file's identity at that time, not proof of an old attempt's input. Unknown -provenance remains unknown. Report missing files and hash mismatches explicitly. -Do not assign the current split to an old publication as though its historical -selection were known, and do not reconstruct overwritten history speculatively. - -A manual split's association with a registered dataset expresses the user's -association; it does not prove that the supplied rows partition the original -CSV. Preserve the supplied artifacts regardless of whether source-row membership -can be established. - -## Consequences and alternatives - -Keeping files supports existing scripts, ML tools, exact-byte preservation, -and experiment archives. It requires coordinated backup and lifecycle handling -for PostgreSQL records and managed files. Stable references and integrity checks -address that coordination; relocating a root alone is not a migration. - -Storing all parsed datasets in PostgreSQL would still require materialization -for existing file-based tools and would not preserve original CSV bytes. -Storing all file bytes as database blobs would enlarge database backup/restore -workloads while still requiring runtime extraction. Neither is required for a -portable download. PostgreSQL replaces SQLite specifically for indexed row -access, with no per-row network-query port of the synchronous SQLite interface. - -Experiment packages resolve pinned dependencies into a versioned archive with -relative references and verified hashes. They omit regenerable row indexes, -caches, and scratch. Packages are logical exports, not database backups, and -exact inputs do not promise identical external-model outputs. - -## Implementation handoff - -Implement #67 first, then #68, #50, #69, and #55 in separately reviewed changes. -Coordinate shared identities and references before implementation; do not -implement follow-up features as incidental scope in #67. Its split history -alone does not make historical execution reproducible before #68 is complete. - -Implementation sessions must read this decision alongside -[the glossary](../../CONTEXT.md) and -[the experiment contracts](../agents/experiment-contracts.md). Table layouts, -exact directory hierarchy, detailed retention, and archive schema remain scoped -to their implementation issues. This decision extends the existing publication -contract without adding another experiment-version counter. diff --git a/docs/agents/experiment-contracts.md b/docs/agents/experiment-contracts.md deleted file mode 100644 index 0c780611..00000000 --- a/docs/agents/experiment-contracts.md +++ /dev/null @@ -1,90 +0,0 @@ -# Shared experiment contracts - -Read before changing experiment datasets, agents, factors, revisions, execution/results, -or measurement behavior in the backend, frontend, SDK, or tests. Paths below are -relative to the repository root; bare service filenames refer to `src/asaree/services/`. -Vocabulary is defined in `CONTEXT.md`. - -## Datasets - -- `experiment_datasets` is the stored many-to-many source of truth. Read/write through - `src/asaree/services/experiments.py`: `set_experiment_datasets`, - `get_experiment_dataset_ids`, and batch `get_dataset_ids_by_experiment` for lists. - Preserve join-row `position`: it is canvas wiring order and agent prompt order. -- `dataset_ids` fully replaces the association; `[]` detaches everything. The compatibility - scalar `dataset_id` is a one-dataset write shorthand and a read view of `dataset_ids[0]`. - The former scalar model FK is dropped; do not create another source of truth. -- Creation and `PATCH /experiments/{id}` both accept dataset associations. Notebook workflows - can create the experiment before registering datasets, then attach them with PATCH. Preserve - both paths and validate ownership before writing associations. No datasets is a valid, - permanent state; do not backfill old experiments speculatively. -- Frontend graph synchronization must never detach stored datasets on initial load. See - [protocol instructions](../../frontend/src/components/protocol/AGENTS.md) before editing it. - -## Agents - -- Agents are reusable per-user templates, not a stored experiment association. There is no - `experiment_agents` join table; do not introduce one for membership displays. -- For a participation display, derive membership from experiment-scoped execution records, - not a new stored relationship. The agent-run API supports server-side `metadata` JSON - filtering (including `experiment_id`); filter before applying a limit rather than fetching - an arbitrary run page and filtering it client-side. See `src/asaree/api/runs.py`. - -## Cells and design history - -- A cell is one unique factor combination with its planned replicates. Group replicate - responses by `cell_id`. Run/progress/scored counts count replicates. “Run all cells” - runs every pending replicate across the cells. -- Cells belong to a design revision. The current revision has `superseded_at IS NULL`; - a partial unique index enforces at most one current revision per experiment. -- Access `FactorialReplicateResult` through `src/asaree/services/factorial_cells.py`'s - `get_replicate`, `list_replicates`, or `upsert_replicate`. Queries must join the owning - cell and scope both experiment and revision, including when `revision_id` is supplied - by a caller. Default to the current revision; read historical revisions explicitly. -- `generate_design_cells` in `src/asaree/services/design_generation.py` preserves an - unpublished revision only while no planned replicate slots are removed and the coordination - strategy is unchanged. Shrinking replicate count can supersede even if no cell disappears. - A strategy change starts clean; it must not reuse results from a different execution model. -- Once a publication references a design, changed declarations or planned slots create a - separate draft revision. Repeating an unchanged declaration reuses the design. Never mutate - a published design to accommodate a seed, level, or replicate-count edit. -- Carry results forward only on compatible unpublished design changes, matching factor-value - identity and replicate number, not display labels alone. Strategy changes and changes to a - published design do not carry results forward. Originals remain in their historical scope. -- `ProtocolRun.design_revision_id` pins planning, execution, and result write-back so - mid-flight regeneration cannot redirect results. Run references use `ondelete="SET NULL"`; - cells cascade when their revision is deleted, allowing runs to outlive designs. -- Reject deleting the current revision or any design referenced by a published version with - 409. Other historical deletion is permanent and cascades to results. Regenerate to replace - the current design; use `design_revisions.py` for numbering and retention rules. - -## Published execution and factor bindings - -- `Protocol.graph` is the autosaved draft. A published experiment version freezes the graph, - experiment settings (including measurement configuration), and design reference together. - Use `protocol_revisions.py`/`experiment_versions.py`; a graph-only comparison cannot decide - whether an experiment has unpublished changes. Production uses a published version, while - canvas Test Runs and node Play have their own preview paths. -- A `ProtocolRun` records both protocol and design revision IDs. Workers load the published - snapshot so editing the canvas cannot alter queued, running, or resumed work. -- A declared factor must bind to at least one canvas field before a cell batch can run. - Unbinding/deleting a field leaves the factor declared and unbound. Require rebind/removal, - design-impact review, and regeneration. `src/asaree/services/factor_bindings.py` is the - shared backend guard; the frontend shows the same invalid state before generation. - -## Results and measurement - -- A replicate, a row execution, and an attempt are different identities. Row mode creates - one execution slot per original dataset row under a parent replicate; rows are not factors - or extra stochastic replicates. Keep experiment, protocol publication, design, and row/slot - scope together in readers and write-back. Counts must name which identity they count. -- `ProtocolRun.attempt_result` retains an attempt's own facts; replicate/row records project - the latest attempt. Rerunning must not replace an older attempt's recorded measurements - with the latest projection. Use execution/attempt readers for history. -- Built-in metrics are evaluated from attempt snapshots and support comparison/aggregation. - Custom metrics report opaque values already produced by the configured Agent or its last - matching Script/MCP call; do not invoke an extra evaluator, coerce them to scalar scores, - or rank/aggregate them. Preserve producer provenance and observation status: measured JSON - `null` differs from unavailable. See `CONTEXT.md`, - `src/asaree/services/measurement_engine.py`, and the available - ADR `docs/adr/0001-measurements-have-explicit-producers.md` for measurement changes. diff --git a/docs/experiment-packages.md b/docs/experiment-packages.md deleted file mode 100644 index 5ead4177..00000000 --- a/docs/experiment-packages.md +++ /dev/null @@ -1,329 +0,0 @@ -# Published experiment packages - -The canvas top bar offers **Download experiment package**. Select a published -version, including an older version, and optionally include its results. The -separate **Download draft definition JSON** action remains a draft definition -export without dependency files. - -API clients create the same owned export job used by Results CSV downloads: - -```http -POST /api/experiments/{experiment_id}/execution-results/jobs?protocol_id={protocol_id}&protocol_revision_id={publication_id} -Content-Type: application/json - -{"kind":"export","format":"experiment_package","include_results":false,"request_key":"unique-client-request"} -``` - -The publication ID is mandatory. Partial cell, replicate, or row selections are -not supported for a package. Poll the returned job ID through the existing job -endpoint. Completed jobs provide a native `download_url`, a manifest -`schema_url`, and `progress.sha256` for the compressed archive. Links are signed -for five minutes; requesting job status renews the link. Prepared files expire -24 hours after job creation. Cancellation and failure never publish partial -archives as completed downloads. - -## Schema versions and compatibility - -New exports use schema **2**. Imports accept schemas **1 and 2**; other versions -are rejected before confirmation. Version 2 adds structured Skill metadata, -Skill file encodings/order, dataset registration metadata, knowledge registration kinds/empty-tree counts, publication notes and -stable row-slot evidence. These additions close reconstruction gaps found by -auditing the actual version 1 exporter. Version 1 files remain readable and -re-exportable; the importer parses recorded Skill frontmatter, but never claims -to recover omitted source filenames, original resource encodings/order or row -slot facts. Such omissions are explicitly reported in preflight. A v1 binary -Skill resource is represented locally as base64 without claiming that was its -original storage encoding. - -Both versions require canonical UUIDs for typed archive identities. MCP -requirement filenames, their IDs and included knowledge directory names must -agree; inconsistent packages are rejected rather than assigning new meanings to -their paths. Explicit missing/unresolved dependencies remain diagnostics, including -legacy name-only lookups. Only a Skill's exact root `SKILL.md` is its entrypoint; -nested files such as `references/SKILL.md` are ordinary bundled resources. Version -2 retains their recorded encoding/order; version 1 retains their bytes with the -same explicit unknown source metadata as other v1 resources. - -The common archive layout is: - -The `.tar.gz` archive contains: - -| Member | Meaning | -| --- | --- | -| `manifest.json` | Format/version, selected publication, capture window, software requirements, completeness and inventory hashes | -| `files.jsonl` | One record per payload member: relative path, source identity, byte count, SHA-256 and provenance | -| `dependencies.jsonl` | Included, missing, unresolved and intentionally excluded dependencies, with reasons | -| `publication/` | Selected canvas and experiment settings, including factors, bindings and measurements | -| `experiment-metadata.json` | Current name/description, explicitly captured at download time | -| `design/` | Referenced design declaration and generated cell/replicate identities | -| `inputs/` | Pinned dataset bindings, originals, exact split files and split provenance | -| `resources/` | Scripts, rendered stored Skills with all bundled resources, and authorized knowledge content | -| `requirements/` | Model configurations and MCP server/tool requirements without connection secrets | -| `results/` | Optional version-scoped attempts, observations, recorded evidence and retained attributable files | -| `sources/` | Imported source manifests/publications and typed identity mappings; with results selected, the exact original source archive | - -The manifest hashes both inventories. `files.jsonl` hashes dependency inventory -bytes but does not hash itself or the manifest, avoiding circular references. -Dataset artifact UUIDs map to paths through the dependency inventory. Arrays in -pinned bindings preserve their recorded ordering and row projections. Resources -are deduplicated within this export by stable identity, never across owners. - -`publication_pinned` identifies recorded publication/configuration and verified -input identities. `captured_at_download` identifies mutable reusable library or -knowledge content. Skill entry points are rendered from stored metadata/body; -bundled UTF-8 and base64 assets retain their stored content. `recorded_attempt` -identifies an attempt's own facts, rather than a latest-attempt projection. -`legacy.unknown` records history that cannot be established. Missing historical -settings, sources, splits or files never resolve to the current draft or split. - -ASAREE records are read under one repeatable-read snapshot. Motoro resources use -a separate snapshot; filesystem captures verify opened files and detect tree -changes. Mutable external knowledge has no cross-file transaction or historical -snapshot. The manifest records this limitation rather than claiming publication -fidelity. Uploaded bundles and documents use the application's per-owner storage -boundary. An external registration or shared browse access alone does not prove -authority to download the registered directory. Broad roots, other owners' -knowledge, symlinks and ambiguous overlaps are unresolved dependencies. - -### External knowledge export grants - -Operators can authorize a specific external bundle for a user with the -`knowledge_export_grants` setting, supplied as JSON through -`ASAREE_KNOWLEDGE_EXPORT_GRANTS`, for example: - -```json -{"00000000-0000-0000-0000-000000000001":["/srv/research/approved-cohort-bundle"]} -``` - -The key is the application user's UUID. Each absolute path must match the -registered bundle root exactly; there is no implicit grant to descendants or -ancestors. A grant is the operator's assertion that **all content under that -exact root is authorized for that user**. It is not inferred from filesystem -ownership, a registration's owner field, or absence of competing registrations. -Configure only narrow named bundle roots after reviewing their full contents. - -Grants support isolated legacy bundles outside today's browse root without -moving or adopting their files. They do not override rejection of the shared -browse root/its ancestors, platform-storage overlaps, or foreign/ownerless -knowledge registrations and other users' grants that overlap in either direction -or exactly. Missing or malformed grants, unreadable registration evidence and -ambiguous knowledge boundaries are reported as unresolved before content capture; -diagnostics do not expose another owner's identifiers, paths, commands or bytes. - -Set the same configuration on the API and worker processes, particularly -`asaree-results-worker`, which builds packages. In the supplied Compose setup, -the configured environment file is already forwarded to `asaree-app`, -`asaree-worker`, and `asaree-results-worker`; a host-shell variable alone is not -automatically forwarded. Deployment overrides can set the JSON value in those -services' `environment` mappings. External paths must be mounted consistently -in the exporting worker. No grant is required for authorized uploaded bundles -and documents, and this correction changes no database schema or package format. - -Credential/connection fields, including typed fallback and sampling snapshot -fields, and recognized credential files are excluded. Dataset bytes, prompts, -scripts and opaque experimental values are preserved. Known knowledge display -paths become relative archive directories; sampling snapshot keys identify -credential-free explicit input in the archive, rather than executable runtime -resolver requests. Importers must use this schema and restore connections; -the package is not a direct runtime-resume image. - -Optional results include every retained production attempt for the selected -publication and design. They exclude test runs, node previews, other versions, -queues, workspace resume/control state, regenerable row views/indexes, caches -and scratch. UUID-isolated retained outputs include Agent slots and Script -working directories. Shared legacy workspaces and experiment-level artifacts -without publication attribution are not assigned to historical versions; the -dependency inventory records unavailable or unscoped evidence. -AgentRun IDs in node evidence are source provenance; native Motoro step history -and resume/control snapshots are not bundled. -Workspace scratch is recognized structurally at `.scratch/` under the workspace -root or its `dataset=`/`agent=` slots. User artifacts such as -`outputs/working/prediction.csv`, `outputs/cache/`, `outputs/scratch/`, and -`outputs/.scratch/` remain durable content. Temporary preparation names use the -reserved hidden producer naming pattern; an ordinary `results.preparing/` -output directory is preserved. -Materialized Script source exclusions apply only to the producer's immediate -`scripts/` directory (including a recorded standalone Agent's directory). -Row-input CSVs and `row-view.json` are excluded only at the exact -`agents/<64-hex Agent key>/` location inside a row attempt. Nested output files -and whole-workspace artifacts retain their bytes even when their names resemble -these inputs. - -Archive generation streams file bytes and SQL evidence slices, spools inventories -to plain files, and discards tar member metadata after writing. Memory does not -grow with the number of attempts, archive members or dataset rows. Publication -configuration and one bounded Skill/resource record are processed at a time. -Copying/compression run off the event loop; cancellation stops and joins active -writer work before cleanup. No new database or SQLite inventory is introduced. - -A package is a logical export, not a database backup. Resuming workspaces and -reproducing external model/tool outputs are outside its scope. See -[ADR 0003](adr/0003-immutable-dataset-inputs-and-managed-artifacts.md). - -## Import workflow - -On **Experiments**, choose a `.tar.gz` package under **Import experiment -package**. Upload starts inspection only. Review the source version, schema, -file categories, missing dependencies, historical results and local configuration -requirements, then explicitly confirm creating a new experiment. The persistent -request list lets you return after navigation or a browser restart. Cancel before -activation or retry a failed unexpired request. A distinct request creates a -distinct owned experiment even for identical archive bytes. - -The new experiment contains an editable draft and planned cells/replicates. -It has no selected local publication and no fabricated completed executions. -Imported source publications, resolver/sampling snapshots, all retained attempts, -observations and artifacts stay immutable in managed files. **Download experiment -package → Imported source evidence** exposes those files separately from local -Runs/Results projections. It also provides an exact source package re-export. -New local exports retain source manifests/publications and typed mappings under -`sources/`; including results additionally preserves the original source archive -as an opaque nested evidence file. Nested archives are never executed or used -as native runtime state. - -Open the imported experiment's editable draft. Its setup panel reports **Ready to -publish** or **Setup needed**, with links to affected canvas nodes. Select saved -destination provider connections and compatible custom MCP connections there; -multiple compatible connections always require an explicit selection. Missing -credentials can be configured in Profile. Refresh readiness after setup changes. -Normal publication validates the current draft and every factor alternative; -there is no acknowledgement checkbox and no return to the upload screen. -Incomplete drafts remain editable and source evidence remains inspectable. -Readiness checks saved records only; live connection tests are explicit actions. -Normal publication resolves new local sampling/input -snapshots; it does not rewrite the preserved source evidence. Resource names -receive an import-specific suffix to avoid collisions. Canvas node IDs remain -protocol-scoped labels because prompts may address them; new protocol ownership -creates a fresh identity namespace. Only typed resource references, selections -and bound factor alternatives are remapped. Opaque strings, scripts, prompts, -dataset values, observation values and provenance are not searched/replaced. - -Imported content receives fresh owned identities, including imported MCP -requirement identities. Runtime bindings may reference authorized destination -system services or explicitly selected owned connections. These bindings are -recorded separately from source-to-local content mappings. New packages record -stable built-in service identities derived from shipped modules; automatic -matching requires a trusted system registration, the same service identity, -all recorded required tools and exactly one compatible destination. The additive -`service_identity` and `required_tool_names` requirement fields are supported in -schema 2; required tools include the union of factor alternatives and implicit -dataset/Script grants. Older requirements without a required-tool subset use -their recorded full tool list conservatively. Display -names and source owner IDs never establish compatibility or authorization. -Older packages without service identities require explicit selection. Destination -commands, URLs, environment and credentials remain untouched. Scalar MCP identity -factor alternatives become complete configurations so each selected identity -retains its matching destination runtime name. Opaque values remain unchanged. - -Before downloading a prepared export, the dialog separates included dependencies, -destination connection requirements and missing/unresolved content. Incomplete -packages are labelled explicitly and retain actionable dependency diagnostics -(up to 100 in the summary; the full inventory remains in the package). Connection -requirements alone do not make content incomplete. The selected historical -publication remains authoritative; missing history never uses current content. -Use **Publish & prepare package** to download current draft changes instead. - -### API - -All routes below require the importing user's authentication: - -1. `POST /api/experiment-package-imports` with `{"request_key":"client-unique-key"}`. - The same owner/key returns the same durable request. -2. `PUT /api/experiment-package-imports/{id}/upload` with raw gzip archive bytes. - A disconnected upload can be repeated before inspection; no multipart buffering - is required. -3. Poll `GET /api/experiment-package-imports/{id}` for status, progress, diagnostics, - preflight, source SHA-256 and destination experiment ID. -4. `POST .../{id}/confirm` explicitly queues activation. Repeated confirmation is - idempotent. `POST .../{id}/cancel` cancels before completed activation; - `POST .../{id}/retry` re-inspects a failed request before another confirmation. -5. `GET .../{id}/files?offset=0&limit=50` pages source inventory; - `GET .../{id}/source?path=publication/canvas.json` downloads one original file. - Omitting `path` re-exports the original source archive byte-for-byte. - `GET .../{id}/identities?offset=0&limit=50` pages durable typed provenance. -6. `GET .../{id}/readiness` returns read-only readiness issues with `node_id`, - compatible authorized MCP candidates, and saved provider selections. - `POST .../{id}/connections` with `{"kind":"mcp","source_id":"source-uuid", - "destination_id":"destination-uuid"}` explicitly selects an existing - connection. Use `"kind":"provider"` and a provider key such as `"openai"` - as `source_id` to select that user's saved provider setting. These actions - never connect, test credentials, or invoke packaged code. Publish using the - normal protocol publication endpoint. The legacy `/configuration` endpoint - remains compatible but its timestamp does not unlock or gate publication. - -`GET /api/experiment-package-imports?experiment_id={id}` finds an experiment's -source history; omitting the filter returns the newest 50 owned requests. - -### Lifecycle, limits and recovery - -The existing results worker relays durable `validating`, `queued` and `activating` -requests. PostgreSQL advisory locks serialize a request across workers. Archive -extraction, inventories and evidence use filesystem staging, not SQLite. Hashes -and references are verified before activation and the archive is re-inspected -before reconstruction. IDs derive from the request and typed source identity; -retry adopts only that request's owned staged resources. Motoro and ASAREE use -separate transactions. Skills stay soft-deleted and MCP registrations stay -disconnected/hidden during resource staging. Native experiment/protocol readers -hide incomplete activation. The relay finishes an interrupted visibility flip; -failures/cancellation compensate only records allocated by that request. - -Uncompleted requests expire after 24 hours; cancellation schedules cleanup on the -next results-worker relay. Cleanup waits for the request's worker lock and removes -only its staging paths and resources. Completed imports are durable evidence and -do not inherit download-export expiry. Include their files and database records -in coordinated backups. The API and results worker must share the same managed -storage configuration. - -Never-validated uploads have no staged resources: cleanup discards their private -files without parsing partially extracted inventories. Each expired request has -its own cleanup transaction. A compensation failure retains that request with -`compensation_required` progress for retry while other requests continue through -cleanup and enqueueing. Staged resources still receive owned deterministic-ID -compensation; their cleanup is not skipped when another upload is malformed. - -Configurable environment limits (positive integers): - -| Setting (`ASAREE_` prefix) | Default | -| --- | --- | -| `PACKAGE_IMPORT_MAX_COMPRESSED` | 1 GiB | -| `PACKAGE_IMPORT_MAX_EXPANDED` | 8 GiB | -| `PACKAGE_IMPORT_MAX_MEMBERS` | 100,000 files | -| `PACKAGE_IMPORT_MAX_DOCUMENT` | 16 MiB per JSON document, JSONL record or Skill resource | - -Files stream in bounded blocks; attempt inventories are disk-backed. JSON canvas, -settings and one evidence document must fit the configured document limit. -Archives exceeding any limit fail inspection with a diagnostic; increase limits -deliberately for larger recorded evidence. Traversal, links, special/sparse files, -duplicate/conflicting members, invalid JSON, unsupported schemas, unlisted files, -incorrect hashes/sizes and inconsistent typed references are rejected. Archive -metadata is bounded before parsing: only the exporter's ordinary files and local -PAX path/size extensions are accepted; global/GNU sparse/nested extensions are -rejected. Resource filename extensions do not turn opaque contents into schema -documents; binary Skill, knowledge and artifact bytes remain opaque. -Archive -ownership fields never confer authorization. No packaged script/tool or server -connection is invoked by inspection or reconstruction. - -### Export-to-import coverage audit - -| Exported component | Local reconstruction / retained evidence | -| --- | --- | -| Manifest, inventories, source version and capture provenance | Immutable exact original files, source archive SHA-256, durable owned request | -| Canvas, Agent configs, model requirements, settings, measurements | Editable sanitized draft; source snapshots retained separately; local publication required | -| Design declarations, cells, planned replicates | New local IDs; typed references and resource-valued factor alternatives remapped | -| Dataset bindings, projections and ordering | Exact source binding evidence; graph wiring/order retained; new owned registrations | -| Original CSVs, pinned split files and split provenance | Exact filesystem bytes/hashes, owned artifact/split records, no row-index import | -| Scripts and inline content | Exact source content; no execution during import | -| Skills, discovery fields, frontmatter and all resource files | Owned Motoro Skills/files; UTF-8/base64 encoding and order from v2 metadata | -| Knowledge trees and MCP requirements | Owned managed copies and disconnected registrations; explicit local configuration | -| Optional attempts, observations, row slots, conversations, node evidence, usage/errors | Source-attributed historical files and identity mappings; no native runtime records or latest-result projection | -| Attributable durable output/artifact files | Exact source files with hashes and attempt attribution; re-exportable source evidence | -| Missing/excluded dependencies and unavailable history | Visible diagnostics and preserved inventories; no same-name substitution | - -The PostgreSQL tests cover isolated source/destination product and resource -schemas, different owners/storage paths/credentials, both dataset modes, exact -CSV/split/binary Skill bytes, publication readiness, built-in compatibility and -ambiguity, explicit custom mapping, factor alternatives, source re-export, -ownership isolation and cross-database crash/retry/cancel boundaries. Archive -tests cover corruption, unsafe members, limits, compatibility and non-execution. -Native Motoro step/resume histories were never exported and cannot be restored. diff --git a/docs/experiment-portability-plan.md b/docs/experiment-portability-plan.md deleted file mode 100644 index 8db71fa8..00000000 --- a/docs/experiment-portability-plan.md +++ /dev/null @@ -1,53 +0,0 @@ -# Experiment portability implementation - -Branch: `fix/package-export-publication-join`; starting HEAD: `f27437d`. -Preserve existing ancestry and leave PR #56 (base `develop`) unmerged. - -1. Add stable built-in service identities and capability-based destination matching. - Preserve destination connection settings; retain owned imported requirement IDs - and record destination runtime bindings separately as provenance. -2. Add explicit authorized destination connection selection for custom MCP and - model providers, including factor alternatives. Never execute packaged code, - import credentials, or run live connection tests during setup validation. -3. Replace acknowledgement with read-only readiness checks in publication; - surface node/resource issues and allow incomplete drafts to remain editable. -4. Show readiness and setup actions in the imported experiment and link completed - imports directly to that draft. Preserve source inspection and existing UI work. -5. Separate export contents, destination requirements, and missing content; - preserve historical fidelity and the publish-before-download option. -6. Add focused cross-installation coverage for connection matching, fresh owned - identities, factor alternatives, exact bytes, evidence, retry and readiness. - -Verification: focused Python unit tests/lint and frontend tests/type checking. -Database integration uses only explicitly configured disposable PostgreSQL, never -application databases or application `.env` files. Obtain approval before starting -infrastructure, checks taking minutes, or browser automation. - -Identity clarification for #70: imported content always receives fresh owned IDs. -Runtime bindings may reference authorized destination system services. Source IDs -and source-to-local mappings remain immutable provenance; destination commands, -environment and credentials are never replaced by archive data. - -Implementation status: all six steps implemented. Readiness and destination -selection are available on the imported canvas; the legacy acknowledgement API -is retained only for compatibility. New schema-2 requirements carry stable -service identities and required-tool subsets. Legacy requirements require -explicit destination selection. Source provenance scopes reselection when -several requirements share one destination connection. - -Verification (2026-11-11): disposable PostgreSQL 16.2, isolated source/destination -product/resource schemas and filesystem roots; full backend suite passed -2,137 tests (3 skipped; 14 statistical-validation tests deselected). Full frontend -suite passed 664 tests with two workers; default concurrency exposed an existing -metrics-autosave timing failure, which passed alone. Backend lint and frontend -type checks passed. Full mypy has 695 existing errors versus 697 at the starting -HEAD, with no new diagnostics; the four portability service modules pass focused -typing. The first full backend attempt had a launcher-relative scripts-path -failure, fixed in the disposable launcher before the successful full rerun. -Final focused checks passed 121 backend tests and 19 frontend tests, additionally -covering later provenance/reselection changes. `git diff --check` and local -documentation links passed. Implementation is recorded in the branch commit. - -No application databases or application `.env` files were used. Browser -appearance and live provider/MCP behavior were not tested. All original commits -and the two previously unpushed commits remain; no push or merge was performed. diff --git a/docs/managed-storage.md b/docs/managed-storage.md deleted file mode 100644 index 53cb44cd..00000000 --- a/docs/managed-storage.md +++ /dev/null @@ -1,291 +0,0 @@ -# Managed storage operations - -ASAREE keeps the existing ASAREE and Motoro PostgreSQL databases. Original -CSVs, immutable splits and derived datasets remain files. Derived row indexes -live in ASAREE PostgreSQL. Portable experiment archives -are issue #55. See [ADR 0003](adr/0003-immutable-dataset-inputs-and-managed-artifacts.md). - -## Configuration and inventory - -Set `ASAREE_DATA_ROOT` to an absolute, shared filesystem mount in every API, -execution worker and results worker. Its compatibility default is `./data`, -resolved against the service's startup directory. Do not start these services -from different directories with a relative default. Application settings use -explicit constructor values, process environment, settings-file values, then -defaults, in that order. A nonempty directory override takes precedence over -the root, even when the root changes. Relative overrides are resolved against -the startup directory; `~` is expanded. Empty overrides select the root's -default child. API/worker settings export resolved absolute storage paths to -the existing Motoro MCP subprocess allowlist. Standalone workspace-core reads -the same environment; explicit `Workspace(root=...)` takes precedence. - -| Namespace | Override (`ASAREE_` prefix) | Default child | Persisted references / lifecycle | -| --- | --- | --- | --- | -| datasets | `DATASET_STORAGE_DIR` | datasets | `dataset_artifacts` UUID, namespace, key, hash, size, status; source/split FKs; immutable inputs | -| workspaces | `DATASET_WORKSPACE_DIR` | workspaces | result workspace IDs, events, state formats 1/2, named slots, manifests, `dataset_inputs.json`; reusable state and durable outputs | -| exports | `RESULT_EXPORT_DIR` | result-exports | `result_jobs` UUID; CSV and schema sidecar; existing export expiry | -| documents | `OKF_DOCUMENT_DIR` | okf-documents | Motoro knowledge server command; mutable managed knowledge | -| bundles | `OKF_BUNDLE_UPLOAD_DIR` | okf-bundles | Motoro knowledge server command; mutable managed knowledge | -| backups | `BACKUP_DIR` | backups | pre-migration PostgreSQL dumps; explicit CLI `--dir` wins | -| scratch | `SCRATCH_DIR` | scratch | reserved operator scratch location; temporary script contexts remain beside their consuming workspace | - -Additional storage outside this table: - -- External knowledge bundles are user-owned. `ASAREE_OKF_BUNDLE_ROOT` controls - browsing/new registrations, separately from managed storage; the local - compatibility default remains `~`. Compose defaults to - `/app/data/external-bundles`, configurable explicitly. Existing absolute - registrations continue to work even outside the new browsing root. Move - external files only with their owner's agreement and explicitly update their - registration; never convert them to owned files based on their location. -- Compose's existing `./backups:/app/backups` mount and explicit backup - `--dir /app/backups` remain overrides. Include these dumps in backup inventory. -- PostgreSQL volumes contain both databases; Redis contains queues, working - memory and other runtime state. Uploaded skills and experiment artifacts - stored as database content are covered by database backups, not file roots. -- Script sources are published graph content; materialized scripts, inline - execution contexts and compatibility directories live under their workspace - or the OS temporary directory. Treat unknown script outputs as durable until - reviewed, rather than assuming everything in a run directory is scratch. -- Legacy row snapshots lived at the dataset directory's parent under - `_protocol_runs`. Inventory that location explicitly; new row snapshots and - scripts share the configured workspace root. They keep the same attempt and - Agent identities, row projection and source hash. - -## References, readiness and retention - -The existing artifact contract remains namespace + relative storage key with -content identity verified separately. `managed:///` is its -filesystem spelling in workspace state and knowledge commands. Dataset UUIDs, -artifact UUIDs, split UUIDs, publication/attempt pins, binding order and input -scope are unchanged. Runtime readers resolve references at use. Workspace APIs -continue to return resolved paths; formats 1 and 2 and external seed paths -remain readable. Legacy absolute paths require the explicit migration below -before their old filesystem is removed. Do not infer historical split choices -or split provenance during migration. Effective legacy target handling remains -the existing dataset/pinned-target contract. - -Whole-dataset sharing rules and attempt isolation stay those of #68. Stable -workspace IDs and slots are retained, not recomputed from a directory name or -content hash. Structured MCP operations retain their scope guards. Row snapshots -are immutable within an attempt and checked against their exact projection. - -Raw uploads, state, manifests, scripts and export metadata publish through -unique sibling staging files and atomic publication. Workspace stage pairs are -prepared and verified together before rename, then state advances. First stage -writes retain the established directory layout; replacements get a distinct -generation so a failed write cannot overwrite the prior readable pair. -Immutable source/split artifact records become ready only after bytes exist. -No reader uses `.preparing`, `.part`, `.building`, or `.partial` files as ready -input. On interruption, retain the previous pointer, inventory partial files, -and retry the owning operation. Never promote a partial file by renaming it -manually. If an input pin's file is missing/mismatched, repair from verified -backup; execution fails explicitly and does not select the current split. - -Retention policy: - -- Immutable sources and every split are retained while their dataset exists. - Dataset deletion checks publication/attempt reference edges and retained - workspace seed references, including legacy state. Unknown/unreadable - workspace state blocks input deletion. Inspect it before retrying. -- PostgreSQL row indexes are retained for the lifetime of their registration, - then cascade with it. Pending, queued and awaiting-confirmation result jobs - protect their driver even when they predate publication/attempt pins. - Terminal job previews release this extra protection; publication, attempt and - workspace protections remain independent. No age-based row-index collector runs. -- Reusable workspaces, derived generations, durable outputs and knowledge - copies are retained by default. Unregistering knowledge removes its Motoro - registration only, including for uploads. This intentionally favors history - and resume protection over automatic reclamation. External files are never - removed. Upload path containment is not ownership evidence. -- Existing result-export retention and token expiry remain in force. The - results worker deletes files only for expired terminal export jobs, using - their exact job IDs. It does not apply export expiry to durable workspace - outputs or database experiment artifacts. -- Package imports use `datasets/package-imports//` for private - uploads, verified payloads and durable source evidence. Dataset artifact keys - refer to these exact bytes. Imported mutable knowledge copies live under the - importing owner's bundle directory. `package_imports` and `imported_identities` - in ASAREE PostgreSQL coordinate staging, provenance and cleanup; Motoro retains - owned Skill and disconnected server records. Incomplete requests expire after - 24 hours; cancellation cleans up after the request worker stops. Completed - source evidence is durable and must be included in coordinated backups, even - after later local publication or experiment archival. See - [package import recovery](experiment-packages.md#lifecycle-limits-and-recovery). -- Pre-migration automatic dumps retain the configured `--keep` per database; - manual dumps remain untouched. Preserve an independent coordinated backup. -- Scratch/abandoned generations are cleanup candidates only after the owning - operation is stopped and database plus retained-workspace references have - been inspected. Active/resumable jobs, historical attempts and publications - protect their dependencies regardless of age. There is deliberately no - directory-name-based orphan collector. The migration never deletes sources, - unknown files, row indexes, lock files, or interrupted writes. - -## Copy-first migration and rollback - -Run this as an offline maintenance operation with every API, worker, MCP -subprocess and external knowledge writer stopped. Keep the old image, settings -and mounts. Obtain coordinated backups first. Run the tool using the new image -and intended destination configuration, with both database URLs configured. - -1. Create `old-roots.json` listing **every** namespace in the table above and - its absolute old directory (including overrides and the old dump location). - Give the destination a fresh root with enough space for a full copy; use - fresh destination overrides as necessary. Do not nest destinations beneath - sources. Unchanged namespaces can be backed up and copied to a fresh - destination override for this operation. Do not clear existing directories. -2. Run the dry-run inventory, saving its owner-only plan outside either tree: - - ```sh - python -m asaree.storage_migration inventory --old-roots old-roots.json --plan storage-plan.json - ``` - - Add `--legacy-attempt-root /absolute/old/data/_protocol_runs` if that - legacy location exists. For each knowledge upload whose ownership has been - confirmed from registration/upload evidence, add - `--managed-knowledge `. Unlisted commands remain external - absolute references; inventory and retain their mounts. Do not infer upload - ownership from directory names. Review the plan's database inventory for - all external commands and legacy paths; include their owned locations in - the coordinated backup with the appropriate permission. -3. Review `files`, `updates`, `databases`, `diagnostics` and `problems`. Inventory hashes files - without mutating storage or either database. It includes source/split - records, publication/attempt input manifests and reference edges, run - statuses, result workspace IDs/events, export jobs and Motoro knowledge - registrations and AgentRun ambient metadata/native snapshots. Historical - artifacts already marked missing or unavailable remain unchanged and appear - in diagnostics; their pinned inputs remain unavailable. Ready artifacts with - missing files or mismatched bytes, pin identity conflicts, symlinks and - malformed workspace state JSON block apply; resolve each explicitly and regenerate the plan. Preserve - unknown files. Plans contain operational/user metadata: restrict access. -4. With writers still stopped, run: - - ```sh - python -m asaree.storage_migration apply --plan storage-plan.json - python -m asaree.storage_migration verify --plan storage-plan.json - ``` - - Apply checks source hashes, copies with verified atomic publication, - rewrites only version-record locators in recognized workspace state and - documented ambient locator fields in Motoro run metadata/native snapshots, - then compares and updates affected - database fields. It changes neither input identities nor historical pins. - Row-view values, input names, learned payloads, provenance and arbitrary JSON - files retain their exact values; opaque JSON files are copied byte for byte. - Existing destination bytes must match. Source files remain untouched. - The databases have separate transactions: if interrupted between them, - keep services stopped and rerun the same plan (idempotent) or roll it back. -5. Start API and workers with the same destination settings/mounts. Check a - pinned historical attempt, a resumable workspace and a knowledge registration - before reopening traffic. Confirm PostgreSQL row-index reads work. Store the - plan and operator validation with the coordinated backup. Retain the source - tree until restore and resume validation are complete. - -For rollback, stop writers again, run -`python -m asaree.storage_migration rollback --plan storage-plan.json` against -the same databases, then restore the previous image/configuration/mounts and -restart using the untouched source tree. Rollback compares exact database -values before restoring them and leaves destination files intact for diagnosis. -If new work was accepted after cutover, reconcile it or restore the complete -coordinated backup; switching to the old tree alone would lose that work. -Never downgrade only one database or roll back file bytes independently of -their database references. - -## Retiring legacy SQLite row indexes - -`ASAREE_RESULT_ROW_INDEX_DIR` is no longer a runtime setting. Its files are -derived data, not authoritative inputs. Keep the previous directory/mount and -old settings in your coordinated backup until this offline migration and -resume validation finish. Do not add its directory to a new storage relocation -plan; finish or roll back any old relocation plan with its original application -version first. New relocation plans use the namespace table above. - -With APIs, workers and MCP writers stopped, upgrade ASAREE migrations, then -run the following commands in the new image with the ASAREE database configured. -Pass `--legacy-dir` once for every previous default/override location. Use an -existing empty directory if there were no SQLite indexes but saved jobs exist. - -```sh -python -m asaree.row_index_migration inventory --legacy-dir /old/result-row-indexes --report row-inventory.json -python -m asaree.row_index_migration rebuild --legacy-dir /old/result-row-indexes --report row-rebuild.json -python -m asaree.row_index_migration verify --legacy-dir /old/result-row-indexes --report row-verified.json -``` - -Inventory reads SQLite only in read-only mode, hashes the originals, parses -them with the recorded v1 CSV rules and compares every legacy row/position and -header in bounded batches. It writes a private report, without changing files -or database rows. Rebuild creates a separate PostgreSQL index per registration, -never globally sharing by hash/owner. It verifies every row against originals -and SQLite before converting active saved job progress to dataset UUID, source -hash, parser version and count. Unprepared legacy jobs remain protected. -Missing originals, changed hashes, inconsistent rows, unsupported parser -versions and unavailable job registrations are explicit failures. Terminal job -evidence appears in diagnostics and does not block unrelated work. Unassociated -indexes, locks, partial writes, symlinks and unknown files remain untouched; -review them separately. A mismatched legacy index must be retained for diagnosis -or moved aside explicitly by the operator before rebuilding from its verified -original; migration never trusts it instead of the original. - -Review the reports and repair failures using verified backups. No historical -identity or source is inferred from a filename. Once verification passes and -you have validated a pinned attempt and resumed batch, stop writers again and -optionally run: - -```sh -python -m asaree.row_index_migration retire --legacy-dir /old/result-row-indexes --report row-retired.json -``` - -Retire re-verifies originals, PostgreSQL and SQLite, preflights file hashes and -destination conflicts, then renames verified `.sqlite` files to `.sqlite.retired`. -It never deletes them or their lock files. Retain retired files with the backup; -manual removal is a separate operator decision. On interruption inspect the -report/files before retrying. A rollback uses the coordinated pre-cutover -database/file backup and old image/settings, renaming retired files back if -needed. New source descriptors omit legacy columns, so running the old image -against newly accepted job progress is not a supported rollback. - -The index stores UTF-8 JSON bytes in BYTEA, preserving exact column order, -NULs, empty strings, leading zeros, Unicode and multiline values. Parser -`csv-utf8-sig-strict-v1` keeps the existing BOM, strict CSV, distinct nonempty -header, equal field-count and skipped-empty-record rules. Job descriptors omit -headers/values; schema cache headers containing NUL use a lossless binary -encoding decoded at the API boundary. Existing execution graph/attempt JSONB -fields still cannot represent NUL strings; this migration does not change that -pre-existing execution limit or escape/change user strings to bypass it. - -Ready indexes always check their source registration and current original. -Each new job, worker tick and process restart hashes original bytes; a job may -reuse verification only for its bounded windows in that tick while file -device/inode/size/modification/change times agree. A change invalidates the -lease. Verification runs before progress/cancellation row locks. Ready indexes -need no temporary copy; ingestion parses a verified temporary snapshot and -publishes metadata and rows in one transaction under a PostgreSQL source lock. - -## Coordinated backup and restore - -Quiesce all writers to establish a common consistency boundary. Dump **both** -ASAREE and Motoro PostgreSQL databases with `pg_dump --format=custom --no-owner`. -Record schema revisions, application/Motoro versions, storage configuration, -artifact inventory/hashes and timestamp. Copy/snapshot all managed namespaces, -explicit external bundle locations with owner permission, and the separate -Compose backup mount. Preserve permissions and relative keys. Encrypt and -restrict database dumps and plans; they contain private data. The automatic -pre-migration dump command runs only when schema changes are pending and is -not a complete backup of files or an unconditional migration backup. - -Redis is runtime state, not the authority for immutable input identity. For a -resume-capable backup, stop dequeuing and snapshot Redis at the same boundary -as the databases/files, retaining queues, working memory, cancellation and -authentication/cache state according to the deployment's Redis policy. If -Redis is intentionally discarded, reconcile pending/running jobs from -PostgreSQL and their retained workspace state before admitting new traffic; -do not claim transparent Agent resume, and do not replay a queue against -unrelated database/file snapshots. Result jobs have their existing relay path. - -Restore into an isolated deployment with services stopped: restore both -databases using the recorded versions/schema revisions, restore every managed -root and required external mount, then restore matching Redis state or perform -the explicit runtime reconciliation above. Configure all services identically, -verify file hashes and reference resolution, and test pinned execution and -workspace resume before reopening access. A storage root rename alone is not -a migration, and an experiment export is not a deployment backup. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 882442bf..b128c948 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -9,7 +9,6 @@ "version": "0.0.0", "dependencies": { "@base-ui/react": "^1.7.0", - "@codemirror/lang-json": "^6.0.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@fontsource-variable/geist": "^5.3.0", @@ -18,7 +17,6 @@ "@xyflow/react": "^12.11.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", - "jsonc-parser": "^3.3.1", "lucide-react": "^1.30.0", "react": "^19.2.8", "react-dom": "^19.2.8", @@ -574,15 +572,6 @@ "@lezer/common": "^1.1.0" } }, - "node_modules/@codemirror/lang-json": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz", - "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@lezer/json": "^1.0.0" - } - }, "node_modules/@codemirror/lang-python": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", @@ -1082,16 +1071,6 @@ "@lezer/common": "^1.3.0" } }, - "node_modules/@lezer/json": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz", - "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==", - "dependencies": { - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" - } - }, "node_modules/@lezer/lr": { "version": "1.4.10", "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz", @@ -4529,11 +4508,6 @@ "node": ">=6" } }, - "node_modules/jsonc-parser": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", - "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==" - }, "node_modules/jsonfile": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index a89d8eeb..79dcd1a4 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -12,7 +12,6 @@ }, "dependencies": { "@base-ui/react": "^1.7.0", - "@codemirror/lang-json": "^6.0.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@fontsource-variable/geist": "^5.3.0", @@ -21,7 +20,6 @@ "@xyflow/react": "^12.11.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", - "jsonc-parser": "^3.3.1", "lucide-react": "^1.30.0", "react": "^19.2.8", "react-dom": "^19.2.8", diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index c52297f9..edafbf30 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -178,7 +178,7 @@ export const packageImportsApi = { create: (requestKey: string) => request(importBase, { method: 'POST', body: { request_key: requestKey } }), upload: (id: string, file: File, signal?: AbortSignal) => request(`${importBase}/${id}/upload`, { method: 'PUT', body: file, signal }), get: (id: string) => request(`${importBase}/${id}`), - command: (id: string, command: 'confirm' | 'cancel' | 'retry') => request(`${importBase}/${id}/${command}`, { method: 'POST' }), + command: (id: string, command: 'cancel' | 'retry') => request(`${importBase}/${id}/${command}`, { method: 'POST' }), files: (id: string, offset = 0) => request<{ items: PackageFile[]; next_offset: number | null }>(`${importBase}/${id}/files?offset=${offset}`), source: (id: string, path?: string) => requestBlob(`${importBase}/${id}/source${path ? `?path=${encodeURIComponent(path)}` : ''}`), readiness: (id: string) => request(`${importBase}/${id}/readiness`), @@ -253,7 +253,7 @@ export const experimentsApi = { request<{ items: { id: string; sequence: number; iteration: number | null; phase: string; preview: string | null }[]; next_after: number | null }>(`/experiments/${id}/execution-results/attempts/${runId}/nodes/${encodeURIComponent(nodeId)}/trace${resultPageQuery(scope, { after })}`, { signal }), getExecutionStep: (id: string, runId: string, nodeId: string, stepId: string, scope: ResultsScope, offset: number, signal?: AbortSignal) => request<{ text: string; next_offset: number | null }>(`/experiments/${id}/execution-results/attempts/${runId}/nodes/${encodeURIComponent(nodeId)}/trace/${stepId}${resultPageQuery(scope, { offset })}`, { signal }), - createResultJob: (id: string, scope: ResultsScope, command: { kind: ResultJob['kind']; request_key: string; cell_id?: string; replicate_ids?: string[]; row_indices?: number[]; rerun_slot_ids?: string[]; rerun_completed?: boolean; format?: 'analysis_csv' | 'experiment_package'; include_results?: boolean }, signal?: AbortSignal) => + createResultJob: (id: string, scope: ResultsScope, command: { kind: ResultJob['kind']; request_key: string; cell_id?: string; replicate_ids?: string[]; row_indices?: number[]; rerun_slot_ids?: string[]; rerun_completed?: boolean; format?: 'analysis_csv' | 'experiment_package'; include_results?: false }, signal?: AbortSignal) => request(`/experiments/${id}/execution-results/jobs${scopeQuery(scope)}`, { method: 'POST', body: command, signal }), getResultJob: (id: string, jobId: string, signal?: AbortSignal) => request(`/experiments/${id}/execution-results/jobs/${jobId}`, { signal }), diff --git a/frontend/src/components/CreateExperimentFromFileDialog.test.tsx b/frontend/src/components/CreateExperimentFromFileDialog.test.tsx new file mode 100644 index 00000000..4ee4e5c4 --- /dev/null +++ b/frontend/src/components/CreateExperimentFromFileDialog.test.tsx @@ -0,0 +1,60 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { experimentsApi, packageImportsApi } from '@/api/client' +import type { Experiment } from '@/types/experiments' +import type { PackageImport } from '@/types/packageImports' +import { CreateExperimentFromFileDialog } from './CreateExperimentFromFileDialog' + +afterEach(() => vi.restoreAllMocks()) + +function show() { + const imported = vi.fn() + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + render() + return { imported, client } +} + +it('keeps legacy JSON definitions and creates their draft without restoring a publication', async () => { + const create = vi.spyOn(experimentsApi, 'importDefinition').mockResolvedValue({ id: 'new' } as Experiment) + const { imported } = show() + const definition = { name: 'Old experiment', graph: { nodes: [], edges: [] }, + canvas: { published: { graph: { nodes: [{ id: 'historical' }], edges: [] } } } } + const file = new File([JSON.stringify(definition)], 'experiment.json', { type: 'application/json' }) + fireEvent.change(screen.getByLabelText('Experiment definition'), { target: { files: [file] } }) + fireEvent.click(await screen.findByRole('button', { name: 'Create experiment' })) + await waitFor(() => expect(imported).toHaveBeenCalledWith('new')) + expect(create).toHaveBeenCalledWith(expect.objectContaining({ name: 'Old experiment', graph: definition.graph })) + expect(create.mock.calls[0][0]).not.toHaveProperty('published_graph') +}) + +it.each(['experiment.zip', 'experiment.ZIP'])('uploads %s and opens its draft automatically', async (filename) => { + const job = { id: 'import', status: 'completed', experiment_id: 'restored', progress: {}, preflight: {} } as PackageImport + vi.spyOn(packageImportsApi, 'create').mockResolvedValue(job) + const upload = vi.spyOn(packageImportsApi, 'upload').mockResolvedValue(job) + vi.spyOn(packageImportsApi, 'get').mockResolvedValue(job) + const command = vi.spyOn(packageImportsApi, 'command') + const { imported } = show() + const file = new File(['archive bytes'], filename, { type: 'application/zip' }) + const input = screen.getByLabelText('Experiment definition') + expect(input).toHaveAttribute('accept', 'application/json,.json,application/zip,.zip') + fireEvent.change(input, { target: { files: [file] } }) + fireEvent.click(screen.getByRole('button', { name: 'Create experiment' })) + await waitFor(() => expect(imported).toHaveBeenCalledWith('restored')) + expect(upload).toHaveBeenCalledWith('import', file) + expect(command).not.toHaveBeenCalled() + expect(screen.queryByText(/Confirm import/)).not.toBeInTheDocument() +}) + +it.each(['Hash mismatch', 'Could not import 2 resources:\n• Could not register skill "Taken skill": already registered\n• Could not register dataset "Invalid dataset": invalid target'])('reports all import errors without navigating to a partial experiment: %s', async (error) => { + const job = { id: 'import', status: 'failed', experiment_id: null, error, progress: {}, preflight: {} } as PackageImport + vi.spyOn(packageImportsApi, 'create').mockResolvedValue(job) + vi.spyOn(packageImportsApi, 'upload').mockResolvedValue(job) + vi.spyOn(packageImportsApi, 'get').mockResolvedValue(job) + const { imported } = show() + fireEvent.change(screen.getByLabelText('Experiment definition'), { target: { files: [new File(['x'], 'bad.zip')] } }) + fireEvent.click(screen.getByRole('button', { name: 'Create experiment' })) + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent(error.replace(/\s+/g, ' '))) + expect(imported).not.toHaveBeenCalled() + expect(screen.getByRole('button', { name: 'Retry import' })).toBeInTheDocument() +}) diff --git a/frontend/src/components/CreateExperimentFromFileDialog.tsx b/frontend/src/components/CreateExperimentFromFileDialog.tsx index a72f6693..f632e143 100644 --- a/frontend/src/components/CreateExperimentFromFileDialog.tsx +++ b/frontend/src/components/CreateExperimentFromFileDialog.tsx @@ -1,11 +1,12 @@ -import { useEffect, useMemo, useState } from 'react' +import { useEffect, useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Upload } from 'lucide-react' -import { ApiError, experimentsApi } from '@/api/client' +import { experimentsApi, packageImportsApi } from '@/api/client' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' +import { newRequestKey } from '@/lib/requestKey' import { FileDropInput } from '@/components/protocol/FileDropInput' import type { DesignSpec, MeasurementPlan } from '@/types/experiments' import type { ProtocolGraph } from '@/types/protocols' @@ -21,7 +22,6 @@ interface ImportedDefinition { designSpec: DesignSpec | null measurementPlan: MeasurementPlan | null graph: ProtocolGraph - publishedGraph: ProtocolGraph | null protocolDescription: string | null } @@ -44,10 +44,6 @@ function parseDefinition(text: string): ImportedDefinition { // usable, while still creating a new experiment rather than merging them. const experiment = isRecord(parsed.experiment) ? parsed.experiment : parsed const canvas = isRecord(parsed.canvas) ? parsed.canvas : parsed - const published = isRecord(canvas.published) ? canvas.published : null - const publishedGraph = published && isRecord(published.graph) && Array.isArray(published.graph.nodes) && Array.isArray(published.graph.edges) - ? published.graph as unknown as ProtocolGraph - : null const sourceName = optionalString(experiment.name)?.trim() || optionalString(parsed.name)?.trim() || 'Imported Experiment' return { @@ -63,21 +59,10 @@ function parseDefinition(text: string): ImportedDefinition { ? parsed.measurement_plan : null) as unknown as MeasurementPlan | null, graph: parsed.graph as unknown as ProtocolGraph, - publishedGraph, protocolDescription: optionalString(canvas.description) ?? optionalString(parsed.description), } } -function nextAvailableExperimentName(preferredName: string, existingNames: Iterable): string { - const preferred = preferredName.trim() || 'Imported Experiment' - const names = new Set(existingNames) - if (!names.has(preferred)) return preferred - - let number = 2 - while (names.has(`${preferred} (${number})`)) number += 1 - return `${preferred} (${number})` -} - export function CreateExperimentFromFileDialog({ open, onOpenChange, @@ -89,28 +74,31 @@ export function CreateExperimentFromFileDialog({ }) { const [definition, setDefinition] = useState(null) const [name, setName] = useState('') - const [nameEdited, setNameEdited] = useState(false) const [file, setFile] = useState(null) const [fileError, setFileError] = useState(null) const queryClient = useQueryClient() - const experimentsQuery = useQuery({ - queryKey: ['experiments', 'all-for-import'], - queryFn: () => experimentsApi.list({ includeArchived: true }), - enabled: open, - }) - const existingNames = useMemo( - () => experimentsQuery.data?.map((experiment) => experiment.name) ?? [], - [experimentsQuery.data], - ) - + const [packageId, setPackageId] = useState() + const isPackage = file?.name.toLowerCase().endsWith('.zip') ?? false + const packageJob = useQuery({ queryKey: ['package-import', packageId], enabled: !!packageId, + queryFn: () => packageImportsApi.get(packageId!), + refetchInterval: query => ['completed', 'failed', 'cancelled', 'expired'].includes(query.state.data?.status ?? '') ? false : 1000 }) useEffect(() => { - if (!definition || nameEdited || !experimentsQuery.data) return - setName(nextAvailableExperimentName(definition.sourceName, existingNames)) - }, [definition, existingNames, experimentsQuery.data, nameEdited]) + if (packageJob.data?.status !== 'completed' || !packageJob.data.experiment_id) return + void queryClient.invalidateQueries({ queryKey: ['experiments'] }) + setPackageId(undefined) + onOpenChange(false) + onImported(packageJob.data.experiment_id) + }, [packageJob.data, queryClient, onOpenChange, onImported]) const importMutation = useMutation({ - mutationFn: () => { + mutationFn: async () => { + if (isPackage && file) { + const job = await packageImportsApi.create(newRequestKey()) + await packageImportsApi.upload(job.id, file) + setPackageId(job.id) + return null + } if (!definition) throw new Error('Choose an experiment definition first.') return experimentsApi.importDefinition({ name: name.trim(), @@ -121,56 +109,47 @@ export function CreateExperimentFromFileDialog({ design_spec: definition.designSpec, measurement_plan: definition.measurementPlan, graph: definition.graph, - published_graph: definition.publishedGraph, protocol_description: definition.protocolDescription, }) }, onSuccess: (experiment) => { + if (!experiment) return queryClient.invalidateQueries({ queryKey: ['experiments'] }) onOpenChange(false) onImported(experiment.id) }, - onError: async (error) => { - // A second tab may create this same name between the lookup above and - // the atomic insert. Refresh, then offer the next free suffix instead - // of leaving the user to discover and resolve the collision manually. - if (!(error instanceof ApiError) || error.status !== 409 || !definition) return - const experiments = await queryClient.fetchQuery({ - queryKey: ['experiments', 'all-for-import'], - queryFn: () => experimentsApi.list({ includeArchived: true }), - }) - setName(nextAvailableExperimentName(definition.sourceName, experiments.map((experiment) => experiment.name))) - setNameEdited(false) - importMutation.reset() - }, + }) function reset() { importMutation.reset() setDefinition(null) setName('') - setNameEdited(false) setFile(null) setFileError(null) } function handleOpenChange(next: boolean) { - if (next) reset() + if (next && !packageId) reset() onOpenChange(next) } async function handleFileSelected(file: File | null) { if (!file) return + setPackageId(undefined) importMutation.reset() + if (file.name.toLowerCase().endsWith('.zip')) { + setDefinition(null) + setFile(file) + setFileError(null) + return + } setFileError(null) try { const parsed = parseDefinition(await file.text()) setDefinition(parsed) setFile(file) - setNameEdited(false) - // If the names request has not completed yet, the effect above fills in - // the collision-safe name as soon as it does. - setName(nextAvailableExperimentName(parsed.sourceName, existingNames)) + setName(parsed.sourceName) } catch (error) { setDefinition(null) setFile(null) @@ -179,7 +158,8 @@ export function CreateExperimentFromFileDialog({ } } - const collisionResolved = !!definition && name !== definition.sourceName + const packageActive = !!packageId && !['completed', 'failed', 'cancelled', 'expired'].includes(packageJob.data?.status ?? '') + const busy = importMutation.isPending || packageActive const mutationError = importMutation.error instanceof Error ? importMutation.error.message : null return ( @@ -188,7 +168,7 @@ export function CreateExperimentFromFileDialog({ Create experiment from file - Import the canvas and experiment definition into a new, editable experiment. Run history and artifact files are not imported. + Create an unpublished editable draft from JSON, or restore the experiment and its input assets from a package. Results are excluded.
@@ -196,10 +176,11 @@ export function CreateExperimentFromFileDialog({ void handleFileSelected(next)} - placeholder="Drop a JSON file or click to browse" + placeholder="Drop a JSON or .zip file or click to browse" />
{definition && ( @@ -210,30 +191,35 @@ export function CreateExperimentFromFileDialog({ value={name} onChange={(event) => { setName(event.target.value) - setNameEdited(true) importMutation.reset() }} onKeyDown={(event) => { if (event.key === 'Enter' && name.trim()) importMutation.mutate() }} /> - {collisionResolved && ( -

- An experiment named “{definition.sourceName}” already exists, so a new available name was suggested. You can edit it. -

- )} + )} + {packageId &&

{packageJob.data?.status === 'failed' + ? packageJob.data.error : `Creating experiment… ${packageJob.data?.progress.phase ?? 'Uploading'}`}

} + {packageJob.error &&

{packageJob.error.message}

} + {packageJob.data?.status === 'failed' && } {fileError &&

{fileError}

} {importMutation.isError &&

{mutationError ?? 'Could not import this experiment.'}

} - - diff --git a/frontend/src/components/protocol/CustomMetricDialogs.test.tsx b/frontend/src/components/protocol/CustomMetricDialogs.test.tsx index 51c2b01f..c207f486 100644 --- a/frontend/src/components/protocol/CustomMetricDialogs.test.tsx +++ b/frontend/src/components/protocol/CustomMetricDialogs.test.tsx @@ -96,7 +96,7 @@ describe('CustomMetricFlow', () => { await user.click(screen.getByRole('checkbox', { name: /^Critic \(FS\)/ })) await user.click(screen.getByRole('checkbox', { name: /^Critic \(DC\)/ })) await user.click(screen.getByRole('combobox', { name: 'Runtime measure' })) - await user.click(screen.getByRole('option', { name: /^Turns/ })) + await user.click(await screen.findByRole('option', { name: /^Turns/ })) expect(screen.getByRole('textbox', { name: 'Metric name' })).toHaveValue('Turns · Critic (DC) + Critic (FS)') await user.click(screen.getByRole('button', { name: 'Add custom metric' })) @@ -187,7 +187,7 @@ describe('CustomMetricFlow', () => { await user.click(option) await waitFor(() => expect(screen.getByRole('combobox', { name: 'MCP tool' })).toHaveTextContent('score')) await user.click(screen.getByRole('combobox', { name: 'MCP tool' })) - expect(screen.getByRole('option', { name: 'score' })).not.toHaveAttribute('aria-disabled', 'true') + expect(await screen.findByRole('option', { name: 'score' })).not.toHaveAttribute('aria-disabled', 'true') }) it('allows multiple metrics to capture the same Python Script result', async () => { diff --git a/frontend/src/components/protocol/ExperimentDefinitionDownload.tsx b/frontend/src/components/protocol/ExperimentDefinitionDownload.tsx deleted file mode 100644 index 2017dd90..00000000 --- a/frontend/src/components/protocol/ExperimentDefinitionDownload.tsx +++ /dev/null @@ -1,112 +0,0 @@ -import { useState } from 'react' -import { Download } from 'lucide-react' -import { experimentsApi, protocolsApi } from '@/api/client' -import { Button } from '@/components/ui/button' -import type { Protocol } from '@/types/protocols' - -export function ExperimentDefinitionDownload({ experimentId, protocol }: { experimentId: string; protocol: Protocol }) { - const [downloadingDefinition, setDownloadingDefinition] = useState(false) - const [definitionDownloadError, setDefinitionDownloadError] = useState(null) - async function downloadDefinition() { - if (!protocol) return - setDownloadingDefinition(true) - setDefinitionDownloadError(null) - try { - // Read fresh rather than exporting whichever React Query snapshot - // happens to be on screen. A portable definition should describe one - // coherent point in time, including the currently published canvas. - const [experiment, canvas, designRevisions] = await Promise.all([ - experimentsApi.get(experimentId), - protocolsApi.get(protocol.id), - experimentsApi.listDesignRevisions(experimentId), - ]) - const revisionIds = [...new Set([canvas.published_revision_id, experiment.locked_protocol_revision_id].filter((id): id is string => !!id))] - const revisions = await Promise.all(revisionIds.map((revisionId) => protocolsApi.getRevision(canvas.id, revisionId))) - const revisionById = new Map(revisions.map((revision) => [revision.id, revision])) - const publishedCanvas = canvas.published_revision_id ? revisionById.get(canvas.published_revision_id) ?? null : null - const lockedCanvas = experiment.locked_protocol_revision_id ? revisionById.get(experiment.locked_protocol_revision_id) ?? null : null - const payload = { - format: 'asaree.experiment-definition', - schema_version: 1, - exported_at: new Date().toISOString(), - // The existing canvas importer consumes these two top-level fields. - // Keep them as the current draft while the richer envelope below - // carries immutable published/locked snapshots and provenance. - name: experiment.name, - description: canvas.description, - graph: canvas.graph, - design_spec: experiment.design_spec, - measurement_plan: experiment.measurement_plan, - experiment: { - source_id: experiment.id, - name: experiment.name, - description: experiment.description, - hypothesis: experiment.hypothesis, - design_type: experiment.design_type, - task_brief: experiment.task_brief, - design_spec: experiment.design_spec, - measurement_plan: experiment.measurement_plan, - dataset_ids: experiment.dataset_ids, - archived_at: experiment.archived_at, - created_at: experiment.created_at, - updated_at: experiment.updated_at, - lock: experiment.locked_at ? { - locked_at: experiment.locked_at, - source_protocol_revision_id: experiment.locked_protocol_revision_id, - design_spec: experiment.locked_design_spec, - measurement_plan: experiment.locked_measurement_plan, - canvas_revision: lockedCanvas ? { - source_id: lockedCanvas.id, - revision: lockedCanvas.revision, - published_at: lockedCanvas.published_at, - graph: lockedCanvas.graph, - } : null, - } : null, - }, - canvas: { - source_protocol_id: canvas.id, - name: canvas.name, - description: canvas.description, - draft: { graph: canvas.graph, updated_at: canvas.updated_at }, - published: publishedCanvas ? { - source_id: publishedCanvas.id, - revision: publishedCanvas.revision, - published_at: publishedCanvas.published_at, - graph: publishedCanvas.graph, - } : null, - has_unpublished_changes: canvas.has_unpublished_changes, - }, - design_revisions: designRevisions.map((revision) => ({ - source_id: revision.id, - revision: revision.revision, - superseded_at: revision.superseded_at, - design_spec: revision.design_spec, - cell_count: revision.cell_count, - replicate_count: revision.replicate_count, - scored_replicate_count: revision.scored_replicate_count, - created_at: revision.created_at, - })), - portability: { - excluded: ['provider credential secrets', 'replicate results and run history', 'dataset file contents', 'knowledge bundle/document contents', 'skill file contents'], - note: 'All canvas nodes and their configuration are included. Dataset, Knowledge, and Skill nodes retain their labels and resource IDs as references; recreate or map their external artifacts before importing into another workspace.', - }, - } - const name = experiment.name || canvas.name - const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }) - const url = URL.createObjectURL(blob) - const link = document.createElement('a') - link.href = url - link.download = `${name.trim().replace(/[^a-z0-9]+/gi, '-').replace(/(^-|-$)/g, '') || 'experiment'}.json` - link.click() - URL.revokeObjectURL(url) - } catch { - setDefinitionDownloadError('Could not prepare the experiment definition. Please try again.') - } finally { - setDownloadingDefinition(false) - } - } - - return <>{definitionDownloadError &&

{definitionDownloadError}

} -} diff --git a/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx b/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx index 173a3c69..3880eaf4 100644 --- a/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx +++ b/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx @@ -1,189 +1,67 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' -import { experimentsApi, protocolsApi, packageImportsApi } from '@/api/client' -import type { Protocol, ProtocolRevision } from '@/types/protocols' +import { experimentsApi, protocolsApi } from '@/api/client' +import type { Protocol } from '@/types/protocols' import { ExperimentPackageDownload } from './ExperimentPackageDownload' -import { protocolForExperimentQueryKey, protocolGraphQueryKey } from '@/lib/protocolGraph' +import { protocolGraphQueryKey } from '@/lib/protocolGraph' afterEach(() => vi.restoreAllMocks()) - const protocol: Protocol = { id: 'p', name: 'Protocol', description: null, experiment_id: 'e', graph: { nodes: [], edges: [] }, published_revision_id: 'current', published_revision: 2, - has_unpublished_changes: true, created_at: '', updated_at: '' } -const versions: ProtocolRevision[] = [ - { id: 'old', protocol_id: 'p', revision: 1, graph: { nodes: [], edges: [] }, published_at: '2026-01-01', experiment_snapshot: null }, - { id: 'current', protocol_id: 'p', revision: 2, graph: { nodes: [], edges: [] }, published_at: '2026-01-02' }, -] - -function show(selectedVersionId?: string, draft = protocol) { - vi.spyOn(packageImportsApi, 'list').mockResolvedValue([]) + has_unpublished_changes: false, created_at: '', updated_at: '' } +function show(draft = protocol, selectedVersionId?: string, draftBusy = false) { + vi.spyOn(protocolsApi, 'get').mockResolvedValue(draft) const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) render() + selectedVersionId={selectedVersionId} draftBusy={draftBusy} />) return client } -it('warns about unpublished changes and publishes the live canvas before packaging the returned version', async () => { - const published = { ...protocol, published_revision_id: 'new', published_revision: 3, has_unpublished_changes: false } - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValueOnce(versions) - .mockResolvedValue([...versions, { ...versions[1], id: 'new', revision: 3 }]) - let finishSave!: (value: Protocol) => void - const save = vi.spyOn(protocolsApi, 'update').mockImplementation(() => new Promise(resolve => { finishSave = resolve })) - const publish = vi.spyOn(protocolsApi, 'publish').mockResolvedValue(published) - const prepared = { id: 'new-job', kind: 'export', status: 'completed', protocol_revision_id: 'new', progress: {}, error: null } as const - const prepare = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(prepared) - vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(prepared) - const client = show('old') - const graph = { nodes: [{ id: 'unsaved', type: 'agent', position: { x: 0, y: 0 }, data: { label: 'Unsaved agent' } }], edges: [] } - client.setQueryData(protocolGraphQueryKey('p'), graph) - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - expect(await screen.findByText('Experiment has unpublished changes')).toBeInTheDocument() - await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) - fireEvent.click(screen.getByRole('checkbox')) - fireEvent.click(screen.getByRole('button', { name: 'Publish & prepare package' })) - await waitFor(() => expect(save).toHaveBeenCalledWith('p', { graph })) +it.each([ + { ...protocol, has_unpublished_changes: true }, + { ...protocol, published_revision_id: null, published_revision: null }, +])('requires publication and offers no publish shortcut', async draft => { + const create = vi.spyOn(experimentsApi, 'createResultJob') + const publish = vi.spyOn(protocolsApi, 'publish') + show(draft) + fireEvent.click(screen.getByRole('button', { name: 'Download' })) + expect(await screen.findByText('Publish before exporting')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: /Publish/ })).not.toBeInTheDocument() + expect(create).not.toHaveBeenCalled() expect(publish).not.toHaveBeenCalled() - expect(prepare).not.toHaveBeenCalled() - expect(screen.getByRole('combobox')).toBeDisabled() - await act(async () => { finishSave(protocol) }) - await waitFor(() => expect(prepare).toHaveBeenCalledWith('e', - { protocol_id: 'p', protocol_revision_id: 'new' }, expect.objectContaining({ include_results: true }))) - expect(publish).toHaveBeenCalledWith('p') - expect(client.getQueryData(protocolForExperimentQueryKey('e'))).toEqual(published) - expect(screen.getByRole('combobox')).toHaveValue('new') -}) - -it('allows publication and package preparation before the first version exists', async () => { - const published = { ...protocol, has_unpublished_changes: false } - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValueOnce([]).mockResolvedValue([versions[1]]) - vi.spyOn(protocolsApi, 'publish').mockResolvedValue(published) - const prepare = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', - protocol_revision_id: 'current', progress: {}, error: 'fixture' }) - vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', - protocol_revision_id: 'current', progress: {}, error: 'fixture' }) - show(undefined, { ...protocol, published_revision_id: null, published_revision: null }) - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - expect(await screen.findByText('Experiment has not been published')).toBeInTheDocument() - expect(screen.getByRole('button', { name: 'Prepare package' })).toBeDisabled() - fireEvent.click(screen.getByRole('button', { name: 'Publish & prepare package' })) - await waitFor(() => expect(prepare).toHaveBeenCalledWith('e', - { protocol_id: 'p', protocol_revision_id: 'current' }, expect.anything())) -}) - -it('reports publication failure without preparing an older version', async () => { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - vi.spyOn(protocolsApi, 'publish').mockRejectedValue(new Error('Generate cells before publishing.')) - const prepare = vi.spyOn(experimentsApi, 'createResultJob') - show('old') - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - fireEvent.click(await screen.findByRole('button', { name: 'Publish & prepare package' })) - expect(await screen.findByRole('alert')).toHaveTextContent('Generate cells before publishing.') - expect(prepare).not.toHaveBeenCalled() - expect(screen.getByRole('combobox')).toHaveValue('old') -}) - -it('starts from the viewed historical publication and explicitly opts into results', async () => { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'pending', - protocol_revision_id: 'old', progress: {}, error: null }) - vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'completed', - protocol_revision_id: 'old', progress: { completeness: { status: 'incomplete', unresolved_count: 1, - included_dependencies: 4, destination_connections: 2, - issues: [{ kind: 'split', id: 'historical-split', reason: 'Pinned split unavailable' }] } }, - error: null, download_url: '/old-package', schema_url: '/manifest' }) - show('old') - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) - expect(screen.getByRole('combobox', { name: 'Published version' })).toHaveValue('old') - expect(screen.getByRole('checkbox')).not.toBeChecked() - fireEvent.click(screen.getByRole('checkbox')) - fireEvent.click(screen.getByRole('button', { name: 'Prepare package' })) - await waitFor(() => expect(experimentsApi.createResultJob).toHaveBeenCalledWith('e', - { protocol_id: 'p', protocol_revision_id: 'old' }, - expect.objectContaining({ kind: 'export', format: 'experiment_package', include_results: true }))) - expect(await screen.findByRole('link', { name: 'Download prepared package' })).toHaveAttribute('href', '/old-package') - expect(screen.getByRole('link', { name: 'Manifest' })).toHaveAttribute('href', '/manifest') - expect(screen.getByText('Incomplete package')).toBeInTheDocument() - expect(screen.getByText('4 included dependencies')).toBeInTheDocument() - expect(screen.getByText(/2 destination connection requirements/)).toBeInTheDocument() - expect(screen.getByText(/Pinned split unavailable/)).toBeInTheDocument() }) -it('does not offer publication for an unchanged published experiment', async () => { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - show(undefined, { ...protocol, has_unpublished_changes: false }) - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - await screen.findByRole('combobox') - expect(screen.queryByRole('button', { name: 'Publish & prepare package' })).not.toBeInTheDocument() - expect(screen.queryByText('Experiment has unpublished changes')).not.toBeInTheDocument() +it('blocks a canvas edit that has not reached autosave', async () => { + const create = vi.spyOn(experimentsApi, 'createResultJob') + const client = show() + client.setQueryData(protocolGraphQueryKey('p'), { nodes: [{ id: 'new', type: 'agent', position: { x: 0, y: 0 }, data: {} }], edges: [] }) + fireEvent.click(screen.getByRole('button', { name: 'Download' })) + expect(await screen.findByText('Publish before exporting')).toBeInTheDocument() + expect(create).not.toHaveBeenCalled() }) -it('defaults to the published version and sends results excluded', async () => { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', - protocol_revision_id: 'current', progress: {}, error: 'Package unavailable' }) - vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', - protocol_revision_id: 'current', progress: {}, error: 'Package unavailable' }) +it('exports the published version without a results option and starts the download automatically', async () => { + const job = { id: 'job', kind: 'export', status: 'completed', protocol_revision_id: 'current', + progress: {}, error: null, download_url: '/package' } as const + const create = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(job) + vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(job) + const download = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) show() - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) - expect(screen.getByRole('combobox', { name: 'Published version' })).toHaveValue('current') - fireEvent.click(screen.getByRole('button', { name: 'Prepare package' })) - await waitFor(() => expect(experimentsApi.createResultJob).toHaveBeenCalledWith('e', - { protocol_id: 'p', protocol_revision_id: 'current' }, - expect.objectContaining({ include_results: false }))) - expect(await screen.findByRole('alert')).toHaveTextContent('Package unavailable') -}) - -const completed = { id: 'job', kind: 'export', status: 'completed', protocol_revision_id: 'old', - progress: {}, error: null, download_url: '/package?token=expired', schema_url: '/manifest?token=expired' } as const - -async function prepareCompletedPackage() { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(completed) - const status = vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(completed) - show('old') - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) - fireEvent.click(screen.getByRole('button', { name: 'Prepare package' })) - await screen.findByRole('link', { name: 'Download prepared package' }) - return status -} - -it('renews stale archive and manifest URLs on activation and uses native navigation', async () => { - const status = await prepareCompletedPackage() - const navigated: string[] = [] - vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { - navigated.push(this.getAttribute('href') ?? '') - }) - status.mockResolvedValue({ ...completed, download_url: '/package?token=fresh', schema_url: '/manifest?token=fresh' }) - fireEvent.click(screen.getByRole('link', { name: 'Download prepared package' })) - await waitFor(() => expect(navigated).toEqual(['/package?token=fresh'])) - fireEvent.click(screen.getByRole('link', { name: 'Manifest' })) - await waitFor(() => expect(navigated).toEqual(['/package?token=fresh', '/manifest?token=fresh'])) - expect(status).toHaveBeenCalledTimes(3) - expect(status).toHaveBeenLastCalledWith('e', 'job', expect.any(AbortSignal)) -}) - -it('reports link renewal failure without navigating to the expired URL', async () => { - const status = await prepareCompletedPackage() - const navigate = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) - status.mockRejectedValue(new Error('Status unavailable')) - fireEvent.click(screen.getByRole('link', { name: 'Download prepared package' })) - expect(await screen.findByRole('alert')).toHaveTextContent('Could not refresh the download link. Try again.') - expect(navigate).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: 'Download' })) + await waitFor(() => expect(download).toHaveBeenCalledTimes(1)) + expect(create).toHaveBeenCalledWith('e', { protocol_id: 'p', protocol_revision_id: 'current' }, + expect.objectContaining({ kind: 'export', format: 'experiment_package' })) + expect(create.mock.calls[0][2]).not.toHaveProperty('include_results') + expect(screen.queryByRole('checkbox')).not.toBeInTheDocument() }) -it('does not navigate after the selected version changes while renewal is pending', async () => { - const status = await prepareCompletedPackage() - const navigate = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) - let finish!: (value: Awaited>) => void - status.mockImplementation(() => new Promise(resolve => { finish = resolve })) - fireEvent.click(screen.getByRole('link', { name: 'Download prepared package' })) - await waitFor(() => expect(status).toHaveBeenCalledTimes(2)) - fireEvent.change(screen.getByRole('combobox', { name: 'Published version' }), { target: { value: 'current' } }) - await act(async () => { finish({ ...completed, download_url: '/package?token=fresh' }) }) - expect(navigate).not.toHaveBeenCalled() - expect(screen.queryByRole('link', { name: 'Download prepared package' })).not.toBeInTheDocument() +it('exports an explicitly viewed historical publication while the draft has changes', async () => { + const job = { id: 'job', kind: 'export', status: 'failed', protocol_revision_id: 'old', progress: {}, error: 'Missing Skill file' } as const + const create = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(job) + vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(job) + show({ ...protocol, has_unpublished_changes: true }, 'old') + fireEvent.click(screen.getByRole('button', { name: 'Download' })) + expect(await screen.findByRole('alert')).toHaveTextContent('Missing Skill file') + expect(create).toHaveBeenCalledWith('e', { protocol_id: 'p', protocol_revision_id: 'old' }, expect.anything()) }) diff --git a/frontend/src/components/protocol/ExperimentPackageDownload.tsx b/frontend/src/components/protocol/ExperimentPackageDownload.tsx index e570597d..64427ccb 100644 --- a/frontend/src/components/protocol/ExperimentPackageDownload.tsx +++ b/frontend/src/components/protocol/ExperimentPackageDownload.tsx @@ -1,5 +1,5 @@ -import { useEffect, useRef, useState, type MouseEvent } from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useEffect, useRef, useState, type ReactNode } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' import type { Edge, Node } from '@xyflow/react' import { Download } from 'lucide-react' import { experimentsApi, protocolsApi } from '@/api/client' @@ -7,150 +7,72 @@ import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { jobActive, useResultJob } from '@/lib/resultJobs' import { newRequestKey } from '@/lib/requestKey' -import { protocolForExperimentQueryKey, protocolGraphQueryKey, toPersistedGraph } from '@/lib/protocolGraph' -import { executionKeys } from '@/lib/executionQueries' +import { protocolGraphQueryKey, toPersistedGraph } from '@/lib/protocolGraph' import type { Protocol } from '@/types/protocols' -import { ExperimentPackageImport } from './ExperimentPackageImport' -export function ExperimentPackageDownload({ experimentId, protocol, selectedVersionId }: { - experimentId: string; protocol: Protocol; selectedVersionId?: string +export function ExperimentPackageDownload({ experimentId, protocol, selectedVersionId, draftBusy = false, renderTrigger }: { + experimentId: string + protocol: Pick & Partial> + selectedVersionId?: string; draftBusy?: boolean + renderTrigger?: (download: () => void, busy: boolean) => ReactNode }) { + const [publicationWarning, setPublicationWarning] = useState(false) const client = useQueryClient() - const [open, setOpen] = useState(false) - const [versionId, setVersionId] = useState('') - const [includeResults, setIncludeResults] = useState(false) const [jobId, setJobId] = useState() - const [linkPending, setLinkPending] = useState(false) - const [linkError, setLinkError] = useState() - const linkScope = useRef('') - linkScope.current = JSON.stringify({ experimentId, protocolId: protocol.id, versionId, includeResults, jobId, open }) - const versions = useQuery({ queryKey: ['protocols', protocol.id, 'revisions'], - queryFn: () => protocolsApi.listRevisions(protocol.id), enabled: open }) + const [revisionId, setRevisionId] = useState() + const [requestScope, setRequestScope] = useState() + const downloaded = useRef(null) + const scope = JSON.stringify({ experimentId, protocolId: protocol.id, version: selectedVersionId || 'draft' }) const job = useResultJob(experimentId, jobId) - useEffect(() => { - if (open && !versionId && versions.data?.length) setVersionId(versions.data[0].id) - }, [open, versionId, versions.data]) - const create = useMutation({ - mutationFn: (revisionId: string) => experimentsApi.createResultJob(experimentId, - { protocol_id: protocol.id, protocol_revision_id: revisionId }, - { kind: 'export', request_key: newRequestKey(), format: 'experiment_package', include_results: includeResults }), - onSuccess: result => setJobId(result.id), - }) - const publish = useMutation({ + const prepare = useMutation({ mutationFn: async () => { + const fresh = await protocolsApi.get(protocol.id) const live = client.getQueryData<{ nodes: Node[]; edges: Edge[] }>(protocolGraphQueryKey(protocol.id)) - if (live) await protocolsApi.update(protocol.id, { graph: toPersistedGraph(live.nodes, live.edges) }) - const published = await protocolsApi.publish(protocol.id) - if (!published.published_revision_id) throw new Error('Publication did not return a downloadable version.') - return published - }, - onSuccess: async published => { - client.setQueryData(protocolForExperimentQueryKey(experimentId), published) - void client.invalidateQueries({ queryKey: ['experiments', experimentId] }) - void client.invalidateQueries({ queryKey: executionKeys.root(experimentId) }) - setVersionId(published.published_revision_id!) - setJobId(undefined) - await client.invalidateQueries({ queryKey: ['protocols', protocol.id, 'revisions'] }) - create.mutate(published.published_revision_id!) + const saved = toPersistedGraph(fresh.graph.nodes as Node[], fresh.graph.edges as Edge[]) + const unsaved = live && JSON.stringify(toPersistedGraph(live.nodes, live.edges)) !== JSON.stringify(saved) + if (!selectedVersionId && (draftBusy || unsaved || fresh.has_unpublished_changes || !fresh.published_revision_id)) { + setPublicationWarning(true) + return null + } + const version = selectedVersionId || fresh.published_revision_id! + setRevisionId(version) + setRequestScope(scope) + return experimentsApi.createResultJob(experimentId, + { protocol_id: protocol.id, protocol_revision_id: version }, + { kind: 'export', request_key: newRequestKey(), format: 'experiment_package' }) }, + onSuccess: result => setJobId(result?.id), }) - const needsPublish = !protocol.published_revision_id || protocol.has_unpublished_changes - const busy = publish.isPending || create.isPending || jobActive(job.data) || (!!jobId && !job.data && !job.error) - const error = linkError ?? publish.error?.message ?? create.error?.message ?? job.error?.message ?? job.data?.error - async function download(event: MouseEvent, metadata: boolean) { - event.preventDefault() - if (linkPending || !jobId) return - const requestedJob = jobId - const requestedScope = linkScope.current - setLinkError(undefined) - setLinkPending(true) - try { - const fresh = (await job.refetch({ throwOnError: true })).data - if (linkScope.current !== requestedScope) return - const url = metadata ? fresh?.schema_url : fresh?.download_url - if (fresh?.id !== requestedJob || fresh.protocol_revision_id !== versionId || fresh.status !== 'completed' || !url) { - setLinkError('This package is no longer available. Prepare a new download.') - return - } - // Keep the server's native Content-Disposition download; only status is - // fetched through the authenticated API, never the archive as a Blob. - const link = document.createElement('a') - link.href = url - link.click() - } catch { - if (linkScope.current === requestedScope) setLinkError('Could not refresh the download link. Try again.') - } finally { - setLinkPending(false) - } + useEffect(() => { + const ready = job.data + if (ready?.status !== 'completed' || !ready.download_url || requestScope !== scope + || ready.protocol_revision_id !== revisionId || downloaded.current === ready.id) return + downloaded.current = ready.id + const link = document.createElement('a') + link.href = ready.download_url + link.click() + }, [job.data, revisionId, scope, requestScope]) + const busy = prepare.isPending || jobActive(job.data) || (!!jobId && !job.data && !job.error) + const error = prepare.error?.message || job.error?.message || job.data?.error + function requestDownload() { + prepare.reset() + setJobId(undefined) + if (!selectedVersionId && (draftBusy || protocol.has_unpublished_changes || protocol.published_revision_id === null)) { + setPublicationWarning(true) + } else prepare.mutate() } return <> - - - - Download published experiment - - - -

Includes published configuration and pinned dataset inputs. Reusable skills and knowledge are captured at download time. The manifest identifies missing dependencies and historical evidence.

-

Credentials are excluded. Prepared downloads expire after 24 hours.

- {versions.isError &&

Could not load published versions.

} - {versions.data?.length === 0 &&

Publish the experiment to create its first downloadable version.

} - {needsPublish &&
-

{protocol.published_revision_id ? 'Experiment has unpublished changes' : 'Experiment has not been published'}

-

Publish the draft to include its current canvas, design settings, and dataset inputs in a new package. Preparing a selected published version includes only that version’s recorded configuration and inputs.

-
} - {error &&

{error}

} - {job.data?.status === 'expired' &&

This package expired. Prepare another download.

} - {job.data?.status === 'cancelled' &&

Package preparation cancelled.

} - {busy &&

Preparing package · {job.data?.progress.bytes?.toLocaleString() ?? 0} bytes

} - {linkPending &&

Refreshing download link…

} - {job.data?.status === 'completed' && job.data.progress.completeness &&
-

{job.data.progress.completeness.status === 'incomplete' ? 'Incomplete package' : 'Package content complete'}

-

{job.data.progress.completeness.included_dependencies} included dependencies

-

{job.data.progress.completeness.destination_connections} destination connection requirements · credentials excluded

-

{job.data.progress.completeness.unresolved_count} missing or unresolved dependencies

- {job.data.progress.completeness.issues.map((issue, index) =>

{issue.kind} {issue.id}: {issue.reason}

)} -
} - {job.data?.status === 'completed' && job.data.progress.sha256 &&

SHA-256: {job.data.progress.sha256}

} -
- {needsPublish && } - - {busy && jobId && } - {job.data?.status === 'completed' && <> - { void download(event, false) }}>Download prepared package - { void download(event, true) }}>Manifest - } -
+ {renderTrigger ? renderTrigger(requestDownload, busy) + : } + {busy && Preparing experiment and input assets…} + {error &&

{error}

} + + + Publish before exporting +

Publish your current canvas and design changes using Publish experiment, then download the package.

+

The package includes all required input assets. Results and execution history are excluded.

+
diff --git a/frontend/src/components/protocol/ExperimentPackageImport.test.tsx b/frontend/src/components/protocol/ExperimentPackageImport.test.tsx deleted file mode 100644 index 3a384a13..00000000 --- a/frontend/src/components/protocol/ExperimentPackageImport.test.tsx +++ /dev/null @@ -1,194 +0,0 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' -import { MemoryRouter } from 'react-router-dom' -import { afterAll, afterEach, beforeAll, expect, it, vi } from 'vitest' -import { packageImportsApi } from '@/api/client' -import type { PackageImport } from '@/types/packageImports' -import { ExperimentPackageImport } from './ExperimentPackageImport' - -afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) - -// CodeMirror measures text ranges; jsdom provides no layout implementation. -const rangeRect = Object.getOwnPropertyDescriptor(Range.prototype, 'getBoundingClientRect') -const rangeRects = Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects') -beforeAll(() => { - Object.defineProperties(Range.prototype, { - getBoundingClientRect: { configurable: true, value: () => new DOMRect() }, - getClientRects: { configurable: true, value: () => [] }, - }) -}) -afterAll(() => { - for (const [name, descriptor] of [['getBoundingClientRect', rangeRect], ['getClientRects', rangeRects]] as const) { - if (descriptor) Object.defineProperty(Range.prototype, name, descriptor) - else Reflect.deleteProperty(Range.prototype, name) - } -}) - -const ready: PackageImport = { id: 'request', status: 'awaiting_confirmation', sha256: 'source-hash', - experiment_id: null, configured_at: null, created_at: '', expires_at: '', error: null, - progress: { phase: 'preflight_ready' }, preflight: { manifest: { schema_version: 2, - experiment_id: 'source', publication: { id: 'publication', version: 7, published_at: '' }, results_included: true }, - categories: { inputs: 4, results: 12 }, unresolved_count: 1, external_requirements: 2, - warnings: ['Configure local credentials before publication.'], - diagnostics: [{ id: 'missing', kind: 'dataset_file', status: 'missing', reason: 'Pinned file unavailable' }] } } - -function show(items: PackageImport[] = []) { - vi.spyOn(packageImportsApi, 'list').mockResolvedValue(items) - vi.spyOn(packageImportsApi, 'get').mockResolvedValue(ready) - vi.spyOn(packageImportsApi, 'files').mockResolvedValue({ items: [], next_offset: null }) - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) - render() -} - -it('uploads for inspection and requires an explicit confirmation after showing requirements', async () => { - vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) }) - const create = vi.spyOn(packageImportsApi, 'create').mockResolvedValue({ ...ready, status: 'uploading', preflight: {} }) - const upload = vi.spyOn(packageImportsApi, 'upload').mockResolvedValue({ ...ready, status: 'validating' }) - const command = vi.spyOn(packageImportsApi, 'command').mockResolvedValue({ ...ready, status: 'queued' }) - show() - const file = new File(['archive bytes'], 'package.tar.gz', { type: 'application/gzip' }) - const input = screen.getByLabelText('Experiment package') - expect(input.accept.split(',')).toEqual(expect.arrayContaining(['.gz', 'application/gzip'])) - fireEvent.change(input, { target: { files: [file] } }) - await waitFor(() => expect(upload).toHaveBeenCalledWith('request', file, expect.any(AbortSignal))) - expect(create).toHaveBeenCalledOnce() - expect(command).not.toHaveBeenCalled() - expect(await screen.findByText(/Source version 7/)).toBeInTheDocument() - expect(screen.getByText(/Pinned file unavailable/)).toBeInTheDocument() - expect(screen.getByText(/Configure local credentials/)).toBeInTheDocument() - fireEvent.click(screen.getByRole('button', { name: 'Confirm import into a new experiment' })) - await waitFor(() => expect(command).toHaveBeenCalledWith('request', 'confirm')) -}) - -it('resumes persisted requests and allows cancellation before activation', async () => { - const command = vi.spyOn(packageImportsApi, 'command').mockResolvedValue({ ...ready, status: 'cancelled' }) - show([ready]) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByRole('button', { name: 'Cancel import' })) - await waitFor(() => expect(command).toHaveBeenCalledWith('request', 'cancel')) -}) - -it('drops a package into the existing inspection flow without confirming import', async () => { - const create = vi.spyOn(packageImportsApi, 'create').mockResolvedValue({ ...ready, status: 'uploading', preflight: {} }) - const upload = vi.spyOn(packageImportsApi, 'upload').mockResolvedValue({ ...ready, status: 'validating' }) - const command = vi.spyOn(packageImportsApi, 'command') - show() - const file = new File(['archive bytes'], 'experiment.tgz', { type: 'application/gzip' }) - const target = screen.getByText('Drop a .tar.gz or .tgz package or click to browse').closest('label')! - fireEvent.dragOver(target) - fireEvent.drop(target, { dataTransfer: { files: [file] } }) - await waitFor(() => expect(upload).toHaveBeenCalledWith('request', file, expect.any(AbortSignal))) - expect(create).toHaveBeenCalledOnce() - expect(command).not.toHaveBeenCalled() - expect(screen.getByText('experiment.tgz')).toBeInTheDocument() - expect(await screen.findByText(/Source version 7/)).toBeInTheDocument() -}) - -it('prevents additional drops and file selection while uploading', async () => { - const create = vi.spyOn(packageImportsApi, 'create').mockResolvedValue({ ...ready, status: 'uploading', preflight: {} }) - const upload = vi.spyOn(packageImportsApi, 'upload').mockReturnValue(new Promise(() => {})) - show() - const input = screen.getByLabelText('Experiment package') - const target = input.closest('label')! - const file = new File(['archive bytes'], 'experiment.tar.gz') - fireEvent.drop(target, { dataTransfer: { files: [file] } }) - await waitFor(() => expect(upload).toHaveBeenCalledOnce()) - expect(input).toBeDisabled() - fireEvent.drop(target, { dataTransfer: { files: [new File(['other'], 'other.tgz')] } }) - expect(create).toHaveBeenCalledOnce() - expect(upload).toHaveBeenCalledOnce() -}) - -it('shows readiness and a direct draft link without an acknowledgement gate', async () => { - const complete = { ...ready, status: 'completed', experiment_id: 'local-experiment' } - vi.spyOn(packageImportsApi, 'readiness').mockResolvedValue({ ready: true, issues: [], mcp: [], providers: [] }) - show([complete]) - vi.mocked(packageImportsApi.get).mockResolvedValue(complete) - fireEvent.click(await screen.findByRole('button', { name: /request.*Imported/ })) - expect(await screen.findByText('Ready to publish')).toBeInTheDocument() - expect(screen.getByRole('link', { name: 'Open editable draft' })).toHaveAttribute('href', '/experiments/local-experiment/protocol') - expect(screen.queryByRole('checkbox')).not.toBeInTheDocument() -}) - -it('inspects immutable observation evidence without coercing null or unavailable values', async () => { - show([ready]) - const path = 'results/attempts/source-attempt/attempt_result.json' - vi.mocked(packageImportsApi.files).mockResolvedValue({ items: [{ path, sha256: 'exact-hash', bytes: 200, - source_id: 'source-attempt', provenance: 'recorded_attempt' }], next_offset: null }) - const source = '{"observations":[{"status":"measured","value":null},{"status":"unavailable"}]}' - vi.spyOn(packageImportsApi, 'source').mockResolvedValue(new Blob([source])) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByText('Inspect source files and historical evidence')) - fireEvent.click(await screen.findByRole('button', { name: 'Inspect JSON' })) - const viewer = await screen.findByRole('textbox', { name: 'JSON source' }) - expect(viewer).toHaveAttribute('aria-readonly', 'true') - expect(viewer).toHaveTextContent('"status": "measured"') - expect(viewer).toHaveTextContent('"value": null') - expect(viewer).toHaveTextContent('"status": "unavailable"') - fireEvent.click(screen.getByRole('button', { name: 'Original' })) - await waitFor(() => expect(viewer.textContent).toBe(source)) - expect(packageImportsApi.source).toHaveBeenCalledWith('request', path) -}) - -it('opens JSON inspection immediately while the file request is pending', async () => { - show([ready]) - const path = 'publication/settings.json' - vi.mocked(packageImportsApi.files).mockResolvedValue({ items: [{ path, sha256: 'hash', bytes: 100, - source_id: 'publication', provenance: 'publication_pinned' }], next_offset: null }) - let finish!: (value: Response) => void - const fetchFile = vi.spyOn(globalThis, 'fetch').mockImplementation(() => new Promise(resolve => { finish = resolve })) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByText('Inspect source files and historical evidence')) - fireEvent.click(await screen.findByRole('button', { name: 'Inspect JSON' })) - const dialog = await screen.findByRole('dialog', { name: 'Inspect JSON' }) - expect(within(dialog).getByRole('status')).toHaveTextContent('Loading JSON') - expect(within(dialog).getByText(path)).toBeInTheDocument() - await waitFor(() => expect(fetchFile).toHaveBeenCalledWith( - '/api/experiment-package-imports/request/source?path=publication%2Fsettings.json', expect.anything())) - const source = '{"exact_integer":9007199254740993,"value":null}' - await act(async () => { finish(new Response(source, { headers: { 'Content-Type': 'application/octet-stream' } })) }) - expect(await within(dialog).findByRole('textbox', { name: 'JSON source' })).toHaveTextContent('9007199254740993') -}) - -it('shows source-loading errors in the inspector and allows retry', async () => { - show([ready]) - const path = 'publication/settings.json' - vi.mocked(packageImportsApi.files).mockResolvedValue({ items: [{ path, sha256: 'hash', bytes: 100, - source_id: 'publication', provenance: 'publication_pinned' }], next_offset: null }) - const source = vi.spyOn(packageImportsApi, 'source').mockRejectedValueOnce(new Error('Source file unavailable')) - .mockResolvedValue(new Blob(['{"restored":true}'])) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByText('Inspect source files and historical evidence')) - fireEvent.click(await screen.findByRole('button', { name: 'Inspect JSON' })) - const dialog = await screen.findByRole('dialog', { name: 'Inspect JSON' }) - expect(await within(dialog).findByRole('alert')).toHaveTextContent('Source file unavailable') - fireEvent.click(within(dialog).getByRole('button', { name: 'Retry loading file' })) - expect(await within(dialog).findByRole('textbox', { name: 'JSON source' })).toHaveTextContent('"restored": true') - expect(source).toHaveBeenCalledTimes(2) - expect(within(dialog).queryByRole('alert')).not.toBeInTheDocument() -}) - -it('keeps a late response from reopening a closed inspector or replacing a newer file', async () => { - show([ready]) - vi.mocked(packageImportsApi.files).mockResolvedValue({ items: ['first.json', 'second.json'].map(path => ({ - path, sha256: 'hash', bytes: 100, source_id: path, provenance: 'publication_pinned', - })), next_offset: null }) - let finishFirst!: (value: Blob) => void - vi.spyOn(packageImportsApi, 'source').mockImplementationOnce(() => new Promise(resolve => { finishFirst = resolve })) - .mockResolvedValue(new Blob(['{"file":"second"}'])) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByText('Inspect source files and historical evidence')) - fireEvent.click((await screen.findAllByRole('button', { name: 'Inspect JSON' }))[0]) - const first = await screen.findByRole('dialog', { name: 'Inspect JSON' }) - fireEvent.click(within(first).getByRole('button', { name: 'Close source inspection' })) - await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) - fireEvent.click(screen.getAllByRole('button', { name: 'Inspect JSON' })[1]) - const second = await screen.findByRole('dialog', { name: 'Inspect JSON' }) - const viewer = await within(second).findByRole('textbox', { name: 'JSON source' }) - expect(viewer).toHaveTextContent('"file": "second"') - await act(async () => { finishFirst(new Blob(['{"file":"first"}'])) }) - expect(within(second).getByText('second.json')).toBeInTheDocument() - expect(viewer).toHaveTextContent('"file": "second"') - fireEvent.click(within(second).getByRole('button', { name: 'Close source inspection' })) - await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) -}) diff --git a/frontend/src/components/protocol/ExperimentPackageImport.tsx b/frontend/src/components/protocol/ExperimentPackageImport.tsx deleted file mode 100644 index f34f5035..00000000 --- a/frontend/src/components/protocol/ExperimentPackageImport.tsx +++ /dev/null @@ -1,278 +0,0 @@ -import { useId, useRef, useState } from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { Link } from 'react-router-dom' -import { ChevronDown, Download, File, FileJson, Search } from 'lucide-react' -import { packageImportsApi } from '@/api/client' -import { Button } from '@/components/ui/button' -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' -import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' -import { Badge } from '@/components/ui/badge' -import type { PackageImport } from '@/types/packageImports' -import { newRequestKey } from '@/lib/requestKey' -import { FileDropInput } from './FileDropInput' -import { JsonSourceViewer } from './JsonSourceViewer' -import { ImportedExperimentSetup } from './ImportedExperimentSetup' - -const provenanceLabels: Record = { - publication_pinned: 'Published snapshot', - captured_at_download: 'Captured at export', - recorded_attempt: 'Recorded attempt', - retained_attempt_artifact: 'Retained artifact', - 'legacy.unknown': 'Unknown historical source', -} - -function fileSize(bytes: number): string { - if (bytes < 1024) return `${bytes.toLocaleString()} B` - const unit = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), 3) - return `${(bytes / 1024 ** unit).toLocaleString(undefined, { maximumFractionDigits: 1 })} ${['B', 'KiB', 'MiB', 'GiB'][unit]}` -} - -const categoryLabels: Record = { - inputs: 'Dataset files and metadata', - resources: 'Scripts, skills, and knowledge', - publication: 'Published configuration', - requirements: 'Local requirements', - results: 'Historical results', - design: 'Experimental design', - sources: 'Imported source evidence', - 'dependencies.jsonl': 'Dependency inventory', - 'experiment-metadata.json': 'Experiment details', -} - -const statusLabels: Record = { - uploading: 'Uploading package', - validating: 'Checking package', - awaiting_confirmation: 'Ready to review', - queued: 'Import queued', - activating: 'Creating experiment', - completed: 'Imported', - failed: 'Import failed', - cancelled: 'Cancelled', - expired: 'Expired', -} - -function PackageSummary({ current }: { current: PackageImport }) { - const { manifest, categories, unresolved_count: unresolved, external_requirements: external } = current.preflight - if (!manifest) return null - const contents = Object.entries(categories ?? {}) - return
-
-

Package summary

-

{current.status === 'awaiting_confirmation' - ? 'Review the contents, then confirm to create a new editable experiment.' - : 'Contents of the uploaded source package.'}

-
-
-
Published version
Source version {manifest.publication.version}
- {manifest.publication.name &&
{manifest.publication.name}
}
-
Historical results
{manifest.results_included ? 'Included' : 'Not included'}
-
- {contents.length > 0 &&
- - - - {contents.map(([name, count]) => - - - )} - -
Included package files by category
ContentsFiles
{categoryLabels[name] ?? name}{count.toLocaleString()}
Total files{contents.reduce((total, [, count]) => total + count, 0).toLocaleString()}
-
} -
- {unresolved !== undefined &&

0 ? 'text-amber-400' : 'text-muted-foreground'}>{unresolved > 0 - ? `${unresolved.toLocaleString()} unresolved ${unresolved === 1 ? 'dependency needs' : 'dependencies need'} attention` - : 'No unresolved dependencies reported'}

} - {external !== undefined &&

{external.toLocaleString()} external {external === 1 ? 'requirement' : 'requirements'}

} -

After import, configure local connections and resolve missing dependencies in the draft before publishing. Import does not run scripts or tools.

-
-
Package identifiers and format -
Package schema
{manifest.schema_version}
-
Source publication
{manifest.publication.id}
-
Archive SHA-256
{current.sha256 ?? 'Unavailable'}
-
-
-} - -/** Persistent imports can be resumed after navigation or a browser restart. */ -export function ExperimentPackageImport({ experimentId }: { experimentId?: string }) { - const client = useQueryClient() - const fileInputId = useId() - const [file, setFile] = useState(null) - const [selected, setSelected] = useState(null) - const [offset, setOffset] = useState(0) - const [error, setError] = useState(null) - const [uploading, setUploading] = useState(false) - const [preview, setPreview] = useState<{ importId: string; path: string; text?: string; error?: string; loading: boolean } | null>(null) - const previewRequest = useRef(0) - const selectedRef = useRef(selected) - selectedRef.current = selected - const uploadController = useRef(null) - const list = useQuery({ queryKey: ['package-imports', experimentId], queryFn: () => packageImportsApi.list(experimentId), - refetchInterval: (query) => query.state.data?.some((item) => ['uploading', 'validating', 'queued', 'activating'].includes(item.status)) ? 3000 : false }) - const job = useQuery({ queryKey: ['package-import', selected], enabled: selected !== null, - queryFn: () => packageImportsApi.get(selected!), - refetchInterval: (query) => !query.state.data || ['uploading', 'validating', 'queued', 'activating'].includes(query.state.data.status) ? 1000 : false }) - const current = job.data - const files = useQuery({ queryKey: ['package-import-files', selected, offset], - enabled: !!current?.preflight.manifest && !['expired', 'cancelled'].includes(current.status), - queryFn: () => packageImportsApi.files(selected!, offset) }) - const action = useMutation({ - mutationFn: async ({ id, command }: { id: string; command: 'confirm' | 'cancel' | 'retry' }) => packageImportsApi.command(id, command), - onSuccess: () => { - void client.invalidateQueries({ queryKey: ['package-import'] }) - void client.invalidateQueries({ queryKey: ['package-imports'] }) - void client.invalidateQueries({ queryKey: ['experiments'] }) - }, - onError: (cause) => setError(String(cause)), - }) - const upload = async (file: File) => { - setError(null) - setUploading(true) - try { - const created = current && ['uploading', 'failed'].includes(current.status) && !current.preflight.manifest - ? current : await packageImportsApi.create(newRequestKey()) - setSelected(created.id) - setOffset(0) - const controller = new AbortController() - uploadController.current = controller - await packageImportsApi.upload(created.id, file, controller.signal) - void client.invalidateQueries({ queryKey: ['package-imports'] }) - } catch (cause) { - if (!(cause instanceof DOMException && cause.name === 'AbortError')) setError(String(cause)) - } - finally { uploadController.current = null; setUploading(false) } - } - const download = async (id: string, path: string) => { - try { - const fresh = await packageImportsApi.get(id) - if (!fresh.source_url) throw new Error('Source download unavailable during activation or after expiry.') - const anchor = document.createElement('a') - anchor.href = `${fresh.source_url}&path=${encodeURIComponent(path)}` - anchor.click() - } - catch (cause) { setError(String(cause)) } - } - const inspectFile = async (id: string, path: string) => { - const request = ++previewRequest.current - setPreview({ importId: id, path, loading: true }) - try { - const blob = await packageImportsApi.source(id, path) - const text = await blob.text() - if (selectedRef.current === id && previewRequest.current === request) setPreview({ importId: id, path, text, loading: false }) - } catch (cause) { - if (selectedRef.current === id && previewRequest.current === request) { - setPreview({ importId: id, path, error: `Could not load this source file. ${String(cause)}`, loading: false }) - } - } - } - const closePreview = () => { - previewRequest.current += 1 - setPreview(null) - } - const select = (item: PackageImport) => { - setSelected(item.id); setOffset(0); setError(null); closePreview() - } - - return - {experimentId ? 'Imported source evidence' : 'Import experiment package'} - - {!experimentId && <> -

Upload a published experiment package. Review its contents before creating a new editable experiment. Import never runs packaged scripts or tools.

- { - if (picked) { setFile(picked); void upload(picked) } - }} /> - {current?.status === 'uploading' &&

To retry an interrupted upload, choose the package file again.

} - } -
{list.data?.map((item) => )}
- {(error || job.error || list.error) &&

{error ?? String(job.error ?? list.error)}

} - {current &&
-

{statusLabels[current.status] ?? current.status}{current.progress.scanned !== undefined ? ` · ${current.progress.scanned.toLocaleString()} processed` : ''}

- {current.error &&

{current.error}

} - {current.preflight.manifest && <> - - {current.preflight.warnings?.map((warning) =>

{warning}

)} - {current.preflight.compatibility?.map((issue) =>

{issue}

)} - {current.preflight.diagnostics?.map((item, index) =>

{item.kind} {item.id}: {item.reason ?? item.status}

)} -
- - Inspect source files and historical evidence - -

Browse original package files. Inspect JSON in a read-only viewer or download any file. Hover over a filename to see its SHA-256.

-
- - - - - - - - - - {files.isPending && } - {files.isError && } - {files.data?.items.length === 0 && } - {files.data?.items.map((file) => { - const isJson = file.path.endsWith('.json') - const FileIcon = isJson ? FileJson : File - const separator = file.path.lastIndexOf('/') - return - - - - - - })} - -
Source files and historical evidence
FileSizeSourceActions
Loading source files…

Could not load source files. {String(files.error)}

No source files listed.
-
{fileSize(file.bytes)}{provenanceLabels[file.provenance] ?? file.provenance.replaceAll('_', ' ')}
- {isJson && file.bytes <= 16 * 1024 * 1024 && } - -
-
-
-

{files.data?.items.length ? `Showing files ${(offset + 1).toLocaleString()}–${(offset + files.data.items.length).toLocaleString()}` : 'Source file inventory'}

-
-
-
-
- } -
- {current.status === 'awaiting_confirmation' && } - {current.status === 'failed' && } - {!['completed', 'expired', 'cancelled'].includes(current.status) && } - {current.experiment_id && } -
- {current.status === 'completed' && current.experiment_id && !experimentId && } -
} -
- { if (!open) closePreview() }}> - - - Inspect JSON - {preview?.path} - -

Read-only source file from the uploaded package.

- {preview?.loading &&

Loading JSON…

} - {preview?.error &&
-

{preview.error}

- -
} - {preview?.text !== undefined && } - -
-
-
-} diff --git a/frontend/src/components/protocol/ImportedExperimentSetup.test.tsx b/frontend/src/components/protocol/ImportedExperimentSetup.test.tsx deleted file mode 100644 index 7a8c9ec5..00000000 --- a/frontend/src/components/protocol/ImportedExperimentSetup.test.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { MemoryRouter } from 'react-router-dom' -import { afterEach, expect, it, vi } from 'vitest' -import { packageImportsApi } from '@/api/client' -import { ImportedExperimentSetup } from './ImportedExperimentSetup' - -afterEach(() => { cleanup(); vi.restoreAllMocks() }) - -it('keeps incomplete drafts accessible and requires explicit connection selection', async () => { - const options = { ready: false, issues: [{ node_id: 'tool', message: 'Choose a local connection' }], - providers: [{ provider: 'openai', id: 'saved-provider', selected: false }], - mcp: [{ source_id: 'source', name: 'Custom server', selected_id: null, - candidates: [{ id: 'one', name: 'Connection one' }, { id: 'two', name: 'Connection two' }] }] } - vi.spyOn(packageImportsApi, 'readiness').mockResolvedValue(options) - const select = vi.spyOn(packageImportsApi, 'selectConnection').mockResolvedValue(options) - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) - const onSelectNode = vi.fn() - render( - - ) - expect(await screen.findByText('Setup needed')).toBeInTheDocument() - expect(select).not.toHaveBeenCalled() - expect(screen.getByText(/Multiple compatible connections/)).toBeInTheDocument() - fireEvent.click(screen.getByRole('button', { name: 'Choose a local connection' })) - expect(onSelectNode).toHaveBeenCalledWith('tool') - fireEvent.change(screen.getByRole('combobox'), { target: { value: 'two' } }) - await waitFor(() => expect(select).toHaveBeenCalledWith('import', 'mcp', 'source', 'two')) - await waitFor(() => expect(screen.getByRole('button', { name: 'Use my saved connection' })).toBeEnabled()) - fireEvent.click(screen.getByRole('button', { name: 'Use my saved connection' })) - await waitFor(() => expect(select).toHaveBeenCalledWith('import', 'provider', 'openai', 'saved-provider')) - expect(screen.queryByRole('checkbox')).not.toBeInTheDocument() -}) diff --git a/frontend/src/components/protocol/ImportedExperimentSetup.tsx b/frontend/src/components/protocol/ImportedExperimentSetup.tsx deleted file mode 100644 index fda556c2..00000000 --- a/frontend/src/components/protocol/ImportedExperimentSetup.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { Link } from 'react-router-dom' -import { packageImportsApi, protocolsApi } from '@/api/client' -import { protocolForExperimentQueryKey, protocolGraphQueryKey, toPersistedGraph } from '@/lib/protocolGraph' -import type { Edge, Node } from '@xyflow/react' -import type { Protocol, ProtocolGraph } from '@/types/protocols' -import { Button } from '@/components/ui/button' - -export function ImportedExperimentSetup({ importId, experimentId, onSelectNode, protocolId, onGraphChange }: { - importId: string; experimentId: string; onSelectNode?: (id: string) => void - protocolId?: string; onGraphChange?: (graph: ProtocolGraph) => void -}) { - const client = useQueryClient() - const effectiveProtocolId = protocolId ?? client.getQueryData(protocolForExperimentQueryKey(experimentId))?.id - const setup = useQuery({ queryKey: ['import-readiness', importId], queryFn: () => packageImportsApi.readiness(importId) }) - const selection = useMutation({ - mutationFn: async ({ kind, source, destination }: { kind: 'mcp' | 'provider'; source: string; destination: string }) => { - if (effectiveProtocolId) { - const live = client.getQueryData<{ nodes: Node[]; edges: Edge[] }>(protocolGraphQueryKey(effectiveProtocolId)) - if (live) await protocolsApi.update(effectiveProtocolId, { graph: toPersistedGraph(live.nodes, live.edges) }) - } - return packageImportsApi.selectConnection(importId, kind, source, destination) - }, - onSuccess: async data => { - client.setQueryData(['import-readiness', importId], data) - if (effectiveProtocolId) { - const fresh = await protocolsApi.get(effectiveProtocolId) - client.setQueryData(protocolForExperimentQueryKey(experimentId), fresh) - onGraphChange?.(fresh.graph) - } - void client.invalidateQueries({ queryKey: ['experiments', experimentId] }) - }, - }) - return
-

{setup.data ? setup.data.ready ? 'Ready to publish' : 'Setup needed' : 'Checking publication readiness…'}

-

Checks saved configuration only. Test live connections explicitly in LLM Settings or MCP Servers. Publish normally when setup is complete.

- Manage destination model credentials - {(setup.error || selection.error) &&

{String(setup.error || selection.error)}

} - {setup.data?.issues.map((issue, index) =>

- {issue.node_id && onSelectNode ? - : {issue.message}} -

)} - {setup.data?.providers.map(provider =>
Model provider: {provider.provider} - -
)} - {setup.data?.mcp.map(requirement => )} - -
-} diff --git a/frontend/src/components/protocol/JsonSourceViewer.tsx b/frontend/src/components/protocol/JsonSourceViewer.tsx deleted file mode 100644 index c73ab177..00000000 --- a/frontend/src/components/protocol/JsonSourceViewer.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { useMemo, useState } from 'react' -import CodeMirror, { EditorView } from '@uiw/react-codemirror' -import { json } from '@codemirror/lang-json' -import { syntaxHighlighting } from '@codemirror/language' -import { oneDarkHighlightStyle } from '@codemirror/theme-one-dark' -import { Button } from '@/components/ui/button' -import { formatJsonSource } from '@/lib/jsonSource' - -const viewerTheme = EditorView.theme({ - '&': { backgroundColor: 'var(--background)', color: 'var(--foreground)', fontSize: '0.75rem' }, - '.cm-content': { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace' }, - '.cm-gutters': { backgroundColor: 'var(--muted)', color: 'var(--muted-foreground)', border: 'none' }, - '&.cm-focused': { outline: 'none' }, -}, { dark: true }) - -const extensions = [json(), syntaxHighlighting(oneDarkHighlightStyle), EditorView.lineWrapping, - EditorView.contentAttributes.of({ role: 'textbox', 'aria-label': 'JSON source', 'aria-readonly': 'true', tabindex: '0' })] - -export function JsonSourceViewer({ source }: { source: string }) { - const formatted = useMemo(() => formatJsonSource(source), [source]) - const [original, setOriginal] = useState(false) - return
-
-

Read-only JSON · expand or collapse sections in the gutter

- {formatted.formatted &&
- - -
} -
- {!formatted.formatted &&

Could not format this file as JSON. Showing the original text.

} - -
-} diff --git a/frontend/src/components/protocol/NodeInspectorDialog.tsx b/frontend/src/components/protocol/NodeInspectorDialog.tsx index eaf91669..82179558 100644 --- a/frontend/src/components/protocol/NodeInspectorDialog.tsx +++ b/frontend/src/components/protocol/NodeInspectorDialog.tsx @@ -5,6 +5,7 @@ import { Dialog, DialogContent } from '@/components/ui/dialog' import { Label } from '@/components/ui/label' import { Slider } from '@/components/ui/slider' import { cardAccent, cn, HUD_ACCENT_RING_CLASSNAME } from '@/lib/utils' +import { NodeInspectorResourceIssues } from './NodeResourceIssues' // Midpoint of the slider's own 20-100 range -- a visible, legible starting // point that still shows the transparency effect is there, rather than @@ -135,7 +136,7 @@ export function NodeInspectorDialog({ -
{children}
+
{children}
) diff --git a/frontend/src/components/protocol/NodeResourceIssues.test.tsx b/frontend/src/components/protocol/NodeResourceIssues.test.tsx new file mode 100644 index 00000000..21adf93c --- /dev/null +++ b/frontend/src/components/protocol/NodeResourceIssues.test.tsx @@ -0,0 +1,57 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { datasetsApi, mcpServersApi, packageImportsApi, protocolsApi } from '@/api/client' +import type { ImportReadiness, PackageImport } from '@/types/packageImports' +import type { Protocol } from '@/types/protocols' +import type { Node } from '@xyflow/react' +import { NodeInspectorResourceIssues, NodeResourceIssuesProvider } from './NodeResourceIssues' +import { withResourceWarnings } from './nodeResourceIssuesContext' +import { protocolGraphQueryKey } from '@/lib/protocolGraph' + +afterEach(() => vi.restoreAllMocks()) +const ResourceNode = withResourceWarnings(({ id }: { id: string }) => {id}) +function show(node: Node) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + render( + + + + + ) + return client +} + +it('uses ordinary registry validation for legacy JSON nodes and clears warnings after repair', async () => { + vi.spyOn(packageImportsApi, 'list').mockResolvedValue([]) + vi.spyOn(datasetsApi, 'list').mockResolvedValue([]) + const client = show({ id: 'dataset', type: 'dataset', position: { x: 0, y: 0 }, + data: { config: { dataset_id: 'missing' } } }) + expect(await screen.findByText('Dataset is no longer registered')).toBeInTheDocument() + act(() => client.setQueryData(['datasets'], [{ id: 'missing', raw_path: '/destination/raw.csv' }])) + await waitFor(() => expect(screen.queryByText('Dataset is no longer registered')).not.toBeInTheDocument()) +}) + +it('leaves a custom connection unselected and repairs it only in its node inspector', async () => { + vi.spyOn(packageImportsApi, 'list').mockResolvedValue([{ id: 'import', status: 'completed' } as PackageImport]) + vi.spyOn(mcpServersApi, 'list').mockResolvedValue([]) + const readiness: ImportReadiness = { ready: false, + issues: [{ node_id: 'tool', resource_id: 'source-tool', message: 'Choose a compatible connection' }], + mcp: [{ source_id: 'source-tool', name: 'Research tools', selected_id: null, + candidates: [{ id: 'destination', name: 'My tools' }] }] } + vi.spyOn(packageImportsApi, 'readiness').mockResolvedValue(readiness) + const select = vi.spyOn(packageImportsApi, 'selectConnection').mockResolvedValue({ ...readiness, ready: true, issues: [] }) + const update = vi.spyOn(protocolsApi, 'update').mockResolvedValue({} as Protocol) + vi.spyOn(protocolsApi, 'get').mockResolvedValue({ graph: { nodes: [], edges: [] } } as unknown as Protocol) + const node = { id: 'tool', type: 'mcp_tool', position: { x: 0, y: 0 }, + data: { config: { server_id: 'placeholder', tool_names: ['score'] } } } + const client = show(node) + client.setQueryData(protocolGraphQueryKey('p'), { nodes: [node], edges: [] }) + const picker = await screen.findByRole('combobox') + expect(picker).toHaveValue('') + expect(select).not.toHaveBeenCalled() + fireEvent.change(picker, { target: { value: 'destination' } }) + await waitFor(() => expect(select).toHaveBeenCalledWith('import', 'mcp', 'source-tool', 'destination')) + expect(update).toHaveBeenCalledWith('p', { graph: expect.objectContaining({ nodes: [node] }) }) +}) diff --git a/frontend/src/components/protocol/NodeResourceIssues.tsx b/frontend/src/components/protocol/NodeResourceIssues.tsx new file mode 100644 index 00000000..13a8c628 --- /dev/null +++ b/frontend/src/components/protocol/NodeResourceIssues.tsx @@ -0,0 +1,72 @@ +import { useContext, type ReactNode } from 'react' +import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query' +import type { Edge, Node } from '@xyflow/react' +import { datasetsApi, skillsApi, mcpServersApi, okfApi, llmSettingsApi, packageImportsApi, protocolsApi } from '@/api/client' +import { protocolForExperimentQueryKey, protocolGraphQueryKey, toPersistedGraph } from '@/lib/protocolGraph' +import type { ProtocolGraph } from '@/types/protocols' +import type { ImportReadiness } from '@/types/packageImports' +import { nodeResourceIssues } from './nodeConfigIssues' +import { ResourceIssues } from './nodeResourceIssuesContext' + +export function NodeResourceIssuesProvider({ experimentId, protocolId, selectedNodeId, onGraphChange, nodes, children }: { + experimentId?: string | null; protocolId: string; selectedNodeId: string | null + onGraphChange: (graph: ProtocolGraph) => void; children: ReactNode + nodes: Node[] +}) { + const client = useQueryClient() + const kinds = new Set(nodes.map(node => node.type)) + const registries = useQueries({ queries: [ + { queryKey: ['datasets'], queryFn: datasetsApi.list, enabled: kinds.has('dataset') }, + { queryKey: ['skills'], queryFn: skillsApi.list, enabled: kinds.has('skill') }, + { queryKey: ['mcp-servers'], queryFn: mcpServersApi.list, enabled: ['mcp_tool', 'mcp_client_tool', 'mcp_scikit_learn'].some(kind => kinds.has(kind)) }, + { queryKey: ['okf-bundles'], queryFn: okfApi.list, enabled: kinds.has('okf_bundle') }, + { queryKey: ['okf-documents'], queryFn: okfApi.listDocuments, enabled: kinds.has('okf_document') }, + { queryKey: ['llm-settings'], queryFn: llmSettingsApi.list, enabled: [...kinds].some(kind => kind?.startsWith('model_') || kind?.startsWith('llm_')) }, + ] }) + // Observe data updates as well as the initial load, including inspector repairs. + const loadedResources = registries.map(registry => registry.data) + const sources = useQuery({ queryKey: ['package-imports', experimentId], enabled: !!experimentId, + queryFn: () => packageImportsApi.list(experimentId!) }) + const source = sources.data?.find(item => item.status === 'completed') + const readiness = useQuery({ queryKey: ['import-readiness', source?.id], enabled: !!source, + queryFn: () => packageImportsApi.readiness(source!.id), refetchInterval: source ? 5000 : false }) + const selection = useMutation({ + mutationFn: async ({ requirement, destination }: { requirement: string; destination: string }) => { + const live = client.getQueryData<{ nodes: Node[]; edges: Edge[] }>(protocolGraphQueryKey(protocolId)) + if (live) await protocolsApi.update(protocolId, { graph: toPersistedGraph(live.nodes, live.edges) }) + return packageImportsApi.selectConnection(source!.id, 'mcp', requirement, destination) + }, + onSuccess: async result => { + client.setQueryData(['import-readiness', source!.id], result) + const fresh = await protocolsApi.get(protocolId) + client.setQueryData(protocolForExperimentQueryKey(experimentId!), fresh) + onGraphChange(fresh.graph) + void client.invalidateQueries({ queryKey: ['experiments', experimentId] }) + }, + }) + const localIssues = loadedResources.some(Boolean) ? nodes.flatMap(node => nodeResourceIssues(node, client) + .map(message => ({ node_id: node.id, message }))) : [] + const issues: ImportReadiness['issues'] = [...(readiness.data?.issues ?? []), ...localIssues] + const selectedIssues = issues.filter(issue => issue.node_id === selectedNodeId) + const requirements = readiness.data?.mcp.filter(requirement => selectedIssues.some(issue => issue.resource_id === requirement.source_id)) ?? [] + const inspector = <> + {selectedIssues.map((issue, index) =>

{issue.message}

)} + {requirements.map(requirement => )} + {(readiness.error || selection.error) &&

{(readiness.error || selection.error)?.message}

} + + return {children} +} + +export function NodeInspectorResourceIssues() { + return useContext(ResourceIssues).inspector +} diff --git a/frontend/src/components/protocol/ProtocolCanvas.tsx b/frontend/src/components/protocol/ProtocolCanvas.tsx index e9bc8971..36c7e8ea 100644 --- a/frontend/src/components/protocol/ProtocolCanvas.tsx +++ b/frontend/src/components/protocol/ProtocolCanvas.tsx @@ -60,8 +60,8 @@ import { import '@xyflow/react/dist/style.css' import { Lock, Play, Plus, Square, X } from 'lucide-react' import { Button } from '@/components/ui/button' -import { ApiError, experimentsApi, protocolsApi, packageImportsApi } from '@/api/client' -import { ImportedExperimentSetup } from './ImportedExperimentSetup' +import { ApiError, experimentsApi, protocolsApi } from '@/api/client' +import { NodeResourceIssuesProvider } from './NodeResourceIssues' import { CONNECTOR_HANDLES } from '@/lib/coordinationStrategy' import { graphWithFactorBaseline, reconcileFactorBaselines, type FactorBindingDiscrepancy } from '@/lib/factorBindings' import { newNodeId } from '@/lib/nodeId' @@ -413,14 +413,14 @@ export const ProtocolCanvas = forwardRef(function ProtocolCanvas({ protocolId, experimentId, initialGraph, hasUnpublishedChanges, publishedRevision, experimentLocked = false, protocol, regenerationRequired = false, unboundFactors = [], bindingDiscrepancies = [] }, canvasHandleRef) { +}>(function ProtocolCanvas({ protocolId, experimentId, initialGraph, hasUnpublishedChanges, publishedRevision, experimentLocked = false, protocol, regenerationRequired = false, draftBusy = false, unboundFactors = [], bindingDiscrepancies = [] }, canvasHandleRef) { const [nodes, setNodes, onNodesChange] = useNodesState(migrateLegacyNodes(initialGraph)) const [edges, setEdges, onEdgesChange] = useEdgesState(migrateLegacyHandles(initialGraph)) const queryClient = useQueryClient() - const importedSources = useQuery({ queryKey: ['package-imports', experimentId], enabled: !!experimentId, - queryFn: () => packageImportsApi.list(experimentId!) }) + // Mirrors the canvas's own live state into the shared query cache on // every change -- immediate, not debounced like autosave below, since @@ -2308,13 +2308,10 @@ export const ProtocolCanvas = forwardRef + { setNodes(migrateLegacyNodes(graph)); setEdges(migrateLegacyHandles(graph)) }}>
- {experimentId && !experimentLocked && importedSources.data?.filter(source => source.status === 'completed').map(source => -
- { setNodes(migrateLegacyNodes(graph)); setEdges(migrateLegacyHandles(graph)) }} /> -
)} editFactorMutation.mutateAsync({ oldName: editingFactor.name, next })} /> )} + ) }) diff --git a/frontend/src/components/protocol/ProtocolCanvasMenu.test.tsx b/frontend/src/components/protocol/ProtocolCanvasMenu.test.tsx new file mode 100644 index 00000000..0349e889 --- /dev/null +++ b/frontend/src/components/protocol/ProtocolCanvasMenu.test.tsx @@ -0,0 +1,80 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter } from 'react-router-dom' +import { afterEach, expect, it, vi } from 'vitest' +import { experimentsApi, protocolsApi } from '@/api/client' +import type { Experiment } from '@/types/experiments' +import type { Protocol } from '@/types/protocols' +import { ProtocolCanvasMenu } from './ProtocolCanvasMenu' +import { protocolForExperimentQueryKey, protocolGraphQueryKey } from '@/lib/protocolGraph' + +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() }) + +const protocol: Protocol = { id: 'p', name: 'Protocol', description: null, experiment_id: 'e', + graph: { nodes: [], edges: [] }, published_revision_id: 'published', published_revision: 1, + has_unpublished_changes: false, created_at: '', updated_at: '' } + +function show(draft = protocol, draftBusy = false) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + client.setQueryData(protocolForExperimentQueryKey('e'), draft) + vi.spyOn(protocolsApi, 'get').mockResolvedValue(draft) + vi.spyOn(experimentsApi, 'get').mockResolvedValue({ id: 'e', name: 'Experiment', description: null } as Experiment) + vi.stubGlobal('URL', class extends URL { + static createObjectURL() { return 'blob:legacy-json' } + static revokeObjectURL() {} + }) + render( + + ) + return client +} + +it('downloads a package from the actual canvas menu instead of a JSON definition', async () => { + const user = userEvent.setup() + const job = { id: 'export', kind: 'export', status: 'completed', protocol_revision_id: 'published', + progress: {}, error: null, download_url: '/api/experiment-package.zip' } as const + const create = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(job) + vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(job) + const downloads: string[] = [] + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { + downloads.push(this.getAttribute('href') ?? '') + }) + show() + await user.click(screen.getByRole('button', { name: 'Experiment menu' })) + await user.click(await screen.findByRole('menuitem', { name: 'Download' })) + await waitFor(() => expect(downloads).toEqual(['/api/experiment-package.zip'])) + expect(create).toHaveBeenCalledWith('e', { protocol_id: 'p', protocol_revision_id: 'published' }, + expect.objectContaining({ kind: 'export', format: 'experiment_package' })) +}) + +it.each([ + { draft: { ...protocol, has_unpublished_changes: true }, draftBusy: false }, + { draft: { ...protocol, published_revision_id: null, published_revision: null }, draftBusy: false }, + { draft: protocol, draftBusy: true }, +])('requires publication from the canvas menu without publishing or downloading JSON: %j', async ({ draft, draftBusy }) => { + const user = userEvent.setup() + const create = vi.spyOn(experimentsApi, 'createResultJob') + const publish = vi.spyOn(protocolsApi, 'publish') + const download = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) + show(draft, draftBusy) + await user.click(screen.getByRole('button', { name: 'Experiment menu' })) + await user.click(await screen.findByRole('menuitem', { name: 'Download' })) + expect(await screen.findByText('Publish before exporting')).toBeInTheDocument() + expect(create).not.toHaveBeenCalled() + expect(publish).not.toHaveBeenCalled() + expect(download).not.toHaveBeenCalled() +}) + +it('checks live canvas edits before autosave when downloading from the menu', async () => { + const user = userEvent.setup() + const create = vi.spyOn(experimentsApi, 'createResultJob') + const client = show() + client.setQueryData(protocolGraphQueryKey('p'), { + nodes: [{ id: 'unsaved', type: 'agent', position: { x: 0, y: 0 }, data: {} }], edges: [], + }) + await user.click(screen.getByRole('button', { name: 'Experiment menu' })) + await user.click(await screen.findByRole('menuitem', { name: 'Download' })) + expect(await screen.findByText('Publish before exporting')).toBeInTheDocument() + expect(create).not.toHaveBeenCalled() +}) diff --git a/frontend/src/components/protocol/ProtocolCanvasMenu.tsx b/frontend/src/components/protocol/ProtocolCanvasMenu.tsx index 959e207e..da2b2ed8 100644 --- a/frontend/src/components/protocol/ProtocolCanvasMenu.tsx +++ b/frontend/src/components/protocol/ProtocolCanvasMenu.tsx @@ -11,7 +11,7 @@ import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Textarea } from '@/components/ui/textarea' import { applyExperimentRenameToProtocolCache, protocolForExperimentQueryKey, toPersistedGraph } from '@/lib/protocolGraph' -import { sanitizeFilename } from '@/lib/utils' +import { ExperimentPackageDownload } from './ExperimentPackageDownload' // Every menu item that opens a follow-up surface renders it as a SEPARATE // controlled Dialog (open/onOpenChange state), not nested inside @@ -143,7 +143,7 @@ function EditDescriptionDialog({ // The canvas-level "⋮" menu, next to Run/+ -- acts on the EXPERIMENT for // identity/lifecycle (rename/description/archive, matching this app's own // "experiments instead of workflows" framing), and on the PROTOCOL's own -// graph for Download. Importing always creates a separate experiment from the +// published package for Download. Importing always creates a separate experiment from the // global Create menu, so a canvas can never be changed by accident here. // Deliberately no Delete here (or anywhere in the GUI) -- Archive is the // only lifecycle-destructive action end users get, so a misclick can't @@ -155,11 +155,13 @@ export function ProtocolCanvasMenu({ experimentId, nodes, edges, + draftBusy = false, }: { protocolId: string experimentId: string | null nodes: Node[] edges: Edge[] + draftBusy?: boolean }) { const [renameOpen, setRenameOpen] = useState(false) const [descriptionOpen, setDescriptionOpen] = useState(false) @@ -210,44 +212,11 @@ export function ProtocolCanvasMenu({ }, }) - async function handleDownload() { - const protocol = await protocolsApi.get(protocolId) - // Protocol.name is "Protocol: {experiment name} [{shortid}]" -- an - // internal, collision-proofed label (renames now keep it in sync, but the - // shape stays). What the user actually calls this thing is the - // experiment's own name, already loaded above for the Archive/Delete/etc. - // actions, so that's what the exported payload and the downloaded - // filename use. - const displayName = experiment?.name ?? protocol.name - // Serializes the canvas's own LIVE nodes/edges (props passed down from - // ProtocolCanvas.tsx), not protocolsApi.get's possibly-stale graph -- - // reuses that file's own toPersistedGraph, the same helper its autosave uses. - // design_spec travels alongside the graph -- a factor is meaningless - // without both halves of its binding (design_spec.factors' declaration - // AND the node's own factor_bindings, already inside the graph), so an - // export/import round-trip that dropped one would silently orphan the - // other. - const payload = { - name: displayName, - description: protocol.description, - graph: toPersistedGraph(nodes, edges), - design_spec: experiment?.design_spec ?? null, - measurement_plan: experiment?.measurement_plan ?? null, - } - const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }) - const url = URL.createObjectURL(blob) - const a = document.createElement('a') - a.href = url - a.download = `${sanitizeFilename(displayName, 'protocol')}.json` - a.click() - URL.revokeObjectURL(url) - } - const isArchived = !!experiment?.archived_at const isLocked = !!experiment?.locked_at - return ( - <> + // Keep the shared export controller mounted after the dropdown closes. + const renderMenu = (download: () => void, busy: boolean) => ( }> @@ -274,12 +243,18 @@ export function ProtocolCanvasMenu({ {isArchived ? 'Unarchive' : 'Archive'} - void handleDownload()}> + Download + ) + + return ( + <> + {experimentId ? : renderMenu(() => {}, true)} {experimentId && experiment && ( <> diff --git a/frontend/src/components/protocol/ResultJobFlows.test.tsx b/frontend/src/components/protocol/ResultJobFlows.test.tsx index 351fe05a..b1aea02b 100644 --- a/frontend/src/components/protocol/ResultJobFlows.test.tsx +++ b/frontend/src/components/protocol/ResultJobFlows.test.tsx @@ -12,7 +12,6 @@ vi.mock('./RunConfirmDialog', () => ({ RunConfirmDialog: ({ additionalContent, o additionalContent: React.ReactNode; onConfirm: () => void; onPublishAndRun: () => void; onCancel: () => void confirmDisabled: boolean; publishDisabled: boolean; publishLabel?: string; publishError?: string }) =>
{additionalContent}{publishError &&

{publishError}

}
})) -vi.mock('./ExperimentDefinitionDownload', () => ({ ExperimentDefinitionDownload: () => null })) const row: ExecutionSlot = { slot_id: 'stable-slot', cell_id: 'cell', cell_label: 'model=a', factor_values: {}, replicate_id: 'parent', replicate_label: 'ambiguous-label', replicate_number: 1, row_result_id: null, row_index: null, dataset_id: null, raw_sha256: null, run_id: 'attempt', status: 'completed', updated_at: null, error: null, result: {}, usage: null } diff --git a/frontend/src/components/protocol/RunsTab.tsx b/frontend/src/components/protocol/RunsTab.tsx index 77c11a11..bce74f49 100644 --- a/frontend/src/components/protocol/RunsTab.tsx +++ b/frontend/src/components/protocol/RunsTab.tsx @@ -17,7 +17,6 @@ import type { ExecutionSlot } from '@/types/executionResults' import { ExecutionBrowser, ExecutionRows } from './ExecutionBrowser' import { runsAgainOnlyOnRequest } from '@/lib/protocolRun' import { newRequestKey } from '@/lib/requestKey' -import { ExperimentDefinitionDownload } from './ExperimentDefinitionDownload' import { RunConfirmDialog } from './RunConfirmDialog' import { ReplicateRunAction } from './CellPresentation' import type { ResultsSelection } from './ResultsTab' @@ -86,7 +85,6 @@ export function RunAllCellsButton({ protocol, experimentId, regenerationRequired {summary.error &&

{summary.error.message}

} {summary.data?.unit === 'row' &&

{summary.data.expected ?? '?'} expected rows across {summary.data.replicate_count ?? 0} replicates.

} {!experiment.data?.locked_at && } -

Completed {summary.data?.unit === 'row' ? 'rows' : 'replicates'}, including ones that hit their iteration limit, are skipped unless selected to run again.

{}} actions={row => runsAgainOnlyOnRequest(row.status) && = 100} onCheckedChange={checked => setReruns(current => { const next = new Set(current); if (checked) next.add(row.slot_id); else next.delete(row.slot_id); return next })} />} /> diff --git a/frontend/src/components/protocol/SkillBrowserPanel.test.tsx b/frontend/src/components/protocol/SkillBrowserPanel.test.tsx new file mode 100644 index 00000000..d6cc3d0c --- /dev/null +++ b/frontend/src/components/protocol/SkillBrowserPanel.test.tsx @@ -0,0 +1,32 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { ApiError, skillsApi } from '@/api/client' +import { SkillBrowserPanel } from './SkillBrowserPanel' + +vi.mock('./RegisterSkillDialog', () => ({ RegisterSkillDialog: () => null })) +afterEach(() => vi.restoreAllMocks()) + +it('explains retained usage and lets the user dismiss the deletion error', async () => { + vi.spyOn(skillsApi, 'list').mockResolvedValue([{ + id: 'skill', name: 'checking', description: 'Check calculations', body: 'Instructions', + frontmatter: {}, files: [], is_system: false, source_filename: null, + created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z', + }]) + const message = 'This skill is used by published version: Experiment A. Remove those references before deleting the skill.' + const remove = vi.spyOn(skillsApi, 'remove').mockRejectedValue(new ApiError(409, message)) + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + render( + + ) + fireEvent.click(await screen.findByRole('button', { name: 'Delete checking' })) + expect(screen.getByText(/cannot be deleted/)).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: 'Delete' })) + expect(await screen.findByRole('alert')).toHaveTextContent(message) + expect(remove).toHaveBeenCalledExactlyOnceWith('skill') + expect(screen.getByRole('button', { name: 'Delete checking' })).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: 'Dismiss deletion error' })) + await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument()) + expect(screen.getByRole('button', { name: 'Delete checking' })).toBeInTheDocument() + expect(remove).toHaveBeenCalledTimes(1) +}) diff --git a/frontend/src/components/protocol/SkillBrowserPanel.tsx b/frontend/src/components/protocol/SkillBrowserPanel.tsx index 3d920baa..733d73b7 100644 --- a/frontend/src/components/protocol/SkillBrowserPanel.tsx +++ b/frontend/src/components/protocol/SkillBrowserPanel.tsx @@ -5,10 +5,11 @@ import { useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { ArrowLeft, Plus, ScrollText, Trash2, X } from 'lucide-react' import { Badge } from '@/components/ui/badge' +import { Alert, AlertAction, AlertDescription, AlertTitle } from '@/components/ui/alert' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Skeleton } from '@/components/ui/skeleton' -import { skillsApi } from '@/api/client' +import { ApiError, skillsApi } from '@/api/client' import { RegisterSkillDialog } from './RegisterSkillDialog' import type { Skill } from '@/types/skills' @@ -19,10 +20,8 @@ import type { Skill } from '@/types/skills' // choosing the skill is how you add the node. // // It doubles as the library's own management surface (register, delete), -// since a skill isn't otherwise reachable from anywhere in the app. Editing -// a skill's TEXT deliberately isn't here: that's a document-editing job, not -// something to do in a 320px canvas rail, and PUT /skills/{id}/markdown -// already exists for whenever it gets a real home. +// since a skill isn't otherwise reachable from anywhere in the app. +// Registrations are immutable; changed content requires a new skill. export function SkillBrowserPanel({ onPick, onBack, @@ -48,6 +47,7 @@ export function SkillBrowserPanel({ queryClient.invalidateQueries({ queryKey: ['skills'] }) setConfirmingDeleteId(null) }, + onError: () => setConfirmingDeleteId(null), }) const skills = skillsQuery.data ?? [] @@ -102,8 +102,8 @@ export function SkillBrowserPanel({ {confirmingDeleteId === skill.id ? (

- Delete {skill.name}? Any node already naming it keeps the id and - will report the skill as missing. + Delete {skill.name}? Skills used by a canvas, + published experiment version, design, or retained run cannot be deleted.

@@ -170,7 +170,20 @@ export function SkillBrowserPanel({
)} - {deleteMutation.isError &&

Could not delete that skill.

} + {deleteMutation.isError && + Couldn’t delete this skill + + {deleteMutation.error instanceof ApiError + ? deleteMutation.error.message + : 'Something went wrong. Please try again.'} + + + + + } {/* Registering just refreshes the list rather than immediately creating a node: uploading and placing are separate decisions, and you may diff --git a/frontend/src/components/protocol/nodeConfigIssues.ts b/frontend/src/components/protocol/nodeConfigIssues.ts index 016ceaa0..df0bd9f3 100644 --- a/frontend/src/components/protocol/nodeConfigIssues.ts +++ b/frontend/src/components/protocol/nodeConfigIssues.ts @@ -6,6 +6,9 @@ import { isUnderIterated, raiseForTruncation, suggestedMaxIterations } from '@/l import type { LLMSettingModelsResponse, ModelCapabilities } from '@/types/llmSettings' import type { OkfBundle, OkfDocument } from '@/types/okf' import type { Skill } from '@/types/skills' +import type { Dataset } from '@/types/datasets' +import type { McpServer } from '@/types/mcpServers' +import type { LLMSetting } from '@/types/llmSettings' import type { DatasetNodeData, ModelNodeData, @@ -26,6 +29,52 @@ export interface NodeConfigIssue { issues: string[] } +// Registry checks are shared by canvas warnings and Run's preflight. They read +// normal application caches and never connect to external providers or tools. +export function nodeResourceIssues(node: Node, client: QueryClient): string[] { + const config = (node.data.config ?? {}) as Record + if (config.enabled === false || node.data.active === false) return [] + const issues: string[] = [] + if (node.type === 'dataset' && config.dataset_id) { + const datasets = client.getQueryData(['datasets']) + const dataset = datasets?.find(item => item.id === config.dataset_id) + if (datasets && !dataset) issues.push('Dataset is no longer registered') + else if (dataset && !dataset.raw_path) issues.push('Dataset source file is unavailable') + } + if (node.type === 'skill' && config.skill_id) { + const skills = client.getQueryData(['skills']) + if (skills && !skills.some(item => item.id === config.skill_id)) issues.push('Skill no longer exists') + } + if (node.type === 'okf_bundle' && config.bundle_id) { + const bundles = client.getQueryData(['okf-bundles']) + if (bundles && !bundles.some(item => item.id === config.bundle_id)) issues.push('OKF bundle is no longer registered') + } + if (node.type === 'okf_document' && config.document_id) { + const documents = client.getQueryData(['okf-documents']) + if (documents && !documents.some(item => item.id === config.document_id)) issues.push('OKF document is no longer stored') + } + if (['mcp_tool', 'mcp_client_tool', 'mcp_scikit_learn'].includes(node.type ?? '')) { + const servers = client.getQueryData(['mcp-servers']) + const server = servers?.find(item => item.id === config.server_id) + if (servers && !server) issues.push('MCP Server is unavailable; select a destination connection') + else if (server) { + if (!server.command && !server.url) issues.push('MCP Server connection is not configured') + if (server.error_message) issues.push(server.error_message) + const available = new Set(server.capabilities?.tools?.map(tool => tool.name) ?? []) + const required = Array.isArray(config.tool_names) ? config.tool_names : [] + if (required.some(tool => !available.has(tool))) issues.push('MCP Server lacks required tools') + } + } + if (node.type?.startsWith('model_') || node.type?.startsWith('llm_')) { + const provider = config.provider || node.type.replace(/^(model_|llm_)/, '') + const settings = client.getQueryData(['llm-settings']) + if (settings && !settings.some(setting => setting.provider === provider)) { + issues.push(`Configure your ${provider} connection in Profile`) + } + } + return issues +} + // A pre-flight scan run right before a real Run fires, so an obviously // misconfigured node (no model, no dataset or skill picked, no script code, an // agent with nothing wired into its required Model connector) surfaces as an @@ -64,7 +113,7 @@ export function findNodeConfigIssues( for (const node of nodes) { const data = node.data as { label?: string } | undefined const label = data?.label || node.type || 'node' - const issues: string[] = [] + const issues: string[] = nodeResourceIssues(node, queryClient) switch (node.type) { case 'agent': @@ -145,15 +194,6 @@ export function findNodeConfigIssues( // Same wording as SkillNode's own badge. if (!config?.skill_id) { issues.push('No skill selected') - } else { - // A set id can still resolve to nothing -- a skill deleted from the - // library, or a graph imported from another account, both leave the - // id (and its cached skill_name) behind. Cache-only, same contract - // as the model check above: a miss means "can't tell," not an issue. - const cached = queryClient.getQueryData(['skills']) - if (cached && !cached.some((s) => s.id === config.skill_id)) { - issues.push(`Skill no longer exists${config.skill_name ? ` ("${config.skill_name}")` : ''}`) - } } break } @@ -169,14 +209,6 @@ export function findNodeConfigIssues( // always a server that failed to spawn. The agent would get nothing // from the bundle, silently, so it's worth flagging up front. issues.push('No tools discovered -- the bundle server may have failed to start') - } else { - // A set id can still resolve to nothing -- deregistered, or a graph - // imported from another account. Cache-only, same contract as the - // skill check above: a miss means "can't tell," not an issue. - const cached = queryClient.getQueryData(['okf-bundles']) - if (cached && !cached.some((b) => b.id === config.bundle_id)) { - issues.push(`OKF bundle is no longer registered${config.bundle_path ? ` ("${config.bundle_path}")` : ''}`) - } } break } @@ -188,13 +220,6 @@ export function findNodeConfigIssues( issues.push('No document selected') } else if ((config.tool_names?.length ?? 0) === 0) { issues.push('No tools discovered -- the document server may have failed to start') - } else { - const cached = queryClient.getQueryData(['okf-documents']) - if (cached && !cached.some((d) => d.id === config.document_id)) { - issues.push( - `OKF document is no longer stored${config.document_title ? ` ("${config.document_title}")` : ''}`, - ) - } } break } diff --git a/frontend/src/components/protocol/nodeResourceIssuesContext.ts b/frontend/src/components/protocol/nodeResourceIssuesContext.ts new file mode 100644 index 00000000..b3703523 --- /dev/null +++ b/frontend/src/components/protocol/nodeResourceIssuesContext.ts @@ -0,0 +1,14 @@ +import { createContext, createElement, useContext, type ComponentType, type ReactNode } from 'react' +import type { ImportReadiness } from '@/types/packageImports' +import { WarningBadge } from './nodes/WarningBadge' + +export const ResourceIssues = createContext<{ issues: ImportReadiness['issues']; inspector: ReactNode }>({ issues: [], inspector: null }) + +// One wrapper applies resource warnings to every registered node renderer. +export function withResourceWarnings

(Renderer: ComponentType

) { + return function ResourceNode(props: P) { + const issues = useContext(ResourceIssues).issues.filter(issue => issue.node_id === props.id).map(issue => issue.message) + return createElement('div', { className: 'relative' }, createElement(Renderer, props), + issues.length ? createElement(WarningBadge, { issues, className: 'absolute -left-1 -top-1 z-10' }) : null) + } +} diff --git a/frontend/src/components/protocol/protocolNodeTypes.ts b/frontend/src/components/protocol/protocolNodeTypes.ts index ad9fe727..f930c9e2 100644 --- a/frontend/src/components/protocol/protocolNodeTypes.ts +++ b/frontend/src/components/protocol/protocolNodeTypes.ts @@ -14,16 +14,17 @@ import { SingleAgentBaselinePatternNode } from './nodes/SingleAgentBaselinePatte import { OkfBundleNode } from './nodes/OkfBundleNode' import { OkfDocumentNode } from './nodes/OkfDocumentNode' import { SkillNode } from './nodes/SkillNode' +import { withResourceWarnings } from './nodeResourceIssuesContext' export const NODE_TYPES = { - agent: AgentNode, sub_agent: AgentNode, - mcp_tool: McpToolNode, mcp_scikit_learn: McpToolNode, mcp_client_tool: McpClientToolNode, - critic_gate: CriticGateNode, tool_step: ToolStepNode, - model_anthropic: ModelNode, model_openai: ModelNode, model_azure_foundry: ModelNode, - model_openrouter: ModelNode, model_local: ModelNode, - memory: MemoryNode, output_parser: OutputParserNode, dataset: DatasetNode, - persona: PersonaNode, - skill: SkillNode, okf_bundle: OkfBundleNode, okf_document: OkfDocumentNode, - script: ScriptNode, pattern_reason_act: ReasonActPatternNode, - pattern_single_agent_baseline: SingleAgentBaselinePatternNode, + agent: withResourceWarnings(AgentNode), sub_agent: withResourceWarnings(AgentNode), + mcp_tool: withResourceWarnings(McpToolNode), mcp_scikit_learn: withResourceWarnings(McpToolNode), mcp_client_tool: withResourceWarnings(McpClientToolNode), + critic_gate: withResourceWarnings(CriticGateNode), tool_step: withResourceWarnings(ToolStepNode), + model_anthropic: withResourceWarnings(ModelNode), model_openai: withResourceWarnings(ModelNode), model_azure_foundry: withResourceWarnings(ModelNode), + model_openrouter: withResourceWarnings(ModelNode), model_local: withResourceWarnings(ModelNode), + memory: withResourceWarnings(MemoryNode), output_parser: withResourceWarnings(OutputParserNode), dataset: withResourceWarnings(DatasetNode), + persona: withResourceWarnings(PersonaNode), + skill: withResourceWarnings(SkillNode), okf_bundle: withResourceWarnings(OkfBundleNode), okf_document: withResourceWarnings(OkfDocumentNode), + script: withResourceWarnings(ScriptNode), pattern_reason_act: withResourceWarnings(ReasonActPatternNode), + pattern_single_agent_baseline: withResourceWarnings(SingleAgentBaselinePatternNode), } diff --git a/frontend/src/components/protocol/useProviderModels.test.tsx b/frontend/src/components/protocol/useProviderModels.test.tsx index ace0d3dc..35347912 100644 --- a/frontend/src/components/protocol/useProviderModels.test.tsx +++ b/frontend/src/components/protocol/useProviderModels.test.tsx @@ -12,7 +12,7 @@ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() }) it('automatically refreshes a mounted provider model list without navigation', async () => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) const response = (id: string): LLMSettingModelsResponse => ({ models: [{ id, label: id, supports_temperature: true, supports_effort: false, effort_levels: [], supports_tool_calling: true }], source: 'api', @@ -38,7 +38,7 @@ it.each([ ['truly-unknown', false, true, 'medium'], ] as const)('uses backend capabilities for off-catalog %s and run warnings', async (model, temperature, effort, defaultEffort) => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) vi.spyOn(llmSettingsApi, 'listModels').mockResolvedValue({ models: [], source: 'static', note: null }) const metadata = { supports_temperature: temperature, supports_effort: effort, effort_levels: effort ? ['low', 'medium', 'high'] : [], default_effort: defaultEffort } const resolve = vi.spyOn(llmSettingsApi, 'modelCapabilities').mockResolvedValue(metadata) @@ -62,7 +62,7 @@ it.each([ it('debounces changed custom IDs and never displays the previous model capabilities', async () => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) vi.spyOn(llmSettingsApi, 'listModels').mockResolvedValue({ models: [], source: 'static', note: null }) const metadata = { supports_temperature: false, supports_effort: true, effort_levels: ['medium'], default_effort: 'medium' } const resolve = vi.spyOn(llmSettingsApi, 'modelCapabilities').mockResolvedValue(metadata) @@ -85,7 +85,7 @@ it('debounces changed custom IDs and never displays the previous model capabilit it('does not resolve custom capabilities when an explicit override is present', async () => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) vi.spyOn(llmSettingsApi, 'listModels').mockResolvedValue({ models: [], source: 'static', note: null }) const resolve = vi.spyOn(llmSettingsApi, 'modelCapabilities') const override = { supports_temperature: true, supports_effort: false, effort_levels: [], default_effort: null } @@ -101,7 +101,7 @@ it('does not resolve custom capabilities when an explicit override is present', it('reports a failed custom lookup instead of guessing effort', async () => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) vi.spyOn(llmSettingsApi, 'listModels').mockResolvedValue({ models: [], source: 'static', note: null }) vi.spyOn(llmSettingsApi, 'modelCapabilities').mockRejectedValue(new Error('offline')) const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) diff --git a/frontend/src/lib/jsonSource.test.ts b/frontend/src/lib/jsonSource.test.ts deleted file mode 100644 index 3f5b242f..00000000 --- a/frontend/src/lib/jsonSource.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { expect, it } from 'vitest' -import { formatJsonSource } from './jsonSource' - -it('indents JSON without changing exact numbers, string escapes, duplicate keys, or opaque values', () => { - const source = '{"large":9007199254740993,"decimal":1.2300e+30,"value":null,"value":false,"escaped":"a\\nb","list":[1,2]}' - const result = formatJsonSource(source) - expect(result.formatted).toBe(true) - expect(result.text).toBe([ - '{', - ' "large": 9007199254740993,', - ' "decimal": 1.2300e+30,', - ' "value": null,', - ' "value": false,', - ' "escaped": "a\\nb",', - ' "list": [', - ' 1,', - ' 2', - ' ]', - '}', - ].join('\n')) -}) - -it('retains malformed or non-JSON source text for inspection', () => { - for (const source of ['{"missing":', '{"trailing":true,}', 'not JSON', '']) { - expect(formatJsonSource(source)).toEqual({ text: source, formatted: false }) - } -}) diff --git a/frontend/src/lib/jsonSource.ts b/frontend/src/lib/jsonSource.ts deleted file mode 100644 index d6462684..00000000 --- a/frontend/src/lib/jsonSource.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { applyEdits, format, visit } from 'jsonc-parser' - -/** Format whitespace without reserializing numbers, strings, or duplicate keys. */ -export function formatJsonSource(source: string): { text: string; formatted: boolean } { - try { - let valid = true - visit(source, { onError: () => { valid = false } }, { disallowComments: true, allowTrailingComma: false }) - if (!valid) return { text: source, formatted: false } - return { text: applyEdits(source, format(source, undefined, { tabSize: 2, insertSpaces: true, eol: '\n' })), formatted: true } - } catch { - return { text: source, formatted: false } - } -} diff --git a/frontend/src/pages/ExperimentsPage.tsx b/frontend/src/pages/ExperimentsPage.tsx index eac4d2f2..db276c24 100644 --- a/frontend/src/pages/ExperimentsPage.tsx +++ b/frontend/src/pages/ExperimentsPage.tsx @@ -14,7 +14,6 @@ import { } from 'lucide-react' import { useNavigate } from 'react-router-dom' import { AppHeader } from '@/components/AppHeader' -import { ExperimentPackageImport } from '@/components/protocol/ExperimentPackageImport' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' @@ -141,7 +140,6 @@ export function ExperimentsPage() {

-
- {protocolQuery.data && experimentId && }

{versionId ? 'Canvas, Design, Runs, and Results show this saved version · read-only.' : !publishedVersion ? 'Publish the experiment to create its first version.' : hasChanges ? `Changes are not published. Runs and Results use version ${publishedVersion}.` @@ -354,6 +351,7 @@ export function ProtocolCanvasPage() { protocolId={protocolQuery.data.id} experimentId={protocolQuery.data.experiment_id} initialGraph={protocolQuery.data.graph} + draftBusy={draftBusy} hasUnpublishedChanges={protocolQuery.data.has_unpublished_changes} publishedRevision={protocolQuery.data.published_revision} experimentLocked={!!experimentQuery.data?.locked_at} diff --git a/frontend/src/types/packageImports.ts b/frontend/src/types/packageImports.ts index a7b1e367..d6a755c1 100644 --- a/frontend/src/types/packageImports.ts +++ b/frontend/src/types/packageImports.ts @@ -35,7 +35,6 @@ export interface PackageFile { export interface ImportReadiness { ready: boolean - issues: { node_id?: string; message: string }[] + issues: { node_id?: string; resource_id?: string; message: string }[] mcp: { source_id: string; name: string; selected_id: string | null; required_tools?: string[]; candidates: { id: string; name: string }[] }[] - providers: { provider: string; id: string; selected: boolean }[] } diff --git a/pyproject.toml b/pyproject.toml index d1a52995..ae726f7f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ readme = "README.md" requires-python = ">=3.12" dependencies = [ - # Pin a tested Motoro release tag; update the lockfile with uv on each bump. + # Use a tested Motoro release tag before production; see the temporary integration source below. # Exact develop commits are temporary integration inputs, never release pins. "motoro", # The on-disk versioned dataset workspace (see [tool.uv.sources] below) — @@ -93,7 +93,8 @@ dev = [ ] [tool.uv.sources] -motoro = { git = "https://github.com/EpistasisLab/motoro.git", tag = "v0.15.1" } +# Transaction-aware native registration (Motoro PR #26); replace with a tested release tag before production. +motoro = { git = "https://github.com/EpistasisLab/motoro.git", rev = "1d75d9c036ebc35217901d8945b69b4841d17798" } asaree-workspace-core = { path = "workspace-core", editable = true } # Every mcp-servers/ package is declared here, including asaree-sklearn-core # (which the six servers each depend on): uv resolves `tool.uv.sources` from diff --git a/sdk/README.md b/sdk/README.md index ede69b1f..e3a72d8f 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -12,6 +12,19 @@ background worker (`POST /runs` returns while the run is pending), so data now belongs on a `FactorialReplicateResult` row, written via `client.experiments.upsert_replicate(...)`. +## Registered skills + +Registered skills are immutable in ASAREE. `skills.update`, `replace_markdown`, +and `replace_folder` raise `AsareeConflictError` without sending a request or +reading local replacement files. Register changed content as a new skill with a +different name. The server also rejects these operations from older SDKs. + +`skills.delete(id)` succeeds only when no retained ASAREE references remain. +A conflict describes the draft canvases, factors, design revisions, published +versions, or runs that retain it. Removing a draft node alone does not remove +published or historical references. Retained Motoro agent configurations and +agent-run snapshots also protect their skills. Motoro itself is unchanged. + ## Auth bootstrap ASAREE has no static server-wide API key; each user is provisioned once and diff --git a/sdk/src/asaree_client/resources/skills.py b/sdk/src/asaree_client/resources/skills.py index a376d647..330a3f5d 100644 --- a/sdk/src/asaree_client/resources/skills.py +++ b/sdk/src/asaree_client/resources/skills.py @@ -8,9 +8,11 @@ from typing import Any from asaree_client._multipart import multipart_directory +from asaree_client.exceptions import AsareeConflictError from asaree_client.models import Skill, SkillPage, SkillUrlPreview ResourceId = uuid.UUID | str +_IMMUTABLE_MESSAGE = "Registered skills are immutable in ASAREE. Register a new skill with a different name instead." class Skills: @@ -35,7 +37,8 @@ def upload_folder(self, directory: str) -> Skill: return self._folder_request("POST", "/skills/upload-folder", directory) def replace_folder(self, skill_id: ResourceId, directory: str) -> Skill: - return self._folder_request("PUT", f"/skills/{skill_id}/folder", directory) + """Retained for compatibility; register a new skill instead.""" + raise AsareeConflictError(_IMMUTABLE_MESSAGE) def _folder_request(self, method: str, path: str, directory: str) -> Skill: with multipart_directory(directory) as files: @@ -72,13 +75,12 @@ def update( description: str | None = None, body: str | None = None, ) -> Skill: - payload = {k: v for k, v in {"name": name, "description": description, "body": body}.items() if v is not None} - return Skill(**self._client._patch(f"/skills/{skill_id}", json=payload)) + """Retained for compatibility; register a new skill instead.""" + raise AsareeConflictError(_IMMUTABLE_MESSAGE) def replace_markdown(self, skill_id: ResourceId, file_path: str) -> Skill: - with open(file_path, "rb") as file: - data = self._client._put(f"/skills/{skill_id}/markdown", files={"file": (Path(file_path).name, file)}) - return Skill(**data) + """Retained for compatibility; register a new skill instead.""" + raise AsareeConflictError(_IMMUTABLE_MESSAGE) def delete(self, skill_id: ResourceId) -> None: self._client._delete(f"/skills/{skill_id}") diff --git a/sdk/tests/test_sdk_gaps.py b/sdk/tests/test_sdk_gaps.py index b6eded7e..8c29c2a0 100644 --- a/sdk/tests/test_sdk_gaps.py +++ b/sdk/tests/test_sdk_gaps.py @@ -12,6 +12,7 @@ from asaree_client._multipart import multipart_directory from asaree_client._transport import RetryPolicy, RetryTransport +from asaree_client.exceptions import AsareeConflictError from asaree_client.models import Agent from asaree_client.resources.skills import Skills from asaree_client.resources.tools import Tools @@ -45,6 +46,20 @@ def _patch(self, path: str, **kwargs: Any) -> Any: return self.response +@pytest.mark.parametrize("operation", ["fields", "markdown", "folder"]) +def test_skills_cannot_be_modified_or_read_replacement_files(operation): + client = RecordingClient({}) + skills = Skills(client) + with pytest.raises(AsareeConflictError, match="immutable"): + if operation == "fields": + skills.update(uuid.uuid4(), body="Changed") + elif operation == "markdown": + skills.replace_markdown(uuid.uuid4(), "/does/not/exist/SKILL.md") + else: + skills.replace_folder(uuid.uuid4(), "/does/not/exist") + assert client.calls == [] + + def _skill_response() -> dict[str, Any]: now = datetime.now(tz=UTC).isoformat() return { diff --git a/src/asaree/api/experiments.py b/src/asaree/api/experiments.py index 223c8386..9c00d46f 100644 --- a/src/asaree/api/experiments.py +++ b/src/asaree/api/experiments.py @@ -39,6 +39,7 @@ from asaree.services.experiment_run_results import RunResultsProjectionError, summarize_experiment_run_results from asaree.services.experiments import ( create_experiment, + create_experiment_with_available_name, create_untitled_experiment, delete_experiment, get_dataset_ids_by_experiment, @@ -68,7 +69,7 @@ validate_metric_values, ) from asaree.services.protocol_graph_schema import normalize_protocol_graph -from asaree.services.protocol_revisions import get_published_revision, is_draft_published, publish_protocol +from asaree.services.protocol_revisions import get_published_revision, is_draft_published from asaree.services.protocol_runs import list_experiment_trials from asaree.services.protocols import ( create_protocol, @@ -516,8 +517,6 @@ async def import_experiment_definition_endpoint( name = body.name.strip() if not name: raise HTTPException(status_code=422, detail="Experiment name cannot be empty") - if await get_experiment_by_name(db, name, owner_id=user.id) is not None: - raise HTTPException(status_code=409, detail="An experiment with this name already exists") if not isinstance(body.graph.get("nodes"), list) or not isinstance(body.graph.get("edges"), list): raise HTTPException(status_code=422, detail="The imported definition must contain a graph with nodes and edges") if body.published_graph is not None and ( @@ -527,69 +526,30 @@ async def import_experiment_definition_endpoint( raise HTTPException(status_code=422, detail="The imported published canvas must contain nodes and edges") graph = normalize_protocol_graph(body.graph) - published_graph = normalize_protocol_graph(body.published_graph) if body.published_graph is not None else None servers = await mcp_service.list_servers(owner_id=user.id) - server_ids_by_name = {str(server.name): str(server.id) for server in servers} - if published_graph is None: - graph, measurement_plan = _localize_imported_mcp_references(graph, body.measurement_plan, server_ids_by_name) - else: - graph, _ = _localize_imported_mcp_references(graph, None, server_ids_by_name) - published_graph, measurement_plan = _localize_imported_mcp_references( - published_graph, body.measurement_plan, server_ids_by_name - ) + from asaree.services.package_connections import service_identity + + server_ids_by_name = {str(server.name): str(server.id) for server in servers if service_identity(server)} + graph, measurement_plan = _localize_imported_mcp_references(graph, body.measurement_plan, server_ids_by_name) try: design_spec = normalize_design_spec(body.design_spec, validate_metrics=True) except ValueError as exc: raise HTTPException(status_code=422, detail=str(exc)) from exc - # Do not attach source dataset IDs here. They refer to source-workspace - # artifacts and may not exist for this owner. MCP references are different: - # server names are portable, so matching visible registrations above replace - # source-install UUIDs before measurement-plan validation. + # JSON has no asset bytes. Preserve its definition as an editable draft; + # only trusted built-ins can be matched automatically in the destination. try: - # The lookup above gives the dialog its friendly suggested name. This - # savepoint covers the unavoidable race where another tab takes it - # between that lookup and the insert, turning it back into a 409 for - # the client rather than an integrity-error 500. async with db.begin_nested(): - experiment = await create_experiment( - db, - name=name, - owner_id=user.id, - description=body.description, - design_type=body.design_type, - task_brief=body.task_brief, - design_spec=design_spec, - measurement_plan=measurement_plan, + experiment = await create_experiment_with_available_name( + db, name=name, owner_id=user.id, description=body.description, + hypothesis=body.hypothesis, + design_type=body.design_type, task_brief=body.task_brief, + design_spec=design_spec, measurement_plan=measurement_plan, ) - # `publish_protocol` can only freeze the protocol's current draft. - # Start from the source published snapshot when one exists, freeze - # it as the imported protocol's revision 1, then restore the - # source draft if it had unpublished edits. - protocol = await create_protocol( - db, - name=generated_protocol_name(experiment.name, experiment.id), - owner_id=user.id, - description=body.protocol_description, - experiment_id=experiment.id, - graph=published_graph or graph, - ) - if body.measurement_plan is not None: - await _require_valid_measurement_plan( - db, - document=experiment.measurement_plan, - metrics=(experiment.design_spec or {}).get("metrics"), - graph=published_graph or graph, - experiment_id=experiment.id, - owner_id=experiment.owner_id, - allow_preserved_bindings=False, - ) - if published_graph is not None: - await publish_protocol(db, protocol, owner_id=user.id) - if graph != published_graph: - protocol.graph = graph - await db.flush() + await create_protocol(db, name=generated_protocol_name(experiment.name, experiment.id), + owner_id=user.id, description=body.protocol_description, + experiment_id=experiment.id, graph=graph) except IntegrityError as exc: if "uq_research_experiments_owner_name" in str(exc.orig): raise HTTPException(status_code=409, detail="An experiment with this name already exists") from exc diff --git a/src/asaree/api/package_imports.py b/src/asaree/api/package_imports.py index 851b6891..659346a0 100644 --- a/src/asaree/api/package_imports.py +++ b/src/asaree/api/package_imports.py @@ -5,12 +5,15 @@ import hashlib import itertools import uuid +import zipfile from datetime import UTC, datetime, timedelta +from pathlib import PurePosixPath from typing import Any +from urllib.parse import quote import jwt from fastapi import APIRouter, HTTPException, Query, Request -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, StreamingResponse from pydantic import BaseModel, Field from sqlalchemy import func, select from sqlalchemy.dialects.postgresql import insert @@ -19,8 +22,8 @@ from asaree.deps import CurrentUser, DbSession from asaree.models.package_import import ImportedIdentity, PackageImport from asaree.services import package_imports as imports -from asaree.services.package_reconstruction import validate_local_dependencies -from asaree.services.package_validation import member_path, records +from asaree.services import package_source +from asaree.services.package_validation import member_path router = APIRouter(prefix='/experiment-package-imports', tags=['experiment-packages']) @@ -33,7 +36,7 @@ def payload(job: PackageImport) -> dict[str, Any]: result = {key: getattr(job, key) for key in ( 'id', 'status', 'sha256', 'preflight', 'progress', 'error', 'experiment_id', 'expires_at', 'configured_at', 'created_at')} - if job.preflight and job.status in {'awaiting_confirmation', 'completed'}: + if job.preflight and job.status == 'completed': token = jwt.encode({'type': 'package_import_source', 'job': str(job.id), 'sub': str(job.owner_id), 'exp': datetime.now(UTC) + timedelta(minutes=5)}, get_settings().auth_secret_key, algorithm='HS256') @@ -91,9 +94,9 @@ async def upload(identifier: uuid.UUID, request: Request, db: DbSession, user: C raise HTTPException(409, 'An upload or import is already processing this request') if job.status not in {'uploading', 'failed'} or job.preflight: raise HTTPException(409, 'Use retry for an inspected upload or create a distinct import request') - root = imports.directory(identifier) - root.mkdir(parents=True, exist_ok=True, mode=0o700) - temporary = root / 'archive.part' + archive = imports.archive_path(identifier) + archive.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + temporary = archive.with_suffix('.part') size, digest = 0, hashlib.sha256() try: with temporary.open('wb') as output: @@ -104,7 +107,7 @@ async def upload(identifier: uuid.UUID, request: Request, db: DbSession, user: C raise HTTPException(413, 'Compressed package exceeds configured upload limit') await asyncio.to_thread(output.write, block) digest.update(block) - temporary.replace(root / 'archive.tar.gz') + temporary.replace(archive) job = await owned(db, identifier, user.id, lock=True) if job.status == 'cancelled': raise HTTPException(409, 'Import cancelled') @@ -116,18 +119,6 @@ async def upload(identifier: uuid.UUID, request: Request, db: DbSession, user: C temporary.unlink(missing_ok=True) -@router.post('/{identifier}/confirm', status_code=202) -async def confirm(identifier: uuid.UUID, db: DbSession, user: CurrentUser) -> dict[str, Any]: - job = await owned(db, identifier, user.id, lock=True) - if job.status == 'awaiting_confirmation': - job.status = 'queued' - job.progress = {'phase': 'confirmed'} - elif job.status not in {'queued', 'activating', 'completed'}: - raise HTTPException(409, 'Inspect a valid preflight before confirmation') - await db.commit() - return payload(job) - - @router.post('/{identifier}/cancel') async def cancel(identifier: uuid.UUID, db: DbSession, user: CurrentUser) -> dict[str, Any]: job = await owned(db, identifier, user.id, lock=True) @@ -142,10 +133,9 @@ async def retry(identifier: uuid.UUID, db: DbSession, user: CurrentUser) -> dict job = await owned(db, identifier, user.id, lock=True) if job.status != 'failed' or job.expires_at <= datetime.now(UTC): raise HTTPException(409, 'Only an unexpired failed import can be retried') - if not (imports.directory(identifier) / 'archive.tar.gz').is_file(): + if not imports.archive_path(identifier).is_file(): raise HTTPException(409, 'Upload archive bytes first') - # A confirmed failure returns to preflight: user sees the same requirements - # again. Durable deterministic IDs prevent duplicates after interruption. + # Durable deterministic identities prevent duplicates after interruption. job.status, job.error = 'validating', None job.generation += 1 await db.commit() @@ -158,8 +148,8 @@ async def files(identifier: uuid.UUID, db: DbSession, user: CurrentUser, job = await owned(db, identifier, user.id) if not job.preflight or job.status in {'expired', 'cancelled'}: raise HTTPException(409, 'Source evidence unavailable') - index = imports.directory(identifier) / 'payload/files.jsonl' - items = list(itertools.islice(records(index, imports.limits()), offset, offset + limit + 1)) + items = list(itertools.islice(package_source.records(identifier, 'files.jsonl', imports.limits()), + offset, offset + limit + 1)) return {'items': items[:limit], 'next_offset': offset + limit if len(items) > limit else None} @@ -174,28 +164,37 @@ async def identities(identifier: uuid.UUID, db: DbSession, user: CurrentUser, 'provenance': row.provenance} for row in rows] -@router.get('/{identifier}/source', response_class=FileResponse) -async def source(identifier: uuid.UUID, db: DbSession, user: CurrentUser, path: str | None = None) -> FileResponse: +@router.get('/{identifier}/source', response_class=FileResponse, response_model=None) +async def source(identifier: uuid.UUID, db: DbSession, user: CurrentUser, + path: str | None = None) -> FileResponse | StreamingResponse: job = await owned(db, identifier, user.id) return source_response(job, path) -def source_response(job: PackageImport, path: str | None) -> FileResponse: +def source_response(job: PackageImport, path: str | None) -> FileResponse | StreamingResponse: if not job.preflight or job.status in {'expired', 'cancelled'}: raise HTTPException(409, 'Source evidence unavailable') - root = imports.directory(job.id) + target = imports.archive_path(job.id) + if not target.is_file(): + raise HTTPException(404, 'Source file unavailable') + headers = {'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff'} try: - target = root / 'payload' / member_path(path) if path else root / 'archive.tar.gz' + if path: + name = member_path(path) + with zipfile.ZipFile(target) as archive: + if name not in archive.namelist(): + raise HTTPException(404, 'Source file unavailable') + headers['Content-Disposition'] = "attachment; filename*=utf-8''" + quote(PurePosixPath(name).name, safe='') + return StreamingResponse(package_source.chunks(job.id, name), + media_type='application/octet-stream', headers=headers) except ValueError as exc: raise HTTPException(422, str(exc)) from exc - if not target.is_file(): - raise HTTPException(404, 'Source file unavailable') - return FileResponse(target, media_type='application/octet-stream', filename=target.name, - headers={'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff'}) + return FileResponse(target, filename='experiment-package.zip', media_type='application/zip', headers=headers) -@router.get('/{identifier}/download', response_class=FileResponse) -async def download(identifier: uuid.UUID, token: str, db: DbSession, path: str | None = None) -> FileResponse: +@router.get('/{identifier}/download', response_class=FileResponse, response_model=None) +async def download(identifier: uuid.UUID, token: str, db: DbSession, + path: str | None = None) -> FileResponse | StreamingResponse: try: claims = jwt.decode(token, get_settings().auth_secret_key, algorithms=['HS256']) if claims.get('type') != 'package_import_source' or claims.get('job') != str(identifier): @@ -206,11 +205,6 @@ async def download(identifier: uuid.UUID, token: str, db: DbSession, path: str | return source_response(await owned(db, identifier, owner_id), path) -class Configuration(BaseModel): - connections_configured: bool - dependencies_resolved: bool - - @router.get('/{identifier}/readiness') async def readiness(identifier: uuid.UUID, db: DbSession, user: CurrentUser) -> dict[str, Any]: from asaree.services.package_setup import setup_options @@ -241,19 +235,3 @@ async def select_destination(identifier: uuid.UUID, command: ConnectionSelection raise HTTPException(422, 'Choose an authorized compatible destination connection.') from exc await db.commit() return await setup_options(db, job) - - -@router.post('/{identifier}/configuration') -async def configuration( - identifier: uuid.UUID, command: Configuration, db: DbSession, user: CurrentUser, -) -> dict[str, Any]: - job = await owned(db, identifier, user.id, lock=True) - if job.status != 'completed' or not command.connections_configured or not command.dependencies_resolved: - raise HTTPException(409, 'Configure the editable draft and resolve dependencies before acknowledging') - try: - await validate_local_dependencies(db, job) - except ValueError as exc: - raise HTTPException(422, str(exc)) from exc - job.configured_at = datetime.now(UTC) - await db.commit() - return payload(job) diff --git a/src/asaree/api/protocols.py b/src/asaree/api/protocols.py index e8ba9426..16b8f452 100644 --- a/src/asaree/api/protocols.py +++ b/src/asaree/api/protocols.py @@ -418,14 +418,13 @@ async def create_protocol_endpoint(body: CreateProtocolRequest, user: CurrentUse if await get_protocol_by_name(db, body.name, owner_id=user.id) is not None: raise HTTPException(status_code=409, detail="A protocol with this name already exists") experiment_id = await _validated_experiment_id(body.experiment_id, db, user) - protocol = await create_protocol( - db, - name=body.name, - owner_id=user.id, - description=body.description, - experiment_id=experiment_id, - graph=body.graph, - ) + try: + protocol = await create_protocol( + db, name=body.name, owner_id=user.id, description=body.description, + experiment_id=experiment_id, graph=body.graph, + ) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc return await _protocol_response(db, protocol) @@ -459,7 +458,10 @@ async def update_protocol_endpoint( raise HTTPException(status_code=409, detail="A protocol with this name already exists") if "experiment_id" in fields: fields["experiment_id"] = await _validated_experiment_id(fields["experiment_id"], db, user) - protocol = await update_protocol(db, protocol_id, fields=fields) + try: + protocol = await update_protocol(db, protocol_id, fields=fields) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc assert protocol is not None # existence already checked above return await _protocol_response(db, protocol) diff --git a/src/asaree/api/result_jobs.py b/src/asaree/api/result_jobs.py index 428ab6c6..7422fa17 100644 --- a/src/asaree/api/result_jobs.py +++ b/src/asaree/api/result_jobs.py @@ -3,7 +3,7 @@ import uuid from dataclasses import replace from datetime import UTC, datetime -from typing import Any +from typing import Any, Literal from fastapi import APIRouter, HTTPException from fastapi.responses import FileResponse @@ -12,9 +12,11 @@ from asaree.api.result_reads import Scope from asaree.deps import CurrentUser, DbSession +from asaree.models.protocol import Protocol from asaree.models.protocol_revision import ProtocolRevision from asaree.models.result_job import ResultJob from asaree.services import result_exports, result_jobs +from asaree.services.experiments import get_experiment router = APIRouter(prefix="/experiments/{experiment_id}/execution-results/jobs", tags=["execution-results"]) @@ -28,7 +30,7 @@ class Command(BaseModel): rerun_slot_ids: list[uuid.UUID] = Field(default_factory=list, max_length=100) rerun_completed: bool = False format: str = Field(default="analysis_csv", pattern="^(analysis_csv|experiment_package)$") - include_results: bool = False + include_results: Literal[False] = False def payload(job: ResultJob) -> dict[str, Any]: @@ -182,11 +184,24 @@ async def download( or not path.is_file() ): raise HTTPException(status_code=410, detail="Export expired or unavailable; request a new export.") + if package: + experiment = await get_experiment(db, job.experiment_id) + if experiment is None or experiment.owner_id != owner: + raise HTTPException(status_code=404, detail="Experiment not found") + version = await db.scalar(select(ProtocolRevision.revision).join( + Protocol, ProtocolRevision.protocol_id == Protocol.id, + ).where( + ProtocolRevision.id == job.protocol_revision_id, Protocol.id == job.protocol_id, + Protocol.experiment_id == experiment_id, Protocol.owner_id == owner, + )) + if version is None: + raise HTTPException(status_code=404, detail="Published experiment version not found") + filename = result_exports.package_filename(experiment.name, version=version, metadata=metadata) + else: + filename = f"results-{job_id}.{'schema.json' if metadata else 'csv'}" return FileResponse( path, - media_type="application/json" if metadata else "application/gzip" if package else "text/csv", - filename=(f"experiment-{job.experiment_id}-version-{job.protocol_revision_id}." - f"{'manifest.json' if metadata else 'tar.gz'}" if package else - f"results-{job_id}.{'schema.json' if metadata else 'csv'}"), + media_type="application/json" if metadata else "application/zip" if package else "text/csv", + filename=filename, headers={"Cache-Control": "private, no-store"}, ) diff --git a/src/asaree/api/runs.py b/src/asaree/api/runs.py index 836de388..b934004a 100644 --- a/src/asaree/api/runs.py +++ b/src/asaree/api/runs.py @@ -28,6 +28,7 @@ from pydantic import BaseModel from asaree.deps import CurrentUser +from asaree.services.skill_references import SkillUnavailableError, protect_agent_run from asaree.worker.enqueue import enqueue_run router = APIRouter(prefix="/runs", tags=["runs"]) @@ -103,15 +104,15 @@ async def create_run_endpoint(body: CreateRunRequest, user: CurrentUser) -> RunR if agent is None or agent.owner_id != user.id: raise HTTPException(status_code=404, detail="No such agent") - run = await create_run( - agent_id=body.agent_id, - user_input=body.user_input, - pattern_overrides=body.pattern_overrides, - owner_id=user.id, - metadata=body.metadata, - model_config_overrides=body.model_config_override, - ) - await enqueue_run(run.id) + try: + async with protect_agent_run(agent, user.id): + run = await create_run( + agent_id=body.agent_id, user_input=body.user_input, pattern_overrides=body.pattern_overrides, + owner_id=user.id, metadata=body.metadata, model_config_overrides=body.model_config_override, + ) + await enqueue_run(run.id) + except SkillUnavailableError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc return _to_response(run) diff --git a/src/asaree/api/skills.py b/src/asaree/api/skills.py index d6bfe1c5..5af26c74 100644 --- a/src/asaree/api/skills.py +++ b/src/asaree/api/skills.py @@ -46,9 +46,10 @@ from pydantic import BaseModel, Field from sqlalchemy.exc import IntegrityError -from asaree.deps import CurrentUser +from asaree.deps import CurrentUser, DbSession from asaree.services import skill_sources from asaree.services.import_visibility import active_resources, resource_active +from asaree.services.skill_references import IMMUTABLE_MESSAGE, SkillInUseError, delete_registered_skill from asaree.services.skill_sources import SkillSourceError router = APIRouter(prefix="/skills", tags=["skills"]) @@ -183,22 +184,11 @@ async def replace_skill_folder_endpoint( user: CurrentUser, files: Annotated[list[UploadFile], File()], ) -> SkillResponse: - """Replace a skill's whole directory from a re-uploaded folder. - - A replacement, not a merge — a re-upload that drops ``FORMS.md`` drops it, - because the alternative leaves the skill holding a document its own - ``SKILL.md`` no longer mentions. - """ + """Compatibility route: registered skills cannot be replaced in ASAREE.""" existing = await skill_service.get_skill(skill_id) if existing is None or existing.owner_id != user.id or not await resource_active(skill_id): raise HTTPException(status_code=404, detail="No such skill") - payload = await _folder_payload(files) - try: - skill = await skill_service.update_skill_from_bundle(skill_id, payload) - except (SkillFormatError, IntegrityError) as exc: - _raise_skill_write_http_error(exc) - assert skill is not None - return SkillResponse.model_validate(skill) + raise HTTPException(status_code=409, detail=IMMUTABLE_MESSAGE) class SkillUrlRequest(BaseModel): @@ -301,9 +291,8 @@ async def get_skill_endpoint(skill_id: uuid.UUID, user: CurrentUser) -> SkillRes async def get_skill_markdown_endpoint(skill_id: uuid.UUID, user: CurrentUser) -> dict[str, str]: """The skill rendered back out as a ``SKILL.md`` document. - So the file a user uploaded is also the thing they can read, edit, and - re-upload — the stored row is a parse of that document, not a replacement - for it. + The result can be downloaded or used to register a new skill. Existing + registrations cannot be edited or replaced through ASAREE. """ skill = await skill_service.get_skill(skill_id) if skill is None or not _readable(skill, user) or not await resource_active(skill_id): @@ -313,15 +302,11 @@ async def get_skill_markdown_endpoint(skill_id: uuid.UUID, user: CurrentUser) -> @router.patch("/{skill_id}", response_model=SkillResponse) async def update_skill_endpoint(skill_id: uuid.UUID, body: SkillUpdate, user: CurrentUser) -> SkillResponse: + """Compatibility route: register a new skill instead of updating content.""" existing = await skill_service.get_skill(skill_id) if existing is None or existing.owner_id != user.id or not await resource_active(skill_id): raise HTTPException(status_code=404, detail="No such skill") - try: - skill = await skill_service.update_skill(skill_id, name=body.name, description=body.description, body=body.body) - except (SkillFormatError, IntegrityError) as exc: - _raise_skill_write_http_error(exc) - assert skill is not None # existence already checked above - return SkillResponse.model_validate(skill) + raise HTTPException(status_code=409, detail=IMMUTABLE_MESSAGE) @router.put("/{skill_id}/markdown", response_model=SkillResponse) @@ -330,21 +315,21 @@ async def replace_skill_markdown_endpoint( user: CurrentUser, file: Annotated[UploadFile, File()], ) -> SkillResponse: - """Replace a skill's contents from a re-uploaded ``SKILL.md``.""" + """Compatibility route: registered skills cannot be replaced in ASAREE.""" existing = await skill_service.get_skill(skill_id) if existing is None or existing.owner_id != user.id or not await resource_active(skill_id): raise HTTPException(status_code=404, detail="No such skill") - try: - skill = await skill_service.update_skill_from_markdown(skill_id, _decode(await file.read())) - except (SkillFormatError, IntegrityError) as exc: - _raise_skill_write_http_error(exc) - assert skill is not None - return SkillResponse.model_validate(skill) + raise HTTPException(status_code=409, detail=IMMUTABLE_MESSAGE) @router.delete("/{skill_id}", status_code=204) -async def delete_skill_endpoint(skill_id: uuid.UUID, user: CurrentUser) -> None: +async def delete_skill_endpoint(skill_id: uuid.UUID, user: CurrentUser, db: DbSession) -> None: existing = await skill_service.get_skill(skill_id) if existing is None or existing.owner_id != user.id or not await resource_active(skill_id): raise HTTPException(status_code=404, detail="No such skill") - await skill_service.delete_skill(skill_id) + try: + deleted = await delete_registered_skill(db, skill_id, user.id) + except SkillInUseError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + if not deleted: + raise HTTPException(status_code=404, detail="No such skill") diff --git a/src/asaree/migrations/env.py b/src/asaree/migrations/env.py index 53df2a03..48547373 100644 --- a/src/asaree/migrations/env.py +++ b/src/asaree/migrations/env.py @@ -38,6 +38,7 @@ import asaree.models.protocol_run # noqa: F401 import asaree.models.result_job # noqa: F401 import asaree.models.result_read_model # noqa: F401 +import asaree.models.skill_reference # noqa: F401 import asaree.models.stats_analysis # noqa: F401 import asaree.models.user # noqa: F401 import asaree.models.user_api_token # noqa: F401 diff --git a/src/asaree/migrations/versions/e12a34b56c78_skill_references.py b/src/asaree/migrations/versions/e12a34b56c78_skill_references.py new file mode 100644 index 00000000..ae2c0f8c --- /dev/null +++ b/src/asaree/migrations/versions/e12a34b56c78_skill_references.py @@ -0,0 +1,223 @@ +"""Retain registered skills across ASAREE drafts, publications, designs and runs. + +The ledger is database-maintained so imports and cascade deletion obey the same +rules as interactive writes. No skill content is copied into ASAREE. +""" + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql as pg + +revision = "e12a34b56c78" +down_revision = "d90e1f2a3b4c" +branch_labels = None +depends_on = None + +SCOPES = {"protocol": "protocols", "publication": "protocol_revisions", "run": "protocol_runs", + "experiment": "research_experiments", "design": "experiment_design_revisions"} + + +def upgrade() -> None: + op.create_table("skill_references", + sa.Column("id", pg.UUID(), primary_key=True), + sa.Column("skill_id", pg.UUID(), nullable=False), + *(sa.Column(f"{scope}_id", pg.UUID(), sa.ForeignKey(f"{table}.id", ondelete="CASCADE")) + for scope, table in SCOPES.items()), + sa.CheckConstraint("num_nonnulls(protocol_id, publication_id, run_id, experiment_id, design_id) = 1", + name="ck_skill_reference_scope"), if_not_exists=True) + op.create_index("ix_skill_references_skill_id", "skill_references", ["skill_id"], if_not_exists=True) + for scope in SCOPES: + op.create_index(f"uq_skill_reference_{scope}", "skill_references", [f"{scope}_id", "skill_id"], + unique=True, if_not_exists=True) + op.execute(""" + CREATE OR REPLACE FUNCTION asaree_skill_uuid(value text) RETURNS uuid + LANGUAGE plpgsql IMMUTABLE AS $$ BEGIN + RETURN value::uuid; + EXCEPTION WHEN invalid_text_representation THEN RETURN NULL; END $$ + """) + op.execute(""" + CREATE OR REPLACE FUNCTION asaree_skill_array(value jsonb) RETURNS jsonb + LANGUAGE sql IMMUTABLE AS $$ + SELECT CASE WHEN jsonb_typeof(value)='array' THEN value ELSE '[]'::jsonb END + $$ + """) + op.execute(""" + CREATE OR REPLACE FUNCTION asaree_skill_design(current_spec jsonb, locked_spec jsonb) RETURNS jsonb + LANGUAGE sql IMMUTABLE AS $$ + SELECT jsonb_build_object('factors', asaree_skill_array(current_spec->'factors') || + asaree_skill_array(locked_spec->'factors')) + $$ + """) + op.execute(""" + CREATE OR REPLACE FUNCTION asaree_skill_ids(graph jsonb, design jsonb) RETURNS uuid[] + LANGUAGE sql IMMUTABLE AS $$ + WITH nodes AS (SELECT value AS n FROM jsonb_array_elements(asaree_skill_array(graph->'nodes'))), + bindings AS ( + SELECT n#>>'{data,factor_bindings,config}' AS name FROM nodes WHERE n->>'type'='skill' + UNION SELECT n#>>'{data,factor_bindings,config.skill_id}' FROM nodes WHERE n->>'type'='skill' + UNION SELECT n#>>'{data,factor_bindings,skill_selection}' FROM nodes + ), levels AS ( + SELECT level FROM jsonb_array_elements(asaree_skill_array(design->'factors')) AS factor, + LATERAL jsonb_array_elements(asaree_skill_array(factor->'levels')) AS level + WHERE factor->>'level_type' IN ('skill_selection','skill_toggle','skill_config') + OR factor->>'name' IN (SELECT name FROM bindings WHERE name IS NOT NULL) + ), candidates AS ( + SELECT n#>>'{data,config,skill_id}' AS value FROM nodes WHERE n->>'type'='skill' + UNION SELECT choice#>>'{}' FROM nodes, + LATERAL jsonb_array_elements(asaree_skill_array(n#>'{data,skill_selection}')) choice + UNION SELECT CASE WHEN jsonb_typeof(level)='string' THEN level#>>'{}' + WHEN jsonb_typeof(level)='object' THEN level->>'skill_id' END FROM levels + UNION SELECT choice#>>'{}' FROM levels, + LATERAL jsonb_array_elements(asaree_skill_array(level)) choice + ) SELECT coalesce(array_agg(DISTINCT asaree_skill_uuid(value)) + FILTER (WHERE asaree_skill_uuid(value) IS NOT NULL), ARRAY[]::uuid[]) FROM candidates + $$ + """) + op.execute(""" + CREATE OR REPLACE FUNCTION asaree_skill_factor_graph(graph jsonb) RETURNS jsonb + LANGUAGE sql IMMUTABLE AS $$ + SELECT jsonb_build_object('nodes', coalesce(jsonb_agg(jsonb_build_object( + 'type', n->'type', 'data', jsonb_build_object('factor_bindings', n#>'{data,factor_bindings}'))), '[]'::jsonb)) + FROM jsonb_array_elements(asaree_skill_array(graph->'nodes')) n + $$ + """) + op.execute(""" + CREATE OR REPLACE FUNCTION asaree_skill_run_ids(graph jsonb, design jsonb, choices jsonb) RETURNS uuid[] + LANGUAGE sql IMMUTABLE AS $$ + SELECT asaree_skill_ids(graph, jsonb_build_object('factors', + asaree_skill_array(design->'factors') || coalesce(( + SELECT jsonb_agg(jsonb_build_object('name', key, 'levels', jsonb_build_array(value))) + FROM jsonb_each(CASE WHEN jsonb_typeof(choices)='object' THEN choices ELSE '{}'::jsonb END) + ), '[]'::jsonb))) + $$ + """) + op.execute(""" + CREATE OR REPLACE FUNCTION asaree_skill_projection(graph jsonb) RETURNS jsonb + LANGUAGE sql IMMUTABLE AS $$ + SELECT coalesce(jsonb_agg(jsonb_build_array(n->>'id', n->>'type', + CASE WHEN n->>'type'='skill' THEN n#>'{data,config,skill_id}' END, + n#>'{data,skill_selection}', n#>'{data,factor_bindings,config}', + n#>'{data,factor_bindings,config.skill_id}', n#>'{data,factor_bindings,skill_selection}') + ORDER BY n->>'id'), '[]'::jsonb) + FROM jsonb_array_elements(asaree_skill_array(graph->'nodes')) n + WHERE n->>'type'='skill' OR n#>'{data,skill_selection}' IS NOT NULL + OR n#>'{data,factor_bindings,skill_selection}' IS NOT NULL + $$ + """) + op.execute(""" + CREATE OR REPLACE FUNCTION asaree_retain_skill_ids(scope text, parent uuid, desired uuid[]) RETURNS void + LANGUAGE plpgsql AS $$ DECLARE identifier uuid; existing uuid[]; column_name text; + BEGIN + IF scope NOT IN ('protocol','publication','run','experiment','design') THEN + RAISE EXCEPTION 'Invalid skill reference scope'; + END IF; + column_name := scope || '_id'; + EXECUTE format('SELECT coalesce(array_agg(skill_id), ARRAY[]::uuid[]) FROM skill_references WHERE %I=$1', + column_name) INTO existing USING parent; + -- Attachment and ASAREE deletion use the same transaction locks in this + -- database, even though the registered payload lives in Motoro's database. + FOR identifier IN SELECT value FROM unnest(desired) value + WHERE NOT value=ANY(existing) ORDER BY value LOOP + PERFORM pg_advisory_xact_lock(1936419180, hashtext(identifier::text)); + END LOOP; + EXECUTE format('INSERT INTO skill_references(id, skill_id, %I) + SELECT gen_random_uuid(), value, $1 FROM unnest($2::uuid[]) value ON CONFLICT DO NOTHING', column_name) + USING parent, desired; + EXECUTE format('DELETE FROM skill_references WHERE %I=$1 AND NOT skill_id=ANY($2::uuid[])', column_name) + USING parent, desired; + END $$ + """) + op.execute(""" + CREATE OR REPLACE FUNCTION asaree_refresh_skill_references() RETURNS trigger LANGUAGE plpgsql AS $$ + DECLARE graph jsonb := '{}'::jsonb; design jsonb := '{}'::jsonb; item record; + BEGIN + IF TG_TABLE_NAME='protocols' THEN + IF TG_OP='UPDATE' AND NEW.experiment_id IS NOT DISTINCT FROM OLD.experiment_id + AND asaree_skill_projection(NEW.graph)=asaree_skill_projection(OLD.graph) THEN RETURN NEW; END IF; + -- Serialize legacy bindings against edits to their experiment's levels. + SELECT asaree_skill_design(design_spec, locked_design_spec) INTO design + FROM research_experiments WHERE id=NEW.experiment_id FOR NO KEY UPDATE; + PERFORM asaree_retain_skill_ids('protocol', NEW.id, asaree_skill_ids(NEW.graph, design)); + ELSIF TG_TABLE_NAME='research_experiments' THEN + IF TG_OP='UPDATE' AND NEW.design_spec IS NOT DISTINCT FROM OLD.design_spec + AND NEW.locked_design_spec IS NOT DISTINCT FROM OLD.locked_design_spec THEN RETURN NEW; END IF; + design := asaree_skill_design(NEW.design_spec, NEW.locked_design_spec); + PERFORM asaree_retain_skill_ids('experiment', NEW.id, asaree_skill_ids(graph, design)); + FOR item IN SELECT id, p.graph FROM protocols p WHERE experiment_id=NEW.id LOOP + PERFORM asaree_retain_skill_ids('protocol', item.id, asaree_skill_ids(item.graph, design)); + END LOOP; + ELSIF TG_TABLE_NAME='protocol_revisions' THEN + PERFORM asaree_retain_skill_ids('publication', NEW.id, + asaree_skill_ids(NEW.graph, coalesce(NEW.experiment_snapshot->'design_spec', + (SELECT design_spec FROM experiment_design_revisions WHERE id=NEW.design_revision_id)))); + ELSIF TG_TABLE_NAME='experiment_design_revisions' THEN + PERFORM id FROM research_experiments WHERE id=NEW.experiment_id FOR NO KEY UPDATE; + SELECT jsonb_build_object('nodes', coalesce(jsonb_agg(n), '[]'::jsonb)) INTO graph + FROM protocols p, LATERAL jsonb_array_elements(asaree_skill_array(p.graph->'nodes')) n + WHERE p.experiment_id=NEW.experiment_id; + PERFORM asaree_retain_skill_ids('design', NEW.id, + asaree_skill_ids(asaree_skill_factor_graph(graph), NEW.design_spec)); + ELSIF TG_TABLE_NAME='protocol_runs' THEN + SELECT p.graph, coalesce(p.experiment_snapshot->'design_spec', d.design_spec) INTO graph, design + FROM protocol_revisions p LEFT JOIN experiment_design_revisions d ON d.id=p.design_revision_id + WHERE p.id=NEW.protocol_revision_id; + IF graph IS NULL THEN + SELECT p.graph, asaree_skill_design(e.design_spec, e.locked_design_spec) INTO graph, design FROM protocols p + LEFT JOIN research_experiments e ON e.id=p.experiment_id WHERE p.id=NEW.protocol_id; + END IF; + PERFORM asaree_retain_skill_ids('run', NEW.id, asaree_skill_run_ids(graph, design, NEW.factor_values)); + END IF; + RETURN NEW; + END $$ + """) + for table, updates in (("protocols", "graph, experiment_id"), + ("research_experiments", "design_spec, locked_design_spec"), + ("experiment_design_revisions", "design_spec")): + op.execute(f"DROP TRIGGER IF EXISTS retain_registered_skills ON {table}") + op.execute(f"CREATE TRIGGER retain_registered_skills AFTER INSERT OR UPDATE OF {updates} ON {table} " + "FOR EACH ROW EXECUTE FUNCTION asaree_refresh_skill_references()") + for table in ("protocol_revisions", "protocol_runs"): + op.execute(f"DROP TRIGGER IF EXISTS retain_registered_skills ON {table}") + op.execute(f"CREATE TRIGGER retain_registered_skills AFTER INSERT ON {table} " + "FOR EACH ROW EXECUTE FUNCTION asaree_refresh_skill_references()") + # Backfill identities even when a source has already been deleted. Audit + # against Motoro separately; never invent or rewrite historical content. + op.execute("""SELECT asaree_retain_skill_ids('experiment', id, + asaree_skill_ids('{}', asaree_skill_design(design_spec, locked_design_spec))) + FROM research_experiments""") + op.execute("""SELECT asaree_retain_skill_ids('protocol', p.id, + asaree_skill_ids(p.graph, asaree_skill_design(e.design_spec, e.locked_design_spec))) + FROM protocols p LEFT JOIN research_experiments e ON e.id=p.experiment_id""") + op.execute("""SELECT asaree_retain_skill_ids('publication', id, + asaree_skill_ids(graph, coalesce(experiment_snapshot->'design_spec', + (SELECT design_spec FROM experiment_design_revisions WHERE id=design_revision_id)))) + FROM protocol_revisions""") + op.execute("""SELECT asaree_retain_skill_ids('design', d.id, asaree_skill_ids( + asaree_skill_factor_graph((SELECT jsonb_build_object('nodes', + coalesce(jsonb_agg(n), '[]'::jsonb)) FROM ( + SELECT p.graph FROM protocols p WHERE p.experiment_id=d.experiment_id + UNION ALL SELECT v.graph FROM protocol_revisions v WHERE v.design_revision_id=d.id + ) sources, LATERAL jsonb_array_elements(asaree_skill_array(sources.graph->'nodes')) n)), + d.design_spec)) FROM experiment_design_revisions d""") + op.execute("""SELECT asaree_retain_skill_ids('run', r.id, + asaree_skill_run_ids(coalesce(v.graph,p.graph), + CASE WHEN v.id IS NOT NULL THEN coalesce(v.experiment_snapshot->'design_spec', d.design_spec) + ELSE asaree_skill_design(e.design_spec, e.locked_design_spec) END, r.factor_values)) + FROM protocol_runs r LEFT JOIN protocol_revisions v ON v.id=r.protocol_revision_id + LEFT JOIN experiment_design_revisions d ON d.id=v.design_revision_id + JOIN protocols p ON p.id=r.protocol_id LEFT JOIN research_experiments e ON e.id=p.experiment_id""") + + +def downgrade() -> None: + for table in SCOPES.values(): + op.execute(f"DROP TRIGGER IF EXISTS retain_registered_skills ON {table}") + op.execute("DROP FUNCTION IF EXISTS asaree_refresh_skill_references()") + op.execute("DROP FUNCTION IF EXISTS asaree_retain_skill_ids(text, uuid, uuid[])") + op.execute("DROP FUNCTION IF EXISTS asaree_skill_projection(jsonb)") + op.execute("DROP FUNCTION IF EXISTS asaree_skill_run_ids(jsonb, jsonb, jsonb)") + op.execute("DROP FUNCTION IF EXISTS asaree_skill_factor_graph(jsonb)") + op.execute("DROP FUNCTION IF EXISTS asaree_skill_ids(jsonb, jsonb)") + op.execute("DROP FUNCTION IF EXISTS asaree_skill_design(jsonb, jsonb)") + op.execute("DROP FUNCTION IF EXISTS asaree_skill_array(jsonb)") + op.execute("DROP FUNCTION IF EXISTS asaree_skill_uuid(text)") + op.drop_table("skill_references", if_exists=True) diff --git a/src/asaree/models/__init__.py b/src/asaree/models/__init__.py index 6ecf2f06..dffc646a 100644 --- a/src/asaree/models/__init__.py +++ b/src/asaree/models/__init__.py @@ -2,3 +2,4 @@ from asaree.models.dataset_row_index import DatasetIndexedRow, DatasetRowIndex # noqa: F401 from asaree.models.factorial_row_result import FactorialRowResult # noqa: F401 +from asaree.models.skill_reference import SkillReference # noqa: F401 diff --git a/src/asaree/models/skill_reference.py b/src/asaree/models/skill_reference.py new file mode 100644 index 00000000..aaac3227 --- /dev/null +++ b/src/asaree/models/skill_reference.py @@ -0,0 +1,31 @@ +"""ASAREE retention of registered Motoro skill identities, without content copies.""" + +from __future__ import annotations + +import uuid + +from sqlalchemy import CheckConstraint, ForeignKey, Index +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import Mapped, mapped_column + +from asaree.models.base import Base, generate_uuid + + +class SkillReference(Base): + __tablename__ = "skill_references" + __table_args__ = ( + CheckConstraint("num_nonnulls(protocol_id, publication_id, run_id, experiment_id, design_id) = 1", + name="ck_skill_reference_scope"), + *(Index(f"uq_skill_reference_{scope}", f"{scope}_id", "skill_id", unique=True) + for scope in ("protocol", "publication", "run", "experiment", "design")), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=generate_uuid) + # Motoro is a separate database; this deliberately is not a foreign key. + skill_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False, index=True) + protocol_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("protocols.id", ondelete="CASCADE")) + publication_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("protocol_revisions.id", ondelete="CASCADE")) + run_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("protocol_runs.id", ondelete="CASCADE")) + experiment_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("research_experiments.id", ondelete="CASCADE")) + design_id: Mapped[uuid.UUID | None] = mapped_column( + ForeignKey("experiment_design_revisions.id", ondelete="CASCADE")) diff --git a/src/asaree/services/datasets.py b/src/asaree/services/datasets.py index 5eccb604..9dd0d5d9 100644 --- a/src/asaree/services/datasets.py +++ b/src/asaree/services/datasets.py @@ -70,6 +70,11 @@ def _dataset_dir(dataset_id: uuid.UUID) -> Path: return Path(get_settings().dataset_storage_dir).resolve() / str(dataset_id) +def discard_registration_files(dataset_id: uuid.UUID) -> None: + """Remove files owned by a discarded registration; the caller checks ownership.""" + shutil.rmtree(_dataset_dir(dataset_id), ignore_errors=True) + + def _artifact(dataset_id: uuid.UUID, path: Path, format: str) -> DatasetArtifact: return DatasetArtifact( id=uuid.uuid4(), dataset_id=dataset_id, namespace="datasets", @@ -91,10 +96,22 @@ def _verify_source(dataset: RegisteredDataset) -> str: return raw_path -async def _publish_split( - db: AsyncSession, dataset: RegisteredDataset, train: pd.DataFrame, test: pd.DataFrame, **provenance: object +async def register_dataset_split( + db: AsyncSession, dataset: RegisteredDataset, train: pd.DataFrame | Path, test: pd.DataFrame | Path, + *, identifier: uuid.UUID | None = None, **provenance: object, ) -> RegisteredDataset: - split_id = uuid.uuid4() + """Store and register a partition pair in the ordinary dataset layout. + + Uploaded/generated frames are serialized normally. Verified Parquet inputs + are validated and copied verbatim, preserving their immutable source bytes. + """ + for role, source in (('train', train), ('test', test)): + if isinstance(source, Path): + try: + pd.read_parquet(source) + except (OSError, ValueError) as exc: + raise DatasetValidationError(f'Could not read the {role} partition: {exc}') from exc + split_id = identifier or uuid.uuid4() parent = _dataset_dir(dataset.id) / "splits" parent.mkdir(parents=True, exist_ok=True) staging = parent / f".{split_id}.preparing" @@ -102,18 +119,19 @@ async def _publish_split( staging.mkdir() published = False try: - train.to_parquet(staging / "train.parquet", index=False) - test.to_parquet(staging / "test.parquet", index=False) + for role, source in (('train', train), ('test', test)): + if isinstance(source, Path): + shutil.copyfile(source, staging / f'{role}.parquet') + else: + source.to_parquet(staging / f'{role}.parquet', index=False) # The directory rename publishes the complete pair; no reader sees a half pair. os.rename(staging, dest) published = True train_artifact = _artifact(dataset.id, dest / "train.parquet", "parquet") test_artifact = _artifact(dataset.id, dest / "test.parquet", "parquet") async with db.begin_nested(): - split = DatasetSplit( - id=split_id, dataset_id=dataset.id, source_sha256=dataset.raw_sha256, - train_artifact=train_artifact, test_artifact=test_artifact, **provenance, - ) + split = DatasetSplit(id=split_id, dataset_id=dataset.id, source_sha256=dataset.raw_sha256, + train_artifact=train_artifact, test_artifact=test_artifact, **provenance) db.add(split) await db.flush() dataset.current_split = split @@ -169,6 +187,7 @@ async def create_dataset( target_column: str | None = None, description: str | None = None, dictionary_json: str | None = None, + identifier: uuid.UUID | None = None, ) -> RegisteredDataset: try: df = pd.read_csv(io.BytesIO(csv_bytes)) @@ -177,14 +196,14 @@ async def create_dataset( if target_column and target_column not in df.columns: raise DatasetValidationError(f"target_column '{target_column}' is not a column in this CSV") - dataset_id = uuid.uuid4() + dataset_id = identifier or uuid.uuid4() dest = _dataset_dir(dataset_id) dest.mkdir(parents=True, exist_ok=True) raw_path = dest / "raw.csv" try: atomic_write(raw_path, csv_bytes) except Exception: - shutil.rmtree(dest, ignore_errors=True) + discard_registration_files(dataset_id) raise dataset = RegisteredDataset( @@ -202,7 +221,7 @@ async def create_dataset( dataset.raw_artifact = _artifact(dataset_id, raw_path, "csv") await db.flush() except IntegrityError as exc: - shutil.rmtree(dest, ignore_errors=True) + discard_registration_files(dataset_id) raise DatasetNameConflictError(f"Dataset name '{name}' is already in use") from exc await db.refresh(dataset) return dataset @@ -237,7 +256,7 @@ async def quick_split_dataset( except ValueError as exc: raise DatasetValidationError(str(exc)) from exc - return await _publish_split( + return await register_dataset_split( db, dataset, train_df, test_df, method="quick", target_column=effective_target, strategy="group_shuffle" if used_group_column else "stratified" if effective_target else "random", group_column=used_group_column, stratify_column=None if used_group_column else effective_target, @@ -273,7 +292,8 @@ async def register_manual_split( raise DatasetValidationError(f"could not parse the test CSV: {exc}") from exc # Association records the supplied origin, without claiming source-row membership. - return await _publish_split(db, dataset, train_df, test_df, method="manual", target_column=dataset.target_column) + return await register_dataset_split(db, dataset, train_df, test_df, + method="manual", target_column=dataset.target_column) async def get_dataset(db: AsyncSession, dataset_id: uuid.UUID) -> RegisteredDataset | None: @@ -340,5 +360,5 @@ async def delete_dataset(db: AsyncSession, dataset_id: uuid.UUID) -> bool: raise DatasetValidationError("Dataset is referenced by a retained workspace and cannot be deleted") await db.delete(dataset) await db.flush() - shutil.rmtree(Path(get_settings().dataset_storage_dir) / str(dataset_id), ignore_errors=True) + discard_registration_files(dataset_id) return True diff --git a/src/asaree/services/design_generation.py b/src/asaree/services/design_generation.py index 8730c7e7..8a8ef720 100644 --- a/src/asaree/services/design_generation.py +++ b/src/asaree/services/design_generation.py @@ -556,6 +556,9 @@ async def generate_design_cells( if current.design_spec != design_spec: current.design_spec = design_spec await db.flush() + from asaree.services.skill_references import validate_references + + await validate_references(db, experiment.owner_id, design_id=current.id) else: revision = await supersede_and_create(db, experiment_id=experiment_id, design_spec=design_spec) revision_id = revision.id diff --git a/src/asaree/services/design_revisions.py b/src/asaree/services/design_revisions.py index 694a6254..8938459c 100644 --- a/src/asaree/services/design_revisions.py +++ b/src/asaree/services/design_revisions.py @@ -122,6 +122,11 @@ async def _create_revision( ) db.add(revision) await db.flush() + from asaree.services.skill_references import validate_references + + experiment = await db.get(ResearchExperiment, experiment_id) + if experiment is not None and (design_spec or {}).get("factors"): + await validate_references(db, experiment.owner_id, design_id=revision.id) await db.refresh(revision) return revision diff --git a/src/asaree/services/experiment_packages.py b/src/asaree/services/experiment_packages.py index 4bea642e..edf36ff1 100644 --- a/src/asaree/services/experiment_packages.py +++ b/src/asaree/services/experiment_packages.py @@ -1,25 +1,24 @@ """Portable logical publication exports, never workspace backups or resume images. Inventories live in JSONL files, not lists. Database evidence is sliced in SQL; -tar member objects are discarded after writing. Only schema-owned locators are -interpreted. Prompts, scripts, dataset values and result payloads remain opaque. +file contents stream in chunks, while ZIP retains per-entry directory metadata. +Only schema-owned locators are interpreted. Prompts, scripts, dataset values and +result payloads remain opaque. """ from __future__ import annotations import asyncio import base64 -import gzip import hashlib import importlib.metadata import json import os -import re import stat -import tarfile import tempfile import threading import time import uuid +import zipfile from collections.abc import Iterator from contextlib import suppress from copy import deepcopy @@ -31,7 +30,7 @@ from motoro.models.mcp_server import MCPServerConfig from motoro.models.skill import Skill, SkillFile from motoro.services.skill_service import render_skill_md -from sqlalchemy import Text, cast, func, select, update +from sqlalchemy import select, update from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import noload @@ -41,19 +40,15 @@ from asaree.models.dataset import RegisteredDataset from asaree.models.dataset_split import DatasetArtifact, DatasetSplit from asaree.models.experiment import ResearchExperiment -from asaree.models.experiment_artifact import ExperimentArtifact from asaree.models.experiment_design_revision import ExperimentDesignRevision from asaree.models.factorial_cell import FactorialCell from asaree.models.factorial_replicate_result import FactorialReplicateResult -from asaree.models.factorial_row_result import FactorialRowResult from asaree.models.protocol import Protocol from asaree.models.protocol_revision import ProtocolRevision -from asaree.models.protocol_run import ProtocolRun from asaree.models.result_job import ResultJob from asaree.services import managed_storage, okf_bundles, okf_documents BLOCK = 1024 * 1024 -SQL_BLOCK = 16384 SECRET_FIELDS = frozenset({ "api_key", "api_token", "access_token", "refresh_token", "password", "secret", "client_secret", "authorization", "headers", "env", "environment", "stdio_env", "credentials", "connection_string", @@ -204,18 +199,15 @@ def node_variants(node: dict[str, Any], design: dict[str, Any] | None) -> Iterat class PackageWriter: - """Disk-backed inventory and constant-buffer tar writer. - - TarFile normally retains every TarInfo even in stream mode. Clearing its - members is deliberate: this writer never seeks, appends, or calls getmember. - """ + """Disk-backed inventory and streamed ZIP entries, with directory metadata in memory.""" def __init__(self, destination: Path, staging: Path): self.staging = staging self.output = destination.open("wb") destination.chmod(0o600) - self.compressor = gzip.GzipFile(filename="", mode="wb", fileobj=self.output, mtime=0) - self.tar = tarfile.open(fileobj=self.compressor, mode="w|", format=tarfile.PAX_FORMAT) # noqa: SIM115 + self.archive = zipfile.ZipFile( # noqa: SIM115 + self.output, mode="w", compression=zipfile.ZIP_DEFLATED, compresslevel=9, + ) self.inventory = (staging / "files.jsonl").open("wb") self.dependencies = (staging / "dependencies.jsonl").open("wb") self.missing = 0 @@ -265,17 +257,12 @@ def add(self, path: Path, name: str, *, provenance: str, identity: str, inventor digest.update(block) size = stream.tell() stream.seek(0) - info = tarfile.TarInfo(name) - info.size, info.mode, info.mtime = size, 0o600, 0 - check = self.check - - class Reader: - def read(self, size: int = -1, /) -> bytes: - check() - return stream.read(size) - - self.tar.addfile(info, Reader()) - self.tar.members.clear() # type: ignore[attr-defined] # Runtime cache omitted by typeshed. + # Passing a name uses ZIP's fixed 1980 timestamp and private file + # permissions, and inherits the archive's compression level. + with self.archive.open(name, "w", force_zip64=size * 1.05 > zipfile.ZIP64_LIMIT) as target: + for block in iter(lambda: stream.read(BLOCK), b""): + self.check() + target.write(block) record = {"path": name, "sha256": digest.hexdigest(), "bytes": size, "source_id": identity, "provenance": provenance} if inventory: @@ -334,8 +321,7 @@ def finish(self, manifest: dict[str, Any]) -> dict[str, Any]: def close(self) -> None: self.inventory.close() self.dependencies.close() - self.tar.close() - self.compressor.close() + self.archive.close() if not self.output.closed: self.output.flush() os.fsync(self.output.fileno()) @@ -606,7 +592,7 @@ async def _server(db: AsyncSession, writer: PackageWriter, config: dict[str, Any await authorize_knowledge_export(db, root, owner, external=owner_storage is None) file_count = await archive_io(writer, capture_tree, writer, root, directory, server_id) writer.dependency(server_id, "knowledge", "captured_at_download", directory=directory, - file_count=file_count, + file_count=file_count, name=root.name, note="Mutable content captured now; no historical snapshot or cross-file transaction.") except (OSError, ValueError, SQLAlchemyError): writer.dependency(server_id, "knowledge", "captured_at_download", status="unresolved", @@ -727,7 +713,23 @@ async def _resources(writer: PackageWriter, graph: dict[str, Any], settings: dic for variant in node_variants(node, settings.get("design_spec")): config = (variant.get("data") or {}).get("config") or {} kind = variant.get("type", "") - if kind == "skill": + if kind == "persona": + from asaree.services.personas import snapshot_identity + + prompt = config.get('persona_text') or '' + persona_id = snapshot_identity(config) + if not writer.seen('persona', persona_id): + path = writer.staging / 'persona.md' + path.write_bytes(prompt.encode('utf-8')) + await archive_io(writer, writer.add, path, f'resources/personas/{persona_id}.md', + provenance='publication_pinned', identity=persona_id) + await archive_io(writer, writer.json, f'resources/personas/{persona_id}.json', { + 'id': persona_id, 'config': config, 'name': config.get('persona_label') + or (variant.get('data') or {}).get('label') or 'Persona', + }, identity=persona_id) + writer.dependency(persona_id, 'persona', 'publication_pinned', + file=f'resources/personas/{persona_id}.md') + elif kind == "skill": await _skill(db, writer, str(config.get("skill_id") or ""), owner) elif kind in {"okf_bundle", "okf_document", "mcp_tool", "mcp_scikit_learn", "mcp_client_tool"}: await _server(db, writer, config, owner, knowledge=kind in {"okf_bundle", "okf_document"}, @@ -761,21 +763,6 @@ async def _resources(writer: PackageWriter, graph: dict[str, Any], settings: dic completed_at=datetime.now(UTC), note="Separate snapshot from ASAREE publication/results.") -async def stream_document(db: AsyncSession, query: Any, path: Path) -> None: - """query selects one text expression; each response is at most SQL_BLOCK characters.""" - offset = 1 - with path.open("wb") as output: - while True: - part = await db.scalar(query.with_only_columns(func.substr(query.selected_columns[0], offset, SQL_BLOCK))) - if part is None: - output.write(b"null" if offset == 1 else b"") - return - output.write(part.encode()) - if len(part) < SQL_BLOCK: - return - offset += SQL_BLOCK - - async def _design(db: AsyncSession, writer: PackageWriter, publication: ProtocolRevision) -> dict[str, Any] | None: if publication.design_revision_id is None: writer.dependency(str(publication.id), "generated_design", "publication_pinned", status="excluded", @@ -816,140 +803,6 @@ async def _design(db: AsyncSession, writer: PackageWriter, publication: Protocol return design if isinstance(design, dict) else None -async def _results( - db: AsyncSession, writer: PackageWriter, job: ResultJob, checkpoint: Any, - graph: dict[str, Any] | None = None, -) -> None: - # Explicit owner/publication/design scope; never mutable latest projections. - conditions = ( - ProtocolRun.owner_id == job.owner_id, ProtocolRun.protocol_id == job.protocol_id, - ProtocolRun.protocol_revision_id == job.protocol_revision_id, - ProtocolRun.design_revision_id == job.design_revision_id, - ProtocolRun.is_test_run.is_(False), ProtocolRun.target_node_id.is_(None), - ) - after = None - while True: - query = select(ProtocolRun.id, ProtocolRun.status, ProtocolRun.created_at, ProtocolRun.started_at, - ProtocolRun.completed_at, ProtocolRun.replicate_result_id, ProtocolRun.row_result_id, - ProtocolRun.replicate_label, ProtocolRun.protocol_id, ProtocolRun.protocol_revision_id, - ProtocolRun.design_revision_id, ProtocolRun.updated_at, ProtocolRun.last_heartbeat_at, - ProtocolRun.cancel_requested_at).where( - *conditions, - ).order_by(ProtocolRun.id).limit(1) - if after is not None: - query = query.where(ProtocolRun.id > after) - row = (await db.execute(query)).mappings().one_or_none() - if row is None: - break - after = row["id"] - directory = f"results/attempts/{after}" - await archive_io(writer, writer.json, f"{directory}/attempt.json", dict(row), - provenance="recorded_attempt", identity=str(after)) - if row["row_result_id"] and not writer.seen("row_slot", str(row["row_result_id"])): - slot = await db.get(FactorialRowResult, row["row_result_id"]) - if slot is not None: - await archive_io(writer, writer.json, f"results/rows/{slot.id}.json", { - key: getattr(slot, key) for key in ( - "id", "replicate_result_id", "protocol_revision_id", "dataset_id", "raw_sha256", "row_index", - ) - }, provenance="recorded_attempt", identity=str(slot.id)) - else: - writer.dependency(str(row["row_result_id"]), "row_slot", "recorded_attempt", status="missing") - for document in ("factor_values", "dataset_inputs", "dataset_row", "attempt_result", "node_runs", - "conversation", - "usage_summary", "error"): - path = writer.staging / "evidence.json" - if document == "factor_values": - values = await db.scalar(select(ProtocolRun.factor_values).where(*conditions, ProtocolRun.id == after)) - await archive_io(writer, writer.json, f"{directory}/{document}.json", - safe_factor_values(values, graph or {}), provenance="recorded_attempt", - identity=str(after)) - continue - column = getattr(ProtocolRun, document) - if document == "error": - column = func.to_jsonb(column) - await stream_document(db, select(cast(column, Text)).where( - *conditions, ProtocolRun.id == after, - ), path) - await archive_io(writer, writer.add, path, f"{directory}/{document}.json", - provenance="recorded_attempt", identity=str(after)) - try: - await _attempt_files(writer, job, after, graph) - except (ValueError, OSError): - writer.dependency(str(after), "attempt_artifacts", "recorded_attempt", status="missing", - reason="Retained artifact tree unavailable or unsafe.") - await checkpoint() - count = await db.scalar(select(func.count()).select_from(ExperimentArtifact).where( - ExperimentArtifact.experiment_id == job.experiment_id, - )) - if count: - writer.dependency(str(job.experiment_id), "unscoped_experiment_artifacts", "legacy.unknown", status="excluded", - count=count, reason="No publication attribution recorded; not assigned to selected version.") - writer.dependency("native_agent_runtime_state", "runtime_state", "recorded_attempt", status="excluded", - reason="AgentRun IDs are source provenance; native steps and resume state are not bundled.") - - -async def _attempt_files( - writer: PackageWriter, job: ResultJob, run_id: uuid.UUID, graph: dict[str, Any] | None = None, -) -> None: - """Only an attempt's identity-isolated durable output, never shared legacy workspaces.""" - from asaree.services.dataset_row_workspaces import row_attempt_workspace_id - - root = managed_storage.roots()["workspaces"] - candidates = (root / str(job.experiment_id) / str(run_id), root / row_attempt_workspace_id(run_id)) - standalone_agents = {re.sub(r"[^A-Za-z0-9_.-]", "_", str(node["id"])) - for node in (graph or {}).get("nodes") or [] if node.get("type") in {"agent", "sub_agent"}} - found = False - for directory in candidates: - if not directory.is_dir(): - continue - found = True - if directory.is_symlink() or not directory.resolve().is_relative_to(root.resolve()): - raise ValueError("Attempt artifact tree escapes storage") - sources = {re.sub(r"[^A-Za-z0-9_.-]", "_", str(node["id"])) + ".py" - for node in (graph or {}).get("nodes") or [] if node.get("type") == "script"} - # Unknown outputs within this UUID-isolated attempt are retained durable - # evidence, including agent= slots, row agents and script working dirs. - # Exclude only known platform control/input/scratch identities. - for relative, path, _ in _tree_files(directory): - parts = PurePosixPath(relative).parts - platform_scratch = parts[0] == ".scratch" or ( - len(parts) > 1 and parts[0].startswith(("dataset=", "agent=")) and parts[1] == ".scratch" - ) - if credential_file(relative) or any( - part.startswith(".asaree-script-context-") - or re.fullmatch(r"\..+\.[A-Za-z0-9_-]{8,}\.preparing", part) for part in parts - ) or platform_scratch: - continue - control_parent = len(parts) == 1 or ( - len(parts) == 2 and parts[0].startswith(("dataset=", "agent=")) - ) or (len(parts) >= 3 and parts[-2].startswith(".") and "-unsplit-" in parts[-2]) - if path.name == "state.json" and control_parent: - continue - row_input = (directory == candidates[1] and len(parts) == 3 and parts[0] == "agents" - and re.fullmatch(r"[0-9a-f]{64}", parts[1])) - if (path.name == "dataset_inputs.json" and len(parts) == 1 - or path.name == "row-view.json" and row_input): - continue - materialized_source = (len(parts) == 2 and parts[0] == "scripts") or ( - directory == candidates[1] and len(parts) == 3 - and parts[0] in standalone_agents and parts[1] == "scripts" - ) - if materialized_source and (path.name in sources or re.fullmatch(r"inline-[0-9a-f]{12}\.py", path.name)): - continue - if row_input and re.fullmatch(r"[0-9a-f]{64}\.csv", path.name): - continue - try: - await archive_io(writer, writer.file, path, f"results/artifacts/{run_id}/{relative}", - identity=str(run_id), provenance="retained_attempt_artifact") - except (ValueError, OSError): - writer.dependency(str(run_id), "attempt_artifact", "recorded_attempt", status="missing", - relative_path=relative, reason="Retained file unavailable or changed.") - if not found: - writer.dependency(str(run_id), "attempt_artifacts", "recorded_attempt", status="missing", - reason="No retained identity-isolated workspace; historical files may be unavailable.") - - async def execute_package(db: AsyncSession, job: ResultJob, temporary: Path, destination: Path) -> None: """Called inside the export worker's repeatable-read/advisory-lock scope.""" from asaree_workspace_core.storage import atomic_write @@ -1008,10 +861,10 @@ async def checkpoint() -> None: design = await _design(db, writer, publication) await _resources(writer, graph, settings if settings else {"design_spec": design}, job.owner_id) await checkpoint() - if job.params["selection"].get("include_results", False): - await _results(db, writer, job, checkpoint, graph) - await _import_sources(db, writer, job.experiment_id, - include_results=job.params['selection'].get('include_results', False)) + if writer.missing: + raise ValueError("Repair required assets before exporting: " + "; ".join( + f"{issue['kind']} {issue['id']}: {issue['reason']}" for issue in writer.issues)) + await _import_sources(db, writer, job.experiment_id) software = {} for package in ("asaree", "motoro", "asaree-workspace-core", "asaree-sklearn-core", "scikit-learn-mcp", "asaree-sklearn-dc", "asaree-sklearn-eda", "asaree-sklearn-fs", "asaree-sklearn-fte", @@ -1029,7 +882,7 @@ async def checkpoint() -> None: "note": publication.note, "annotations_provenance": "captured_at_download"}, "design_revision_id": str(publication.design_revision_id) if publication.design_revision_id else None, - "results_included": job.params["selection"].get("include_results", False), + "results_included": False, "capture": {"started_at": started, "completed_at": datetime.now(UTC), "database": "ASAREE repeatable-read snapshot; separate Motoro resource snapshot", "mutable_files": "download-time capture; no historical/cross-file atomicity claim"}, @@ -1058,22 +911,23 @@ async def checkpoint() -> None: )) -async def _import_sources(db: AsyncSession, writer: PackageWriter, experiment_id: uuid.UUID, - *, include_results: bool) -> None: +async def _import_sources(db: AsyncSession, writer: PackageWriter, experiment_id: uuid.UUID) -> None: """Local exports keep imported provenance separate from local attempt history.""" from asaree.models.package_import import ImportedIdentity, PackageImport - from asaree.services.package_imports import directory + from asaree.services import package_source imports = await db.stream_scalars(select(PackageImport).where( PackageImport.experiment_id == experiment_id, PackageImport.status == 'completed', ).execution_options(yield_per=1)) async for imported in imports: prefix = f'sources/{imported.id}' - root = directory(imported.id) # Source manifest and publication always remain immutable attribution. for name in ('manifest.json', 'publication/canvas.json', 'publication/settings.json', 'experiment-metadata.json'): - source = root / 'payload' / name + if not package_source.archive_path(imported.id).is_file(): + break # Native resources and the identity ledger do not depend on retained ZIP evidence. + source = writer.staging / 'source-document' + await archive_io(writer, package_source.copy_member, imported.id, name, source) await archive_io(writer, writer.file, source, f'{prefix}/{name}', identity=str(imported.id), provenance='imported_source') path = writer.staging / 'source-identities.jsonl' @@ -1082,15 +936,8 @@ async def _import_sources(db: AsyncSession, writer: PackageWriter, experiment_id ).order_by(ImportedIdentity.kind, ImportedIdentity.source_id).execution_options(yield_per=1)) with path.open('wb') as output: async for row in rows: - if not include_results and row.kind.startswith('historical_'): - continue output.write(encoded({'kind': row.kind, 'source_id': row.source_id, 'local_id': row.local_id, 'provenance': row.provenance})) await archive_io(writer, writer.add, path, f'{prefix}/identities.jsonl', identity=str(imported.id), provenance='imported_source') - if include_results: - await archive_io(writer, writer.file, root / 'archive.tar.gz', f'{prefix}/source.tar.gz', - identity=str(imported.id), provenance='imported_source', expected=imported.sha256) - writer.dependency(str(imported.id), 'imported_source', 'imported_source', directory=prefix, - archive_included=include_results, - note='Source evidence is separate from local execution; nested archives are never executed.') + writer.dependency(str(imported.id), 'imported_source', 'imported_source', directory=prefix) diff --git a/src/asaree/services/experiments.py b/src/asaree/services/experiments.py index 0a2c0a9c..1662719e 100644 --- a/src/asaree/services/experiments.py +++ b/src/asaree/services/experiments.py @@ -19,6 +19,7 @@ design_metrics_from_measurement_plan, recommended_runtime_measurements, ) +from asaree.services.skill_references import validate_references # No "dataset_id" here any more -- an experiment's datasets are rows in # experiment_datasets, not a column, so they're written by @@ -72,12 +73,14 @@ async def create_experiment( name: str, owner_id: uuid.UUID, description: str | None = None, + hypothesis: str | None = None, design_type: str = "factorial", task_brief: dict[str, Any] | None = None, design_spec: dict[str, Any] | None = None, measurement_plan: dict[str, Any] | None = None, metric_recommendations: dict[str, Any] | None = None, dataset_ids: Sequence[uuid.UUID] | None = None, + identifier: uuid.UUID | None = None, ) -> ResearchExperiment: spec = dict(design_spec or {}) normalized_measurement_plan = normalize_measurement_plan(measurement_plan) if measurement_plan is not None else None @@ -100,8 +103,10 @@ async def create_experiment( elif design_spec is None: spec["metrics"] = design_metrics_from_measurement_plan(normalized_measurement_plan) experiment = ResearchExperiment( + **({'id': identifier} if identifier else {}), name=name, description=description, + hypothesis=hypothesis, design_type=design_type, task_brief=task_brief, design_spec=spec, @@ -111,12 +116,33 @@ async def create_experiment( ) db.add(experiment) await db.flush() + if (spec.get("factors") or []): + await validate_references(db, owner_id, experiment_id=experiment.id) if dataset_ids: await set_experiment_datasets(db, experiment.id, dataset_ids) await db.refresh(experiment) return experiment +async def create_experiment_with_available_name( + db: AsyncSession, *, name: str, owner_id: uuid.UUID, **fields: Any, +) -> ResearchExperiment: + """Use the normal creation contract, retrying only a concurrent name collision.""" + from asaree.services.resource_names import available_name + + for _ in range(_ALLOCATION_ATTEMPTS): + names = (await db.scalars(select(ResearchExperiment.name).where( + ResearchExperiment.owner_id == owner_id))).all() + candidate = available_name(name, names) + try: + async with db.begin_nested(): + return await create_experiment(db, name=candidate, owner_id=owner_id, **fields) + except IntegrityError as exc: + if _UNIQUE_NAME_INDEX not in str(exc.orig): + raise + raise ExperimentNameAllocationError('Could not allocate an available experiment name; retry creation.') + + async def _next_untitled_number(db: AsyncSession, owner_id: uuid.UUID) -> int: """Lowest free N for this owner's ``Untitled Experiment N``. @@ -198,6 +224,8 @@ async def update_experiment( value = normalize_measurement_plan(value) setattr(experiment, key, value) await db.flush() + if {"design_spec", "locked_design_spec"}.intersection(fields): + await validate_references(db, experiment.owner_id, experiment_id=experiment.id) await db.refresh(experiment) return experiment diff --git a/src/asaree/services/okf_bundles.py b/src/asaree/services/okf_bundles.py index a50daa23..71812e86 100644 --- a/src/asaree/services/okf_bundles.py +++ b/src/asaree/services/okf_bundles.py @@ -47,11 +47,14 @@ import uuid from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from motoro.services import mcp_service from asaree.config import get_settings + +if TYPE_CHECKING: + from sqlalchemy.ext.asyncio import AsyncSession from asaree.services.system_mcp_servers import command_for # Every bundle server's name starts with this. Names are globally unique in @@ -191,7 +194,35 @@ def slugify(value: str, fallback: str = "bundle") -> str: return slug[:64].strip("-") or fallback -def allocate_storage_dir(base: Path, slug: str) -> Path: +def _discard_on_rollback(db: AsyncSession, directory: Path) -> None: + """Keep filesystem ownership aligned with the caller's transaction/savepoint.""" + from sqlalchemy import event + + session = db.sync_session + target = session.get_nested_transaction() or session.get_transaction() or session.begin() + committed, finished = False, False + + def record_commit(current: Any) -> None: + nonlocal committed + if not finished and (current.get_nested_transaction() or current.get_transaction()) is target: + committed = True + + def transaction_ended(_session: Any, ended: Any) -> None: + nonlocal target, committed, finished + if finished or ended is not target: + return + if committed and ended.parent is not None: + target, committed = ended.parent, False + return + if not committed: + shutil.rmtree(directory, ignore_errors=True) + finished = True + + event.listen(session, 'after_commit', record_commit) + event.listen(session, 'after_transaction_end', transaction_ended) + + +def allocate_storage_dir(base: Path, slug: str, *, db: AsyncSession | None = None) -> Path: """A fresh, empty directory under *base*, suffixing a taken *slug*. ``-2``, ``-3`` ... rather than reusing or replacing what's there: existing @@ -207,6 +238,8 @@ def allocate_storage_dir(base: Path, slug: str) -> Path: continue except OSError as exc: raise OkfBundleError(f"Could not create storage at {candidate}: {exc}") from exc + if db is not None: + _discard_on_rollback(db, candidate) return candidate raise OkfBundleError(f"Too many folders already stored under the name {slug!r} -- delete some first.") @@ -269,7 +302,18 @@ def normalise_upload_paths(names: list[str]) -> tuple[str, list[str]]: return folder, relatives -async def register_uploaded_bundle(*, owner_id: uuid.UUID, files: list[tuple[str, str]]) -> Any: +def validate_uploaded_bundle(files: list[tuple[str, str]]) -> tuple[str, list[str]]: + """Apply the upload rules to a directory before registration or import.""" + total = sum(len(text.encode('utf-8')) for _name, text in files) + if total > MAX_UPLOAD_BYTES: + raise OkfBundleError(f"That folder is larger than the {MAX_UPLOAD_BYTES // 1_000_000}MB upload limit.") + return normalise_upload_paths([name for name, _text in files]) + + +async def register_uploaded_bundle( + *, owner_id: uuid.UUID, files: list[tuple[str, str]], db: AsyncSession | None = None, + identifier: uuid.UUID | None = None, connect: bool = True, +) -> Any: """Store an uploaded folder of concepts and spawn an OKF server over it. *files* is ``(webkitRelativePath, text)`` pairs. Not idempotent, unlike @@ -277,12 +321,9 @@ async def register_uploaded_bundle(*, owner_id: uuid.UUID, files: list[tuple[str because whatever the first copy has since become is not what's being uploaded now. """ - total = sum(len(text.encode("utf-8")) for _name, text in files) - if total > MAX_UPLOAD_BYTES: - raise OkfBundleError(f"That folder is larger than the {MAX_UPLOAD_BYTES // 1_000_000}MB upload limit.") - folder, relatives = normalise_upload_paths([name for name, _text in files]) + folder, relatives = validate_uploaded_bundle(files) - directory = allocate_storage_dir(owner_upload_root(owner_id), slugify(folder)) + directory = allocate_storage_dir(owner_upload_root(owner_id), slugify(folder), db=db) try: ensure_command_safe(directory) for relative, (_name, text) in zip(relatives, files, strict=True): @@ -294,8 +335,9 @@ async def register_uploaded_bundle(*, owner_id: uuid.UUID, files: list[tuple[str transport="stdio", command=command_for_bundle(directory, managed=True), owner_id=owner_id, + db=db, identifier=identifier, connect=connect, ) - except Exception: + except BaseException: # The directory only exists because this call created it, so a failure # anywhere after mkdir leaves nothing behind -- otherwise a rejected # upload would burn the folder name and push the next try to "-2". diff --git a/src/asaree/services/okf_documents.py b/src/asaree/services/okf_documents.py index 5059513c..7d836b69 100644 --- a/src/asaree/services/okf_documents.py +++ b/src/asaree/services/okf_documents.py @@ -43,7 +43,7 @@ import uuid from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any import yaml from motoro.services import mcp_service @@ -57,6 +57,9 @@ ) from asaree.services.okf_bundles import slugify as _base_slugify +if TYPE_CHECKING: + from sqlalchemy.ext.asyncio import AsyncSession + # Distinct from BUNDLE_SERVER_NAME_PREFIX so the two registries stay separable # with a string check: ``/okf/bundles`` must not list (or delete, or refresh) a # document, and vice versa, even though both are ordinary mcp_server_configs @@ -247,7 +250,18 @@ async def list_documents(owner_id: uuid.UUID) -> list[Any]: return [s for s in servers if is_document_server(s) and s.owner_id == owner_id] -async def register_document(*, owner_id: uuid.UUID, text: str, filename: str | None = None) -> Any: +def validate_document_upload(text: str) -> dict[str, Any]: + """Shared concept registration validation for uploads and packaged documents.""" + if len(text.encode('utf-8')) > MAX_DOCUMENT_BYTES: + raise OkfDocumentError(f"That file is larger than the {MAX_DOCUMENT_BYTES // 1000}kB limit for one concept.") + frontmatter, _body = parse_document(text) + return frontmatter + + +async def register_document( + *, owner_id: uuid.UUID, text: str, filename: str | None = None, + db: AsyncSession | None = None, identifier: uuid.UUID | None = None, connect: bool = True, +) -> Any: """Store an uploaded concept and spawn an OKF server over it. Spawns during registration (via ``mcp_service.register_server``) so a @@ -257,9 +271,7 @@ async def register_document(*, owner_id: uuid.UUID, text: str, filename: str | N documents, because the second upload's content may differ from what the first one has since become. """ - if len(text.encode("utf-8")) > MAX_DOCUMENT_BYTES: - raise OkfDocumentError(f"That file is larger than the {MAX_DOCUMENT_BYTES // 1000}kB limit for one concept.") - frontmatter, _body = parse_document(text) + frontmatter = validate_document_upload(text) # The title, not the upload's filename: the filename is often "Untitled # 3.md" or a temp name, while the title is what the user actually called # the concept and what every OKF listing shows. The filename is only the @@ -267,7 +279,7 @@ async def register_document(*, owner_id: uuid.UUID, text: str, filename: str | N stem = frontmatter.get("title") or (Path(filename).stem if filename else "") slug = slugify(str(stem)) - directory = allocate_storage_dir(owner_root(owner_id), slug) + directory = allocate_storage_dir(owner_root(owner_id), slug, db=db) try: ensure_command_safe(directory) (directory / f"{slug}.md").write_text(text, encoding="utf-8") @@ -276,8 +288,9 @@ async def register_document(*, owner_id: uuid.UUID, text: str, filename: str | N transport="stdio", command=command_for_bundle(directory, managed=True), owner_id=owner_id, + db=db, identifier=identifier, connect=connect, ) - except Exception: + except BaseException: # The directory only exists because this call created it, so an # upload that fails anywhere after mkdir leaves nothing behind -- # otherwise a rejected registration would silently burn the slug and diff --git a/src/asaree/services/package_imports.py b/src/asaree/services/package_imports.py index 7818e0ed..6b580443 100644 --- a/src/asaree/services/package_imports.py +++ b/src/asaree/services/package_imports.py @@ -15,16 +15,19 @@ from motoro.models.mcp_server import MCPServerConfig from motoro.models.skill import Skill from sqlalchemy import delete, func, or_, select, update +from sqlalchemy.exc import IntegrityError from asaree.config import get_settings from asaree.models.database import get_session from asaree.models.dataset import RegisteredDataset from asaree.models.experiment import ResearchExperiment from asaree.models.package_import import ImportedIdentity, PackageImport +from asaree.models.persona import Persona from asaree.models.protocol import Protocol -from asaree.services import managed_storage -from asaree.services.package_reconstruction import Reconstruction, identity -from asaree.services.package_validation import Limits, PackageError, digest, inspect, records +from asaree.services import managed_storage, package_source +from asaree.services.datasets import discard_registration_files +from asaree.services.package_reconstruction import Reconstruction, RegistrationBatchError, identity, registration_error +from asaree.services.package_validation import Limits, PackageError, digest, inspect logger = logging.getLogger(__name__) @@ -36,9 +39,11 @@ def limits() -> Limits: def directory(identifier: uuid.UUID) -> Path: - # Deliberately under datasets: restored dataset artifacts can point to stable - # relative keys without another storage namespace or absolute path column. - return managed_storage.roots()['datasets'] / 'package-imports' / str(identifier) + return package_source.scratch_path(identifier) + + +def archive_path(identifier: uuid.UUID) -> Path: + return package_source.archive_path(identifier) async def joined(operation: Any, *args: Any, stopping: threading.Event, identifier: uuid.UUID) -> Any: @@ -64,24 +69,35 @@ async def compensate(job: PackageImport) -> None: # and archive hash. Failed/partial extraction is untrusted cleanup input. if not job.sha256 or not job.preflight.get('manifest'): return - root = directory(job.id) / 'payload' - if not root.exists(): - return - if not (root / 'dependencies.jsonl').is_file(): + if not archive_path(job.id).is_file(): return async with system_session(reason='compensate incomplete owned package import') as db: - for dep in records(root / 'dependencies.jsonl', limits()): + for dep in package_source.records(job.id, 'dependencies.jsonl', limits()): if dep.get('kind') == 'skill': await db.execute(delete(Skill).where(Skill.id == identity(job, 'skill', dep['id']), Skill.owner_id == job.owner_id, Skill.is_system.is_(False))) if dep.get('kind') == 'mcp': local = identity(job, 'mcp', dep['id']) + server = await db.scalar(select(MCPServerConfig).where(MCPServerConfig.id == local, + MCPServerConfig.owner_id == job.owner_id, MCPServerConfig.is_system.is_(False))) + if server is not None and server.command: + from asaree.services.okf_bundles import bundle_path_from_command + + raw = bundle_path_from_command(server.command) + if raw: + destination = Path(raw).resolve() + roots = managed_storage.roots() + if any(destination.is_relative_to(roots[namespace] / str(job.owner_id)) + for namespace in ('bundles', 'documents')): + await asyncio.to_thread(shutil.rmtree, destination, ignore_errors=True) await db.execute(delete(MCPServerConfig).where(MCPServerConfig.id == local, MCPServerConfig.owner_id == job.owner_id, MCPServerConfig.is_system.is_(False))) - for namespace in ('bundles', 'documents'): - destination = managed_storage.roots()[namespace] / str(job.owner_id) / 'imports' / str(local) - await asyncio.to_thread(shutil.rmtree, destination, ignore_errors=True) - await asyncio.to_thread(shutil.rmtree, destination.with_suffix('.preparing'), ignore_errors=True) + # Dataset files use the ordinary registration layout, even when a worker + # died before its product transaction (and identity ledger) could commit. + if 'inputs/bindings.json' in package_source.members(job.id, 'inputs/'): + bindings = package_source.document(job.id, 'inputs/bindings.json', limits()) + for pin in bindings.get('inputs', []): + await asyncio.to_thread(discard_registration_files, identity(job, 'dataset', pin['dataset_id'])) async def checkpoint(identifier: uuid.UUID, phase: str, **progress: Any) -> None: @@ -94,17 +110,22 @@ async def checkpoint(identifier: uuid.UUID, phase: str, **progress: Any) -> None async def activate_resources(job: PackageImport) -> None: """Retryable visibility flip; no server registration or connection calls.""" - root = directory(job.id) / 'payload' async with system_session(reason='activate staged package resources without execution') as db: - for dep in records(root / 'dependencies.jsonl', limits()): + for dep in package_source.records(job.id, 'dependencies.jsonl', limits()): if dep.get('kind') == 'skill': - await db.execute(update(Skill).where(Skill.id == identity(job, 'skill', dep['id']), - Skill.owner_id == job.owner_id).values(deleted_at=None)) + local = identity(job, 'skill', dep['id']) + name = await db.scalar(select(Skill.name).where(Skill.id == local, Skill.owner_id == job.owner_id)) + try: + await db.execute(update(Skill).where(Skill.id == local, + Skill.owner_id == job.owner_id).values(deleted_at=None)) + except IntegrityError as exc: + raise registration_error('skill', name or dep['id'], exc) from exc elif dep.get('kind') == 'mcp': await db.execute(update(MCPServerConfig).where( MCPServerConfig.id == identity(job, 'mcp', dep['id']), MCPServerConfig.owner_id == job.owner_id, - ).values(error_message='Imported requirement: configure locally before connection.')) + MCPServerConfig.is_system.is_(False), + ).values(error_message=None)) async def remove_staged_product(db: Any, job: PackageImport) -> None: @@ -118,6 +139,9 @@ async def remove_staged_product(db: Any, job: PackageImport) -> None: ImportedIdentity.kind == 'dataset') await db.execute(delete(RegisteredDataset).where(RegisteredDataset.id.in_(identifiers), RegisteredDataset.owner_id == job.owner_id)) + await db.execute(delete(Persona).where(Persona.owner_id == job.owner_id, Persona.id.in_( + select(ImportedIdentity.local_id).where(ImportedIdentity.import_id == job.id, + ImportedIdentity.kind == 'persona')))) await db.execute(delete(ImportedIdentity).where(ImportedIdentity.import_id == job.id)) job.experiment_id = None @@ -136,7 +160,8 @@ async def execute_package_import(_ctx: dict[str, Any], job_id: str) -> None: if job is None or job.status not in {'validating', 'queued', 'activating'}: return root = directory(identifier) - archive, payload = root / 'archive.tar.gz', root / 'payload' + root.mkdir(parents=True, exist_ok=True, mode=0o700) + archive, payload = archive_path(identifier), root / 'payload' if job.status == 'validating': for path in (payload, root / 'payload-verified'): await asyncio.to_thread(shutil.rmtree, path, ignore_errors=True) @@ -147,8 +172,8 @@ async def execute_package_import(_ctx: dict[str, Any], job_id: str) -> None: async with get_session() as status_db: await status_db.execute(update(PackageImport).where( PackageImport.id == identifier, PackageImport.status == 'validating', - ).values(status='awaiting_confirmation', preflight=preflight, sha256=sha256, - progress={'phase': 'preflight_ready'}, error=None)) + ).values(status='queued', preflight=preflight, sha256=sha256, + progress={'phase': 'validated'}, error=None)) return await checkpoint(identifier, 'reconstructing') if await asyncio.to_thread(digest, archive) != job.sha256: @@ -164,6 +189,7 @@ async def execute_package_import(_ctx: dict[str, Any], job_id: str) -> None: raise PackageError('Import cancelled') current.status, current.error = 'completed', None current.progress = {'phase': 'completed'} + await asyncio.to_thread(shutil.rmtree, root, ignore_errors=True) return # Re-inspect verified bytes for every activation/retry, including # partial extraction left by a terminated worker. @@ -204,6 +230,7 @@ async def io(operation: Any, *args: Any) -> Any: raise PackageError('Import cancelled') current.status = 'completed' current.progress = {'phase': 'completed'} + await asyncio.to_thread(shutil.rmtree, root, ignore_errors=True) except (Exception, asyncio.CancelledError) as exc: logger.exception('package_import_failed', extra={'import_id': job_id}) async with get_session() as db: @@ -218,8 +245,11 @@ async def io(operation: Any, *args: Any) -> Any: job.progress = {'phase': 'compensation_required'} if job.status not in {'cancelled', 'expired'}: job.status = 'failed' - job.error = (str(exc)[:2000] if isinstance(exc, ValueError) - else 'Import interrupted; retry this request.') + if isinstance(exc, RegistrationBatchError): + job.error = str(exc) + else: + job.error = (str(exc)[:2000] if isinstance(exc, ValueError) + else 'Import interrupted; retry this request.') if isinstance(exc, asyncio.CancelledError): raise @@ -251,6 +281,7 @@ async def relay_imports(ctx: dict[Any, Any], *args: Any, **kwargs: Any) -> None: await compensate(job) await remove_staged_product(db, job) await asyncio.to_thread(shutil.rmtree, directory(job.id), ignore_errors=True) + await asyncio.to_thread(archive_path(job.id).unlink, missing_ok=True) job.status = 'expired' except Exception: logger.exception('package_import_cleanup_failed', extra={'import_id': str(identifier)}) diff --git a/src/asaree/services/package_reconstruction.py b/src/asaree/services/package_reconstruction.py index 7af0be9b..4ab1cad4 100644 --- a/src/asaree/services/package_reconstruction.py +++ b/src/asaree/services/package_reconstruction.py @@ -2,82 +2,81 @@ from __future__ import annotations import asyncio -import base64 -import shutil +import hashlib import threading import uuid +from collections.abc import AsyncIterator, Awaitable +from contextlib import AsyncExitStack, asynccontextmanager from copy import deepcopy from datetime import UTC, datetime from pathlib import Path from typing import Any from motoro.models.database import system_session -from motoro.models.mcp_server import MCPServerConfig, MCPTransport -from motoro.models.skill import Skill, SkillFile -from motoro.services.skill_service import parse_skill_markdown +from motoro.models.mcp_server import MCPServerConfig +from motoro.models.skill import Skill +from motoro.services import mcp_service, skill_service +from motoro.services.skill_service import MAX_BUNDLE_BYTES, MAX_BUNDLE_FILES, SkillFormatError from sqlalchemy import select +from sqlalchemy.exc import DataError, IntegrityError, SQLAlchemyError from sqlalchemy.ext.asyncio import AsyncSession from asaree.models.dataset import RegisteredDataset -from asaree.models.dataset_split import DatasetArtifact, DatasetSplit from asaree.models.experiment import ResearchExperiment from asaree.models.experiment_design_revision import ExperimentDesignRevision from asaree.models.factorial_cell import FactorialCell from asaree.models.factorial_replicate_result import FactorialReplicateResult from asaree.models.package_import import ImportedIdentity, PackageImport from asaree.models.protocol import Protocol -from asaree.services import managed_storage +from asaree.services.datasets import create_dataset, discard_registration_files, register_dataset_split from asaree.services.experiment_packages import node_variants, portable_definition -from asaree.services.experiments import set_experiment_datasets +from asaree.services.experiments import create_experiment_with_available_name, set_experiment_datasets from asaree.services.package_validation import ( Limits, PackageError, canonical_identity, document, - member_path, payload_path, records, ) +from asaree.services.personas import create_persona, snapshot_identity +from asaree.services.protocols import create_protocol, generated_protocol_name def identity(job: PackageImport, kind: str, source: Any) -> uuid.UUID: return uuid.uuid5(job.id, f'{kind}:{source}') -def copy_knowledge(source: Path, destination: Path, stopping: threading.Event) -> None: - """Copy exact bytes with cooperative cancellation and atomic publication.""" - from asaree.services.package_validation import digest +def registration_error(kind: str, name: str, exc: Exception) -> PackageError: + if isinstance(exc, IntegrityError): + reason = f'A {kind} with this name is already registered to your account.' + elif isinstance(exc, SQLAlchemyError): + reason = 'The registration could not be saved. Check the resource’s registration fields.' + elif isinstance(exc, UnicodeError): + reason = 'Packaged files must contain UTF-8 text.' + else: + reason = str(exc) + return PackageError(f'Could not register {kind} "{name}": {reason}') - temporary = destination.with_suffix('.preparing') - shutil.rmtree(temporary, ignore_errors=True) - temporary.mkdir(parents=True, mode=0o700) - try: - for file in source.rglob('*'): - if stopping.is_set(): - raise PackageError('Import cancelled') - if not file.is_file(): - continue - relative = file.relative_to(source) - file = payload_path(source, relative.as_posix()) - target = temporary / relative - target.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - with file.open('rb') as input_file, target.open('xb') as output: - target.chmod(0o600) - while block := input_file.read(1024 * 1024): - if stopping.is_set(): - raise PackageError('Import cancelled') - output.write(block) - if destination.exists() and (not (destination / relative).is_file() - or digest(destination / relative) != digest(file)): - raise PackageError('Staged knowledge bytes changed; refusing replacement') - if destination.exists(): - for file in destination.rglob('*'): - if file.is_file() and not (temporary / file.relative_to(destination)).is_file(): - raise PackageError('Staged knowledge has unexpected files') - else: - temporary.replace(destination) - finally: - shutil.rmtree(temporary, ignore_errors=True) + +class RegistrationBatchError(PackageError): + """All resource registration failures from one reconstruction attempt.""" + + def __init__(self, errors: list[str]): + self.errors = errors + label = 'resource' if len(errors) == 1 else 'resources' + super().__init__(f'Could not import {len(errors)} {label}:\n' + '\n'.join(f'• {error}' for error in errors)) + + +def knowledge_files(root: Path) -> list[tuple[str, str]]: + from asaree.services import okf_bundles + + paths = [payload_path(root, path.relative_to(root).as_posix()) for path in root.rglob('*') if path.is_file()] + if len(paths) > okf_bundles.MAX_UPLOAD_FILES or sum(path.stat().st_size for path in paths) > ( + okf_bundles.MAX_UPLOAD_BYTES + ): + raise ValueError('Knowledge files exceed the normal upload count or size limit.') + return [(path.relative_to(root).as_posix(), path.read_bytes().decode('utf-8')) for path in paths] class Reconstruction: @@ -89,32 +88,79 @@ def __init__(self, db: AsyncSession, job: PackageImport, root: Path, limits: Lim self.maps: dict[tuple[str, str], str] = {} self.names: dict[tuple[str, str], str] = {} self.knowledge_namespaces: dict[str, str] = {} + self.knowledge_paths: dict[str, str] = {} self.runtime_bindings: dict[str, str] = {} + self._registration_keys: list[tuple[str, str]] | None = None + + @asynccontextmanager + async def registration(self, resources: AsyncSession, errors: list[str], kind: str, + name: str) -> AsyncIterator[None]: + """Keep native validation failures local so the remaining resources can be checked.""" + mapped: list[tuple[str, str]] = [] + self._registration_keys = mapped + try: + async with AsyncExitStack() as stack: + await stack.enter_async_context(self.db.begin_nested()) + if resources is not self.db: + await stack.enter_async_context(resources.begin_nested()) + yield + except (ValueError, IntegrityError, DataError, OSError) as exc: + for key in mapped: + self.maps.pop(key, None) + errors.append(str(registration_error(kind, name, exc))) + finally: + self._registration_keys = None + + async def register_resources(self, motoro: AsyncSession) -> list[uuid.UUID]: + errors: list[str] = [] + + async def collect(operation: Awaitable[list[uuid.UUID] | None]) -> list[uuid.UUID] | None: + try: + return await operation + except RegistrationBatchError as exc: + errors.extend(exc.errors) + return None + + datasets = await collect(self.datasets()) + await collect(self.personas()) + await collect(self.skills(motoro)) + await collect(self.servers(motoro)) + if errors: + raise RegistrationBatchError(errors) + return datasets or [] async def report(self, phase: str, scanned: int) -> None: if self.progress is not None and scanned % 25 == 0: await self.progress(phase, scanned=scanned) - def map(self, kind: str, source_id: Any, **provenance: Any) -> uuid.UUID: + def map(self, kind: str, source_id: Any, *, local_id: uuid.UUID | None = None, **provenance: Any) -> uuid.UUID: key = kind, str(source_id) - local = identity(self.job, 'mcp' if kind == 'knowledge' else kind, str(source_id)) + local = local_id or identity(self.job, 'mcp' if kind == 'knowledge' else kind, str(source_id)) if key not in self.maps: self.db.add(ImportedIdentity(import_id=self.job.id, kind=kind, source_id=str(source_id), local_id=local, provenance=provenance)) - if kind not in {'cell', 'replicate', 'historical_attempt', 'historical_row', 'historical_artifact', - 'skill_file', 'payload_member'}: + if kind not in {'cell', 'replicate', 'skill_file'}: self.maps[key] = str(local) + if self._registration_keys is not None: + self._registration_keys.append(key) return local def read(self, path: str) -> Any: return document(payload_path(self.root, path), self.limits) - def name(self, kind: str, source: str, name: str, maximum: int = 255) -> str: - # Import UUID namespaces avoid name collisions without cross-owner lookup. - prefix = name[:maximum - 34].rstrip('-') if kind == 'skill' else name[:maximum - 34] - value = f'{prefix}-{identity(self.job, kind, source).hex}' - self.names[kind, source] = value - return value + async def personas(self) -> None: + """Restore exact node snapshots as reusable destination personas.""" + errors: list[str] = [] + for path in (self.root / 'resources/personas').glob('*.json'): + source = self.read(path.relative_to(self.root).as_posix()) + config = source['config'] + async with self.registration(self.db, errors, 'persona', source['name']): + local = self.map('persona', source['id'], source=source) + await create_persona(self.db, identifier=local, owner_id=self.job.owner_id, + name=source['name'], prompt=config.get('persona_text') or '', + description=config.get('persona_description'), source_filename=config.get('persona_file')) + if errors: + raise RegistrationBatchError(errors) async def datasets(self) -> list[uuid.UUID]: path = self.root / 'inputs/bindings.json' @@ -122,212 +168,259 @@ async def datasets(self) -> list[uuid.UUID]: return [] bindings = self.read('inputs/bindings.json') dataset_ids = [] + errors: list[str] = [] + seen: set[str] = set() for pin in bindings.get('inputs', []): source = canonical_identity(pin['dataset_id']) - if ('dataset', source) in self.maps: + if source in seen: continue - local = self.map('dataset', source, pin=pin) + seen.add(source) metadata_path = f'inputs/datasets/{source}.json' metadata = self.read(metadata_path) if payload_path(self.root, metadata_path).exists() else pin - dataset = RegisteredDataset(id=local, owner_id=self.job.owner_id, - name=self.name('dataset', source, metadata.get('name') or pin['dataset_name']), - description=pin.get('description', metadata.get('description')), - dictionary_json=pin.get('dictionary_json', metadata.get('dictionary_json')), - target_column=pin.get('target_column', metadata.get('target_column')), - raw_sha256=pin.get('raw_sha256')) - self.db.add(dataset) - dataset_ids.append(local) - await self.db.flush() - for dep in records(self.root / 'dependencies.jsonl', self.limits): - if dep.get('kind') != 'dataset_file' or dep.get('status') != 'included': - continue - source = dep['id'] - dataset_id = self.maps.get(('dataset', dep['dataset_id'])) - if dataset_id is None: - raise PackageError('Dataset file has no pinned registration') - # Dataset namespace stores stable relative keys to retained verified bytes. - file = payload_path(self.root, dep['file']) - relative = file.relative_to(managed_storage.roots()['datasets']) - from asaree.services.package_validation import digest - - artifact_id = self.map('artifact', source, dependency=dep) - self.db.add(DatasetArtifact(id=artifact_id, dataset_id=uuid.UUID(dataset_id), namespace='datasets', - storage_key=relative.as_posix(), sha256=await asyncio.to_thread(digest, file), - byte_size=file.stat().st_size, - format=file.suffix.lstrip('.'), status='ready')) - if dep['role'] == 'raw_artifact': - loaded = await self.db.get(RegisteredDataset, uuid.UUID(dataset_id)) - if loaded is None: - raise PackageError('Dataset registration disappeared') - loaded.raw_artifact_id = artifact_id + name = metadata.get('name') or pin.get('dataset_name') or 'Imported dataset' + async with self.registration(self.db, errors, 'dataset', name): + local = self.map('dataset', source, pin=pin) + raw = next((dep for dep in records(self.root / 'dependencies.jsonl', self.limits) + if dep.get('kind') == 'dataset_file' and dep.get('dataset_id') == source + and dep.get('role') == 'raw_artifact' and dep.get('status') == 'included'), None) + if raw is None: + raise ValueError('The package does not contain the original dataset file.') + raw_path = payload_path(self.root, raw['file']) + if await self.db.get(RegisteredDataset, local) is not None: + raise ValueError('This import already has a dataset registration; retry activation instead.') + # Reclaim files left by a worker that died before committing + # its product transaction, using only this request's unused ID. + await self.io(discard_registration_files, local) + dataset = await create_dataset(self.db, identifier=local, owner_id=self.job.owner_id, + name=name, csv_bytes=await self.io(raw_path.read_bytes), + description=pin.get('description', metadata.get('description')), + dictionary_json=pin.get('dictionary_json', metadata.get('dictionary_json')), + target_column=pin.get('target_column', metadata.get('target_column'))) + if dataset.raw_artifact is None: + raise ValueError('Dataset registration did not create an original source artifact.') + self.map('artifact', raw['id'], local_id=dataset.raw_artifact.id, dependency=raw) + self.names['dataset', source] = dataset.name + dataset_ids.append(local) await self.db.flush() for file in (self.root / 'inputs/splits').glob('*.json'): source = document(file, self.limits) - local = self.map('split', source['id'], source=source) dataset_id = self.maps.get(('dataset', source['dataset_id'])) if not dataset_id: + if source['dataset_id'] in seen: + # Its original registration failed; avoid a cascading split error. + continue raise PackageError('Split has no pinned registration') fields = {key: source.get(key) for key in ( - 'source_sha256', 'target_column', 'method', 'strategy', 'group_column', 'stratify_column', + 'target_column', 'method', 'strategy', 'group_column', 'stratify_column', 'test_size', 'seed', 'legacy')} - for key in ('train_artifact_id', 'test_artifact_id'): - mapped = self.maps.get(('artifact', source.get(key))) - fields[key] = uuid.UUID(mapped) if mapped else None fields['created_at'] = datetime.fromisoformat(source['created_at']) - self.db.add(DatasetSplit(id=local, dataset_id=uuid.UUID(dataset_id), **fields)) + registered_dataset = await self.db.get(RegisteredDataset, uuid.UUID(dataset_id)) + if registered_dataset is None: + raise PackageError('Dataset registration disappeared') + async with self.registration(self.db, errors, 'dataset split', source['id']): + local = self.map('split', source['id'], source=source) + partitions = [] + for key in ('train_artifact_id', 'test_artifact_id'): + dep = next((dep for dep in records(self.root / 'dependencies.jsonl', self.limits) + if dep.get('kind') == 'dataset_file' and dep.get('id') == source.get(key) + and dep.get('status') == 'included'), None) + if dep is None: + role = key.removesuffix('_artifact_id') + raise ValueError(f'The package does not contain the {role} partition.') + partitions.append(dep) + await register_dataset_split(self.db, registered_dataset, + payload_path(self.root, partitions[0]['file']), payload_path(self.root, partitions[1]['file']), + identifier=local, **fields) + split = registered_dataset.current_split + if split is None or split.train_artifact is None or split.test_artifact is None: + raise ValueError('Dataset split registration did not create its partition artifacts.') + for dep, artifact in zip(partitions, (split.train_artifact, split.test_artifact), strict=True): + self.map('artifact', dep['id'], local_id=artifact.id, dependency=dep) await self.db.flush() # Only pinned whole-dataset selections become local defaults. Original # selections remain unsplit even if another source default now exists. for pin in bindings.get('inputs', []): + if ('dataset', pin['dataset_id']) not in self.maps: + continue loaded = await self.db.get(RegisteredDataset, uuid.UUID(self.maps['dataset', pin['dataset_id']])) if loaded is None: raise PackageError('Dataset registration disappeared') - split = self.maps.get(('split', pin.get('split_id'))) - if split: - loaded.current_split_id = uuid.UUID(split) + selected_split = self.maps.get(('split', pin.get('split_id'))) + if selected_split: + loaded.current_split_id = uuid.UUID(selected_split) elif pin.get('split_id'): # A missing source split is a requirement, never an explicit # original-only selection. Keep it across worker restarts. self.map('unresolved_split', pin['split_id'], pin=pin) await self.db.flush() + if errors: + raise RegistrationBatchError(errors) return dataset_ids async def skills(self, motoro: AsyncSession) -> None: + registered = [] + errors: list[str] = [] for dep in records(self.root / 'dependencies.jsonl', self.limits): - if dep.get('kind') != 'skill' or dep.get('status') != 'included': + if dep.get('kind') != 'skill': + continue + if dep.get('status') != 'included': + errors.append(str(registration_error('skill', dep['id'], ValueError( + 'The package does not contain the required skill files.')))) continue source_id = canonical_identity(dep['id']) if dep['directory'] != f'resources/skills/{source_id}': raise PackageError('Skill directory and identity disagree') metadata = payload_path(self.root, f'resources/skill-metadata/{source_id}.json') - if metadata.exists(): - source = document(metadata, self.limits) - else: - # v1's rendered frontmatter contains explicit discovery facts. - # Parse those facts, preserving unavailable filename/order as unknown. - entrypoint = payload_path(self.root, f'{dep["directory"]}/SKILL.md') - if entrypoint.stat().st_size > self.limits.document: - raise PackageError('Skill entrypoint exceeds resource limit') - parsed = parse_skill_markdown(entrypoint.read_text(encoding='utf-8')) - source = {'id': dep['id'], 'name': parsed.name, 'description': parsed.description, - 'body': parsed.body, 'frontmatter': parsed.frontmatter} - local = self.map('skill', source['id'], source=source) - name = self.name('skill', source['id'], source['name'], 64) - existing = await motoro.get(Skill, local) - if existing is not None: - if existing.owner_id != self.job.owner_id: - raise PackageError('Import resource ownership conflict') - continue - # No upload service: those may validate by invoking external tools. - motoro.add(Skill(id=local, owner_id=self.job.owner_id, is_system=False, - name=name, - description=source['description'], body=source['body'], frontmatter=source['frontmatter'], - source_filename=source.get('source_filename'), deleted_at=datetime.now(UTC))) + source = document(metadata, self.limits) if metadata.exists() else {'id': source_id} + name = source.get('name', source_id) + async with self.registration(motoro, errors, 'skill', name): + local = self.map('skill', source_id, source=source) + bundle, file_dependencies = self.skill_bundle(dep) + skill = await motoro.get(Skill, local) + if skill is not None: + if skill.owner_id != self.job.owner_id or skill.is_system: + raise ValueError('The staged skill does not belong to this import request.') + skill_service.parse_skill_bundle(bundle) + else: + skill = await skill_service.create_skill_from_bundle(bundle, db=motoro, identifier=local, + owner_id=self.job.owner_id, source_filename=source.get('source_filename')) + for resource in skill.files: + file_dep = file_dependencies[resource.path] + self.map('skill_file', file_dep['id'], local_id=resource.id, dependency=file_dep) + self.names['skill', source_id] = skill.name + registered.append(skill) + # Keep the whole batch live until every registration has passed the + # normal uniqueness check, then hide it before the Motoro commit. + for skill in registered: + skill.deleted_at = datetime.now(UTC) await motoro.flush() + if errors: + raise RegistrationBatchError(errors) + + def skill_bundle(self, dep: dict[str, Any]) -> tuple[list[tuple[str, bytes]], dict[str, dict[str, Any]]]: + directory = dep['directory'] + entrypoint = payload_path(self.root, f'{directory}/SKILL.md') + if entrypoint.stat().st_size > self.limits.document: + raise SkillFormatError('Skill entrypoint exceeds resource limit') + files = [('SKILL.md', entrypoint.read_bytes())] + identifiers = {} + total = 0 for record in records(self.root / 'files.jsonl', self.limits): - if not record['path'].startswith('resources/skills/'): + if not record['path'].startswith(directory + '/') or record['path'] == f'{directory}/SKILL.md': continue - parts = record['path'].split('/') - source_skill = parts[2] - relative = '/'.join(parts[3:]) - canonical_identity(source_skill) - if relative == 'SKILL.md': - continue - file_dep: dict[str, Any] | None = next((entry for entry in records( - self.root / 'dependencies.jsonl', self.limits) if entry.get('kind') == 'skill_file' - and entry.get('file') == record['path'] and entry.get('status') == 'included'), None) + relative = record['path'][len(directory) + 1:] + path = payload_path(self.root, record['path']) + total += path.stat().st_size + if len(files) > MAX_BUNDLE_FILES or total > MAX_BUNDLE_BYTES: + raise SkillFormatError('Skill bundle exceeds the normal file count or size registration limit.') + file_dep = next((entry for entry in records(self.root / 'dependencies.jsonl', self.limits) + if entry.get('kind') == 'skill_file' and entry.get('file') == record['path'] + and entry.get('status') == 'included'), None) if file_dep is None: if self.read('manifest.json')['schema_version'] >= 2: raise PackageError('Missing structured Skill file metadata') - file_dep = {'id': record['source_id'], 'skill_id': source_skill, 'file': record['path'], - 'relative_path': relative, 'encoding': 'base64', 'position': 0, - 'source_encoding': 'legacy.unknown', 'source_position': 'legacy.unknown'} - skill_id = self.maps.get(('skill', file_dep['skill_id'])) - if not skill_id: - raise PackageError('Skill file has no structured Skill record') - local = self.map('skill_file', file_dep['id'], dependency=file_dep) - if await motoro.get(SkillFile, local) is not None: - continue - path = payload_path(self.root, file_dep['file']) - if path.stat().st_size > self.limits.document: - raise PackageError('Skill resource exceeds per-resource limit') - raw = path.read_bytes() - content = base64.b64encode(raw).decode() if file_dep['encoding'] == 'base64' else raw.decode('utf-8') - motoro.add(SkillFile(id=local, skill_id=uuid.UUID(skill_id), path=member_path(file_dep['relative_path']), - encoding=file_dep['encoding'], position=file_dep['position'], content=content)) - await motoro.flush() + file_dep = {'id': record['source_id'], 'skill_id': dep['id'], 'file': record['path'], + 'relative_path': relative, 'source_encoding': 'legacy.unknown', 'source_position': 'legacy.unknown'} + identifiers[relative] = file_dep + files.append((relative, path.read_bytes())) + return files, identifiers async def servers(self, motoro: AsyncSession) -> None: - from asaree.services import okf_documents - from asaree.services.okf_bundles import command_for_bundle, server_name_for + from asaree.services import okf_bundles, okf_documents from asaree.services.package_connections import automatic_match + errors: list[str] = [] for file in (self.root / 'requirements/mcp').glob('*.json'): source = self.read(file.relative_to(self.root).as_posix()) source_id = canonical_identity(source['id']) if file.name != f'{source_id}.json': raise PackageError('MCP requirement filename and identity disagree') - local = self.map('mcp', source['id'], source=source) - command = None - name = self.name('mcp', source['id'], source['name']) knowledge = payload_path(self.root, f'resources/knowledge/{source_id}') included = next(( dep for dep in records(self.root / 'dependencies.jsonl', self.limits) if dep.get('kind') == 'knowledge' and dep.get('id') == source_id and dep.get('status') == 'included' ), None) - destination_server = None - if included is None and source.get('service_identity'): - authorized = list((await motoro.scalars(select(MCPServerConfig).where( - (MCPServerConfig.owner_id == self.job.owner_id) | MCPServerConfig.is_system.is_(True), - ))).all()) - destination_server = automatic_match(source, authorized) - if destination_server is not None: - self.runtime_bindings[source_id] = str(destination_server.id) - self.names['mcp', source_id] = destination_server.name - self.db.add(ImportedIdentity(import_id=self.job.id, kind='runtime_mcp', source_id=source_id, - local_id=destination_server.id, provenance={'requirement_id': str(local), - 'service_identity': source['service_identity'], 'selection': 'automatic'})) - # The owned requirement identity remains separate from its runtime binding. - continue - if included is not None: - if included.get('directory') != f'resources/knowledge/{source_id}': - raise PackageError('Knowledge directory and identity disagree') - knowledge_kind = source.get('knowledge_kind') - if knowledge_kind not in {'bundle', 'document'}: - source_graph = self.read('publication/canvas.json') - source_settings = self.read('publication/settings.json') - knowledge_kind = next(( - 'document' if node.get('type') == 'okf_document' else 'bundle' - for node in source_graph.get('nodes', []) if node.get('type') in {'okf_bundle', 'okf_document'} - for variant in node_variants(node, source_settings.get('design_spec')) - if source['id'] in {((variant.get('data') or {}).get('config') or {}).get('bundle_id'), - ((variant.get('data') or {}).get('config') or {}).get('document_id')} - ), None) - if knowledge_kind is None: - raise PackageError('Knowledge registration type is unknown; source files remain inspectable') - namespace = 'documents' if knowledge_kind == 'document' else 'bundles' - self.knowledge_namespaces[source['id']] = namespace - self.map('knowledge', source['id'], directory=knowledge.relative_to(self.root).as_posix()) - destination = managed_storage.roots()[namespace] / str(self.job.owner_id) / 'imports' / str(local) - destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - await self.io(copy_knowledge, knowledge, destination, self.stopping) - command = command_for_bundle(destination, managed=True) - name = (okf_documents.server_name_for(self.job.owner_id, destination) if knowledge_kind == 'document' - else server_name_for(self.job.owner_id, destination)) - self.names['mcp', source['id']] = name - existing = await motoro.get(MCPServerConfig, local) - if existing is not None: - if existing.owner_id != self.job.owner_id or existing.is_system: + if included is not None and included.get('directory') != f'resources/knowledge/{source_id}': + raise PackageError('Knowledge directory and identity disagree') + name = source['name'] + async with self.registration(motoro, errors, 'knowledge' if included else 'MCP server', name): + local = self.map('mcp', source['id'], source=source) + destination_server = None + if included is None and source.get('service_identity'): + authorized = list((await motoro.scalars(select(MCPServerConfig).where( + (MCPServerConfig.owner_id == self.job.owner_id) | MCPServerConfig.is_system.is_(True), + ))).all()) + destination_server = automatic_match(source, authorized) + if destination_server is not None: + self.runtime_bindings[source_id] = str(destination_server.id) + self.names['mcp', source_id] = destination_server.name + self.db.add(ImportedIdentity(import_id=self.job.id, kind='runtime_mcp', source_id=source_id, + local_id=destination_server.id, provenance={'requirement_id': str(local), + 'service_identity': source['service_identity'], 'selection': 'automatic'})) + # The owned requirement identity remains separate from its runtime binding. + continue + if included is not None: + knowledge_kind = source.get('knowledge_kind') + if knowledge_kind not in {'bundle', 'document'}: + source_graph = self.read('publication/canvas.json') + source_settings = self.read('publication/settings.json') + knowledge_kind = next(( + 'document' if node.get('type') == 'okf_document' else 'bundle' + for node in source_graph.get('nodes', []) + if node.get('type') in {'okf_bundle', 'okf_document'} + for variant in node_variants(node, source_settings.get('design_spec')) + if source['id'] in {((variant.get('data') or {}).get('config') or {}).get('bundle_id'), + ((variant.get('data') or {}).get('config') or {}).get('document_id')} + ), None) + if knowledge_kind is None: + raise ValueError('The package does not identify this knowledge source as a bundle or document.') + namespace = 'documents' if knowledge_kind == 'document' else 'bundles' + self.knowledge_namespaces[source['id']] = namespace + self.map('knowledge', source['id'], directory=knowledge.relative_to(self.root).as_posix()) + existing = await motoro.get(MCPServerConfig, local) + if existing is not None and (existing.owner_id != self.job.owner_id or existing.is_system): raise PackageError('Import server ownership conflict') - continue - motoro.add(MCPServerConfig(id=local, owner_id=self.job.owner_id, is_system=False, - name=name, transport=MCPTransport(source['transport']), command=command, - capabilities={'tools': [{'name': value} for value in source.get('tool_names', [])]}, - error_message='Import staging: configure locally after activation.')) + if existing is not None: + server = existing + elif included is not None: + files = await self.io(knowledge_files, knowledge) + if knowledge_kind == 'document': + concepts = [(path, text) for path, text in files + if '/' not in path and Path(path).stem not in {'index', 'log'}] + if len(concepts) != 1: + raise ValueError('An OKF document must contain exactly one concept Markdown file.') + server = await okf_documents.register_document(owner_id=self.job.owner_id, + text=concepts[0][1], filename=concepts[0][0], db=motoro, identifier=local, connect=False) + else: + folder = included.get('name') or 'knowledge' + server = await okf_bundles.register_uploaded_bundle(owner_id=self.job.owner_id, + files=[(f'{folder}/{path}', text) for path, text in files], + db=motoro, identifier=local, connect=False) + else: + server = await mcp_service.register_server(db=motoro, identifier=local, connect=False, + owner_id=self.job.owner_id, name=name, transport=source['transport']) + self.names['mcp', source_id] = server.name + # Hide the native row until the product identity ledger commits; + # activation removes this marker before completing the request. + server.error_message = 'Import staging: awaiting experiment activation.' + if included is not None: + stored = okf_bundles.bundle_path_from_command(server.command) + if stored is None: + raise ValueError('Knowledge registration did not provide its managed storage location.') + self.knowledge_paths[source_id] = stored await motoro.flush() + if errors: + raise RegistrationBatchError(errors) def config(self, kind: str, config: dict[str, Any]) -> dict[str, Any]: result = deepcopy(config) + if kind == 'persona': + source = snapshot_identity(config) + local = self.maps.get(('persona', source)) + if local: + result.update(mode='library', persona_id=local, persona_ids=[local], + persona_sources=[{'id': local, 'revision': 1, + 'prompt_sha256': hashlib.sha256((config.get('persona_text') or '').encode()).hexdigest()}]) fields = {'dataset': ('dataset_id', 'dataset'), 'skill': ('skill_id', 'skill'), 'okf_bundle': ('bundle_id', 'knowledge'), 'okf_document': ('document_id', 'knowledge'), 'mcp_tool': ('server_id', 'mcp'), 'mcp_client_tool': ('server_id', 'mcp'), @@ -356,9 +449,7 @@ def config(self, kind: str, config: dict[str, Any]) -> dict[str, Any]: result['server_name'] = self.names.get(('mcp', source), f'unconfigured-import-{result[field]}') if category == 'knowledge': key = 'document_path' if kind == 'okf_document' else 'bundle_path' - namespace = self.knowledge_namespaces.get(source, 'documents' if kind == 'okf_document' else 'bundles') - result[key] = str(managed_storage.roots()[namespace] / str(self.job.owner_id) - / 'imports' / str(identity(self.job, 'mcp', source))) + result[key] = self.knowledge_paths.get(source, '') return result def definition(self) -> tuple[dict[str, Any], dict[str, Any]]: @@ -424,29 +515,41 @@ def definition(self) -> tuple[dict[str, Any], dict[str, Any]]: return graph, settings async def activate(self, motoro: AsyncSession) -> uuid.UUID: + # Imported registrations are staged in Motoro until activation commits. + # The ledger still retains their IDs; readiness gates any execution. + previous = self.db.info.get('staging_skill_import') + self.db.info['staging_skill_import'] = True + try: + return await self._activate(motoro) + finally: + if previous is None: + self.db.info.pop('staging_skill_import', None) + else: + self.db.info['staging_skill_import'] = previous + + async def _activate(self, motoro: AsyncSession) -> uuid.UUID: manifest = self.read('manifest.json') metadata = self.read('experiment-metadata.json') experiment_id = self.map('experiment', manifest['experiment_id'], source=metadata) protocol_id = self.map('protocol', manifest['protocol_id']) - self.map('source_publication', manifest['publication']['id'], source=manifest['publication']) - datasets = await self.datasets() - await self.skills(motoro) - await self.servers(motoro) + self.map('source_publication', manifest['publication']['id'], source=manifest['publication'], + graph=self.read('publication/canvas.json'), settings=self.read('publication/settings.json'), + design=self.read('design/revision.json') if (self.root / 'design/revision.json').is_file() else None) + datasets = await self.register_resources(motoro) # Capture knowledge and external requirements as owned, typed records. # Content remains in managed storage; connections require explicit setup. for dep in records(self.root / 'dependencies.jsonl', self.limits): if dep.get('kind') in {'knowledge', 'mcp'}: self.map(dep['kind'], dep['id'], dependency=dep) graph, settings = self.definition() - experiment = ResearchExperiment(id=experiment_id, owner_id=self.job.owner_id, - name=self.name('experiment', manifest['experiment_id'], metadata.get('name') or 'Imported experiment'), + experiment = await create_experiment_with_available_name(self.db, + identifier=experiment_id, owner_id=self.job.owner_id, + name=metadata.get('name') or 'Imported experiment', description=metadata.get('description'), **{key: settings.get(key) for key in ( 'hypothesis', 'design_spec', 'measurement_plan', 'task_brief')}, design_type=settings.get('design_type') or 'factorial') - self.db.add(experiment) - await self.db.flush() - self.db.add(Protocol(id=protocol_id, owner_id=self.job.owner_id, experiment_id=experiment_id, - name=f'Imported protocol {protocol_id}', graph=graph)) + await create_protocol(self.db, identifier=protocol_id, owner_id=self.job.owner_id, + experiment_id=experiment_id, name=generated_protocol_name(experiment.name, experiment_id), graph=graph) await set_experiment_datasets(self.db, experiment_id, datasets) if manifest.get('design_revision_id'): design_id = self.map('design', manifest['design_revision_id'], source=self.read('design/revision.json')) @@ -480,23 +583,6 @@ async def activate(self, motoro: AsyncSession) -> uuid.UUID: cell_id=cell, replicate_number=source['replicate_number'], replicate_label=source['replicate_label'])) await self.db.flush() - for path in (self.root / 'results/attempts').glob('*/attempt.json'): - source = document(path, self.limits) - self.map('historical_attempt', source['id'], source=source, - directory=path.parent.relative_to(self.root).as_posix()) - await self.db.flush() - for path in (self.root / 'results/rows').glob('*.json'): - source = document(path, self.limits) - self.map('historical_row', source['id'], source=source) - await self.db.flush() - for scanned, record in enumerate(records(self.root / 'files.jsonl', self.limits)): - await self.report('recording_provenance', scanned) - if record['path'].startswith('results/artifacts/'): - self.map('historical_artifact', record['path'], source=record) - await self.db.flush() - else: - self.map('payload_member', record['path'], source=record) - await self.db.flush() await self.db.flush() return experiment_id diff --git a/src/asaree/services/package_setup.py b/src/asaree/services/package_setup.py index 5b3b7c51..ee0ddd61 100644 --- a/src/asaree/services/package_setup.py +++ b/src/asaree/services/package_setup.py @@ -17,27 +17,30 @@ from asaree.services.package_connections import compatible +async def source_requirements(db: AsyncSession, job: PackageImport) -> list[dict[str, Any]]: + records = (await db.scalars(select(ImportedIdentity).where( + ImportedIdentity.import_id == job.id, ImportedIdentity.kind == 'mcp'))).all() + return [record.provenance['source'] for record in records if 'source' in record.provenance] + + async def runtime_requirement_issues(db: AsyncSession, job: PackageImport, graph: dict[str, Any], design: dict[str, Any] | None) -> list[dict[str, Any]]: - from asaree.services import package_imports from asaree.services.experiment_packages import node_variants from asaree.services.package_reconstruction import identity - from asaree.services.package_validation import document implicit = {'asaree.system:asaree.mcp_servers.workspace_server': 'dataset', 'asaree.system:scikit_learn_mcp': 'dataset', 'asaree.system:asaree.mcp_servers.script_server': 'script'} issues: list[dict[str, Any]] = [] async with system_session(reason='validate imported runtime requirements without connecting') as resources: - for path in (package_imports.directory(job.id) / 'payload/requirements/mcp').glob('*.json'): - requirement = document(path, package_imports.limits()) + for requirement in await source_requirements(db, job): if requirement.get('knowledge_kind'): continue binding = await db.get(ImportedIdentity, (job.id, 'runtime_mcp', requirement['id'])) local = binding.local_id if binding else identity(job, 'mcp', requirement['id']) affected = [] for node in graph.get('nodes', []): - if (node.get('type') == implicit.get(requirement.get('service_identity')) + if (node.get('type') == implicit.get(requirement.get('service_identity') or '') or any(((variant.get('data') or {}).get('config') or {}).get('server_id') == str(local) for variant in node_variants(node, design))): affected.append(node['id']) @@ -57,26 +60,20 @@ async def validate_model_connection(db: AsyncSession, job: PackageImport, config provider = config.get('provider') or kind.removeprefix('model_').removeprefix('llm_') setting = await db.scalar(select(UserLLMSetting).where( UserLLMSetting.user_id == job.owner_id, UserLLMSetting.provider == provider)) - selection = await db.get(ImportedIdentity, (job.id, 'runtime_provider', provider)) - if setting is None or selection is None or selection.local_id != setting.id: - raise ValueError(f'Select the saved destination {provider} connection for Model node {node_id}.') + if setting is None: + raise ValueError(f'Configure your saved {provider} connection for Model node {node_id}.') for fallback in config.get('fallback_models') or []: await validate_model_connection(db, job, fallback, kind, node_id) async def setup_options(db: AsyncSession, job: PackageImport) -> dict[str, Any]: - from asaree.models.experiment import ResearchExperiment - from asaree.services import package_imports - from asaree.services.experiment_packages import node_variants from asaree.services.package_reconstruction import readiness_issues - from asaree.services.package_validation import document requirements = [] async with system_session(reason='list authorized import destination connections without connecting') as resources: servers = list((await resources.scalars(select(MCPServerConfig).where( (MCPServerConfig.owner_id == job.owner_id) | MCPServerConfig.is_system.is_(True)))).all()) - for path in (package_imports.directory(job.id) / 'payload/requirements/mcp').glob('*.json'): - source = document(path, package_imports.limits()) + for source in await source_requirements(db, job): if source.get('knowledge_kind'): continue binding = await db.get(ImportedIdentity, (job.id, 'runtime_mcp', source['id'])) @@ -85,28 +82,8 @@ async def setup_options(db: AsyncSession, job: PackageImport) -> dict[str, Any]: 'selected_id': str(binding.local_id) if binding else None, 'candidates': [{'id': str(server.id), 'name': server.name} for server in servers if compatible(source, server)]}) - protocol = await db.scalar(select(Protocol).where(Protocol.experiment_id == job.experiment_id)) - experiment = await db.get(ResearchExperiment, job.experiment_id) - required_providers: set[str] = set() - - def require_provider(config: dict[str, Any], kind: str) -> None: - required_providers.add(config.get('provider') or kind.removeprefix('model_').removeprefix('llm_')) - for fallback in config.get('fallback_models') or []: - require_provider(fallback, kind) - - for node in (protocol.graph if protocol else {}).get('nodes', []): - if str(node.get('type', '')).startswith(('model_', 'llm_')): - for variant in node_variants(node, experiment.design_spec if experiment else None): - require_provider((variant.get('data') or {}).get('config') or {}, node['type']) - settings = (await db.scalars(select(UserLLMSetting).where(UserLLMSetting.user_id == job.owner_id, - UserLLMSetting.provider.in_(required_providers)))).all() - providers = [] - for setting in settings: - binding = await db.get(ImportedIdentity, (job.id, 'runtime_provider', setting.provider)) - providers.append({'provider': setting.provider, 'id': str(setting.id), - 'selected': binding is not None and binding.local_id == setting.id}) issues = await readiness_issues(db, job) - return {'ready': not issues, 'issues': issues, 'mcp': requirements, 'providers': providers} + return {'ready': not issues, 'issues': issues, 'mcp': requirements} def rebind_definition(graph: dict[str, Any], design: dict[str, Any] | None, @@ -161,20 +138,15 @@ def config(value: dict[str, Any]) -> None: async def select_connection(db: AsyncSession, job: PackageImport, kind: str, source: str, destination: uuid.UUID) -> None: from asaree.models.experiment import ResearchExperiment - from asaree.services import package_imports from asaree.services.package_reconstruction import identity - from asaree.services.package_validation import canonical_identity, document - - if kind == 'provider': - setting = await db.scalar(select(UserLLMSetting).where(UserLLMSetting.id == destination, - UserLLMSetting.user_id == job.owner_id, UserLLMSetting.provider == source)) - if setting is None: - raise ValueError('Choose an authorized saved connection for this provider.') - mapping_kind = 'runtime_provider' - elif kind == 'mcp': + from asaree.services.package_validation import canonical_identity + + if kind == 'mcp': source = canonical_identity(source) - path = package_imports.directory(job.id) / f'payload/requirements/mcp/{source}.json' - requirement = document(path, package_imports.limits()) + recorded = await db.get(ImportedIdentity, (job.id, 'mcp', source)) + if recorded is None or 'source' not in recorded.provenance: + raise ValueError('Source connection requirement is unavailable.') + requirement = recorded.provenance['source'] async with system_session(reason='select authorized destination connection without execution') as resources: server = await resources.scalar(select(MCPServerConfig).where(MCPServerConfig.id == destination, (MCPServerConfig.owner_id == job.owner_id) | MCPServerConfig.is_system.is_(True))) @@ -191,13 +163,15 @@ async def select_connection(db: AsyncSession, job: PackageImport, kind: str, if protocol is None or experiment is None or experiment.locked_at is not None: raise ValueError('Unlock the editable experiment before changing connections.') old_design = deepcopy(experiment.design_spec) - source_root = package_imports.directory(job.id) / 'payload/publication' - source_graph = document(source_root / 'canvas.json', package_imports.limits()) - source_settings = document(source_root / 'settings.json', package_imports.limits()) + publication = await db.scalar(select(ImportedIdentity).where( + ImportedIdentity.import_id == job.id, ImportedIdentity.kind == 'source_publication')) + if publication is None: + raise ValueError('Source publication metadata is unavailable.') + source_graph = publication.provenance['graph'] + source_settings = publication.provenance['settings'] source_design = source_settings.get('design_spec') - legacy_design = source_root.parent / 'design/revision.json' - if source_design is None and legacy_design.exists(): - source_design = document(legacy_design, package_imports.limits()).get('design_spec') + if source_design is None: + source_design = (publication.provenance.get('design') or {}).get('design_spec') protocol.graph, experiment.design_spec = rebind_definition(protocol.graph, old_design, old, server, source_graph=source_graph, source_design=source_design, source_id=source, source_name=requirement['name']) diff --git a/src/asaree/services/package_source.py b/src/asaree/services/package_source.py new file mode 100644 index 00000000..70211956 --- /dev/null +++ b/src/asaree/services/package_source.py @@ -0,0 +1,51 @@ +"""Read retained package evidence without permanent extracted copies.""" +import uuid +import zipfile +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +from asaree.services import managed_storage +from asaree.services.package_validation import Limits, PackageError, document_bytes, member_path + + +def archive_path(identifier: uuid.UUID) -> Path: + root = managed_storage.roots()['backups'] + root.mkdir(parents=True, exist_ok=True, mode=0o700) + return root / f'experiment-package-{identifier}.zip' + + +def scratch_path(identifier: uuid.UUID) -> Path: + return managed_storage.roots()['scratch'] / f'experiment-package-{identifier}' + + +def members(identifier: uuid.UUID, prefix: str) -> list[str]: + with zipfile.ZipFile(archive_path(identifier)) as archive: + return [entry.filename for entry in archive.infolist() + if entry.filename.startswith(prefix) and not entry.is_dir()] + + +def document(identifier: uuid.UUID, name: str, limits: Limits) -> Any: + with zipfile.ZipFile(archive_path(identifier)) as archive, archive.open(member_path(name)) as source: + return document_bytes(source.read(limits.document + 1), name, limits) + + +def records(identifier: uuid.UUID, name: str, limits: Limits) -> Iterator[dict[str, Any]]: + with zipfile.ZipFile(archive_path(identifier)) as archive, archive.open(member_path(name)) as source: + while line := source.readline(limits.document + 1): + value = document_bytes(line, name, limits) + if not isinstance(value, dict): + raise PackageError(f'Expected object record: {name}') + yield value + + +def chunks(identifier: uuid.UUID, name: str) -> Iterator[bytes]: + with zipfile.ZipFile(archive_path(identifier)) as archive, archive.open(member_path(name)) as source: + while block := source.read(1024 * 1024): + yield block + + +def copy_member(identifier: uuid.UUID, name: str, destination: Path) -> None: + with destination.open('wb') as output: + for block in chunks(identifier, name): + output.write(block) diff --git a/src/asaree/services/package_validation.py b/src/asaree/services/package_validation.py index ef1522db..baf804a4 100644 --- a/src/asaree/services/package_validation.py +++ b/src/asaree/services/package_validation.py @@ -1,17 +1,19 @@ """Bounded, non-executing package inspection. Extracted bytes stay private.""" from __future__ import annotations -import gzip import hashlib import importlib.metadata import json -import tarfile +import stat +import struct import threading import uuid +import zipfile +import zlib from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path -from typing import Any, Protocol, cast +from typing import Any, BinaryIO from asaree.services.experiment_packages import BLOCK, credential_file, relative_path @@ -69,11 +71,17 @@ def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: def document(path: Path, limits: Limits) -> Any: if path.stat().st_size > limits.document: raise PackageError(f'JSON document exceeds limit: {path.name}') + return document_bytes(path.read_bytes(), path.name, limits) + + +def document_bytes(raw: bytes, name: str, limits: Limits) -> Any: + if len(raw) > limits.document: + raise PackageError(f'JSON document exceeds limit: {name}') try: - return json.loads(path.read_bytes(), object_pairs_hook=unique_object, + return json.loads(raw, object_pairs_hook=unique_object, parse_constant=lambda value: invalid(f'Non-finite JSON: {value}')) except (ValueError, UnicodeError, RecursionError) as exc: - raise PackageError(f'Invalid JSON: {path.name}: {exc}') from exc + raise PackageError(f'Invalid JSON: {name}: {exc}') from exc def records(path: Path, limits: Limits) -> Iterator[dict[str, Any]]: @@ -103,140 +111,114 @@ def verify(root: Path, record: dict[str, Any]) -> None: raise PackageError(f'Missing member or size/hash mismatch: {record["path"]}') -class Readable(Protocol): - def read(self, size: int = -1, /) -> bytes: ... - - -class ExpandedReader: - def __init__(self, stream: Readable, limit: int, stopping: threading.Event): - self.stream, self.limit, self.stopping, self.count = stream, limit, stopping, 0 - self.tail = b'' - - def read(self, size: int = -1) -> bytes: - if self.stopping.is_set(): - raise PackageError('Import cancelled') - value = self.stream.read(min(BLOCK, self.limit - self.count + 1, size if size >= 0 else BLOCK)) - self.count += len(value) - self.tail = (self.tail + value[-1024:])[-1024:] - if self.count > self.limit: - raise PackageError('Expanded archive exceeds configured limit') - return value - - -class PackageTarInfo(tarfile.TarInfo): - """Gate metadata before tarfile can allocate attacker-declared PAX buffers. +def check_zip_directory(source: BinaryIO, limits: Limits, stopping: threading.Event) -> int: + """Bound metadata before ZipFile buffers its central directory and entry objects. - The exporter emits ordinary files and local PAX path/size extensions only. - GNU sparse maps, global headers and nested extensions are not this format. + Read fixed ZIP/ZIP64 end records, then scan directory headers without loading + variable fields. Packages are single-disk ZIPs without executable prefixes, + trailing data or ZIP64 extensible data. Directory bytes use the document limit. """ - header_limit = 200002 - - @staticmethod - def padded(size: int) -> int: - return (size + 511) // 512 * 512 - - def _proc_member(self, archive: Any) -> Any: - headers = getattr(archive, '_package_headers', 0) + 1 - archive._package_headers = headers - if headers > self.header_limit: - raise PackageError('Archive metadata exceeds configured member count') - if self.type == tarfile.XHDTYPE: - return self._proc_pax(archive) - if self.type not in {tarfile.REGTYPE, tarfile.AREGTYPE}: - raise PackageError('Only ordinary files and local path/size PAX metadata are supported') - return super()._proc_member(archive) # type: ignore[misc] # Private stdlib hook, covered on supported Pythons. - - def _proc_pax(self, archive: Any) -> Any: - if self.size < 0 or self.size > 4096 or getattr(archive, '_package_pax_active', False): - raise PackageError('Oversized or nested archive metadata') - archive._package_pax_active = True - try: - raw = archive.fileobj.read(self.padded(self.size))[:self.size] - values: dict[str, str] = {} - offset = 0 - while offset < len(raw): - space = raw.find(b' ', offset) - if space < 0 or not raw[offset:space].isdigit(): - raise PackageError('Invalid archive metadata length') - length = int(raw[offset:space]) - if length <= space - offset + 1 or offset + length > len(raw): - raise PackageError('Invalid archive metadata record') - record = raw[space + 1:offset + length] - if not record.endswith(b'\n') or b'=' not in record: - raise PackageError('Invalid archive metadata field') - key, value = record[:-1].split(b'=', 1) - name = key.decode('ascii') - if name not in {'path', 'size'} or name in values: - raise PackageError('Unsupported or duplicate archive metadata field') - values[name] = value.decode('utf-8') - offset += length - following = type(self).fromtarfile(archive) - if following is None: - raise PackageError('Archive metadata has no file header') - if 'path' in values: - following.name = member_path(values['path']) - if 'size' in values: - if not values['size'].isdigit(): - raise PackageError('Invalid extended member size') - following.size = int(values['size']) - archive.offset = following.offset_data + self.padded(following.size) - following.pax_headers = values - following.offset = self.offset - return following - finally: - archive._package_pax_active = False + source.seek(0, 2) + size = source.tell() + source.seek(max(0, size - 65557)) # 22-byte end record plus the maximum ZIP comment. + tail = source.read(65557) + offset = tail.rfind(b'PK\x05\x06') + if offset < 0 or len(tail) - offset < 22: + raise PackageError('Expected a ZIP experiment package') + _, disk, directory_disk, disk_count, count, directory_size, directory_offset, comment_size = struct.unpack( + '<4s4H2IH', tail[offset:offset + 22]) + if offset + 22 + comment_size != len(tail): + raise PackageError('Truncated ZIP comment or unexpected trailing data') + directory_end = size - len(tail) + offset + if directory_end >= 20: + source.seek(directory_end - 20) + locator = source.read(20) + if locator.startswith(b'PK\x06\x07'): + _, locator_disk, zip64_offset, disks = struct.unpack('<4sIQI', locator) + if locator_disk or disks != 1 or zip64_offset + 56 != directory_end - 20: + raise PackageError('Unsupported ZIP64 directory layout') + source.seek(zip64_offset) + signature, record_size, _, _, disk, directory_disk, disk_count, count, directory_size, directory_offset = ( + struct.unpack('<4sQ2H2I4Q', source.read(56))) + if signature != b'PK\x06\x06' or record_size != 44: + raise PackageError('Unsupported ZIP64 directory metadata') + directory_end = zip64_offset + if disk or directory_disk or disk_count != count: + raise PackageError('Multi-disk ZIP packages are unsupported') + if count > limits.members: + raise PackageError('Archive exceeds configured member count') + if directory_size > limits.document: + raise PackageError('ZIP directory metadata exceeds configured document limit') + if directory_offset + directory_size != directory_end: + raise PackageError('Invalid ZIP directory bounds') + source.seek(directory_offset) + actual_count = 0 + while source.tell() < directory_end: + if stopping.is_set(): + raise PackageError('Import cancelled') + header = struct.unpack('<4s6H3I5H2I', source.read(46)) + actual_count += 1 + if actual_count > limits.members: + raise PackageError('Archive exceeds configured member count') + if header[0] != b'PK\x01\x02' or header[10] > 1024: + raise PackageError('Invalid ZIP directory entry or member path length') + source.seek(sum(header[10:13]), 1) # Filename, extra fields and entry comment. + if source.tell() > directory_end: + raise PackageError('Truncated ZIP directory entry') + if actual_count != count: + raise PackageError('ZIP directory member counts differ') + source.seek(0) + return actual_count def inspect(archive: Path, root: Path, limits: Limits, stopping: threading.Event) -> dict[str, Any]: - """Fresh root only. Never extractall, follow links, or trust tar metadata.""" + """Fresh root only. Never extractall, follow links, or trust ZIP sizes.""" if archive.stat().st_size > limits.compressed: raise PackageError('Compressed archive exceeds configured limit') root.mkdir(mode=0o700) - count = 0 try: - with gzip.open(archive, 'rb') as compressed: - expanded = ExpandedReader(compressed, limits.expanded, stopping) - class BoundedTarInfo(PackageTarInfo): - header_limit = limits.members * 2 + 2 - # Tar stream mode uses only read(), not the broader seekable IO API. - with tarfile.open(fileobj=cast(Any, expanded), mode='r|', tarinfo=BoundedTarInfo) as tar: - for member in tar: - count += 1 - if count > limits.members: - raise PackageError('Archive exceeds configured member count') - name = member_path(member.name) + if stopping.is_set(): + raise PackageError('Import cancelled') + with archive.open('rb') as stream: + count = check_zip_directory(stream, limits, stopping) + with zipfile.ZipFile(stream) as zipped: + expanded = 0 + for member in zipped.infolist(): + if member.orig_filename != member.filename: + raise PackageError('Invalid ZIP member filename') + name = member_path(member.filename) if credential_file(name): raise PackageError('Package contains an excluded credential-file identity') - if not member.isfile() or member.sparse is not None or member.size < 0: + mode = stat.S_IFMT(member.external_attr >> 16) + if member.is_dir() or member.external_attr & 0x10 or mode not in {0, stat.S_IFREG}: raise PackageError(f'Only ordinary files are accepted: {name}') - if member.size > limits.expanded: + if member.flag_bits & 1: + raise PackageError('Encrypted ZIP packages are unsupported') + if member.compress_type not in {zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED}: + raise PackageError('Unsupported ZIP compression method') + if expanded + member.file_size > limits.expanded: raise PackageError(f'Member exceeds expanded limit: {name}') destination = root / name destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - source = tar.extractfile(member) - if source is None: - raise PackageError(f'Missing member bytes: {name}') - with destination.open('xb') as output: + with zipped.open(member) as source, destination.open('xb') as output: destination.chmod(0o600) - remaining = member.size - while remaining: + written = 0 + while True: if stopping.is_set(): raise PackageError('Import cancelled') - block = source.read(min(remaining, BLOCK)) + block = source.read(min(BLOCK, limits.expanded - expanded + 1)) if not block: - raise PackageError(f'Truncated member: {name}') + break + written += len(block) + expanded += len(block) + if expanded > limits.expanded: + raise PackageError('Expanded archive exceeds configured limit') output.write(block) - remaining -= len(block) - tar.members.clear() # type: ignore[attr-defined] # Runtime cache, absent from typeshed. - if getattr(tar.fileobj, 'buf', b'').strip(b'\0'): - raise PackageError('Unexpected buffered data after tar end') - while block := expanded.read(BLOCK): - if block.strip(b'\0'): - raise PackageError('Unexpected data after tar end') - if expanded.count % 512 or expanded.tail != b'\0' * 1024: - raise PackageError('Missing complete tar end records') + if written != member.file_size: + raise PackageError(f'Truncated member: {name}') return validate(root, limits, count) - except (OSError, EOFError, tarfile.TarError, KeyError, TypeError, AttributeError, UnicodeError) as exc: + except (OSError, EOFError, zipfile.BadZipFile, zlib.error, struct.error, + NotImplementedError, KeyError, TypeError, AttributeError, UnicodeError) as exc: raise PackageError(f'Malformed experiment package: {exc}') from exc @@ -245,8 +227,8 @@ def validate(root: Path, limits: Limits, count: int) -> dict[str, Any]: if (manifest.get('format') != 'asaree.experiment-package' or type(manifest.get('schema_version')) is not int or manifest['schema_version'] not in (1, 2)): raise PackageError('Unsupported experiment package format/version; supported: 1, 2') - if type(manifest.get('results_included')) is not bool: - raise PackageError('results_included must be a Boolean') + if manifest.get('results_included') is not False: + raise PackageError('Experiment packages contain configuration and input assets only; results are unsupported') for key, name in (('files', 'files.jsonl'), ('dependencies', 'dependencies.jsonl')): if manifest[key]['path'] != name: raise PackageError(f'Invalid {key} inventory locator') @@ -262,12 +244,12 @@ def validate(root: Path, limits: Limits, count: int) -> dict[str, Any]: (markers / hashlib.sha256(name.encode()).hexdigest()).touch(exist_ok=False) verify(root, record) if name.split('/')[0] not in {'dependencies.jsonl', 'publication', 'experiment-metadata.json', - 'design', 'inputs', 'resources', 'requirements', 'results', 'sources'}: + 'design', 'inputs', 'resources', 'requirements', 'sources'}: raise PackageError(f'Unsupported payload category: {name}') schema_json = name in {'experiment-metadata.json', 'publication/canvas.json', 'publication/settings.json', 'inputs/bindings.json', 'design/revision.json'} or name.startswith(( 'inputs/datasets/', 'inputs/splits/', 'requirements/', 'resources/skill-metadata/', - 'results/attempts/', 'results/rows/')) + 'resources/personas/')) if schema_json and name.endswith('.json'): document(root / name, limits) elif name in {'dependencies.jsonl', 'design/cells.jsonl', 'design/replicates.jsonl'}: @@ -292,6 +274,26 @@ def validate(root: Path, limits: Limits, count: int) -> dict[str, Any]: settings = document(root / 'publication/settings.json', limits) if not isinstance(graph, dict) or not isinstance(settings, dict): raise PackageError('Canvas and settings must be objects') + for path in (root / 'resources/personas').glob('*.json'): + from asaree.services.personas import MAX_PROMPT_BYTES, snapshot_identity + + persona = document(path, limits) + source = snapshot_identity(persona['config']) + prompt = persona['config'].get('persona_text') or '' + if (persona['id'] != source or path.stem != source or not isinstance(prompt, str) + or len(prompt.encode()) > MAX_PROMPT_BYTES + or (path.with_suffix('.md')).read_bytes() != prompt.encode()): + raise PackageError('Persona snapshot identity or content mismatch') + from asaree.services.experiment_packages import node_variants + from asaree.services.personas import snapshot_identity + + for node in graph.get('nodes', []): + if node.get('type') != 'persona': + continue + for variant in node_variants(node, settings.get('design_spec')): + source = snapshot_identity((variant.get('data') or {}).get('config') or {}) + if not (root / f'resources/personas/{source}.json').is_file(): + raise PackageError('Persona snapshot is missing from the package') node_ids = [node['id'] for node in graph.get('nodes', [])] if len(set(node_ids)) != len(node_ids): raise PackageError('Duplicate canvas node identity') @@ -467,22 +469,3 @@ def require(kind: str, source: Any) -> dict[str, Any]: if type(record['replicate_number']) is not int or record['replicate_number'] < 1: raise PackageError('Invalid planned replicate number') remember(category, record['id'], record) - for path in (root / 'results/rows').glob('*.json'): - row = document(path, limits) - require('replicate', row['replicate_result_id']) - if row['protocol_revision_id'] != manifest['publication']['id']: - raise PackageError('Historical row belongs to a different publication') - remember('row', row['id'], row) - for path in (root / 'results/attempts').glob('*/attempt.json'): - attempt = document(path, limits) - if path.parent.name != str(uuid.UUID(attempt['id'])): - raise PackageError('Attempt path and identity disagree') - if not manifest.get('results_included'): - raise PackageError('Results present while manifest excludes results') - if attempt.get('replicate_result_id'): - require('replicate', attempt['replicate_result_id']) - if attempt.get('row_result_id') and manifest['schema_version'] >= 2: - require('row', attempt['row_result_id']) - remember('attempt', attempt['id'], attempt) - for file in (root / 'results/artifacts').glob('*'): - require('attempt', file.name) diff --git a/src/asaree/services/personas.py b/src/asaree/services/personas.py index 424a2524..fb0d6205 100644 --- a/src/asaree/services/personas.py +++ b/src/asaree/services/personas.py @@ -3,6 +3,7 @@ from __future__ import annotations import hashlib +import json import uuid from collections.abc import Sequence from pathlib import PurePosixPath @@ -12,6 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from asaree.models.persona import Persona +from asaree.services.import_visibility import active_identity MAX_PROMPT_BYTES = 1_000_000 @@ -24,6 +26,13 @@ def prompt_sha256(prompt: str) -> str: return hashlib.sha256(prompt.encode("utf-8")).hexdigest() +def snapshot_identity(config: dict[str, Any]) -> str: + """Identity of saved persona content, independent of source IDs and availability.""" + snapshot = {field: config.get(field) for field in ( + 'persona_text', 'persona_label', 'persona_description', 'persona_file')} + return hashlib.sha256(json.dumps(snapshot, sort_keys=True, ensure_ascii=False).encode()).hexdigest() + + def persona_name(name: str | None, source_filename: str | None, prompt: str) -> str: if name and name.strip(): return name.strip()[:255] @@ -47,21 +56,26 @@ def decode_persona_upload(filename: str | None, raw: bytes) -> tuple[str, str]: async def list_personas(db: AsyncSession, *, owner_id: uuid.UUID) -> Sequence[Persona]: - statement = select(Persona).where(Persona.owner_id == owner_id).order_by(Persona.name, Persona.id) + statement = select(Persona).where(Persona.owner_id == owner_id, active_identity(Persona.id)).order_by( + Persona.name, Persona.id) return (await db.scalars(statement)).all() async def get_persona(db: AsyncSession, persona_id: uuid.UUID, *, owner_id: uuid.UUID) -> Persona | None: - return await db.scalar(select(Persona).where(Persona.id == persona_id, Persona.owner_id == owner_id)) + persona: Persona | None = await db.scalar(select(Persona).where( + Persona.id == persona_id, Persona.owner_id == owner_id, active_identity(Persona.id))) + return persona async def create_persona( db: AsyncSession, *, owner_id: uuid.UUID, prompt: str, name: str | None = None, description: str | None = None, source_filename: str | None = None, traits: dict[str, Any] | None = None, + identifier: uuid.UUID | None = None, ) -> Persona: if len(prompt.encode("utf-8")) > MAX_PROMPT_BYTES: raise ValueError("Persona text must be no larger than 1 MB.") persona = Persona( + **({'id': identifier} if identifier else {}), owner_id=owner_id, name=persona_name(name, source_filename, prompt), prompt=prompt, description=description, source_filename=source_filename, traits=traits or {}, revision=1, ) @@ -75,7 +89,7 @@ async def update_persona( db: AsyncSession, persona_id: uuid.UUID, *, owner_id: uuid.UUID, expected_revision: int, fields: dict[str, Any], ) -> Persona | None: persona = await db.scalar( - select(Persona).where(Persona.id == persona_id, Persona.owner_id == owner_id) + select(Persona).where(Persona.id == persona_id, Persona.owner_id == owner_id, active_identity(Persona.id)) .with_for_update().execution_options(populate_existing=True) ) if persona is None: diff --git a/src/asaree/services/protocol_revisions.py b/src/asaree/services/protocol_revisions.py index ef176362..ee77edfa 100644 --- a/src/asaree/services/protocol_revisions.py +++ b/src/asaree/services/protocol_revisions.py @@ -24,6 +24,7 @@ from asaree.services.indexed_row_source import read_indexed_row_source from asaree.services.protocol_graph_schema import functional_protocol_graph_hash from asaree.services.sampling_snapshots import freeze_sampling, sampling_policy_is_current +from asaree.services.skill_references import skill_projection, validate_references async def get_revision(db: AsyncSession, revision_id: uuid.UUID) -> ProtocolRevision | None: @@ -155,6 +156,8 @@ async def publish_protocol( and published.dataset_inputs == dataset_inputs ) if published is not None and unchanged: + if skill_projection(published.graph): + await validate_references(db, protocol.owner_id, publication_id=published.id) return published if experiment is not None and experiment.locked_at is not None: raise ValueError("Experiment is locked. Unlock it before publishing a changed experiment.") @@ -203,6 +206,8 @@ async def publish_protocol( ) db.add(revision) await db.flush() + if skill_projection(revision.graph): + await validate_references(db, protocol.owner_id, publication_id=revision.id) retain_inputs(db, dataset_inputs, publication_id=revision.id) protocol.published_revision_id = revision.id await db.flush() diff --git a/src/asaree/services/protocol_runs.py b/src/asaree/services/protocol_runs.py index e9672824..9763c8e4 100644 --- a/src/asaree/services/protocol_runs.py +++ b/src/asaree/services/protocol_runs.py @@ -223,6 +223,11 @@ async def create_protocol_run( ) db.add(run) await db.flush() + from asaree.services.skill_references import skill_projection, validate_references + + retained_graph = publication.graph if publication else protocol.graph if protocol else {} + if skill_projection(retained_graph): + await validate_references(db, owner_id, run_id=run.id) retain_inputs(db, dataset_inputs, run_id=run.id) if row_slot is not None: row_slot.run_id = run.id diff --git a/src/asaree/services/protocols.py b/src/asaree/services/protocols.py index d1cddaab..62b0e110 100644 --- a/src/asaree/services/protocols.py +++ b/src/asaree/services/protocols.py @@ -12,6 +12,7 @@ from asaree.models.protocol import Protocol from asaree.services.protocol_graph_schema import normalize_protocol_graph +from asaree.services.skill_references import skill_projection, validate_references _DEFAULT_GRAPH: dict[str, Any] = {"nodes": [], "edges": []} _SETTABLE_FIELDS = frozenset({"name", "description", "experiment_id", "graph"}) @@ -82,8 +83,10 @@ async def create_protocol( description: str | None = None, experiment_id: uuid.UUID | None = None, graph: dict[str, Any] | None = None, + identifier: uuid.UUID | None = None, ) -> Protocol: protocol = Protocol( + **({'id': identifier} if identifier else {}), name=name, description=description, experiment_id=experiment_id, @@ -92,16 +95,21 @@ async def create_protocol( ) db.add(protocol) await db.flush() + if skill_projection(protocol.graph): + await validate_references(db, owner_id, protocol_id=protocol.id) await db.refresh(protocol) return protocol -async def get_protocol(db: AsyncSession, protocol_id: uuid.UUID) -> Protocol | None: +async def get_protocol(db: AsyncSession, protocol_id: uuid.UUID, *, lock: bool = False) -> Protocol | None: from asaree.models.package_import import PackageImport - return (await db.execute(select(Protocol).where(Protocol.id == protocol_id, + query = select(Protocol).where(Protocol.id == protocol_id, ~select(PackageImport.id).where(PackageImport.experiment_id == Protocol.experiment_id, - PackageImport.status != 'completed').exists()))).scalar_one_or_none() + PackageImport.status != 'completed').exists()) + if lock: + query = query.with_for_update().execution_options(populate_existing=True) + return (await db.execute(query)).scalar_one_or_none() async def get_protocol_by_name(db: AsyncSession, name: str, *, owner_id: uuid.UUID) -> Protocol | None: @@ -146,14 +154,20 @@ async def update_protocol( if unknown: raise ValueError(f"not settable on a protocol: {sorted(unknown)}") - protocol = await get_protocol(db, protocol_id) + protocol = await get_protocol(db, protocol_id, lock=True) if protocol is None: return None if isinstance(fields.get("graph"), dict): fields = {**fields, "graph": normalize_protocol_graph(fields["graph"])} + skill_change = ("experiment_id" in fields or ( + isinstance(fields.get("graph"), dict) + and skill_projection(fields["graph"]) != skill_projection(protocol.graph) + )) for key, value in fields.items(): setattr(protocol, key, value) await db.flush() + if skill_change: + await validate_references(db, protocol.owner_id, protocol_id=protocol.id) await db.refresh(protocol) return protocol diff --git a/src/asaree/services/resource_names.py b/src/asaree/services/resource_names.py new file mode 100644 index 00000000..3bec2d39 --- /dev/null +++ b/src/asaree/services/resource_names.py @@ -0,0 +1,15 @@ +"""Shared display-name allocation; database uniqueness remains authoritative.""" +from collections.abc import Iterable + + +def available_name(preferred: str, existing: Iterable[str], *, maximum: int = 255, + skill: bool = False) -> str: + names = set(existing) + base = preferred.strip()[:maximum] + candidate = base + number = 2 + while candidate in names: + suffix = f'-{number}' if skill else f' ({number})' + candidate = base[:maximum - len(suffix)].rstrip('-' if skill else ' ') + suffix + number += 1 + return candidate diff --git a/src/asaree/services/result_exports.py b/src/asaree/services/result_exports.py index 6767e3c8..c58c39b6 100644 --- a/src/asaree/services/result_exports.py +++ b/src/asaree/services/result_exports.py @@ -7,6 +7,7 @@ import io import json import logging +import re import shutil import time import uuid @@ -35,10 +36,16 @@ RETENTION = timedelta(hours=24) +def package_filename(experiment_name: str, *, version: int, metadata: bool = False) -> str: + """Identify the experiment and the published version contained in a package.""" + stem = re.sub(r'[^a-zA-Z0-9_-]+', '-', experiment_name.strip()).strip('-') or 'experiment' + return f"{stem}-v{version}.{'manifest.json' if metadata else 'zip'}" + + def export_path(identifier: uuid.UUID, *, metadata: bool = False, package: bool = False) -> Path: root = Path(get_settings().result_export_dir) root.mkdir(parents=True, exist_ok=True, mode=0o700) - return root / f"{identifier}.{'schema.json' if metadata else 'tar.gz' if package else 'csv'}" + return root / f"{identifier}.{'schema.json' if metadata else 'zip' if package else 'csv'}" def download_token(job: ResultJob) -> str: diff --git a/src/asaree/services/skill_references.py b/src/asaree/services/skill_references.py new file mode 100644 index 00000000..f1154e4f --- /dev/null +++ b/src/asaree/services/skill_references.py @@ -0,0 +1,262 @@ +"""ASAREE's immutable-registration policy and cross-database retention checks. + +Reference triggers and deletion share advisory transaction locks in ASAREE's +database. Validate AFTER a reference write: its lock then protects the Motoro +availability check until ASAREE commits. Motoro itself remains unchanged. +""" + +from __future__ import annotations + +import asyncio +import json +import re +import uuid +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Any + +from motoro.models.database import system_session +from motoro.models.skill import Skill +from motoro.services import skill_service +from sqlalchemy import func, literal, or_, select, text, union_all +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.sql.selectable import Subquery + +from asaree.models.experiment import ResearchExperiment +from asaree.models.experiment_design_revision import ExperimentDesignRevision +from asaree.models.package_import import ImportedIdentity, PackageImport +from asaree.models.protocol import Protocol +from asaree.models.protocol_revision import ProtocolRevision +from asaree.models.protocol_run import ProtocolRun +from asaree.models.skill_reference import SkillReference + +IMMUTABLE_MESSAGE = "Registered skills are immutable in ASAREE. Register a new skill with a different name instead." + + +class SkillUnavailableError(ValueError): + """An ASAREE definition tries to retain an unavailable registered skill.""" + + +class SkillInUseError(ValueError): + def __init__(self, uses: list[dict[str, Any]]): + self.uses = uses + kinds = {"draft canvas": "Canvas", "published version": "Published experiment version", + "run": "Saved run", "experiment factors": "Experiment factors", + "design revision": "Design history", "agent": "Saved agent", "agent run": "Saved agent run"} + labels = [] + for item in uses[:5]: + kind = kinds.get(item["kind"], item["kind"]) + name = str(item["name"]) + if item["kind"] in {"agent", "agent run"} and re.match(r"^protocol-[0-9a-fA-F-]{36}-", name): + labels.append(f"• {kind} from an experiment canvas") + else: + labels.append(f"• {kind}: {name}") + if len(uses) > 5: + labels.append(f"• And {len(uses) - 5} more") + super().__init__("This skill can’t be deleted while it’s in use.\n\nUsed by:\n" + "\n".join(labels) + + "\n\nRemove it from editable canvases or factor choices first. " + "Published versions, design history, saved agents, and runs also keep it in use.") + + +def skill_projection(graph: dict[str, Any]) -> list[Any]: + """Ignore positions and unrelated fields on the frequent canvas save path.""" + result = [] + for node in graph.get("nodes") or []: + data = node.get("data") or {} + bindings = data.get("factor_bindings") or {} + if node.get("type") == "skill" or "skill_selection" in data or "skill_selection" in bindings: + source = (data.get("config") or {}).get("skill_id") if node.get("type") == "skill" else None + if source: + try: + uuid.UUID(str(source)) + except (ValueError, TypeError, AttributeError) as exc: + raise SkillUnavailableError( + "A Skill node has an invalid skill ID. Select a registered skill.") from exc + result.append((node.get("id"), node.get("type"), source, data.get("skill_selection"), + bindings.get("config"), bindings.get("config.skill_id"), bindings.get("skill_selection"))) + return sorted(result, key=lambda item: str(item[0])) + + +def _uses_query() -> Subquery: + r = SkillReference + def fields(kind: str, identifier: Any, name: Any, owner: Any) -> tuple[Any, ...]: + return (r.skill_id, literal(kind).label("kind"), identifier.label("id"), + name.label("name"), owner.label("owner_id")) + + return union_all( + select(*fields("draft canvas", Protocol.id, Protocol.name, Protocol.owner_id)) + .join(Protocol, r.protocol_id == Protocol.id), + select(*fields("published version", ProtocolRevision.id, + func.concat(Protocol.name, " / version ", ProtocolRevision.revision), Protocol.owner_id)) + .join(ProtocolRevision, r.publication_id == ProtocolRevision.id) + .join(Protocol, ProtocolRevision.protocol_id == Protocol.id), + select(*fields("run", ProtocolRun.id, Protocol.name, ProtocolRun.owner_id)) + .join(ProtocolRun, r.run_id == ProtocolRun.id).join(Protocol, ProtocolRun.protocol_id == Protocol.id), + select(*fields("experiment factors", ResearchExperiment.id, + ResearchExperiment.name, ResearchExperiment.owner_id)) + .join(ResearchExperiment, r.experiment_id == ResearchExperiment.id), + select(*fields("design revision", ExperimentDesignRevision.id, + func.concat(ResearchExperiment.name, " / design ", ExperimentDesignRevision.revision), + ResearchExperiment.owner_id)) + .join(ExperimentDesignRevision, r.design_id == ExperimentDesignRevision.id) + .join(ResearchExperiment, ExperimentDesignRevision.experiment_id == ResearchExperiment.id), + ).subquery() + + +async def skill_uses(db: AsyncSession, skill_id: uuid.UUID) -> list[dict[str, Any]]: + uses = _uses_query() + product = [dict(row) for row in (await db.execute(select(uses).where(uses.c.skill_id == skill_id) + .order_by(uses.c.kind, uses.c.id))).mappings()] + async with system_session(reason="check registered skills retained by agents and agent runs") as resources: + runtime = [dict(row) for row in (await resources.execute(_runtime_uses_sql(), + {"skill_id": str(skill_id)})).mappings()] + return product + runtime + + +def _runtime_uses_sql() -> Any: + # Deletion/audit only: runtime cache rows and standalone runs are in the + # other database, so they cannot be foreign-key parents in the ledger. + return text(""" + WITH configurations AS ( + SELECT 'agent' AS kind, id, name, owner_id, skill_config::jsonb AS config + FROM agents WHERE deleted_at IS NULL + UNION ALL + SELECT 'agent run', r.id, a.name, coalesce(r.owner_id, a.owner_id), + coalesce(r.config_snapshot::jsonb->'skill_config', a.skill_config::jsonb) + FROM agent_runs r JOIN agents a ON a.id=r.agent_id + ) SELECT DISTINCT lower(value) AS skill_id, kind, id, name, owner_id + FROM configurations, LATERAL jsonb_array_elements_text( + CASE WHEN jsonb_typeof(config->'skill_ids')='array' THEN config->'skill_ids' ELSE '[]'::jsonb END) value + WHERE CAST(:skill_id AS text) IS NULL OR lower(value)=CAST(:skill_id AS text) + ORDER BY kind, id + """) + + +async def validate_references(db: AsyncSession, owner_id: uuid.UUID, **scope: uuid.UUID) -> None: + """Called after flush only when a definition's skill references change.""" + # Import registrations are uncommitted/soft-deleted until cross-database + # activation. Its existing readiness checks gate execution and publication. + if db.info.get("staging_skill_import"): + return + if len(scope) != 1 or next(iter(scope)) not in { + "protocol_id", "publication_id", "run_id", "experiment_id", "design_id" + }: + raise ValueError("Exactly one skill reference scope is required") + field, identifier = next(iter(scope.items())) + predicate = getattr(SkillReference, field) == identifier + if field == "experiment_id": + predicate = or_(predicate, SkillReference.protocol_id.in_( + select(Protocol.id).where(Protocol.experiment_id == identifier))) + identifiers = set((await db.scalars(select(SkillReference.skill_id).where(predicate))).all()) + await _validate_ids(db, owner_id, identifiers) + + +async def _validate_ids(db: AsyncSession, owner_id: uuid.UUID, identifiers: set[uuid.UUID]) -> None: + if not identifiers: + return + if await db.scalar(select(ImportedIdentity.local_id).join(PackageImport).where( + ImportedIdentity.kind == "skill", ImportedIdentity.local_id.in_(identifiers), + PackageImport.status != "completed", + ).limit(1)): + raise SkillUnavailableError("A selected skill belongs to an incomplete package import.") + async with system_session(reason="validate ASAREE registered skill references") as resources: + # Column selection deliberately avoids eagerly loading bundled files. + available = set((await resources.scalars(select(Skill.id).where( + Skill.id.in_(identifiers), Skill.deleted_at.is_(None), + (Skill.owner_id == owner_id) | Skill.is_system.is_(True), + ))).all()) + if available != identifiers: + raise SkillUnavailableError("A skill reference is unavailable. Register and select an available skill; " + "existing missing skill content cannot be reconstructed.") + + +@asynccontextmanager +async def protect_agent_run(agent: Any, owner_id: uuid.UUID) -> AsyncIterator[None]: + """Close the standalone-run creation/deletion race without changing Motoro.""" + identifiers = set(skill_service.skill_ids_from_config(getattr(agent, "skill_config", None))) + if not identifiers: + yield + return + from asaree.models.database import get_session + + async with get_session() as db: + for identifier in sorted(identifiers): + await db.execute(select(func.pg_advisory_xact_lock(1936419180, func.hashtext(str(identifier))))) + await _validate_ids(db, owner_id, identifiers) + yield + + +async def delete_registered_skill(db: AsyncSession, skill_id: uuid.UUID, owner_id: uuid.UUID) -> bool: + await db.execute(select(func.pg_advisory_xact_lock(1936419180, func.hashtext(str(skill_id))))) + skill = await skill_service.get_skill(skill_id) + if skill is None or skill.owner_id != owner_id: + return False + uses = await skill_uses(db, skill_id) + if uses: + # Legacy graphs could contain foreign IDs before attachment validation + # existed. Protect those records without exposing another user's data. + visible = [use if use["owner_id"] == owner_id else { + **use, "name": "another user's retained record", "id": "private", + } for use in uses] + raise SkillInUseError(visible) + # Keep the ASAREE lock until its transaction ends. A later attachment waits, + # then validates the now-deleted Motoro row and rolls back its reference. + return await skill_service.delete_skill(skill_id) + + +async def audit_references(db: AsyncSession) -> list[dict[str, Any]]: + """Report pre-existing missing/deleted/foreign sources without changing history.""" + uses = _uses_query() + issues = [] + async def inspect_batch(batch: Any) -> None: + normalized = [] + for row in batch: + try: + normalized.append({**dict(row), "skill_id": uuid.UUID(str(row["skill_id"]))}) + except (ValueError, TypeError): + issues.append({**dict(row), "reason": "invalid skill ID"}) + identifiers = {row["skill_id"] for row in normalized} + async with system_session(reason="audit ASAREE skill availability") as resources: + sources = {row.id: row for row in (await resources.execute(select( + Skill.id, Skill.owner_id, Skill.is_system, Skill.deleted_at, + ).where(Skill.id.in_(identifiers))))} + for row in normalized: + source = sources.get(row["skill_id"]) + reason = ("missing" if source is None else "deleted" if source.deleted_at else + "not accessible" if source.owner_id != row["owner_id"] and not source.is_system else None) + if reason: + issues.append({**row, "reason": reason}) + + stream = await db.stream(select(uses).order_by(uses.c.skill_id)) + try: + async for batch in stream.mappings().partitions(500): + await inspect_batch(batch) + finally: + await stream.close() + async with system_session(reason="audit skill references on agents and agent runs") as resources: + stream = await resources.stream(_runtime_uses_sql(), {"skill_id": None}) + try: + async for batch in stream.mappings().partitions(500): + await inspect_batch(batch) + finally: + await stream.close() + return issues + + +async def _audit() -> int: + from motoro.models.database import dispose_engine as dispose_motoro + + from asaree.models.database import dispose_engine, get_session + + try: + async with get_session() as db: + issues = await audit_references(db) + print(json.dumps({"unavailable_references": issues, "count": len(issues)}, default=str, indent=2)) + return bool(issues) + finally: + await dispose_engine() + await dispose_motoro() + + +if __name__ == "__main__": + raise SystemExit(asyncio.run(_audit())) diff --git a/tests/package_import_helpers.py b/tests/package_import_helpers.py new file mode 100644 index 00000000..cd4c596b --- /dev/null +++ b/tests/package_import_helpers.py @@ -0,0 +1,11 @@ +"""Storage configuration shared by package import tests.""" +from asaree_workspace_core.storage import NAMESPACES + +from asaree.config import AsareeSettings + + +def storage_settings(root): + # Child-process configuration exports explicit namespace paths into the + # environment. Reset those too: data_root alone cannot isolate a test. + return AsareeSettings(_env_file=None, data_root=str(root), + **{field: '' for field, _ in NAMESPACES.values()}) diff --git a/tests/test_experiment_creation_contract.py b/tests/test_experiment_creation_contract.py index d4e9eb79..b176f0a2 100644 --- a/tests/test_experiment_creation_contract.py +++ b/tests/test_experiment_creation_contract.py @@ -163,7 +163,7 @@ async def create_imported_experiment(_db: object, **kwargs: Any) -> SimpleNamesp return experiment monkeypatch.setattr(experiments_api, "get_experiment_by_name", AsyncMock(return_value=None)) - monkeypatch.setattr(experiments_api, "create_experiment", create_imported_experiment) + monkeypatch.setattr(experiments_api, "create_experiment_with_available_name", create_imported_experiment) monkeypatch.setattr(experiments_api, "create_protocol", AsyncMock(return_value=SimpleNamespace())) monkeypatch.setattr(experiments_api, "_require_valid_measurement_plan", require_local_server) monkeypatch.setattr(experiments_api, "get_experiment_dataset_ids", AsyncMock(return_value=[])) @@ -177,6 +177,7 @@ async def create_imported_experiment(_db: object, **kwargs: Any) -> SimpleNamesp name="asaree-sklearn-model", owner_id=None, is_system=True, + command="python -m asaree.mcp_servers.workspace_server", ) ] ), diff --git a/tests/test_experiment_package_boundaries.py b/tests/test_experiment_package_boundaries.py index 83489fe5..6657c5ea 100644 --- a/tests/test_experiment_package_boundaries.py +++ b/tests/test_experiment_package_boundaries.py @@ -163,151 +163,3 @@ async def test_missing_boundary_evidence_is_unresolved_before_capture(tmp_path, assert not any(name.startswith("resources/knowledge/") for name in contents) assert b"PRIVATE REGISTRY DETAILS" not in b"".join(contents.values()) registry.capture.assert_not_called() - - -@pytest.mark.parametrize(("row_mode", "verification"), [(False, "durable_outputs"), (False, "platform_scratch"), - (True, "durable_outputs")]) -async def test_wired_script_user_directories_survive_and_actual_workspace_scratch_does_not( - tmp_path, monkeypatch, verification, row_mode, -): - import pandas as pd - from asaree_workspace_core import Workspace - - from asaree.mcp_servers import script_server, workspace_server - from asaree.services import protocol_execution - - run, experiment = uuid.uuid4(), uuid.uuid4() - root = tmp_path / "workspaces" - workspace_id = f"_protocol_runs/{run}" if row_mode else f"{experiment}/{run}" - monkeypatch.setattr(protocol_execution, "_workspace_storage_root", lambda: root) - monkeypatch.setattr(packages.managed_storage, "roots", lambda: {"workspaces": root}) - source = ( - "from pathlib import Path\n" - "for name in ('working', 'cache', 'scratch', '__pycache__', '.scratch', " - "'results.preparing', '.report.preparing'):\n" - " output = Path('outputs') / name / 'prediction.csv'\n" - " output.parent.mkdir(parents=True, exist_ok=True)\n" - " output.write_text('durable prediction')\n" - ) - script = protocol_execution._materialize_script(workspace_id, "script", source) - ctx = SimpleNamespace(request_context=SimpleNamespace(meta=SimpleNamespace(model_extra={ - "motoro.ambient.script_path": script, - }))) - result = json.loads(script_server.run_wired_script(ctx=ctx)) - assert result["exit_code"] == 0 - for slot in (() if row_mode else (None, "dataset:cohort", "agent:worker")): - seed = tmp_path / f"seed-{slot or 'default'}.parquet" - pd.DataFrame({"x": [1], "y": [0]}).to_parquet(seed, index=False) - ws = Workspace.open(workspace_id, root=str(root), slot=slot, target_column="y", - seed_train_path=str(seed), seed_test_path=str(seed)) - scratch = workspace_server._scratch_dir(ws, "dc") - scratch.mkdir(parents=True, exist_ok=True) - (scratch / "unretained.tmp").write_text("PLATFORM SCRATCH MUST NOT APPEAR") - (ws.slot_dir / ".train.parquet.abcdefgh.preparing").write_text("PLATFORM PREPARATION MUST NOT APPEAR") - writer = writer_at(tmp_path) - await packages._attempt_files(writer, SimpleNamespace(experiment_id=experiment), run, - {"nodes": [{"id": "script", "type": "script"}]}) - writer.finish({}) - contents = unpack(tmp_path) - if verification == "durable_outputs": - for name in ("working", "cache", "scratch", "__pycache__", ".scratch", "results.preparing", - ".report.preparing"): - assert any(path.endswith(f"scripts/outputs/{name}/prediction.csv") for path in contents) - else: - assert all(b"PLATFORM SCRATCH MUST NOT APPEAR" not in value for value in contents.values()) - assert all(b"PLATFORM PREPARATION MUST NOT APPEAR" not in value for value in contents.values()) - - -@pytest.mark.parametrize("placement", ["workspace", "standalone_agent"]) -async def test_nested_script_outputs_keep_source_like_names_but_materialized_sources_are_excluded( - tmp_path, monkeypatch, placement, -): - from asaree.mcp_servers import script_server - from asaree.services import protocol_execution - - run, experiment = uuid.uuid4(), uuid.uuid4() - root = tmp_path / "workspaces" - monkeypatch.setattr(protocol_execution, "_workspace_storage_root", lambda: root) - monkeypatch.setattr(packages.managed_storage, "roots", lambda: {"workspaces": root}) - materialization = f"{experiment}/{run}" if placement == "workspace" else ( - protocol_execution._script_workspace_id(None, run, "worker") - ) - source = ( - "from pathlib import Path\n" - "for directory in ('outputs', 'outputs/scripts'):\n" - " Path(directory).mkdir(parents=True, exist_ok=True)\n" - " for name in ('script.py', 'inline-0123456789ab.py'):\n" - " (Path(directory) / name).write_text('durable Script output')\n" - ) - script = Path(protocol_execution._materialize_script(materialization, "script", source)) - inline = Path(protocol_execution._materialize_script(materialization, "inline-0123456789ab", "print('source')")) - ctx = SimpleNamespace(request_context=SimpleNamespace(meta=SimpleNamespace(model_extra={ - "motoro.ambient.script_path": str(script), - }))) - assert json.loads(script_server.run_wired_script(ctx=ctx))["exit_code"] == 0 - assert script.is_file() and inline.is_file() - writer = writer_at(tmp_path) - await packages._attempt_files(writer, SimpleNamespace(experiment_id=experiment), run, {"nodes": [ - {"id": "script", "type": "script"}, {"id": "worker", "type": "agent"}, - ]}) - writer.finish({}) - contents = unpack(tmp_path) - attempt = root / str(experiment) / str(run) if placement == "workspace" else root / "_protocol_runs" / str(run) - prefix = f"results/artifacts/{run}/" - for file in (script, inline): - assert prefix + file.relative_to(attempt).as_posix() not in contents - for directory in ("outputs", "outputs/scripts"): - for name in ("script.py", "inline-0123456789ab.py"): - member = prefix + (script.parent / directory / name).relative_to(attempt).as_posix() - assert contents[member] == b"durable Script output" - - -async def test_row_inputs_are_excluded_only_at_the_producers_exact_row_location(tmp_path, monkeypatch): - from asaree.mcp_servers import script_server - from asaree.services import dataset_row_workspaces, protocol_execution - from asaree.services.dataset_row_csv import RowSource - - run, whole_run, experiment, dataset = uuid.uuid4(), uuid.uuid4(), uuid.uuid4(), uuid.uuid4() - root = tmp_path / "workspaces" - monkeypatch.setattr(dataset_row_workspaces, "_workspace_root", lambda: root) - monkeypatch.setattr(protocol_execution, "_workspace_storage_root", lambda: root) - monkeypatch.setattr(packages.managed_storage, "roots", lambda: {"workspaces": root}) - prepared = dataset_row_workspaces.prepare_agent_row_inputs(run_id=run, agent_node_id="worker", - source=RowSource(str(dataset), "0" * 64, ("x",), (("exact",),)), - bindings=[{"agent_node_id": "worker", "dataset_id": str(dataset), "dataset_name": "cohort", - "row_index": 0, "columns": ["x"], "target_column": ""}]) - snapshot = Path(prepared["row_inputs"][0]["path"]) - row_attempt = root / "_protocol_runs" / str(run) - whole_attempt = root / str(experiment) / str(whole_run) - whole_agent = whole_attempt / "agents" / snapshot.parent.name - outputs = [snapshot.parent / "outputs" / snapshot.name, snapshot.parent / "outputs" / "row-view.json", - whole_agent / snapshot.name, whole_agent / "row-view.json", - row_attempt / "agents" / "user-output" / snapshot.name, - row_attempt / "agents" / "user-output" / "row-view.json"] - source = ( - "from pathlib import Path\n" - f"for filename in {[str(path) for path in outputs]!r}:\n" - " path = Path(filename)\n" - " path.parent.mkdir(parents=True, exist_ok=True)\n" - " path.write_text('durable row output')\n" - ) - script = protocol_execution._materialize_script(prepared["workspace_id"], "script", source) - ctx = SimpleNamespace(request_context=SimpleNamespace(meta=SimpleNamespace(model_extra={ - "motoro.ambient.script_path": script, - }))) - assert json.loads(script_server.run_wired_script(ctx=ctx))["exit_code"] == 0 - assert snapshot.is_file() and snapshot.with_name("row-view.json").is_file() - writer = writer_at(tmp_path) - for attempt_id in (run, whole_run): - await packages._attempt_files(writer, SimpleNamespace(experiment_id=experiment), attempt_id, - {"nodes": [{"id": "script", "type": "script"}]}) - writer.finish({}) - contents = unpack(tmp_path) - prefix = f"results/artifacts/{run}/" - assert prefix + snapshot.relative_to(row_attempt).as_posix() not in contents - assert prefix + snapshot.with_name("row-view.json").relative_to(row_attempt).as_posix() not in contents - for path in outputs: - attempt = whole_attempt if path.is_relative_to(whole_attempt) else row_attempt - attempt_id = whole_run if attempt == whole_attempt else run - member = f"results/artifacts/{attempt_id}/" + path.relative_to(attempt).as_posix() - assert contents[member] == b"durable row output" diff --git a/tests/test_experiment_package_postgres.py b/tests/test_experiment_package_postgres.py index ad579cc0..f0b63f20 100644 --- a/tests/test_experiment_package_postgres.py +++ b/tests/test_experiment_package_postgres.py @@ -1,14 +1,10 @@ """Package assembly against the existing disposable, isolated PostgreSQL fixture.""" -import json -import tarfile import uuid -from types import SimpleNamespace -from unittest.mock import AsyncMock +import zipfile from test_result_reads import results_db as _results_db from asaree.models.protocol_revision import ProtocolRevision -from asaree.models.protocol_run import ProtocolRun from asaree.services import experiment_packages as packages from asaree.services.dataset_inputs import freeze_dataset_inputs from asaree.services.datasets import create_dataset, quick_split_dataset @@ -16,7 +12,7 @@ results_db = _results_db -async def test_historical_package_pins_all_sources_splits_and_every_attempt(results_db, tmp_path, monkeypatch): +async def test_historical_package_pins_all_sources_and_splits_without_results(results_db, tmp_path, monkeypatch): from asaree.config import AsareeSettings db, scope, cell, user = results_db @@ -44,35 +40,18 @@ async def test_historical_package_pins_all_sources_splits_and_every_attempt(resu dataset = await db.get(RegisteredDataset, uuid.UUID(pin["dataset_id"])) await quick_split_dataset(db, dataset=dataset, seed=42) assert str(dataset.current_split_id) != pin["split_id"] - runs = [] - for number in range(3): - run = ProtocolRun(protocol_id=scope.protocol_id, owner_id=user.id, - protocol_revision_id=scope.protocol_revision_id if number < 2 else None, - design_revision_id=scope.design_revision_id, status="completed", - attempt_result={"measurement": {"observations": [{"value": "é" * 100000}]}}, - node_runs={}, factor_values={"attempt": number}) - db.add(run) - await db.flush() - runs.append(run.id) staging = tmp_path / "stage" staging.mkdir() - writer = packages.PackageWriter(tmp_path / "package.tar.gz", staging) + writer = packages.PackageWriter(tmp_path / "package.zip", staging) await packages._datasets(db, writer, publication, user.id) await packages._design(db, writer, publication) - await packages._results(db, writer, SimpleNamespace(owner_id=user.id, experiment_id=scope.experiment_id, - protocol_id=scope.protocol_id, protocol_revision_id=scope.protocol_revision_id, - design_revision_id=scope.design_revision_id), AsyncMock()) writer.finish({}) - with tarfile.open(tmp_path / "package.tar.gz") as archive: - names = archive.getnames() - assert f"results/attempts/{runs[0]}/attempt_result.json" in names - assert f"results/attempts/{runs[1]}/attempt_result.json" in names - assert all(str(runs[2]) not in name for name in names) + with zipfile.ZipFile(tmp_path / "package.zip") as archive: + names = archive.namelist() + assert not any(name.startswith('results/') for name in names) for pin in publication.dataset_inputs["inputs"]: - assert archive.extractfile(f"inputs/files/{pin['raw_artifact']['id']}.csv").read() == originals[ + assert archive.read(f"inputs/files/{pin['raw_artifact']['id']}.csv") == originals[ pin["dataset_id"]] assert f"inputs/splits/{pin['split_id']}.json" in names assert all(f"inputs/splits/{split}.json" in names for split in pinned_splits) - document = json.load(archive.extractfile(f"results/attempts/{runs[0]}/attempt_result.json")) - assert document["measurement"]["observations"][0]["value"] == "é" * 100000 assert all("row-index" not in name and "scratch" not in name for name in names) diff --git a/tests/test_experiment_packages.py b/tests/test_experiment_packages.py index f25d26c0..45e9fa68 100644 --- a/tests/test_experiment_packages.py +++ b/tests/test_experiment_packages.py @@ -4,6 +4,7 @@ import hashlib import json import uuid +import zipfile from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta from pathlib import Path @@ -23,21 +24,19 @@ def writer_at(tmp_path): staging = tmp_path / "stage" staging.mkdir() - return packages.PackageWriter(tmp_path / "package.tar.gz", staging) + return packages.PackageWriter(tmp_path / "package.zip", staging) def unpack(tmp_path): - import tarfile + with zipfile.ZipFile(tmp_path / "package.zip") as archive: + assert archive.testzip() is None + return {name: archive.read(name) for name in archive.namelist()} - with tarfile.open(tmp_path / "package.tar.gz") as archive: - return {member.name: archive.extractfile(member).read() for member in archive.getmembers()} - -def test_archive_hashes_inventory_and_tar_metadata_are_bounded(tmp_path): +def test_zip_archive_preserves_inventory_hashes_and_file_metadata(tmp_path): writer = writer_at(tmp_path) for number in range(1250): writer.json(f"records/{number}.json", {"number": number}, identity=str(number)) - assert not writer.tar.members writer.dependency("missing", "dataset", "publication_pinned", status="missing") result = writer.finish({"schema_version": 1}) contents = unpack(tmp_path) @@ -50,9 +49,16 @@ def test_archive_hashes_inventory_and_tar_metadata_are_bounded(tmp_path): assert record["sha256"] == hashlib.sha256(contents[record["path"]]).hexdigest() assert not Path(record["path"]).is_absolute() assert len(contents) == 1253 + with zipfile.ZipFile(tmp_path / "package.zip") as archive: + for member in archive.infolist(): + assert member.compress_type == zipfile.ZIP_DEFLATED + assert member.date_time == (1980, 1, 1, 0, 0, 0) + assert member.external_attr >> 16 == 0o600 -def test_exact_opaque_bytes_credentials_and_mismatched_source(tmp_path): +@pytest.mark.parametrize("zip64_limit", [zipfile.ZIP64_LIMIT, 32]) +def test_exact_opaque_bytes_credentials_and_mismatched_source(tmp_path, monkeypatch, zip64_limit): + monkeypatch.setattr(zipfile, "ZIP64_LIMIT", zip64_limit) writer = writer_at(tmp_path) source = tmp_path / "dataset.csv" original = b'api_key,password,path\r\n"not a credential",exact,/app/data/original\r\n' @@ -248,25 +254,6 @@ async def test_missing_and_foreign_datasets_never_substitute_current_bytes(tmp_p assert all(not name.startswith("inputs/files/") for name in unpack(tmp_path)) -async def test_results_evidence_is_sliced_in_sql_without_loading_whole_document(tmp_path): - text = json.dumps({"large": "é" * (packages.SQL_BLOCK * 3)}) - offsets = [] - - async def scalar(statement): - compiled = statement.compile(dialect=postgresql.dialect()) - offset, size = compiled.params["substr_2"], compiled.params["substr_3"] - offsets.append((offset, size)) - return text[offset - 1:offset - 1 + size] - - from sqlalchemy import Text, cast, select - - from asaree.models.protocol_run import ProtocolRun - - path = tmp_path / "result.json" - await packages.stream_document(SimpleNamespace(scalar=scalar), select(cast(ProtocolRun.attempt_result, Text)), path) - assert path.read_text() == text - assert len(offsets) >= 3 - assert all(size == packages.SQL_BLOCK for _, size in offsets) async def test_skill_capture_has_binary_resources_and_owner_predicate(tmp_path): @@ -359,42 +346,6 @@ async def close(self): assert sum(path.startswith("requirements/mcp/") for path in contents) == 1 -async def test_actual_row_script_and_compatibility_outputs_and_agent_slots_are_retained(tmp_path, monkeypatch): - from asaree.mcp_servers import script_server - from asaree.services import protocol_execution - - run, experiment = uuid.uuid4(), uuid.uuid4() - root = tmp_path / "workspaces" - monkeypatch.setattr(protocol_execution, "_workspace_storage_root", lambda: root) - monkeypatch.setattr(packages.managed_storage, "roots", lambda: {"workspaces": root}) - source = "from pathlib import Path\nPath('predictions.csv').write_text('exact prediction')\nprint('done')\n" - script = protocol_execution._materialize_script(f"_protocol_runs/{run}", "script-node", source) - extra = {"motoro.ambient.script_path": script} - ctx = SimpleNamespace(request_context=SimpleNamespace(meta=SimpleNamespace(model_extra=extra))) - result = json.loads(script_server.run_wired_script(ctx=ctx)) - assert result["exit_code"] == 0 - legacy = source.replace("print('done')", "assert Path('state.json').exists()") - script = protocol_execution._materialize_script(f"_protocol_runs/{run}", "legacy-script", legacy) - extra.update({"motoro.ambient.script_path": script, "motoro.ambient.dataset_mode": "per_row", - "motoro.ambient.data_path": str(tmp_path / "row.csv")}) - result = json.loads(script_server.run_wired_script(ctx=ctx)) - assert result["exit_code"] == 0 - agent_slot = root / str(experiment) / str(run) / "agent=worker" / "v1_dc" - agent_slot.mkdir(parents=True) - (agent_slot / "manifest.json").write_text('{"learned": "exact"}') - row_output = root / f"_protocol_runs/{run}/agents/hash/outputs" - row_output.mkdir(parents=True) - (row_output / "state.json").write_text("opaque user output with a familiar filename") - writer = writer_at(tmp_path) - graph = {"nodes": [{"id": "script-node", "type": "script"}, {"id": "legacy-script", "type": "script"}]} - await packages._attempt_files(writer, SimpleNamespace(experiment_id=experiment), run, graph) - writer.finish({}) - contents = unpack(tmp_path) - assert any(path.endswith("scripts/predictions.csv") for path in contents) - assert any("-unsplit-" in path and path.endswith("predictions.csv") for path in contents) - assert any(path.endswith("agent=worker/v1_dc/manifest.json") for path in contents) - assert any(path.endswith("agents/hash/outputs/state.json") for path in contents) - assert all(not path.endswith(("script-node.py", "legacy-script.py")) for path in contents) def selected_scope(): @@ -421,14 +372,13 @@ async def test_api_requires_explicit_publication_and_allows_legacy_without_curre assert create.call_args.kwargs["params"]["include_results"] is False -@pytest.mark.parametrize("include_results", [False, True]) -async def test_legacy_package_reports_missing_history_and_optional_results(tmp_path, monkeypatch, include_results): +async def test_package_fails_when_historical_inputs_are_unavailable(tmp_path, monkeypatch): publication = SimpleNamespace(id=uuid.uuid4(), graph={"nodes": [], "edges": []}, experiment_snapshot=None, dataset_inputs=None, design_revision_id=None, revision=1, published_at=datetime.now(UTC), name=None, note=None) job = SimpleNamespace(id=uuid.uuid4(), owner_id=uuid.uuid4(), experiment_id=uuid.uuid4(), protocol_id=uuid.uuid4(), protocol_revision_id=publication.id, design_revision_id=None, - params={"selection": {"include_results": include_results}}) + params={"selection": {}}) records = iter([SimpleNamespace(), publication]) queries = [] @@ -447,19 +397,57 @@ async def session(): monkeypatch.setattr(packages, "get_session", session) monkeypatch.setattr(packages, "_resources", AsyncMock()) monkeypatch.setattr(packages, "_import_sources", AsyncMock()) - results = AsyncMock() - monkeypatch.setattr(packages, "_results", results) monkeypatch.setattr(result_exports, "get_settings", lambda: SimpleNamespace(result_export_dir=str(tmp_path))) - await packages.execute_package(db, job, tmp_path / "partial", tmp_path / "package.tar.gz") + with pytest.raises(ValueError, match="Repair required assets"): + await packages.execute_package(db, job, tmp_path / "partial", tmp_path / "package.zip") assert "JOIN protocols ON protocol_revisions.protocol_id = protocols.id" in str(queries[1]) assert set(queries[1].params.values()) == { job.protocol_revision_id, job.protocol_id, job.experiment_id, job.owner_id, } - manifest = json.loads(unpack(tmp_path)["manifest.json"]) - assert manifest["completeness"]["status"] == "incomplete" - assert json.loads(unpack(tmp_path)["publication/settings.json"]) == {} - assert results.await_count == int(include_results) - assert not (tmp_path / "partial").exists() + assert not (tmp_path / "package.zip").exists() + + +async def test_configuration_only_package_excludes_results_even_if_a_stale_job_requests_them(tmp_path, monkeypatch): + import threading + + from asaree.services.package_validation import Limits, inspect + + publication = SimpleNamespace(id=uuid.uuid4(), graph={'nodes': [], 'edges': []}, + experiment_snapshot={'design_spec': {'factors': []}}, dataset_inputs={'schema_version': 1, 'inputs': []}, + design_revision_id=None, revision=1, published_at=datetime.now(UTC), name=None, note=None) + job = SimpleNamespace(id=uuid.uuid4(), owner_id=uuid.uuid4(), experiment_id=uuid.uuid4(), protocol_id=uuid.uuid4(), + protocol_revision_id=publication.id, design_revision_id=None, params={'selection': {'include_results': True}}) + db = SimpleNamespace(scalar=AsyncMock(side_effect=[SimpleNamespace(), publication])) + status_db = SimpleNamespace(scalar=AsyncMock(return_value='running'), execute=AsyncMock()) + + @asynccontextmanager + async def session(): + yield status_db + + monkeypatch.setattr(packages, 'get_session', session) + monkeypatch.setattr(packages, '_resources', AsyncMock()) + monkeypatch.setattr(packages, '_import_sources', AsyncMock()) + monkeypatch.setattr(result_exports, 'get_settings', lambda: SimpleNamespace(result_export_dir=str(tmp_path))) + await packages.execute_package(db, job, tmp_path / 'partial', tmp_path / 'package.zip') + contents = unpack(tmp_path) + manifest = json.loads(contents['manifest.json']) + assert manifest['results_included'] is False + assert not any(name.startswith('results/') for name in contents) + assert manifest['completeness']['unresolved_count'] == 0 + summary = inspect(tmp_path / 'package.zip', tmp_path / 'payload', Limits(), threading.Event()) + assert summary['unresolved_count'] == 0 + assert (tmp_path / 'package.zip').stat().st_mode & 0o777 == 0o600 + update_values = status_db.execute.call_args.args[0].compile().params + progress = update_values['progress'] + assert progress['bytes'] == (tmp_path / 'package.zip').stat().st_size + assert progress['sha256'] == hashlib.sha256((tmp_path / 'package.zip').read_bytes()).hexdigest() + + +def test_api_rejects_results_in_packages(): + from pydantic import ValidationError + + with pytest.raises(ValidationError): + api.Command(kind='export', request_key='results', format='experiment_package', include_results=True) async def test_package_download_expiry_and_owner_token(tmp_path, monkeypatch): @@ -478,6 +466,56 @@ async def test_package_download_expiry_and_owner_token(tmp_path, monkeypatch): assert owned.call_args.args[-1] == job.owner_id +@pytest.mark.parametrize('metadata', [False, True]) +@pytest.mark.parametrize('version', [1, 7]) +@pytest.mark.parametrize('name,stem', [ + ('My Experiment', 'My-Experiment'), + (' Study_2 - Revised ', 'Study_2---Revised'), + ('../../Study / "review"\r\n', 'Study-review'), + ('???', 'experiment'), +]) +async def test_package_download_uses_the_experiment_name_and_exported_version( + tmp_path, monkeypatch, metadata, version, name, stem, +): + job = SimpleNamespace(id=uuid.uuid4(), owner_id=uuid.uuid4(), experiment_id=uuid.uuid4(), kind='export', + status='completed', created_at=datetime.now(UTC), protocol_revision_id=uuid.uuid4(), protocol_id=uuid.uuid4(), + params={'selection': {'format': 'experiment_package'}}) + monkeypatch.setattr(result_exports, 'get_settings', lambda: SimpleNamespace( + result_export_dir=str(tmp_path), auth_secret_key='test-secret-key-at-least-32-characters')) + monkeypatch.setattr(api, 'owned_job', AsyncMock(return_value=job)) + get_experiment = AsyncMock(return_value=SimpleNamespace(name=name, owner_id=job.owner_id)) + monkeypatch.setattr(api, 'get_experiment', get_experiment) + path = result_exports.export_path(job.id, package=True, metadata=metadata) + path.write_bytes(b'prepared export') + db = SimpleNamespace(scalar=AsyncMock(return_value=version)) + response = await api.download(job.experiment_id, job.id, result_exports.download_token(job), db, metadata) + suffix = 'manifest.json' if metadata else 'zip' + assert response.headers['content-disposition'] == f'attachment; filename="{stem}-v{version}.{suffix}"' + assert response.headers['content-type'] == ('application/json' if metadata else 'application/zip') + assert response.path == path + get_experiment.assert_awaited_once_with(db, job.experiment_id) + # Resolve the publication pinned to the job, even if a newer version exists. + parameters = db.scalar.call_args.args[0].compile().params.values() + assert job.protocol_revision_id in parameters + assert job.protocol_id in parameters + assert job.experiment_id in parameters + assert job.owner_id in parameters + + +async def test_package_download_cannot_use_another_owners_experiment(tmp_path, monkeypatch): + job = SimpleNamespace(id=uuid.uuid4(), owner_id=uuid.uuid4(), experiment_id=uuid.uuid4(), kind='export', + status='completed', created_at=datetime.now(UTC), params={'selection': {'format': 'experiment_package'}}) + monkeypatch.setattr(result_exports, 'get_settings', lambda: SimpleNamespace( + result_export_dir=str(tmp_path), auth_secret_key='test-secret-key-at-least-32-characters')) + monkeypatch.setattr(api, 'owned_job', AsyncMock(return_value=job)) + monkeypatch.setattr(api, 'get_experiment', AsyncMock(return_value=SimpleNamespace( + name='Foreign experiment', owner_id=uuid.uuid4()))) + result_exports.export_path(job.id, package=True).write_bytes(b'prepared export') + with pytest.raises(HTTPException) as error: + await api.download(job.experiment_id, job.id, result_exports.download_token(job), SimpleNamespace()) + assert error.value.status_code == 404 + + async def test_expiry_removes_package_csv_and_partial_files(tmp_path, monkeypatch): identifier = uuid.uuid4() monkeypatch.setattr(result_exports, "get_settings", lambda: SimpleNamespace(result_export_dir=str(tmp_path))) diff --git a/tests/test_package_import_api.py b/tests/test_package_import_api.py new file mode 100644 index 00000000..c7a5074d --- /dev/null +++ b/tests/test_package_import_api.py @@ -0,0 +1,67 @@ +"""ZIP upload, retry and retained source downloads without external services.""" +import shutil +import threading +import uuid +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from test_package_import_validation import package + +from asaree.api import package_imports as api +from asaree.models.package_import import PackageImport +from asaree.services import package_imports as imports +from asaree.services import package_source +from asaree.services.package_validation import Limits, digest, inspect + + +@pytest.fixture +def upload_job(tmp_path, monkeypatch): + job = PackageImport(id=uuid.uuid4(), owner_id=uuid.uuid4(), request_key='zip-upload', status='uploading', + preflight={}, progress={}, expires_at=datetime.now(UTC) + timedelta(hours=1)) + db = SimpleNamespace(scalar=AsyncMock(return_value=True), commit=AsyncMock()) + root = tmp_path / 'scratch' + retained = tmp_path / 'backups' / 'experiment-package.zip' + monkeypatch.setattr(imports, 'directory', lambda identifier: root) + monkeypatch.setattr(package_source, 'archive_path', lambda identifier: retained) + monkeypatch.setattr(imports, 'limits', Limits) + monkeypatch.setattr(api, 'owned', AsyncMock(return_value=job)) + return job, db, root + + +async def test_uploaded_zip_can_be_inspected_retried_and_downloaded(tmp_path, upload_job): + job, db, root = upload_job + source = tmp_path / 'source' + source.mkdir() + archive = package(source) + data = archive.read_bytes() + + async def chunks(): + yield data[:17] + yield data[17:] + + response = await api.upload(job.id, SimpleNamespace(stream=chunks), db, SimpleNamespace(id=job.owner_id)) + stored = imports.archive_path(job.id) + assert stored.read_bytes() == data + assert stored.stat().st_mode & 0o777 == 0o600 + assert response['status'] == 'validating' + assert response['sha256'] == digest(archive) + assert not stored.with_suffix('.part').exists() + root.mkdir() + job.preflight = inspect(stored, root / 'payload', Limits(), threading.Event()) + expected_member = (root / 'payload/publication/canvas.json').read_bytes() + shutil.rmtree(root) # Source evidence survives removal of the temporary extraction. + job.status, job.generation = 'failed', 0 + retried = await api.retry(job.id, db, SimpleNamespace(id=job.owner_id)) + assert retried['status'] == 'validating' + assert job.generation == 1 + job.status = 'queued' + source_response = api.source_response(job, None) + assert source_response.path == stored + assert source_response.headers['content-type'] == 'application/zip' + assert source_response.headers['content-disposition'] == 'attachment; filename="experiment-package.zip"' + member_response = api.source_response(job, 'publication/canvas.json') + content = b''.join([chunk async for chunk in member_response.body_iterator]) + assert content == expected_member + assert member_response.headers['content-type'] == 'application/octet-stream' diff --git a/tests/test_package_import_lifecycle.py b/tests/test_package_import_lifecycle.py index b08719db..62773c30 100644 --- a/tests/test_package_import_lifecycle.py +++ b/tests/test_package_import_lifecycle.py @@ -1,10 +1,10 @@ """Real cross-database crash/retry and cancel/cleanup boundaries; CI PostgreSQL.""" -import io +import hashlib import os import shutil -import tarfile import threading import uuid +import zipfile from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta from pathlib import Path @@ -18,11 +18,12 @@ from alembic.script import ScriptDirectory from motoro.models.mcp_server import MCPServerConfig from motoro.models.skill import Skill, SkillFile +from package_import_helpers import storage_settings from sqlalchemy import func, select, text from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from asaree.api import package_imports as api -from asaree.config import AsareeSettings +from asaree.models.dataset import RegisteredDataset from asaree.models.experiment import ResearchExperiment from asaree.models.package_import import ImportedIdentity, PackageImport from asaree.models.user import User @@ -69,22 +70,22 @@ def migrate(connection, number=number): await engine.dispose() -def write_archive(job, root, *, version=2): +def write_archive(job, root, *, version=2, skill_name='retained-skill'): root.mkdir(parents=True) stage = root / 'writer' stage.mkdir() skill_id = str(uuid.uuid4()) - writer = PackageWriter(root / 'archive.tar.gz', stage) + writer = PackageWriter(imports.archive_path(job.id), stage) writer.json('publication/canvas.json', {'nodes': [ {'id': 'skill', 'type': 'skill', 'data': {'config': {'skill_id': skill_id}}}], 'edges': []}) writer.json('publication/settings.json', {'design_spec': {'factors': []}}) writer.json('experiment-metadata.json', {'name': 'Interrupted import'}) if version >= 2: writer.json(f'resources/skill-metadata/{skill_id}.json', { - 'id': skill_id, 'name': 'retained-skill', 'description': 'Source discovery', 'body': 'Never execute', + 'id': skill_id, 'name': skill_name, 'description': 'Source discovery', 'body': 'Never execute', 'frontmatter': {}, 'source_filename': None}) raw = stage / 'skill.md' - raw.write_text('---\nname: retained-skill\ndescription: Source discovery\n---\nNever execute') + raw.write_text(f'---\nname: {skill_name}\ndescription: Source discovery\n---\nNever execute') writer.add(raw, f'resources/skills/{skill_id}/SKILL.md', identity=skill_id, provenance='captured_at_download') resource_id = str(uuid.uuid4()) raw.write_bytes(b'\x00\xffnot JSON\r\n') @@ -101,8 +102,9 @@ def write_archive(job, root, *, version=2): async def test_durable_crash_retry_cancel_cleanup_and_ownership(import_databases, tmp_path, monkeypatch): product, resources = import_databases - settings = AsareeSettings(_env_file=None, data_root=str(tmp_path / 'storage')) + settings = storage_settings(tmp_path / 'storage') monkeypatch.setattr('asaree.config.get_settings', lambda: settings) + monkeypatch.setattr('asaree.services.managed_storage.get_settings', lambda: settings) @asynccontextmanager async def product_session(): @@ -144,12 +146,11 @@ async def resource_session(**kwargs): await imports.execute_package_import({}, str(job.id)) async with product.begin() as db: checked = await db.get(PackageImport, job.id) - assert checked.status == 'awaiting_confirmation' + assert checked.status == 'queued' assert await db.scalar(select(func.count()).select_from(ResearchExperiment)) == 0 with pytest.raises(Exception) as denied: - await api.confirm(job.id, db, foreign) + await api.get(job.id, db, foreign) assert denied.value.status_code == 404 - await api.confirm(job.id, db, owner) kill_after_resource_commit = resource_commits + 1 with pytest.raises(WorkerKilled): await imports.execute_package_import({}, str(job.id)) @@ -167,20 +168,33 @@ async def resource_session(**kwargs): assert await db.scalar(select(func.count()).select_from(ResearchExperiment)) == 1 assert await db.scalar(select(func.count()).select_from(ImportedIdentity).where( ImportedIdentity.kind == 'skill')) == 1 + assert not imports.directory(job.id).exists() + assert imports.archive_path(job.id).is_file() async with resources.begin() as db: assert await db.scalar(select(func.count()).select_from(Skill)) == 1 - # A second independent import of the exact same bytes has fresh identities. - # Simulate death after the visibility flip but before marking ASAREE complete. + # Importing the same skill again fails, just like a normal registration. async with product.begin() as db: - repeated = PackageImport(id=uuid.uuid4(), owner_id=owner.id, request_key='same-bytes-new-request', + collision = PackageImport(id=uuid.uuid4(), owner_id=owner.id, request_key='same-bytes-new-request', + status='validating', preflight={}, progress={}, expires_at=datetime.now(UTC) + timedelta(days=1)) + db.add(collision) + imports.directory(collision.id).mkdir(parents=True) + shutil.copyfile(imports.archive_path(job.id), imports.archive_path(collision.id)) + await imports.execute_package_import({}, str(collision.id)) + await imports.execute_package_import({}, str(collision.id)) + async with product.begin() as db: + rejected = await db.get(PackageImport, collision.id) + assert rejected.status == 'failed' + assert 'Could not register skill "retained-skill"' in rejected.error + assert 'already registered' in rejected.error + assert rejected.experiment_id is None + assert await db.scalar(select(func.count()).select_from(ResearchExperiment)) == 1 + # A different skill can be imported, including recovery after visibility activation. + async with product.begin() as db: + repeated = PackageImport(id=uuid.uuid4(), owner_id=owner.id, request_key='different-skill', status='validating', preflight={}, progress={}, expires_at=datetime.now(UTC) + timedelta(days=1)) db.add(repeated) - imports.directory(repeated.id).mkdir(parents=True) - shutil.copyfile(imports.directory(job.id) / 'archive.tar.gz', - imports.directory(repeated.id) / 'archive.tar.gz') + write_archive(repeated, imports.directory(repeated.id), skill_name='another-skill') await imports.execute_package_import({}, str(repeated.id)) - async with product.begin() as db: - await api.confirm(repeated.id, db, owner) kill_after_resource_commit = resource_commits + 2 with pytest.raises(WorkerKilled): await imports.execute_package_import({}, str(repeated.id)) @@ -200,15 +214,13 @@ async def resource_session(**kwargs): original_done = await db.get(PackageImport, job.id) assert repeated_done.status == 'completed' assert repeated_done.experiment_id != original_done.experiment_id - assert repeated_done.sha256 == original_done.sha256 + assert repeated_done.sha256 != original_done.sha256 async with product.begin() as db: cancelled = PackageImport(id=uuid.uuid4(), owner_id=owner.id, request_key='request-two', status='validating', preflight={}, progress={}, expires_at=datetime.now(UTC) + timedelta(days=1)) db.add(cancelled) - write_archive(cancelled, imports.directory(cancelled.id)) + write_archive(cancelled, imports.directory(cancelled.id), skill_name='cancelled-skill') await imports.execute_package_import({}, str(cancelled.id)) - async with product.begin() as db: - await api.confirm(cancelled.id, db, owner) original_checkpoint = imports.checkpoint async def cancel_at_activation(identifier, phase, **progress): @@ -228,12 +240,129 @@ async def cancel_at_activation(identifier, phase, **progress): assert await db.scalar(select(func.count()).select_from(Skill)) == 2 +def registration_failures_package(tmp_path, names): + from test_package_import_validation import package + + skills = [(str(uuid.uuid4()), name) for name in [*names, 'new-skill', 'new-skill']] + datasets = [(str(uuid.uuid4()), name, target) for name, target in ( + ('Valid dataset', 'y'), ('Invalid dataset', 'missing'))] + knowledge = [(str(uuid.uuid4()), name, content) for name, content in ( + ('Valid knowledge', '---\ntitle: Normal imported document\n---\nKnowledge'), + ('Invalid knowledge', 'Missing frontmatter'))] + + def populate(writer): + raw = writer.staging / 'resource' + for source, name in skills: + writer.json(f'resources/skill-metadata/{source}.json', {'id': source, 'name': name}) + raw.write_text(f'---\nname: {name}\ndescription: Import me\n---\nInstructions') + writer.add(raw, f'resources/skills/{source}/SKILL.md', identity=source, provenance='captured_at_download') + writer.dependency(source, 'skill', 'captured_at_download', directory=f'resources/skills/{source}') + pins = [] + for source, name, target in datasets: + artifact = str(uuid.uuid4()) + raw.write_bytes(b'x,y\n1,0\n2,1\n') + checksum = hashlib.sha256(raw.read_bytes()).hexdigest() + file = f'inputs/{artifact}.csv' + writer.add(raw, file, identity=artifact, provenance='publication_pinned') + writer.dependency(artifact, 'dataset_file', 'publication_pinned', file=file, + dataset_id=source, role='raw_artifact') + pins.append({'dataset_id': source, 'dataset_name': name, 'mode': 'whole_dataset', + 'target_column': target, 'raw_sha256': checksum, 'split_id': None, + 'raw_artifact': {'id': artifact, 'sha256': checksum}}) + writer.json('inputs/bindings.json', {'schema_version': 1, 'inputs': pins, 'bindings': []}) + for source, name, content in knowledge: + writer.json(f'requirements/mcp/{source}.json', {'id': source, 'name': name, + 'transport': 'stdio', 'knowledge_kind': 'document'}) + raw.write_text(content) + directory = f'resources/knowledge/{source}' + writer.add(raw, f'{directory}/concept.md', identity=source, provenance='captured_at_download') + writer.dependency(source, 'knowledge', 'captured_at_download', directory=directory, file_count=1) + writer.dependency(source, 'mcp', 'external_requirement') + + build = tmp_path / 'build' + build.mkdir() + graph = {'nodes': [ + *[{'id': source, 'type': 'skill', 'data': {'config': {'skill_id': source}}} for source, _ in skills], + *[{'id': source, 'type': 'dataset', 'data': {'config': {'dataset_id': source}}} + for source, _, _ in datasets], + *[{'id': source, 'type': 'okf_document', 'data': {'config': {'document_id': source}}} + for source, _, _ in knowledge], + ], 'edges': []} + return package(build, graph=graph, modify=populate) + + +async def test_all_registration_failures_are_reported_and_successful_resources_are_rolled_back( + import_databases, tmp_path, monkeypatch, +): + product, resources = import_databases + preserved = [] + for field in ('dataset_storage_dir', 'okf_document_dir'): + existing = tmp_path / 'existing' / field + existing.mkdir(parents=True) + marker = existing / 'keep.txt' + marker.write_text('Existing resource') + preserved.append(marker) + monkeypatch.setenv(f'ASAREE_{field.upper()}', str(existing)) + settings = storage_settings(tmp_path / 'storage') + for module in ('asaree.config', 'asaree.services.datasets', 'asaree.services.managed_storage', + 'asaree.services.okf_bundles', 'asaree.services.okf_documents'): + monkeypatch.setattr(f'{module}.get_settings', lambda: settings) + + @asynccontextmanager + async def product_session(): + async with product.begin() as db: + yield db + + @asynccontextmanager + async def resource_session(**kwargs): + async with resources.begin() as db: + yield db + + monkeypatch.setattr(imports, 'get_session', product_session) + monkeypatch.setattr(imports, 'system_session', resource_session) + async with product.begin() as db: + owner = User(email='batch@example.test', hashed_password='test', display_name='Importer') + db.add(owner) + names = [f'taken-{index:02}' for index in range(24)] + async with resources.begin() as db: + db.add_all([Skill(name=name, owner_id=owner.id, description='Existing', body='Keep me') for name in names]) + async with product.begin() as db: + job = PackageImport(id=uuid.uuid4(), owner_id=owner.id, request_key='batch-errors', + status='validating', preflight={}, progress={}, expires_at=datetime.now(UTC) + timedelta(days=1)) + db.add(job) + archive = registration_failures_package(tmp_path, names) + shutil.copyfile(archive, imports.archive_path(job.id)) + await imports.execute_package_import({}, str(job.id)) + async with product.begin() as db: + checked = await db.get(PackageImport, job.id) + assert checked.status == 'queued', checked.error + await imports.execute_package_import({}, str(job.id)) + async with product.begin() as db: + failed = await db.get(PackageImport, job.id) + assert failed.status == 'failed' + assert failed.error.startswith('Could not import 27 resources:'), failed.error + assert len(failed.error) > 2000 # Every error survives persistence, beyond the old single-error limit. + assert all(f'"{name}"' in failed.error for name in [*names, 'new-skill', + 'Invalid dataset', 'Invalid knowledge']) + assert failed.experiment_id is None + for model in (ResearchExperiment, RegisteredDataset, ImportedIdentity): + assert await db.scalar(select(func.count()).select_from(model)) == 0 + async with resources.begin() as db: + assert await db.scalar(select(func.count()).select_from(Skill)) == len(names) + assert await db.scalar(select(func.count()).select_from(MCPServerConfig)) == 0 + for root in (settings.dataset_storage_dir, settings.okf_document_dir): + remaining = [str(path) for path in Path(root).rglob('*') if path.is_file()] + assert not remaining, remaining + assert all(marker.read_text() == 'Existing resource' for marker in preserved) + + async def test_expiry_isolates_malformed_upload_and_compensation_failure_from_pending_import( import_databases, tmp_path, monkeypatch, ): product, resources = import_databases - settings = AsareeSettings(_env_file=None, data_root=str(tmp_path / 'storage')) + settings = storage_settings(tmp_path / 'storage') monkeypatch.setattr('asaree.config.get_settings', lambda: settings) + monkeypatch.setattr('asaree.services.managed_storage.get_settings', lambda: settings) @asynccontextmanager async def product_session(): @@ -260,11 +389,9 @@ async def resource_session(**kwargs): bad, failing, staged, pending = jobs root = imports.directory(bad.id) root.mkdir(parents=True) - with tarfile.open(root / 'archive.tar.gz', 'w:gz') as output: + with zipfile.ZipFile(imports.archive_path(bad.id), 'w') as output: for name, data in [('manifest.json', b'{}'), ('dependencies.jsonl', b'{not-json\n')]: - member = tarfile.TarInfo(name) - member.size = len(data) - output.addfile(member, io.BytesIO(data)) + output.writestr(name, data) await imports.execute_package_import({}, str(bad.id)) assert (root / 'payload/dependencies.jsonl').is_file() staged_ids = [] @@ -272,14 +399,14 @@ async def resource_session(**kwargs): for job in (failing, staged): job_root = imports.directory(job.id) write_archive(job, job_root) - preflight = inspect(job_root / 'archive.tar.gz', job_root / 'payload', Limits(), threading.Event()) + preflight = inspect(imports.archive_path(job.id), job_root / 'payload', Limits(), threading.Event()) source_skill = next((job_root / 'payload/resources/skills').iterdir()).name local_id = identity(job, 'skill', source_skill) staged_ids.append(local_id) async with product.begin() as db: current = await db.get(PackageImport, job.id) current.preflight = preflight - current.sha256 = digest(job_root / 'archive.tar.gz') + current.sha256 = digest(imports.archive_path(job.id)) async with resources.begin() as motoro: reconstruction = Reconstruction(db, current, job_root / 'payload', Limits()) current.experiment_id = await reconstruction.activate(motoro) @@ -312,7 +439,7 @@ async def run_enqueued(function, job_id, **kwargs): assert retained.experiment_id == staged_experiments[failing.id] assert await db.get(ResearchExperiment, retained.experiment_id) is not None assert await db.get(ResearchExperiment, staged_experiments[staged.id]) is None - assert (await db.get(PackageImport, pending.id)).status == 'awaiting_confirmation' + assert (await db.get(PackageImport, pending.id)).status == 'queued' assert not root.exists() assert not imports.directory(staged.id).exists() assert imports.directory(failing.id).exists() diff --git a/tests/test_package_import_postgres.py b/tests/test_package_import_postgres.py index ed92ab23..eeefd966 100644 --- a/tests/test_package_import_postgres.py +++ b/tests/test_package_import_postgres.py @@ -8,11 +8,11 @@ import os import threading import uuid +import zipfile from contextlib import asynccontextmanager from dataclasses import replace from datetime import UTC, datetime, timedelta from pathlib import Path -from types import SimpleNamespace from unittest.mock import AsyncMock import pytest @@ -20,6 +20,7 @@ from fastapi import HTTPException from motoro.models.mcp_server import MCPServerConfig, MCPTransport from motoro.models.skill import Skill, SkillFile +from package_import_helpers import storage_settings from sqlalchemy import func, select, text from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from test_result_reads import results_db as _results_db @@ -29,9 +30,6 @@ from asaree.config import AsareeSettings from asaree.models.dataset import RegisteredDataset from asaree.models.experiment import ResearchExperiment -from asaree.models.factorial_cell import FactorialCell -from asaree.models.factorial_replicate_result import FactorialReplicateResult -from asaree.models.factorial_row_result import FactorialRowResult from asaree.models.package_import import ImportedIdentity, PackageImport from asaree.models.protocol import Protocol from asaree.models.protocol_revision import ProtocolRevision @@ -40,33 +38,90 @@ from asaree.services import experiment_packages as packages from asaree.services import okf_bundles, okf_documents from asaree.services import package_imports as imports -from asaree.services.dataset_inputs import freeze_dataset_inputs, resolve_attempt_inputs +from asaree.services.dataset_inputs import freeze_dataset_inputs from asaree.services.datasets import create_dataset, quick_split_dataset from asaree.services.design_generation import generate_design_cells +from asaree.services.experiment_packages import PackageWriter from asaree.services.package_reconstruction import Reconstruction, require_configured -from asaree.services.package_validation import Limits, inspect +from asaree.services.package_validation import Limits, PackageError, inspect results_db = _results_db -def storage_settings(root): - from asaree_workspace_core.storage import NAMESPACES +@pytest.mark.parametrize('same_owner', [True, False]) +async def test_imported_skills_follow_normal_owner_name_uniqueness( + results_db, resource_db, tmp_path, monkeypatch, same_owner, +): + from test_package_import_lifecycle import write_archive - return AsareeSettings(_env_file=None, data_root=str(root), - **{field: '' for field, _ in NAMESPACES.values()}) + db, _, _, owner = results_db + settings = AsareeSettings(_env_file=None, data_root=str(tmp_path / 'storage')) + monkeypatch.setattr('asaree.config.get_settings', lambda: settings) + existing = Skill(id=uuid.uuid4(), owner_id=owner.id if same_owner else uuid.uuid4(), + name='retained-skill', description='Existing registration', body='Keep existing content', is_system=False) + resource_db.add(existing) + await resource_db.flush() + job = PackageImport(id=uuid.uuid4(), owner_id=owner.id, request_key='skill-conflict', status='queued', + preflight={}, progress={}, expires_at=datetime.now(UTC) + timedelta(days=1)) + db.add(job) + await db.flush() + root = imports.directory(job.id) + write_archive(job, root) + inspect(imports.archive_path(job.id), root / 'payload', Limits(), threading.Event()) + importer = Reconstruction(db, job, root / 'payload', Limits()) + if same_owner: + with pytest.raises(PackageError, match='Could not register skill "retained-skill".*already registered'): + async with db.begin_nested(), resource_db.begin_nested(): + await importer.skills(resource_db) + count = await resource_db.scalar(select(func.count()).select_from(Skill)) + assert count == 1 + assert existing.name == 'retained-skill' and existing.body == 'Keep existing content' + else: + await importer.skills(resource_db) + source = next((root / 'payload/resources/skills').iterdir()).name + restored = await resource_db.get(Skill, uuid.UUID(importer.maps['skill', source])) + assert restored.owner_id == owner.id and restored.name == 'retained-skill' + assert restored.id != existing.id -async def select_test_provider(db, job): - from asaree.services.package_setup import select_connection +async def test_imported_dataset_name_conflict_fails_without_renaming(results_db, tmp_path, monkeypatch): + db, _, _, owner = results_db + settings = AsareeSettings(_env_file=None, data_root=str(tmp_path / 'storage')) + monkeypatch.setattr('asaree.config.get_settings', lambda: settings) + monkeypatch.setattr('asaree.services.datasets.get_settings', lambda: settings) + raw = b'x,y\n1,0\n2,1\n' + existing = await create_dataset(db, owner_id=owner.id, name='Existing dataset', csv_bytes=raw) + job = PackageImport(id=uuid.uuid4(), owner_id=owner.id, request_key='dataset-conflict', status='queued', + preflight={}, progress={}, expires_at=datetime.now(UTC) + timedelta(days=1)) + db.add(job) + await db.flush() + root = imports.directory(job.id) / 'payload' + (root / 'inputs').mkdir(parents=True) + source, artifact = str(uuid.uuid4()), str(uuid.uuid4()) + (root / f'inputs/{artifact}.csv').write_bytes(raw) + (root / 'inputs/bindings.json').write_text(json.dumps({'inputs': [ + {'dataset_id': source, 'dataset_name': 'Existing dataset'}]})) + (root / 'dependencies.jsonl').write_text(json.dumps({'id': artifact, 'kind': 'dataset_file', + 'status': 'included', 'role': 'raw_artifact', 'dataset_id': source, 'file': f'inputs/{artifact}.csv'}) + '\n') + importer = Reconstruction(db, job, root, Limits()) + with pytest.raises(PackageError, match='Could not register dataset "Existing dataset".*already in use'): + async with db.begin_nested(): + await importer.datasets() + assert await db.scalar(select(func.count()).select_from(RegisteredDataset).where( + RegisteredDataset.owner_id == owner.id, RegisteredDataset.name == 'Existing dataset')) == 1 + assert Path(existing.raw_path).read_bytes() == raw + +async def select_test_provider(db, job): setting = UserLLMSetting(user_id=job.owner_id, provider='openai', api_key_encrypted='destination-only') db.add(setting) await db.flush() - await select_connection(db, job, 'provider', 'openai', setting.id) -async def test_provider_factor_alternatives_need_explicit_owned_connections(results_db, monkeypatch, tmp_path): - from asaree.services import package_reconstruction, package_setup +async def test_provider_factor_alternatives_use_saved_owned_connections_automatically( + results_db, monkeypatch, tmp_path, +): + from asaree.services import package_reconstruction db, scope, _, owner = results_db settings = storage_settings(tmp_path / 'provider-setup') @@ -87,9 +142,6 @@ async def test_provider_factor_alternatives_need_explicit_owned_connections(resu anthropic = UserLLMSetting(user_id=owner.id, provider='anthropic', api_key_encrypted='destination-anthropic') db.add(anthropic) await db.flush() - with pytest.raises(ValueError, match='authorized'): - await package_setup.select_connection(db, job, 'provider', 'openai', anthropic.id) - await package_setup.select_connection(db, job, 'provider', 'anthropic', anthropic.id) await package_reconstruction.require_configured(db, experiment.id) assert job.configured_at is None assert anthropic.api_key_encrypted == 'destination-anthropic' @@ -160,10 +212,9 @@ async def resources(**kwargs): monkeypatch.setattr(package_reconstruction, 'system_session', resources) monkeypatch.setattr(sampling_snapshots, 'build_model_config', AsyncMock(return_value=ModelConfig(model='gpt-test'))) monkeypatch.setattr(sampling_snapshots, 'resolve_discovery_context', AsyncMock(return_value={})) - command = api.Configuration(connections_configured=True, dependencies_resolved=True) - with pytest.raises(HTTPException, match='split') as error: - await api.configuration(job.id, command, db, owner) - assert error.value.status_code == 422 and job.configured_at is None + readiness = await api.readiness(job.id, db, owner) + assert not readiness['ready'] + assert any('split' in issue['message'] for issue in readiness['issues']) with pytest.raises(HTTPException) as error: await publish_protocol_endpoint(protocol.id, owner, db) assert error.value.status_code == 422 and protocol.published_revision_id is None @@ -223,6 +274,112 @@ async def destination_resource_db(): yield value +async def test_legacy_json_creates_only_a_draft_and_uses_shared_collision_handling(results_db, monkeypatch): + from asaree.api import experiments as api_experiments + from asaree.services.experiments import create_experiment_with_available_name + + db, _, _, owner = results_db + existing = await create_experiment_with_available_name(db, name='Imported JSON', owner_id=owner.id) + existing.archived_at = datetime.now(UTC) + monkeypatch.setattr(api_experiments.mcp_service, 'list_servers', AsyncMock(return_value=[])) + graph = {'nodes': [{'id': 'draft-node', 'type': 'agent', + 'data': {'config': {'system_prompt': 'Preserve the current draft'}}}], 'edges': []} + request = api_experiments.ImportExperimentDefinitionRequest(name='Imported JSON', graph=graph, + hypothesis='Preserve this hypothesis', + published_graph={'nodes': [{'id': 'old-node', 'type': 'agent', 'data': {}}], 'edges': []}) + for number in (2, 3): + created = await api_experiments.import_experiment_definition_endpoint(request, owner, db) + assert created.name == f'Imported JSON ({number})' + assert created.hypothesis == 'Preserve this hypothesis' + protocol = await db.scalar(select(Protocol).where(Protocol.experiment_id == created.id)) + assert protocol.graph == graph + assert protocol.published_revision_id is None + assert await db.scalar(select(func.count()).select_from(ProtocolRevision).where( + ProtocolRevision.protocol_id == protocol.id)) == 0 + + +async def test_persona_snapshots_and_subagents_survive_repeated_independent_imports( + results_db, resource_db, tmp_path, monkeypatch, +): + from asaree.models.persona import Persona + from asaree.services.experiments import create_experiment_with_available_name + from asaree.services.personas import get_persona, list_personas, snapshot_identity + + db, _, _, owner = results_db + settings = storage_settings(tmp_path / 'personas') + monkeypatch.setattr('asaree.services.managed_storage.get_settings', lambda: settings) + config = {'mode': 'library', 'persona_ids': [str(uuid.uuid4()), str(uuid.uuid4())], + 'persona_text': '# First\r\nBe careful.\n\n# Second\nBe curious. λ', + 'persona_label': 'Combined persona', 'persona_file': 'combined.md'} + graph = {'nodes': [ + {'id': 'parent', 'type': 'agent', 'data': {'config': {'system_prompt': 'Delegate to @child'}, + 'factor_bindings': {'sub_agent_selection': 'Workers', 'persona_selection': 'Personas'}, + 'sub_agent_selection': ['child'], 'persona_selection': ['persona']}}, + {'id': 'child', 'type': 'sub_agent', 'data': {'config': {'system_prompt': 'Preserve my instructions'}}}, + {'id': 'persona', 'type': 'persona', 'data': {'config': config}}, + ], 'edges': [{'source': 'child', 'target': 'parent', 'targetHandle': 'sub_agents'}, + {'source': 'persona', 'target': 'parent', 'targetHandle': 'persona'}]} + design = {'factors': [{'name': 'Workers', 'level_type': 'sub_agent_toggle', 'levels': [[], ['child']]}, + {'name': 'Personas', 'level_type': 'persona_toggle', 'levels': [[], ['persona']]}]} + + @asynccontextmanager + async def resources(**kwargs): + yield resource_db + + monkeypatch.setattr(packages, 'system_session', resources) + await resource_db.connection() + await create_experiment_with_available_name(db, name='Portable', owner_id=owner.id) + imported_ids, persona_ids = [], [] + for number in range(2): + job = PackageImport(id=uuid.uuid4(), owner_id=owner.id, request_key=uuid.uuid4().hex, + status='queued', preflight={}, progress={}, expires_at=datetime.now(UTC) + timedelta(days=1)) + db.add(job) + await db.flush() + root = imports.directory(job.id) + stage = root / 'writer' + stage.mkdir(parents=True) + writer = PackageWriter(imports.archive_path(job.id), stage) + writer.json('publication/canvas.json', graph) + writer.json('publication/settings.json', {'design_spec': design}) + writer.json('experiment-metadata.json', {'name': 'Portable'}) + await packages._resources(writer, graph, {'design_spec': design}, owner.id) + assert writer.missing == 0 + writer.finish({'format': 'asaree.experiment-package', 'schema_version': 2, + 'experiment_id': str(uuid.uuid4()), 'protocol_id': str(uuid.uuid4()), + 'publication': {'id': str(uuid.uuid4()), 'version': 1}, 'results_included': False}) + job.preflight = inspect(imports.archive_path(job.id), root / 'payload', Limits(), threading.Event()) + importer = Reconstruction(db, job, root / 'payload', Limits()) + job.experiment_id = await importer.activate(resource_db) + await db.flush() + local_id = uuid.UUID(importer.maps['persona', snapshot_identity(config)]) + assert await get_persona(db, local_id, owner_id=owner.id) is None # Staged resources stay hidden. + job.status = 'completed' + await db.flush() + persona = await get_persona(db, local_id, owner_id=owner.id) + assert persona.prompt == config['persona_text'] + assert persona.source_filename == 'combined.md' + assert persona.name == 'Combined persona' # Personas allow duplicate display names. + assert persona.id not in [uuid.UUID(value) for value in config['persona_ids']] + markdown = root / f'payload/resources/personas/{snapshot_identity(config)}.md' + assert markdown.read_bytes() == persona.prompt.encode() + protocol = await db.scalar(select(Protocol).where(Protocol.experiment_id == job.experiment_id)) + experiment = await db.get(ResearchExperiment, job.experiment_id) + assert experiment.name == f'Portable ({number + 2})' + assert experiment.design_spec['factors'] == design['factors'] + assert protocol.published_revision_id is None + assert [node['id'] for node in protocol.graph['nodes']] == ['parent', 'child', 'persona'] + assert protocol.graph['nodes'][0]['data']['sub_agent_selection'] == ['child'] + assert protocol.graph['nodes'][0]['data']['config']['system_prompt'] == 'Delegate to @child' + restored = protocol.graph['nodes'][2]['data']['config'] + assert restored['persona_ids'] == [str(local_id)] and restored['persona_text'] == config['persona_text'] + assert restored['persona_sources'][0]['id'] == str(local_id) + imported_ids.append(job.experiment_id) + persona_ids.append(local_id) + assert len(set(imported_ids)) == len(set(persona_ids)) == 2 + assert len(await list_personas(db, owner_id=owner.id)) == 2 + assert await db.scalar(select(func.count()).select_from(Persona).where(Persona.owner_id == owner.id)) == 2 + + @pytest.mark.parametrize('builtin_state', ['compatible', 'incompatible', 'ambiguous']) async def test_destination_services_and_explicit_custom_mapping( results_db, resource_db, destination_results_db, destination_resource_db, @@ -261,7 +418,7 @@ async def test_destination_services_and_explicit_custom_mapping( 'factor_bindings': {'config.server_id': 'Connection'}}}], 'edges': [{'source': 'model', 'target': 'agent', 'targetHandle': 'model'}]} design_spec = {'factors': [{'name': 'Connection', 'levels': [str(source_custom.id)]}]} - writer = packages.PackageWriter(root / 'archive.tar.gz', stage) + writer = PackageWriter(imports.archive_path(job.id), stage) writer.json('publication/canvas.json', graph) writer.json('publication/settings.json', {'design_spec': design_spec}) writer.json('experiment-metadata.json', {'name': 'Service portability'}) @@ -270,7 +427,7 @@ async def test_destination_services_and_explicit_custom_mapping( writer.finish({'format': 'asaree.experiment-package', 'schema_version': 2, 'experiment_id': str(scope.experiment_id), 'protocol_id': str(scope.protocol_id), 'publication': {'id': str(scope.protocol_revision_id), 'version': 1}, 'results_included': False}) - job.preflight = inspect(root / 'archive.tar.gz', root / 'payload', Limits(), threading.Event()) + job.preflight = inspect(imports.archive_path(job.id), root / 'payload', Limits(), threading.Event()) requirements = ''.join(path.read_text() for path in (root / 'payload/requirements/mcp').glob('*.json')) assert 'SOURCE_SECRET' not in requirements destination_builtin = MCPServerConfig(id=uuid.uuid4(), name='Renamed built-in', is_system=True, @@ -329,10 +486,9 @@ async def destination_resources(**kwargs): @pytest.mark.parametrize('mode', ['whole_dataset', 'per_row']) -@pytest.mark.parametrize('include_results', [False, True]) async def test_export_import_independent_owner_and_reexport( results_db, resource_db, destination_results_db, destination_resource_db, - tmp_path, monkeypatch, mode, include_results, + tmp_path, monkeypatch, mode, ): db, scope, cell, owner = results_db destination_db, _, _, destination_owner = destination_results_db @@ -367,6 +523,10 @@ async def read_fixture_skill(identifier): value = await resource_db.get(Skill, uuid.UUID(str(identifier))) return value if value is not None and value.deleted_at is None else None monkeypatch.setattr('motoro.services.skill_service.get_skill', read_fixture_skill) + @asynccontextmanager + async def policy_resources(**kwargs): + yield resource_db + monkeypatch.setattr('asaree.services.skill_references.system_session', policy_resources) graph = {'nodes': [ {'id': 'agent', 'type': 'agent', 'data': {'config': { 'system_prompt': str(dataset.id), 'api_key': 'NEVER_IMPORT_CONNECTION_SECRET'}, @@ -403,7 +563,7 @@ async def read_fixture_skill(identifier): knowledge_root = settings.okf_document_dir if document else settings.okf_bundle_upload_dir knowledge = Path(knowledge_root) / str(owner.id) / 'source' knowledge.mkdir(parents=True) - knowledge_bytes = b'# Exact knowledge\r\n\xc3\xa9\n' + knowledge_bytes = b'---\r\ntitle: Exact knowledge\r\n---\r\n\xc3\xa9\n' (knowledge / 'concept.md').write_bytes(knowledge_bytes) server = MCPServerConfig(id=uuid.uuid4(), owner_id=owner.id, transport=MCPTransport.STDIO, name=(okf_documents.server_name_for(owner.id, knowledge) if document else @@ -456,8 +616,8 @@ async def read_fixture_skill(identifier): root.mkdir(parents=True) staging = root / 'writer' staging.mkdir() - archive = root / 'archive.tar.gz' - writer = packages.PackageWriter(archive, staging) + archive = imports.archive_path(job.id) + writer = PackageWriter(archive, staging) portable_graph, portable_settings = packages.portable_definition(graph, publication.experiment_snapshot) writer.json('publication/canvas.json', portable_graph) writer.json('publication/settings.json', portable_settings) @@ -469,47 +629,10 @@ async def source_resources(**kwargs): yield resource_db monkeypatch.setattr(packages, 'system_session', source_resources) await packages._resources(writer, portable_graph, portable_settings, owner.id) - if include_results: - parent, factor_values = (await db.execute(select( - FactorialReplicateResult, FactorialCell.factor_values, - ).join(FactorialCell).where(FactorialCell.design_revision_id == design.id).limit(1))).one() - slot = None - if mode == 'per_row': - slot = FactorialRowResult(replicate_result_id=parent.id, protocol_revision_id=publication.id, - dataset_id=dataset.id, raw_sha256=dataset.raw_sha256, row_index=0) - db.add(slot) - await db.flush() - row_snapshot = {'dataset_id': str(dataset.id), 'raw_sha256': dataset.raw_sha256, - 'row_index': 0, 'values': {'x': '01'}} if slot else None - from asaree.services.protocol_execution import apply_factor_bindings - attempt_inputs = resolve_attempt_inputs(publication.dataset_inputs, apply_factor_bindings(graph, factor_values), - dataset_row=row_snapshot) - run = ProtocolRun(protocol_id=scope.protocol_id, owner_id=owner.id, - protocol_revision_id=publication.id, design_revision_id=scope.design_revision_id, status='completed', - replicate_result_id=parent.id, row_result_id=slot.id if slot else None, - dataset_row=row_snapshot, dataset_inputs=attempt_inputs, factor_values=factor_values, - attempt_result={'measurement': {'observations': [ - {'metric_id': 'null', 'status': 'measured', 'value': None}, - {'metric_id': 'missing', 'status': 'unavailable'}, - {'metric_id': 'legacy', 'provenance': 'legacy.unknown', 'value': str(dataset.id)}]}}) - db.add(run) - db.add(ProtocolRun(protocol_id=scope.protocol_id, owner_id=owner.id, - protocol_revision_id=publication.id, design_revision_id=scope.design_revision_id, - replicate_result_id=parent.id, row_result_id=slot.id if slot else None, status='failed', - dataset_row=row_snapshot, dataset_inputs=attempt_inputs, factor_values=factor_values, - attempt_result={'legacy': {'provenance': 'legacy.unknown', 'value': str(dataset.id)}}, - created_at=datetime.now(UTC) - timedelta(hours=1))) - await db.flush() - outputs = Path(settings.dataset_workspace_dir) / str(scope.experiment_id) / str(run.id) / 'agent=agent' - outputs.mkdir(parents=True) - (outputs / 'output.bin').write_bytes(binary) - await packages._results(db, writer, SimpleNamespace(owner_id=owner.id, protocol_id=scope.protocol_id, - protocol_revision_id=publication.id, design_revision_id=scope.design_revision_id, - experiment_id=scope.experiment_id), AsyncMock(), graph) manifest = writer.finish({'format': 'asaree.experiment-package', 'schema_version': 2, 'experiment_id': str(scope.experiment_id), 'protocol_id': str(scope.protocol_id), 'publication': {'id': str(publication.id), 'version': 1}, - 'design_revision_id': str(scope.design_revision_id), 'results_included': include_results}) + 'design_revision_id': str(scope.design_revision_id), 'results_included': False}) # Cross-installation boundary: independent PostgreSQL schemas, owners, # registrations, managed roots and saved credentials. Only archive bytes cross. archive_bytes = archive.read_bytes() @@ -518,7 +641,7 @@ async def source_resources(**kwargs): root = imports.directory(job.id) assert root != source_root root.mkdir(parents=True) - archive = root / 'archive.tar.gz' + archive = imports.archive_path(job.id) archive.write_bytes(archive_bytes) db, resource_db = destination_db, destination_resource_db assert await db.get(RegisteredDataset, dataset.id) is None @@ -545,10 +668,17 @@ async def resource_session(**kwargs): assert Path(local_dataset.raw_path).read_bytes() == source assert bool(local_dataset.current_split_id) == (mode == 'whole_dataset') local_server = await resource_db.get(MCPServerConfig, uuid.UUID(importer.maps['mcp', str(server.id)])) + await resource_db.refresh(local_server) assert local_server.owner_id == destination_owner.id + assert local_server.error_message is None + assert not (local_server.capabilities or {}).get('tools') assert okf_documents.is_document_server(local_server) == document restored_knowledge = Path(okf_bundles.bundle_path_from_command(local_server.command)) - assert (restored_knowledge / 'concept.md').read_bytes() == knowledge_bytes + concept = okf_documents.concept_file_for(local_server) if document else restored_knowledge / 'concept.md' + assert concept.read_bytes() == knowledge_bytes + assert restored_knowledge.parent == (okf_documents.owner_root(destination_owner.id) if document else + okf_bundles.owner_upload_root(destination_owner.id)) + assert local_dataset.raw_artifact.storage_key == f'{local_dataset.id}/raw.csv' local_skill = await resource_db.get(Skill, uuid.UUID(importer.maps['skill', str(skill.id)])) assert local_skill.owner_id == destination_owner.id and not local_skill.is_system assert local_skill.body == skill.body and local_skill.frontmatter == skill.frontmatter @@ -556,17 +686,17 @@ async def resource_session(**kwargs): select(SkillFile).where(SkillFile.skill_id == local_skill.id))).all()} assert set(local_files) == {'assets/binary.bin', *(entry[0] for entry in nested_resources)} local_file = local_files['assets/binary.bin'] - assert base64.b64decode(local_file.content) == binary and local_file.position == 7 - for path, encoding, content, position in nested_resources: + assert base64.b64decode(local_file.content) == binary and local_file.position == 0 + for position, (path, encoding, content, _) in enumerate(nested_resources, start=1): restored = local_files[path] assert (restored.encoding, restored.content, restored.position) == (encoding, content, position) monkeypatch.setattr('asaree.services.package_reconstruction.system_session', resource_session) - with pytest.raises(ValueError, match='destination openai'): + with pytest.raises(ValueError, match='saved openai'): await require_configured(db, experiment_id) assert await db.scalar(select(func.count()).select_from(ProtocolRun).where( ProtocolRun.owner_id == destination_owner.id)) == 0 identities = (await db.scalars(select(ImportedIdentity).where(ImportedIdentity.import_id == job.id))).all() - assert len([row for row in identities if row.kind == 'historical_attempt']) == 2 * int(include_results) + assert not any(row.kind.startswith('historical_') for row in identities) # Exact source re-export is a first-class owned API operation, including # evidence absent from current execution projections. response = await api.source(job.id, db, destination_owner) @@ -595,6 +725,13 @@ async def local_model_config(config, *, owner_id): 'provider': 'openai', 'credential_revision': 'local-fixture', 'discovered_at': None})) monkeypatch.setattr(package_reconstruction, 'system_session', resource_session) await select_test_provider(db, job) + # Native deferred registration does not trust source discovery. Publication + # stays blocked until the destination discovers the configured tool. Stub + # that connection boundary here, just like provider discovery above. + with pytest.raises(ValueError, match='Local server lacks required tools: tool'): + await require_configured(db, experiment_id) + local_server.capabilities = {'tools': [{'name': 'read_concept'}]} + await resource_db.flush() async def read_local_server(identifier): return await resource_db.get(MCPServerConfig, identifier) monkeypatch.setattr('asaree.services.reported_metrics.mcp_service.get_server', read_local_server) @@ -622,7 +759,7 @@ async def read_local_server(identifier): assert local_publication.graph['sampling_snapshot'] != graph['sampling_snapshot'] local_stage = root / 'second-writer' local_stage.mkdir() - second = packages.PackageWriter(root / 'second.tar.gz', local_stage) + second = packages.PackageWriter(root / 'second.zip', local_stage) local_graph, local_settings = packages.portable_definition(local_publication.graph, local_publication.experiment_snapshot) second.json('publication/canvas.json', local_graph) @@ -631,27 +768,25 @@ async def read_local_server(identifier): await packages._datasets(db, second, local_publication, destination_owner.id) await packages._design(db, second, local_publication) await packages._resources(second, local_graph, local_settings, destination_owner.id) - await packages._import_sources(db, second, experiment_id, include_results=include_results) + await packages._import_sources(db, second, experiment_id) second.finish({'format': 'asaree.experiment-package', 'schema_version': 2, 'experiment_id': str(experiment_id), 'protocol_id': str(protocol.id), 'publication': {'id': str(local_publication.id), 'version': local_publication.revision}, - 'design_revision_id': str(local_publication.design_revision_id), 'results_included': include_results}) - inspect(root / 'second.tar.gz', root / 'second-payload', Limits(), threading.Event()) - import tarfile - with tarfile.open(root / 'second.tar.gz') as reexport: - reexport_dependencies = [json.loads(line) for line in reexport.extractfile('dependencies.jsonl')] + 'design_revision_id': str(local_publication.design_revision_id), 'results_included': False}) + inspect(root / 'second.zip', root / 'second-payload', Limits(), threading.Event()) + with zipfile.ZipFile(root / 'second.zip') as reexport: + assert reexport.testzip() is None + reexport_dependencies = [json.loads(line) for line in reexport.read('dependencies.jsonl').splitlines()] pin = local_publication.dataset_inputs['inputs'][0] - assert reexport.extractfile(f'inputs/files/{pin["raw_artifact"]["id"]}.csv').read() == source - assert reexport.extractfile(f'resources/skills/{local_skill.id}/assets/binary.bin').read() == binary - for path, encoding, content, position in nested_resources: + assert reexport.read(f'inputs/files/{pin["raw_artifact"]["id"]}.csv') == source + assert reexport.read(f'resources/skills/{local_skill.id}/assets/binary.bin') == binary + for position, (path, encoding, content, _) in enumerate(nested_resources, start=1): expected = base64.b64decode(content) if encoding == 'base64' else content.encode('utf-8') - assert reexport.extractfile(f'resources/skills/{local_skill.id}/{path}').read() == expected + assert reexport.read(f'resources/skills/{local_skill.id}/{path}') == expected dependency = next(entry for entry in reexport_dependencies if entry.get('kind') == 'skill_file' and entry.get('file') == f'resources/skills/{local_skill.id}/{path}') assert (dependency['encoding'], dependency['position']) == (encoding, position) - if include_results: - nested = reexport.extractfile(f'sources/{job.id}/source.tar.gz').read() - assert hashlib.sha256(nested).hexdigest() == job.sha256 + assert not any(name.startswith('results/') or name.endswith('/source.zip') for name in reexport.namelist()) assert manifest['schema_version'] == 2 # Later draft setup changes do not revoke an immutable local publication. broken = copy.deepcopy(protocol.graph) @@ -679,7 +814,7 @@ async def test_v1_skill_binary_content_is_restored_with_explicit_unknown_source_ await db.flush() root = imports.directory(job.id) write_archive(job, root, version=1) - summary = inspect(root / 'archive.tar.gz', root / 'payload', Limits(), threading.Event()) + summary = inspect(imports.archive_path(job.id), root / 'payload', Limits(), threading.Event()) assert any('v1 omits' in warning for warning in summary['warnings']) importer = Reconstruction(db, job, root / 'payload', Limits()) experiment = await importer.activate(resource_db) @@ -694,7 +829,7 @@ async def test_v1_skill_binary_content_is_restored_with_explicit_unknown_source_ assert protocol.published_revision_id is None -async def test_missing_source_stays_unresolved_instead_of_using_an_existing_same_name_dataset( +async def test_missing_dataset_source_fails_registration_instead_of_reusing_same_name( results_db, resource_db, tmp_path, monkeypatch, ): db, scope, cell, owner = results_db @@ -718,7 +853,7 @@ async def test_missing_source_stays_unresolved_instead_of_using_an_existing_same root = imports.directory(job.id) stage = root / 'writer' stage.mkdir(parents=True) - writer = packages.PackageWriter(root / 'archive.tar.gz', stage) + writer = PackageWriter(imports.archive_path(job.id), stage) writer.json('publication/canvas.json', graph) writer.json('publication/settings.json', {'design_spec': {'factors': []}}) writer.json('experiment-metadata.json', {'name': 'Missing original'}) @@ -728,21 +863,9 @@ async def test_missing_source_stays_unresolved_instead_of_using_an_existing_same writer.finish({'format': 'asaree.experiment-package', 'schema_version': 2, 'experiment_id': str(scope.experiment_id), 'protocol_id': str(scope.protocol_id), 'publication': {'id': str(scope.protocol_revision_id), 'version': 1}, 'results_included': False}) - job.preflight = inspect(root / 'archive.tar.gz', root / 'payload', Limits(), threading.Event()) + job.preflight = inspect(imports.archive_path(job.id), root / 'payload', Limits(), threading.Event()) assert job.preflight['unresolved_count'] == 1 importer = Reconstruction(db, job, root / 'payload', Limits()) - job.experiment_id = await importer.activate(resource_db) - job.status = 'completed' - await db.flush() - local = await db.get(RegisteredDataset, uuid.UUID(importer.maps['dataset', source_id])) - assert local.id != existing.id and local.raw_artifact_id is None - assert local.raw_sha256 == pin['raw_sha256'] and local.name != existing.name - @asynccontextmanager - async def resources(**kwargs): - yield resource_db - monkeypatch.setattr('asaree.services.package_reconstruction.system_session', resources) - from fastapi import HTTPException - with pytest.raises(HTTPException, match='unresolved') as rejected: - await api.configuration(job.id, api.Configuration(connections_configured=True, dependencies_resolved=True), - db, owner) - assert rejected.value.status_code == 422 and job.configured_at is None + with pytest.raises(ValueError, match='Could not register dataset.*original dataset file'): + await importer.activate(resource_db) + assert existing.raw_artifact_id is not None diff --git a/tests/test_package_import_validation.py b/tests/test_package_import_validation.py index fc04a12c..51828939 100644 --- a/tests/test_package_import_validation.py +++ b/tests/test_package_import_validation.py @@ -1,8 +1,10 @@ -"""Real exporter archives through the untrusted upload parser.""" -import io -import tarfile +"""Real ZIP exports through the bounded, untrusted upload parser.""" +import gzip +import stat +import struct import threading import uuid +import zipfile from dataclasses import replace import pytest @@ -14,7 +16,7 @@ def package(tmp_path, *, version=2, graph=None, modify=None): stage = tmp_path / 'writer' stage.mkdir() - archive = tmp_path / 'package.tar.gz' + archive = tmp_path / 'package.zip' writer = PackageWriter(archive, stage) writer.json('publication/canvas.json', graph or {'nodes': [], 'edges': []}) writer.json('publication/settings.json', {'design_spec': {'factors': []}}) @@ -28,15 +30,19 @@ def package(tmp_path, *, version=2, graph=None, modify=None): @pytest.mark.parametrize('version', [1, 2]) -def test_exporter_archive_preflight_preserves_exact_source_files(tmp_path, version): +@pytest.mark.parametrize('zip64_limit', [zipfile.ZIP64_LIMIT, 32]) +def test_import_archive_preflight_preserves_exact_source_files(tmp_path, version, monkeypatch, zip64_limit): + monkeypatch.setattr(zipfile, 'ZIP64_LIMIT', zip64_limit) archive = package(tmp_path, version=version) summary = inspect(archive, tmp_path / 'read', Limits(), threading.Event()) assert summary['manifest']['publication']['version'] == 3 assert summary['categories']['publication'] == 2 assert len(summary['warnings']) == (2 if version == 1 else 1) - with tarfile.open(archive) as tar: - for member in tar: - assert (tmp_path / 'read' / member.name).read_bytes() == tar.extractfile(member).read() + with zipfile.ZipFile(archive) as zipped: + for name in zipped.namelist(): + path = tmp_path / 'read' / name + assert path.read_bytes() == zipped.read(name) + assert path.stat().st_mode & 0o777 == 0o600 @pytest.mark.parametrize('field,value', [ @@ -59,24 +65,32 @@ def test_rejects_unsupported_schema_without_guessing(tmp_path, version): @pytest.mark.parametrize('name,kind', [('../escape', 'file'), ('/absolute', 'file'), ('x/../escape', 'file'), - ('x\\y', 'file'), ('x//y', 'file'), ('x', 'symlink'), ('x', 'hardlink'), ('x', 'fifo'), ('x', 'directory')]) + ('x\\y', 'file'), ('x//y', 'file'), ('x', 'symlink'), ('x', 'socket'), ('x', 'fifo'), + ('x', 'directory'), ('x/', 'file'), ('x', 'dos-directory'), ('x', 'device'), + ('x\n', 'file'), ('x' * 1025, 'file'), ('credentials.json', 'file')]) def test_rejects_unsafe_archive_entries(tmp_path, name, kind): - path = tmp_path / 'malformed.tar.gz' - with tarfile.open(path, 'w:gz') as tar: - member = tarfile.TarInfo(name) - member.type = {'file': tarfile.REGTYPE, 'symlink': tarfile.SYMTYPE, 'hardlink': tarfile.LNKTYPE, - 'fifo': tarfile.FIFOTYPE, 'directory': tarfile.DIRTYPE}[kind] - member.linkname = '/tmp/escape' - tar.addfile(member) + path = tmp_path / 'malformed.zip' + with zipfile.ZipFile(path, 'w') as zipped: + member = zipfile.ZipInfo(name) + member.external_attr = {'file': stat.S_IFREG, 'symlink': stat.S_IFLNK, 'socket': stat.S_IFSOCK, + 'fifo': stat.S_IFIFO, 'directory': stat.S_IFDIR, 'device': stat.S_IFCHR, 'dos-directory': 0}[kind] << 16 + if kind == 'dos-directory': + member.external_attr |= 0x10 + zipped.writestr(member, b'/tmp/escape') with pytest.raises(ValueError): inspect(path, tmp_path / 'read', Limits(), threading.Event()) -def test_duplicate_and_conflicting_members_rejected(tmp_path): - path = tmp_path / 'malformed.tar.gz' - with tarfile.open(path, 'w:gz') as tar: - tar.addfile(tarfile.TarInfo('same')) - tar.addfile(tarfile.TarInfo('same')) +@pytest.mark.parametrize('names', [('same', 'same'), ('same', 'same/child'), ('same/child', 'same')]) +def test_duplicate_and_conflicting_members_rejected(tmp_path, names): + path = tmp_path / 'malformed.zip' + with zipfile.ZipFile(path, 'w') as zipped: + zipped.writestr(names[0], b'') + if names[0] == names[1]: + with pytest.warns(UserWarning, match='Duplicate name'): + zipped.writestr(names[1], b'') + else: + zipped.writestr(names[1], b'') with pytest.raises(PackageError, match='Malformed'): inspect(path, tmp_path / 'read', Limits(), threading.Event()) @@ -97,14 +111,13 @@ def test_cancellation_stops_copy(tmp_path): def test_hash_mismatch_rejected_before_activation(tmp_path): path = package(tmp_path) - tampered = tmp_path / 'tampered.tar.gz' - with tarfile.open(path) as original, tarfile.open(tampered, 'w:gz') as output: - for member in original: - raw = original.extractfile(member).read() - if member.name == 'publication/settings.json': + tampered = tmp_path / 'tampered.zip' + with zipfile.ZipFile(path) as original, zipfile.ZipFile(tampered, 'w') as output: + for name in original.namelist(): + raw = original.read(name) + if name == 'publication/settings.json': raw = b'{}' - member.size = len(raw) - output.addfile(member, io.BytesIO(raw)) + output.writestr(name, raw) with pytest.raises(PackageError, match='hash mismatch'): inspect(tampered, tmp_path / 'read', Limits(), threading.Event()) @@ -132,33 +145,118 @@ def test_no_scripts_executed_during_inspection(tmp_path): assert not sentinel.exists() -@pytest.mark.parametrize('headers', [{'GNU.sparse.map': '0,1000000000'}, {'comment': 'unsupported'}, - {'path': 'unicode/é/' + 'x' * 110}]) -def test_pax_metadata_is_bounded_and_only_exporter_extensions_are_accepted(tmp_path, headers): - archive = tmp_path / 'metadata.tar.gz' - with tarfile.open(archive, 'w:gz', format=tarfile.PAX_FORMAT) as tar: - member = tarfile.TarInfo('payload') - member.pax_headers = headers - tar.addfile(member) - if 'path' in headers: - # The supported long Unicode path is parsed; this standalone fixture - # then fails because it is not a complete experiment package. - with pytest.raises(PackageError, match='Malformed'): - inspect(archive, tmp_path / 'read', Limits(), threading.Event()) - assert (tmp_path / 'read' / headers['path']).is_file() +def test_unicode_resource_paths_and_zip_comments_preserve_bytes(tmp_path): + name = 'resources/knowledge/unicode/é/' + 'x' * 110 + def modify(writer): + raw = tmp_path / 'resource' + raw.write_bytes(b'\x00\xffopaque\r\n') + writer.add(raw, name, identity='resource', provenance='captured_at_download') + writer.archive.comment = b'ZIP package comment' + inspect(package(tmp_path, modify=modify), tmp_path / 'read', Limits(), threading.Event()) + assert (tmp_path / 'read' / name).read_bytes() == b'\x00\xffopaque\r\n' + + +@pytest.mark.parametrize('fault', ['metadata-size', 'member-count', 'hidden-members']) +def test_metadata_limits_apply_before_zipfile_buffers_the_directory(tmp_path, monkeypatch, fault): + path = package(tmp_path) + data = bytearray(path.read_bytes()) + end = data.rindex(b'PK\x05\x06') + limits = Limits(members=1) if fault != 'metadata-size' else Limits() + if fault == 'metadata-size': + struct.pack_into(' None: @@ -34,6 +35,80 @@ async def _duplicate(**_kwargs: object) -> None: assert exc_info.value.detail == "A skill with this name is already registered to your account." +@pytest.mark.parametrize("operation", ["fields", "markdown", "folder"]) +async def test_registered_skill_modification_is_rejected(monkeypatch, operation): + from unittest.mock import AsyncMock + + from motoro.schemas.skill import SkillUpdate + + owner_id, skill_id = uuid.uuid4(), uuid.uuid4() + monkeypatch.setattr(skills.skill_service, "get_skill", AsyncMock( + return_value=SimpleNamespace(id=skill_id, owner_id=owner_id))) + monkeypatch.setattr(skills, "resource_active", AsyncMock(return_value=True)) + writers = [AsyncMock() for _ in range(3)] + for name, writer in zip(("update_skill", "update_skill_from_markdown", "update_skill_from_bundle"), + writers, strict=True): + monkeypatch.setattr(skills.skill_service, name, writer) + user = SimpleNamespace(id=owner_id) + file = UploadFile(BytesIO(b"replacement"), filename="skill/SKILL.md") + with pytest.raises(HTTPException) as error: + if operation == "fields": + await skills.update_skill_endpoint(skill_id, SkillUpdate(body="Changed"), user) + elif operation == "markdown": + await skills.replace_skill_markdown_endpoint(skill_id, user, file) + else: + await skills.replace_skill_folder_endpoint(skill_id, user, [file]) + assert error.value.status_code == 409 + assert error.value.detail == IMMUTABLE_MESSAGE + for writer in writers: + writer.assert_not_awaited() + + +async def test_update_does_not_disclose_foreign_skill(monkeypatch): + from unittest.mock import AsyncMock + + from motoro.schemas.skill import SkillUpdate + + monkeypatch.setattr(skills.skill_service, "get_skill", AsyncMock( + return_value=SimpleNamespace(owner_id=uuid.uuid4()))) + with pytest.raises(HTTPException) as error: + await skills.update_skill_endpoint(uuid.uuid4(), SkillUpdate(body="Changed"), SimpleNamespace(id=uuid.uuid4())) + assert error.value.status_code == 404 + + +async def test_delete_reports_retained_usages_as_conflict(monkeypatch): + from unittest.mock import AsyncMock + + from asaree.services.skill_references import SkillInUseError + + owner_id, skill_id = uuid.uuid4(), uuid.uuid4() + publication_id = uuid.uuid4() + monkeypatch.setattr(skills.skill_service, "get_skill", AsyncMock( + return_value=SimpleNamespace(id=skill_id, owner_id=owner_id))) + monkeypatch.setattr(skills, "resource_active", AsyncMock(return_value=True)) + monkeypatch.setattr(skills, "delete_registered_skill", AsyncMock(side_effect=SkillInUseError([ + {"kind": "published version", "name": "Experiment A", "id": publication_id}, + ]))) + with pytest.raises(HTTPException) as error: + await skills.delete_skill_endpoint(skill_id, SimpleNamespace(id=owner_id), AsyncMock()) + assert error.value.status_code == 409 + assert "Published experiment version: Experiment A" in error.value.detail + assert str(publication_id) not in error.value.detail + + +def test_skill_usage_message_hides_internal_canvas_agent_names(): + from asaree.services.skill_references import SkillInUseError + + protocol_id, node_id = uuid.uuid4(), uuid.uuid4() + internal_name = f"protocol-{protocol_id}-{node_id}" + message = str(SkillInUseError([ + {"kind": "agent run", "name": internal_name, "id": uuid.uuid4()}, + ])) + assert "Saved agent run from an experiment canvas" in message + assert "can’t be deleted while it’s in use" in message + assert internal_name not in message + + async def test_uploading_duplicate_skill_folder_returns_conflict(monkeypatch: pytest.MonkeyPatch) -> None: async def _duplicate(*_args: object, **_kwargs: object) -> None: raise IntegrityError( diff --git a/uv.lock b/uv.lock index dc564c56..0a4b6e7d 100644 --- a/uv.lock +++ b/uv.lock @@ -253,7 +253,7 @@ requires-dist = [ { name = "bcrypt", specifier = ">=4.2.0" }, { name = "email-validator", specifier = ">=2.2.0" }, { name = "fastapi", specifier = ">=0.121.0" }, - { name = "motoro", git = "https://github.com/EpistasisLab/motoro.git?tag=v0.15.1" }, + { name = "motoro", git = "https://github.com/EpistasisLab/motoro.git?rev=1d75d9c036ebc35217901d8945b69b4841d17798" }, { name = "pandas", specifier = ">=2.2.0" }, { name = "pyarrow", specifier = ">=18.0.0" }, { name = "pydantic", specifier = ">=2.10.0" }, @@ -1878,8 +1878,8 @@ wheels = [ [[package]] name = "motoro" -version = "0.15.1" -source = { git = "https://github.com/EpistasisLab/motoro.git?tag=v0.15.1#805fa51455642b01c1fb9aff52fabd28ebfbb6b8" } +version = "0.15.2.dev2+g1d75d9c03" +source = { git = "https://github.com/EpistasisLab/motoro.git?rev=1d75d9c036ebc35217901d8945b69b4841d17798#1d75d9c036ebc35217901d8945b69b4841d17798" } dependencies = [ { name = "alembic" }, { name = "asyncpg" },