Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(pack): restore account backups without deleting target-only data (#4003)

Qin Haojie46f0d60c6099
diff --git a/docs/en/api/14-ovpack.md b/docs/en/api/14-ovpack.md
index 5f0eb61a7..a7193737e 100644
--- a/docs/en/api/14-ovpack.md
+++ b/docs/en/api/14-ovpack.md
@@ -291,11 +291,16 @@ ov import ./exports/my-project.ovpack viking://resources/imported/ --vector-mode
### backup_ovpack
Back up public scope roots as a restore-only `.ovpack` file. The backup includes
-`resources` and `user`; sessions are included through the user namespace under
-`user/{user_id}/sessions`. It excludes internal runtime data such as `temp` and
-`queue`. Set `include_vectors=true` to include compatible
+`resources` and all `user/{user_id}` content in the current account; sessions
+are included through the user namespace under `user/{user_id}/sessions`. It
+excludes internal runtime data such as `temp` and `queue`, as well as user
+accounts and API keys. Only ROOT or ADMIN can call this endpoint. Set
+`include_vectors=true` to include compatible
pure-dense vector snapshots; hybrid index types reject vector snapshot export.
+Backup reads live files and does not provide an atomic point-in-time snapshot.
+Callers that require strict consistency should pause writes during the backup window.
+
```
POST /api/v1/pack/backup
```
@@ -350,7 +355,20 @@ The Go SDK and CLI write the stream to the requested path and return or print th
Restore a backup package created by `backup_ovpack` to the original public scope
roots. Regular import rejects backup packages. Vector handling follows
`vector_mode`; session files under the user namespace are restored without
-vectorization.
+vectorization. Only ROOT or ADMIN can call this endpoint, and it restores all
+packaged user paths in the current account.
+
+`on_conflict=overwrite` performs a merge-upsert: package paths missing from the
+target are created, matching paths are overwritten, and target-only paths are
+preserved. It does not delete the full `viking://resources` or `viking://user`
+tree. Only added or overwritten package content has its vectors updated. `skip`
+remains a scope-root-level skip, but the complete manifest, content checksums,
+and vector metadata are validated before it can return. Corrupt backups fail
+even with `skip`.
+
+OVPack does not create user accounts or restore API keys. After restoring into
+a new environment, create users with the same packaged `user_id` values and use
+the API keys generated by the target environment.
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
diff --git a/docs/en/guides/09-ovpack.md b/docs/en/guides/09-ovpack.md
index ffc61a2d4..0bf0797ba 100644
--- a/docs/en/guides/09-ovpack.md
+++ b/docs/en/guides/09-ovpack.md
@@ -21,7 +21,11 @@ Full migration uses the separate `backup/restore` flow. It packages public
scope roots together:
- `viking://resources`
-- `viking://user`
+- all `viking://user/{user_id}` content in the current account
+
+Only ROOT or ADMIN can call `backup/restore`, and these operations traverse all
+user content within the current account. Backup packages do not contain user
+accounts, API keys, or other authentication data.
Sessions are included through the user namespace at
`viking://user/{user_id}/sessions/{session_id}`. The
@@ -157,6 +161,15 @@ ov restore ./backups/openviking.ovpack --on-conflict overwrite
Backup packages can only be restored with `restore`; regular `import` rejects
them.
+Backup reads live files and is not an atomic point-in-time snapshot. Content
+that changes during backup may represent different moments. Pause writes during
+the backup window when strict consistency is required.
+
+When restoring into a new environment, restore content first and then create
+users with the same `user_id` values found in the package. Existing user
+directories do not mean that user accounts exist, and the target environment
+generates new API keys.
+
## Python SDK
```python
@@ -308,6 +321,18 @@ curl -X POST http://localhost:1933/api/v1/pack/backup \
`skip` is a root-level skip, not a file-level merge.
+The table above describes regular `import`. For full `restore`, `overwrite`
+performs a merge-upsert: missing target paths are created, matching paths are
+overwritten, and target-only paths absent from the backup are preserved. Restore
+does not delete the full `viking://resources` or `viking://user` tree, and it
+does not create or write the aggregate `viking://user` container itself.
+Vectors are restored or recomputed only for package content that is added or
+overwritten; vectors for target-only content remain unchanged.
+
+Every conflict policy first validates the complete manifest, files, checksums,
+and vector metadata. A corrupt package fails even with `skip`; it cannot return
+success without validation.
+
## Package Layout
OVPack v3 is a standard ZIP archive with one package root directory:
@@ -414,6 +439,9 @@ id, uri, account_id, owner_user_id, owner_space,
created_at, updated_at, active_count
```
+User ownership is rebuilt from `viking://user/{user_id}` paths. User accounts
+and API keys are not OVPack content.
+
With `--include-vectors`, export also stores pure-dense vectors and embedding
metadata. Even when import restores dense snapshots, runtime fields are rebuilt
from the target URI, target account, and current time. Hybrid indexes do not
diff --git a/docs/zh/api/14-ovpack.md b/docs/zh/api/14-ovpack.md
index 92e278654..80f53ba54 100644
--- a/docs/zh/api/14-ovpack.md
+++ b/docs/zh/api/14-ovpack.md
@@ -291,10 +291,13 @@ ov import ./exports/my-project.ovpack viking://resources/imported/ --vector-mode
### backup_ovpack
将公开 scope root 备份为只能通过 restore 恢复的 `.ovpack` 文件。备份包含
-`resources` 和 `user`;session 会通过 user 命名空间下的 `user/{user_id}/sessions`
-一起包含,不包含 `temp`、`queue` 等内部运行态数据。
+`resources` 和当前账号下所有 `user/{user_id}` 内容;session 会通过 user 命名空间下的
+`user/{user_id}/sessions` 一起包含,不包含 `temp`、`queue` 等内部运行态数据,也不包含
+用户账号或 API Key。该接口仅允许 ROOT 或 ADMIN 调用。
设置 `include_vectors=true` 时,会额外导出兼容的纯 dense 向量快照;底层 index type 为 hybrid 时会拒绝导出向量快照。
+备份是在线逐文件读取,不保证同一时刻的原子快照。需要严格一致性时,调用方应在备份窗口暂停写入。
+
```
POST /api/v1/pack/backup
```
@@ -348,6 +351,15 @@ Go SDK 和 CLI 将字节流写入指定路径,并返回或输出该本地路
恢复 `backup_ovpack` 生成的备份包到原始公开 scope root。普通 import 不接受备份包。
向量处理遵循 `vector_mode`;user 命名空间下的 session 文件只恢复文件状态,不触发向量化。
+该接口仅允许 ROOT 或 ADMIN 调用,并恢复当前账号下包内所有用户路径。
+
+`on_conflict=overwrite` 使用合并覆盖:包内缺失于目标的路径会创建,同路径会覆盖,目标独有路径
+会保留;不会删除整个 `viking://resources` 或 `viking://user`。向量只更新包内新增或覆盖的
+内容。`skip` 仍是 scope root 级跳过,但返回前也会完整校验 manifest、内容 checksum 和向量元数据。
+损坏的备份不会因为 `skip` 而返回成功。
+
+OVPack 不创建用户账号或恢复 API Key。新环境恢复后,需要使用包内相同的 `user_id` 创建用户,
+并使用目标环境新生成的 API Key。
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
diff --git a/docs/zh/guides/09-ovpack.md b/docs/zh/guides/09-ovpack.md
index 600551425..3084446a0 100644
--- a/docs/zh/guides/09-ovpack.md
+++ b/docs/zh/guides/09-ovpack.md
@@ -17,7 +17,10 @@ checksum,保证包内容没有偏离 manifest;如果攻击者能同时篡改
全量迁移使用单独的 `backup/restore`,它会把公开 scope root 一起打进备份包:
- `viking://resources`
-- `viking://user`
+- 当前账号下所有 `viking://user/{user_id}` 内容
+
+`backup/restore` 仅允许 ROOT 或 ADMIN 调用,并以账号为边界访问所有用户内容。备份包不包含
+用户账号、API Key 或其他鉴权数据。
Session 通过 user 命名空间一起迁移,路径为
`viking://user/{user_id}/sessions/{session_id}`。`viking://session/...`
@@ -138,6 +141,12 @@ ov restore ./backups/openviking.ovpack --on-conflict overwrite
备份包只能通过 `restore` 恢复,不能通过普通 `import` 导入到任意父目录。
+备份是在线逐文件读取,不是同一时刻的原子快照。备份期间仍在变化的内容可能来自不同时间点;
+需要严格一致性时,应由使用方在备份窗口暂停写入。
+
+恢复到新环境时,先恢复内容,再使用备份中的相同 `user_id` 创建用户。用户目录已存在不代表
+用户账号已经创建,API Key 会由目标环境重新生成。
+
## Python SDK
```python
@@ -289,6 +298,14 @@ curl -X POST http://localhost:1933/api/v1/pack/backup \
`skip` 是 root 级跳过,不是文件级补齐导入。
+上表描述普通 `import`。全量 `restore` 的 `overwrite` 使用合并覆盖:包内不存在的目标路径会
+创建,同路径内容会覆盖,目标环境中仅有而备份中没有的路径会保留。恢复不会删除整个
+`viking://resources` 或 `viking://user`,也不会创建或写入 `viking://user` 聚合目录本身。
+向量只恢复或重建包内新增、覆盖的内容,目标环境独有内容的向量保持不变。
+
+无论使用哪种冲突策略,都会先完整校验 manifest、文件、checksum 和向量元数据。损坏的包
+即使使用 `skip` 也会报错,不会返回成功。
+
## 包结构
OVPack v3 是标准 ZIP。ZIP 内部有一个包根目录:
@@ -389,6 +406,8 @@ id, uri, account_id, owner_user_id, owner_space,
created_at, updated_at, active_count
```
+用户归属从 `viking://user/{user_id}` 路径重建;用户账号和 API Key 不属于 OVPack 内容。
+
如果使用 `--include-vectors`,会额外导出纯 dense 向量和 embedding 元数据。导入时即使恢复
dense 快照,也会按目标 URI、目标账号和当前时间重建运行态字段。hybrid index 当前不支持
向量快照导出。
diff --git a/openviking/core/namespace.py b/openviking/core/namespace.py
index 715abd65b..2cfdd626a 100644
--- a/openviking/core/namespace.py
+++ b/openviking/core/namespace.py
@@ -8,6 +8,7 @@ from typing import Optional
from openviking.core.identifiers import validate_user_id
from openviking.core.peer_id import normalize_peer_id
from openviking.server.identity import RequestContext
+from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.uri import VikingURI
_CONTENT_TYPES_BY_SCOPE = {
@@ -359,6 +360,19 @@ def owner_fields_for_uri(
}
+def content_owner_context_for_uri(uri: str, ctx: RequestContext) -> RequestContext:
+ """Use the URI owner for user-scoped content writes while retaining caller authority."""
+ owner = owner_fields_for_uri(uri, ctx=ctx).get("owner_user_id")
+ if not owner or owner == ctx.user.user_id:
+ return ctx
+ return RequestContext(
+ user=UserIdentifier(ctx.account_id, owner),
+ role=ctx.role,
+ actor_peer_id=ctx.actor_peer_id,
+ from_oauth=ctx.from_oauth,
+ )
+
+
def owner_space_for_uri(uri: str, ctx: RequestContext) -> str:
"""Derive the legacy owner_space bucket for vector records from URI scope and context."""
parts = uri_parts(uri)
diff --git a/openviking/service/pack_service.py b/openviking/service/pack_service.py
index be963f753..f339ffb8c 100644
--- a/openviking/service/pack_service.py
+++ b/openviking/service/pack_service.py
@@ -10,13 +10,13 @@ from typing import Optional
from openviking.core.namespace import canonicalize_uri
from openviking.core.uri_validation import validate_viking_uri
-from openviking.server.identity import RequestContext
+from openviking.server.identity import RequestContext, Role
from openviking.storage.ovpack.operations import backup_ovpack as local_backup_ovpack
from openviking.storage.ovpack.operations import export_ovpack as local_export_ovpack
from openviking.storage.ovpack.operations import import_ovpack as local_import_ovpack
from openviking.storage.ovpack.operations import restore_ovpack as local_restore_ovpack
from openviking.storage.viking_fs import VikingFS
-from openviking_cli.exceptions import NotInitializedError
+from openviking_cli.exceptions import NotInitializedError, PermissionDeniedError
from openviking_cli.utils import get_logger
logger = get_logger(__name__)
@@ -44,6 +44,17 @@ class PackService:
raise NotInitializedError("VikingFS")
return self._viking_fs
+ @staticmethod
+ def _account_maintenance_ctx(ctx: RequestContext) -> RequestContext:
+ """Return an account-scoped context that can traverse every user namespace."""
+ if ctx.role not in {Role.ROOT, Role.ADMIN}:
+ raise PermissionDeniedError("OVPack backup and restore require ROOT or ADMIN role")
+ return RequestContext(
+ user=ctx.user,
+ role=Role.ROOT,
+ from_oauth=ctx.from_oauth,
+ )
+
async def export_ovpack(
self,
uri: str,
@@ -79,10 +90,11 @@ class PackService:
) -> str:
"""Back up all public OpenViking scopes as a restore-only .ovpack file."""
viking_fs = self._ensure_initialized()
+ maintenance_ctx = self._account_maintenance_ctx(ctx)
return await local_backup_ovpack(
viking_fs,
to,
- ctx=ctx,
+ ctx=maintenance_ctx,
vector_store=self._vector_store,
include_vectors=include_vectors,
)
@@ -126,10 +138,11 @@ class PackService:
) -> str:
"""Restore a backup .ovpack file to its original public scope roots."""
viking_fs = self._ensure_initialized()
+ maintenance_ctx = self._account_maintenance_ctx(ctx)
return await local_restore_ovpack(
viking_fs,
file_path,
- ctx=ctx,
+ ctx=maintenance_ctx,
on_conflict=on_conflict,
vector_mode=vector_mode,
vector_store=self._vector_store,
diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.py
index e2ade3916..be323b0ec 100644
--- a/openviking/service/reindex_executor.py
+++ b/openviking/service/reindex_executor.py
@@ -18,6 +18,7 @@ from openviking.core.context import (
)
from openviking.core.namespace import (
classify_uri,
+ content_owner_context_for_uri,
context_type_for_uri,
is_session_uri,
owner_fields_for_uri,
@@ -135,15 +136,7 @@ class ReindexExecutor:
Reindex authorization and task ownership use the actor ctx, but semantic
and vector records should retain ownership from the target URI.
"""
- owner = owner_fields_for_uri(uri, ctx=ctx).get("owner_user_id")
- if not owner or owner == ctx.user.user_id:
- return ctx
- return RequestContext(
- user=UserIdentifier(ctx.account_id, owner),
- role=ctx.role,
- actor_peer_id=ctx.actor_peer_id,
- from_oauth=ctx.from_oauth,
- )
+ return content_owner_context_for_uri(uri, ctx)
async def execute(
self,
diff --git a/openviking/storage/ovpack/operations.py b/openviking/storage/ovpack/operations.py
index 5edd2eaa3..e25e6e3bf 100644
--- a/openviking/storage/ovpack/operations.py
+++ b/openviking/storage/ovpack/operations.py
@@ -8,7 +8,12 @@ import os
import zipfile
from typing import Any, Optional
-from openviking.core.namespace import context_type_for_uri, is_session_uri, relative_uri_path
+from openviking.core.namespace import (
+ content_owner_context_for_uri,
+ context_type_for_uri,
+ is_session_uri,
+ relative_uri_path,
+)
from openviking.server.identity import RequestContext
from openviking.storage.index_consistency import check_index_consistency
from openviking.storage.ovpack.format import (
@@ -187,6 +192,7 @@ async def _enqueue_direct_vectorization(
ctx: RequestContext,
index_records: Optional[list[dict[str, Any]]] = None,
manifest_path_root_uri: Optional[str] = None,
+ entries: Optional[list[dict[str, Any]]] = None,
) -> None:
if is_session_uri(uri):
logger.info(f"[ovpack] Skipped vectorization for session namespace: {uri}")
@@ -194,7 +200,8 @@ async def _enqueue_direct_vectorization(
index_records = index_records or []
manifest_path_root_uri = manifest_path_root_uri or uri
- entries = await viking_fs.tree(uri, node_limit=None, level_limit=None, ctx=ctx)
+ if entries is None:
+ entries = await viking_fs.tree(uri, node_limit=None, level_limit=None, ctx=ctx)
dir_uris = {uri}
file_entries: list[tuple[str, str, str, str]] = []
for entry in entries:
@@ -307,8 +314,11 @@ async def import_ovpack(
validate_import_target_uri(root_uri)
members = validated_import_members(infolist, base_name, root_uri)
- existing_roots = [root_uri] if await _root_exists(viking_fs, root_uri, ctx) else []
+ index_records = validate_manifest_content(zf, manifest, infolist, base_name)
+ dense_vectors = read_dense_vectors(zf, manifest, base_name, index_records)
+
+ existing_roots = [root_uri] if await _root_exists(viking_fs, root_uri, ctx) else []
if existing_roots:
if conflict_action == "skip":
logger.info(f"[ovpack] Skipped existing resource at {root_uri}")
@@ -321,8 +331,6 @@ async def import_ovpack(
resource=resource,
)
- index_records = validate_manifest_content(zf, manifest, infolist, base_name)
- dense_vectors = read_dense_vectors(zf, manifest, base_name, index_records)
if not is_session_uri(root_uri):
vector_action = choose_vector_restore_action(
manifest,
@@ -331,6 +339,7 @@ async def import_ovpack(
vector_store=vector_store,
vector_mode=vector_action_mode,
)
+
if parent != "viking://":
await _ensure_parent_exists(viking_fs, parent, ctx)
@@ -629,6 +638,7 @@ async def restore_ovpack(
index_records: list[dict[str, Any]] = []
dense_vectors: dict[str, list[float]] = {}
vector_action = "recompute"
+ restored_entries: list[dict[str, Any]] = []
with zipfile.ZipFile(file_path, "r") as zf:
infolist = zf.infolist()
@@ -647,8 +657,11 @@ async def restore_ovpack(
manifest_entries = manifest_entries_by_path(manifest)
backup_scopes = backup_scopes_from_manifest(manifest, manifest_entries)
members = validated_import_members(infolist, base_name, root_uri)
- existing_roots = await _existing_scope_roots(viking_fs, backup_scopes, ctx)
+ index_records = validate_manifest_content(zf, manifest, infolist, base_name)
+ dense_vectors = read_dense_vectors(zf, manifest, base_name, index_records)
+
+ existing_roots = await _existing_scope_roots(viking_fs, backup_scopes, ctx)
if existing_roots:
if conflict_action == "skip":
logger.info("[ovpack] Skipped backup restore because target scopes exist")
@@ -661,8 +674,6 @@ async def restore_ovpack(
resource=resource,
)
- index_records = validate_manifest_content(zf, manifest, infolist, base_name)
- dense_vectors = read_dense_vectors(zf, manifest, base_name, index_records)
vector_action = choose_vector_restore_action(
manifest,
index_records,
@@ -671,19 +682,38 @@ async def restore_ovpack(
vector_mode=vector_action_mode,
)
- for existing_root in existing_roots:
- logger.info(f"[ovpack] Overwriting existing resource at {existing_root}")
- await _remove_existing_root(viking_fs, existing_root, ctx)
+ content_members = [
+ member for member in members if member[2] not in {"manifest", "internal"} and member[3]
+ ]
+ content_members.sort(key=lambda member: (member[2] != "directory", member[3].count("/")))
- for _, safe_zip_path, kind, rel_path in members:
- if kind in {"manifest", "internal"} or rel_path == "":
- continue
- if kind == "directory":
- await viking_fs.mkdir(join_uri(root_uri, rel_path), exist_ok=True, ctx=ctx)
+ for _, safe_zip_path, kind, rel_path in content_members:
+ target_uri = join_uri(root_uri, rel_path)
+ if target_uri == "viking://user":
continue
- data = zf.read(safe_zip_path)
- await viking_fs.write_file_bytes(join_uri(root_uri, rel_path), data, ctx=ctx)
+ try:
+ target_stat = await viking_fs.stat(target_uri, ctx=ctx)
+ except (NotFoundError, FileNotFoundError):
+ target_stat = None
+
+ target_is_dir = bool(target_stat and target_stat.get("isDir"))
+ if target_stat is not None and target_is_dir != (kind == "directory"):
+ await _remove_existing_root(viking_fs, target_uri, ctx)
+
+ if kind == "directory":
+ await viking_fs.mkdir(target_uri, exist_ok=True, ctx=ctx)
+ else:
+ await viking_fs.write_file_bytes(target_uri, zf.read(safe_zip_path), ctx=ctx)
+
+ restored_entries.append(
+ {
+ "rel_path": rel_path,
+ "uri": target_uri,
+ "name": leaf_name(rel_path),
+ "isDir": kind == "directory",
+ }
+ )
logger.info(f"[ovpack] Successfully restored backup {file_path}")
@@ -692,15 +722,27 @@ async def restore_ovpack(
logger.info("[ovpack] Restored vector snapshot for backup")
return root_uri
- for scope in backup_scopes:
- scope_uri = f"viking://{scope}"
+ vectorization_groups: dict[str, list[dict[str, Any]]] = {}
+ for entry in restored_entries:
+ parts = entry["rel_path"].split("/")
+ if parts[0] == "resources":
+ group_uri = "viking://resources"
+ elif parts[0] == "user" and len(parts) >= 2:
+ group_uri = f"viking://user/{parts[1]}"
+ else:
+ continue
+ vectorization_groups.setdefault(group_uri, []).append(entry)
+
+ for group_uri, entries in vectorization_groups.items():
+ owner_ctx = content_owner_context_for_uri(group_uri, ctx)
await _enqueue_direct_vectorization(
viking_fs,
- scope_uri,
- ctx=ctx,
+ group_uri,
+ ctx=owner_ctx,
index_records=index_records,
manifest_path_root_uri=root_uri,
+ entries=entries,
)
- logger.info(f"[ovpack] Enqueued direct vectorization for: {scope_uri}")
+ logger.info(f"[ovpack] Enqueued direct vectorization for: {group_uri}")
return root_uri
diff --git a/openviking/storage/ovpack/vectors.py b/openviking/storage/ovpack/vectors.py
index caa3335f4..9efc759cb 100644
--- a/openviking/storage/ovpack/vectors.py
+++ b/openviking/storage/ovpack/vectors.py
@@ -9,7 +9,12 @@ import struct
import zipfile
from typing import Any
-from openviking.core.namespace import context_type_for_uri, is_session_uri, owner_fields_for_uri
+from openviking.core.namespace import (
+ content_owner_context_for_uri,
+ context_type_for_uri,
+ is_session_uri,
+ owner_fields_for_uri,
+)
from openviking.server.identity import RequestContext
from openviking.storage.ovpack.format import (
OVPACK_DENSE_PATH,
@@ -315,12 +320,13 @@ async def restore_vector_snapshot(
if not isinstance(rel_path, str):
continue
target_uri = join_uri(root_uri, rel_path)
- if is_session_uri(target_uri):
+ if target_uri == "viking://user" or is_session_uri(target_uri):
continue
+ owner_ctx = content_owner_context_for_uri(target_uri, ctx)
await _upsert_vector_snapshot_record(
vector_store,
target_uri,
record,
dense_vectors[record_id],
- ctx,
+ owner_ctx,
)
diff --git a/tests/misc/test_ovpack_import_policy.py b/tests/misc/test_ovpack_import_policy.py
index 005b245f5..b4b1db1a7 100644
--- a/tests/misc/test_ovpack_import_policy.py
+++ b/tests/misc/test_ovpack_import_policy.py
@@ -10,10 +10,12 @@ import os
import tempfile
import zipfile
from pathlib import Path
+from unittest.mock import AsyncMock
import pytest
from openviking.server.identity import RequestContext, Role
+from openviking.service.pack_service import PackService
from openviking.storage.index_consistency import IndexConsistencyReport, IndexExpectation
from openviking.storage.ovpack.operations import (
backup_ovpack,
@@ -171,6 +173,7 @@ class FakeBackupVikingFS:
"viking://resources/README.md": b"hello",
"viking://user/alice/sessions/sess_1/.meta.json": b'{"session_id":"sess_1"}',
}
+ self.tree_contexts: list[tuple[str, RequestContext]] = []
async def tree(
self,
@@ -183,6 +186,7 @@ class FakeBackupVikingFS:
assert show_all_hidden is True
assert node_limit is None
assert level_limit is None
+ self.tree_contexts.append((uri, ctx))
if uri == "viking://resources":
return [
{
@@ -588,12 +592,13 @@ async def test_export_ovpack_skips_missing_semantic_sidecars(
@pytest.mark.asyncio
-async def test_backup_restore_contract(temp_ovpack_path: Path, request_ctx: RequestContext):
- await backup_ovpack(
- FakeBackupVikingFS(),
- str(temp_ovpack_path),
- ctx=request_ctx,
- )
+async def test_backup_restore_contract(
+ temp_ovpack_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+):
+ admin_ctx = RequestContext(user=UserIdentifier("acct", "admin"), role=Role.ADMIN)
+ backup_fs = FakeBackupVikingFS()
+ await PackService(backup_fs).backup_ovpack(str(temp_ovpack_path), ctx=admin_ctx)
with zipfile.ZipFile(temp_ovpack_path, "r") as zf:
names = set(zf.namelist())
@@ -601,6 +606,7 @@ async def test_backup_restore_contract(temp_ovpack_path: Path, request_ctx: Requ
assert "openviking-backup/files/resources/README.md" in names
assert "openviking-backup/files/user/alice/sessions/sess_1/.meta.json" in names
+ assert all(ctx.role == Role.ROOT for _, ctx in backup_fs.tree_contexts)
assert manifest["root"] == {
"name": "openviking-backup",
"uri": "viking://",
@@ -610,15 +616,33 @@ async def test_backup_restore_contract(temp_ovpack_path: Path, request_ctx: Requ
assert manifest["scopes"] == ["resources", "user"]
with pytest.raises(InvalidArgumentError, match=r"must be restored"):
- await import_ovpack(FakeVikingFS(), str(temp_ovpack_path), "viking://", request_ctx)
+ await import_ovpack(FakeVikingFS(), str(temp_ovpack_path), "viking://", admin_ctx)
+
+ monkeypatch.setattr(
+ "openviking.storage.ovpack.operations._enqueue_direct_vectorization",
+ AsyncMock(),
+ )
fake_fs = FakeVikingFS()
- assert await restore_ovpack(fake_fs, str(temp_ovpack_path), request_ctx) == "viking://"
+ fake_fs.ls = AsyncMock(return_value=[])
+ fake_fs.stat = AsyncMock(side_effect=FileNotFoundError())
+ fake_fs.rm = AsyncMock()
+ restore_service = PackService(fake_fs)
+
+ assert (
+ await restore_service.restore_ovpack(
+ str(temp_ovpack_path),
+ admin_ctx,
+ on_conflict="overwrite",
+ )
+ == "viking://"
+ )
assert fake_fs.written_files == [
"viking://resources/README.md",
"viking://user/alice/sessions/sess_1/.meta.json",
]
- assert fake_fs.tree_calls == ["viking://resources", "viking://user"]
+ fake_fs.rm.assert_not_awaited()
+ assert "viking://user" not in fake_fs.created_dirs
@pytest.mark.asyncio
@@ -887,9 +911,16 @@ async def test_import_ovpack_rejects_manifest_file_hash_mismatch(
manifest=manifest,
)
fake_fs = FakeVikingFS()
+ fake_fs.ls = AsyncMock(return_value=[])
with pytest.raises(InvalidArgumentError, match=r"sha256 does not match manifest"):
- await import_ovpack(fake_fs, str(temp_ovpack_path), "viking://resources", request_ctx)
+ await import_ovpack(
+ fake_fs,
+ str(temp_ovpack_path),
+ "viking://resources",
+ request_ctx,
+ on_conflict="skip",
+ )
assert fake_fs.written_files == []