Skip to content

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

fix(api): 区分参数错误、锁冲突和内部故障 (#5097)

Qin Haojie945527244d07
diff --git a/crates/ragfs-python/src/lib.rs b/crates/ragfs-python/src/lib.rs
index e2e4ecf38..251038250 100644
--- a/crates/ragfs-python/src/lib.rs
+++ b/crates/ragfs-python/src/lib.rs
@@ -174,7 +174,7 @@ fn pathlock_err_to_py(err: PathLockError) -> PyErr {
}
PathLockError::InvalidRequest(_) => PyValueError::new_err(err.to_string()),
PathLockError::Io(_) | PathLockError::InvalidToken(_) | PathLockError::Internal(_) => {
- PyRuntimeError::new_err(err.to_string())
+ new_py_err("AGFSInternalError", err.to_string())
}
}
}
@@ -972,6 +972,7 @@ fn to_py_err(e: ragfs::core::Error) -> PyErr {
ragfs::core::Error::Network(_) => new_py_err("AGFSNetworkError", msg),
ragfs::core::Error::Timeout(_) => new_py_err("AGFSTimeoutError", msg),
ragfs::core::Error::WouldBlock(_) => new_py_err("AGFSTimeoutError", msg),
+ ragfs::core::Error::PathLock(error) => pathlock_err_to_py(error),
ragfs::core::Error::SyncWriteQuorum { .. } => new_py_err("AGFSInternalError", msg),
ragfs::core::Error::ContextMissing(_) => new_py_err("AGFSInternalError", msg),
ragfs::core::Error::Internal(_) => new_py_err("AGFSInternalError", msg),
@@ -3053,7 +3054,7 @@ mod tests {
}
#[test]
- fn pathlock_io_error_maps_to_runtime_error() {
+ fn pathlock_failures_remain_internal_through_filesystem_wrappers() {
Python::initialize();
Python::attach(|py| {
let errors_mod = py.import("openviking.storage.errors").unwrap();
@@ -3064,15 +3065,25 @@ mod tests {
.unwrap();
let _ = LOCK_ACQUISITION_ERROR_TYPE.set(lock_error_type.clone_ref(py));
- let error =
- pathlock_err_to_py(PathLockError::Io("failed to create lock dir".to_string()));
-
- assert!(error.is_instance_of::<PyRuntimeError>(py));
+ let internal_error_type = get_exception(py, "AGFSInternalError").unwrap();
+ for wrapped in [false, true] {
+ for failure in [
+ PathLockError::Io("failed to create lock dir".to_string()),
+ PathLockError::InvalidToken("missing ':' in token".to_string()),
+ ] {
+ let error = if wrapped {
+ to_py_err(failure.into())
+ } else {
+ pathlock_err_to_py(failure)
+ };
+ assert!(error.is_instance(py, &internal_error_type));
+ }
+ }
});
}
#[test]
- fn pathlock_busy_error_maps_to_lock_acquisition_error() {
+ fn pathlock_contention_survives_filesystem_wrappers() {
Python::initialize();
Python::attach(|py| {
let errors_mod = py.import("openviking.storage.errors").unwrap();
@@ -3083,12 +3094,22 @@ mod tests {
.unwrap();
let _ = LOCK_ACQUISITION_ERROR_TYPE.set(lock_error_type.clone_ref(py));
- let error = pathlock_err_to_py(PathLockError::Busy {
- lock_path: "/data/.path.ovlock".to_string(),
- operation: "remove".to_string(),
- });
-
- assert!(error.is_instance(py, lock_error_type.bind(py)));
+ for wrapped in [false, true] {
+ for contention in [
+ PathLockError::Busy {
+ lock_path: "/data/.path.ovlock".to_string(),
+ operation: "remove".to_string(),
+ },
+ PathLockError::Timeout { elapsed_ms: 1000 },
+ ] {
+ let error = if wrapped {
+ to_py_err(contention.into())
+ } else {
+ pathlock_err_to_py(contention)
+ };
+ assert!(error.is_instance(py, lock_error_type.bind(py)));
+ }
+ }
});
}
diff --git a/crates/ragfs/src/core/encryption_wrapper.rs b/crates/ragfs/src/core/encryption_wrapper.rs
index 9237b1596..ce26b3905 100644
--- a/crates/ragfs/src/core/encryption_wrapper.rs
+++ b/crates/ragfs/src/core/encryption_wrapper.rs
@@ -408,19 +408,13 @@ impl FileSystem for EncryptionWrappedFS {
Some(
self.pathlock_manager
.acquire_batch(&requests, Duration::from_secs(1), Some(owner_capability))
- .await
- .map_err(|error| {
- Error::internal(format!("encrypted write lock error: {error}"))
- })?,
+ .await?,
)
}
AutoPathLockAction::Acquire => Some(
self.pathlock_manager
.acquire_batch(&requests, Duration::from_secs(1), None)
- .await
- .map_err(|error| {
- Error::internal(format!("encrypted write lock error: {error}"))
- })?,
+ .await?,
),
};
diff --git a/crates/ragfs/src/core/errors.rs b/crates/ragfs/src/core/errors.rs
index f7cd32bfa..9ee84e5c2 100644
--- a/crates/ragfs/src/core/errors.rs
+++ b/crates/ragfs/src/core/errors.rs
@@ -92,6 +92,10 @@ pub enum Error {
#[error("operation would block: {0}")]
WouldBlock(String),
+ /// Preserve acquisition failures so callers can distinguish contention from corruption.
+ #[error(transparent)]
+ PathLock(#[from] crate::lock::types::PathLockError),
+
/// Multi-write synchronous fanout failed to reach the required acknowledgement quorum
#[error(
"sync write quorum failed: {succeeded}/{attempted} backups succeeded (required {required}); failures: {failures:?}"
@@ -193,6 +197,7 @@ impl Error {
Self::Network(_) => "network",
Self::Timeout(_) => "timeout",
Self::WouldBlock(_) => "would_block",
+ Self::PathLock(_) => "path_lock",
Self::SyncWriteQuorum { .. } => "sync_write_quorum",
Self::ContextMissing(_) => "context_missing",
Self::Internal(_) => "internal",
diff --git a/crates/ragfs/src/core/mountable.rs b/crates/ragfs/src/core/mountable.rs
index 0a9df8537..995604558 100644
--- a/crates/ragfs/src/core/mountable.rs
+++ b/crates/ragfs/src/core/mountable.rs
@@ -697,8 +697,7 @@ impl MountableFS {
Ok(AutoPathLockAction::Acquire) => Some(
manager
.acquire_exact(dst_path, Duration::ZERO, None)
- .await
- .map_err(|error| Error::internal(format!("lock error: {error}")))?,
+ .await?,
),
Err(error) => {
return Err(Error::internal(format!("lock lease error: {error}")));
diff --git a/crates/ragfs/src/lock/wrapper.rs b/crates/ragfs/src/lock/wrapper.rs
index 1afd56ce6..ec6bdc7fd 100644
--- a/crates/ragfs/src/lock/wrapper.rs
+++ b/crates/ragfs/src/lock/wrapper.rs
@@ -131,8 +131,7 @@ impl FileSystem for PathLockWrappedFS {
let lease = self
.manager
.acquire_exact(path, self.manager.default_lock_timeout(), None)
- .await
- .map_err(|e| crate::core::Error::internal(format!("lock error: {e}")))?;
+ .await?;
let result = self.inner.create(path).await;
let release = self.manager.release(&lease).await;
Self::merge_operation_and_release(result, release)
@@ -159,8 +158,7 @@ impl FileSystem for PathLockWrappedFS {
let lease = self
.manager
.acquire_exact(path, self.manager.default_lock_timeout(), None)
- .await
- .map_err(|e| crate::core::Error::internal(format!("lock error: {e}")))?;
+ .await?;
let result = self.inner.remove(path).await;
let release = self.manager.release(&lease).await;
Self::merge_operation_and_release(result, release)
@@ -183,8 +181,7 @@ impl FileSystem for PathLockWrappedFS {
let lease = self
.manager
.acquire_tree(path, self.manager.default_lock_timeout(), None)
- .await
- .map_err(|e| crate::core::Error::internal(format!("lock error: {e}")))?;
+ .await?;
let result = self.inner.remove_all(path).await;
let release = self.manager.release(&lease).await;
Self::merge_operation_and_release(result, release)
@@ -214,8 +211,7 @@ impl FileSystem for PathLockWrappedFS {
let lease = self
.manager
.acquire_exact(path, self.manager.default_lock_timeout(), None)
- .await
- .map_err(|e| crate::core::Error::internal(format!("lock error: {e}")))?;
+ .await?;
let result = self.inner.write(path, data, offset, flags).await;
let release = self.manager.release(&lease).await;
Self::merge_operation_and_release(result, release)
@@ -282,8 +278,7 @@ impl FileSystem for PathLockWrappedFS {
let lease = self
.manager
.acquire_batch(&requests, self.manager.default_lock_timeout(), None)
- .await
- .map_err(|e| crate::core::Error::internal(format!("lock error: {e}")))?;
+ .await?;
let result = self.inner.rename(old_path, new_path).await;
let release = self.manager.release(&lease).await;
Self::merge_operation_and_release(result, release)
@@ -310,8 +305,7 @@ impl FileSystem for PathLockWrappedFS {
let lease = self
.manager
.acquire_batch(&requests, self.manager.default_lock_timeout(), None)
- .await
- .map_err(|e| crate::core::Error::internal(format!("lock error: {e}")))?;
+ .await?;
let result = self.inner.replace(src_path, dst_path).await;
let release = self.manager.release(&lease).await;
Self::merge_operation_and_release(result, release)
@@ -335,8 +329,7 @@ impl FileSystem for PathLockWrappedFS {
let lease = self
.manager
.acquire_exact(path, self.manager.default_lock_timeout(), None)
- .await
- .map_err(|e| crate::core::Error::internal(format!("lock error: {e}")))?;
+ .await?;
let result = self.inner.truncate(path, size).await;
let release = self.manager.release(&lease).await;
Self::merge_operation_and_release(result, release)
diff --git a/crates/ragfs/src/plugins/serverinfofs/mod.rs b/crates/ragfs/src/plugins/serverinfofs/mod.rs
index 9c490ce77..18c958de3 100644
--- a/crates/ragfs/src/plugins/serverinfofs/mod.rs
+++ b/crates/ragfs/src/plugins/serverinfofs/mod.rs
@@ -163,7 +163,7 @@ impl FileSystem for ServerInfoFileSystem {
}
if path == "/" {
- return Err(Error::plugin("is a directory: /".to_string()));
+ return Err(Error::IsADirectory(path.to_string()));
}
let data = match path {
@@ -220,7 +220,7 @@ impl FileSystem for ServerInfoFileSystem {
sort_order: Option<crate::core::SortOrder>,
) -> Result<Vec<FileInfo>> {
if path != "/" {
- return Err(Error::plugin(format!("not a directory: {}", path)));
+ return Err(Error::NotADirectory(path.to_string()));
}
let now = std::time::SystemTime::now();
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index 27cde2bdb..e54e0e28a 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -333,6 +333,8 @@ JSON output - error:
| `SESSION_EXPIRED` | 410 | Session no longer exists |
| `NOT_INITIALIZED` | - | Service or component not initialized (need to call initialize() first) |
+File/directory type misuse, copying or removing a directory without `recursive=true`, and a definitively nonexistent HTTP source hostname return `INVALID_ARGUMENT` (400). Path-lock contention, including encrypted writes, returns `CONFLICT` (409); corrupt lock tokens, lock I/O failures, and stored-data decryption failures return `INTERNAL` (500). An unavailable HTTP source or temporary network failure returns `UNAVAILABLE` (503), while a fetch timeout returns `DEADLINE_EXCEEDED` (504).
+
---
## API Endpoints
diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.md
index 22e75e89e..e3bda1f82 100644
--- a/docs/en/api/03-filesystem.md
+++ b/docs/en/api/03-filesystem.md
@@ -709,7 +709,7 @@ ov cp -r viking://resources/docs viking://resources/docs-backup
`semantic_status: "queued"` means the copy has already committed and the destination parent's overview and abstract will be rebuilt asynchronously from summaries available at the destination. The API does not wait for that refresh. A refresh enqueue failure may return `semantic_status: "failed"` and `semantic_error`; it does not roll back the completed file and vector copy.
-Common errors include `NOT_FOUND` when the source or destination parent is missing, `CONFLICT` when a path lock is busy, `FAILED_PRECONDITION` when a directory is copied without `recursive=true`, and `INVALID_ARGUMENT` for invalid source/destination relationships or file/directory type conflicts.
+Common errors include `NOT_FOUND` when the source or destination parent is missing, `CONFLICT` when a path lock is busy, and `INVALID_ARGUMENT` (HTTP 400) when a directory is copied or removed without `recursive=true`, a directory operation targets a file, or the source/destination relationship or file/directory types are invalid.
---
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 779c30f9b..278cb22b3 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -328,6 +328,8 @@ JSON 输出 - 错误:
| `SESSION_EXPIRED` | 410 | 会话已过期 |
| `NOT_INITIALIZED` | - | 服务或组件未初始化(需要先调用 initialize()) |
+文件/目录类型不符合操作要求、复制或删除目录时缺少 `recursive=true`,以及 HTTP 来源域名明确不存在,均返回 `INVALID_ARGUMENT`(400)。正常路径锁竞争(包括加密写入)返回 `CONFLICT`(409);锁令牌损坏、锁 I/O 故障和落盘数据解密失败返回 `INTERNAL`(500)。HTTP 来源站不可用或发生临时网络故障时返回 `UNAVAILABLE`(503),抓取超时返回 `DEADLINE_EXCEEDED`(504)。
+
---
## API 端点总览
diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.md
index 1ecc99ee3..39e696a49 100644
--- a/docs/zh/api/03-filesystem.md
+++ b/docs/zh/api/03-filesystem.md
@@ -743,7 +743,7 @@ ov cp -r viking://resources/docs viking://resources/docs-backup
`semantic_status: "queued"` 表示复制已经提交,目标父目录的 overview 和 abstract 将根据目标目录中已有的摘要异步重建,接口不会等待刷新完成。若语义刷新入队失败,响应可能包含 `semantic_status: "failed"` 和 `semantic_error`;已经完成的文件和向量复制不会因此回滚。
-常见错误包括:源或目标父目录不存在时返回 `NOT_FOUND`;路径锁繁忙时返回 `CONFLICT`;复制目录但未设置 `recursive=true` 时返回 `FAILED_PRECONDITION`;源和目标关系非法或类型冲突时返回 `INVALID_ARGUMENT`。
+常见错误包括:源或目标父目录不存在时返回 `NOT_FOUND`;路径锁繁忙时返回 `CONFLICT`;复制或删除目录但未设置 `recursive=true`、对文件执行目录操作、源和目标关系非法或类型冲突时返回 `INVALID_ARGUMENT`(HTTP 400)。
---
diff --git a/openviking/parse/accessors/http_accessor.py b/openviking/parse/accessors/http_accessor.py
index 395640566..b8f20b533 100644
--- a/openviking/parse/accessors/http_accessor.py
+++ b/openviking/parse/accessors/http_accessor.py
@@ -16,6 +16,7 @@ Features:
- IANA Media Type (MIME) based content detection for URLs without file extensions
"""
+import socket
import tempfile
from enum import Enum
from pathlib import Path
@@ -30,8 +31,15 @@ from openviking.parse.parsers.media.constants import (
VIDEO_EXTENSIONS,
)
from openviking.utils import is_code_hosting_blob_url
+from openviking.utils.exceptions import error_code_from_http_status
from openviking.utils.network_guard import build_httpx_request_validation_hooks
-from openviking_cli.exceptions import PermissionDeniedError
+from openviking_cli.exceptions import (
+ DeadlineExceededError,
+ InvalidArgumentError,
+ OpenVikingError,
+ PermissionDeniedError,
+ UnavailableError,
+)
from openviking_cli.utils.logger import get_logger
from .base import DataAccessor, LocalResource, SourceType
@@ -581,27 +589,29 @@ class HTTPAccessor(DataAccessor):
response = await client.get(url, headers=headers)
response.raise_for_status()
except httpx.ConnectError as e:
- user_msg = "HTTP request failed: could not connect to server. Check the URL or your network."
- raise RuntimeError(f"{user_msg} URL: {url}. Details: {e}") from e
+ cause: BaseException | None = e
+ while cause is not None:
+ if isinstance(cause, socket.gaierror) and cause.errno == socket.EAI_NONAME:
+ raise InvalidArgumentError(
+ f"Source URL host does not exist: {url}", details={"source": url}
+ ) from e
+ cause = cause.__cause__ or cause.__context__
+ raise UnavailableError(
+ "source URL", reason=f"Could not connect to {url}: {e}"
+ ) from e
except httpx.TimeoutException as e:
- user_msg = "HTTP request failed: timeout. The server took too long to respond."
- raise RuntimeError(f"{user_msg} URL: {url}. Details: {e}") from e
+ raise DeadlineExceededError(f"Fetch source URL {url}", self.timeout) from e
except httpx.HTTPStatusError as e:
- status_code = e.response.status_code if e.response else "unknown"
- if status_code == 401:
- user_msg = f"HTTP request failed: authentication error ({status_code}). Check your credentials or permissions."
- elif status_code == 403:
- user_msg = f"HTTP request failed: access denied ({status_code}). The site blocked the request (login or anti-bot may be required)."
- elif status_code == 404:
- user_msg = f"HTTP request failed: not found ({status_code}). The URL may be invalid or the resource was removed."
- elif 500 <= status_code < 600:
- user_msg = f"HTTP request failed: server error ({status_code}). The server encountered an error."
- else:
- user_msg = f"HTTP request failed: status code {status_code}."
- raise RuntimeError(f"{user_msg} URL: {url}. Details: {e}") from e
- except Exception as e:
- user_msg = "HTTP request failed: unexpected error."
- raise RuntimeError(f"{user_msg} URL: {url}. Details: {e}") from e
+ status_code = e.response.status_code
+ raise OpenVikingError(
+ f"Source URL returned HTTP {status_code}: {url}",
+ code=error_code_from_http_status(status_code),
+ details={"source": url, "upstream_status_code": status_code},
+ ) from e
+ except httpx.InvalidURL as e:
+ raise InvalidArgumentError(f"Invalid source URL: {url}") from e
+ except httpx.RequestError as e:
+ raise UnavailableError("source URL", reason=str(e)) from e
meta = self._finalize_download_metadata(
url=url,
diff --git a/openviking/server/error_mapping.py b/openviking/server/error_mapping.py
index dcfa11256..856f96ba7 100644
--- a/openviking/server/error_mapping.py
+++ b/openviking/server/error_mapping.py
@@ -34,6 +34,7 @@ from openviking.utils.exceptions import HTTP_STATUS_TO_ERROR_CODE, error_code_fr
from openviking_cli.exceptions import (
ConflictError,
FailedPreconditionError,
+ InternalError,
InvalidArgumentError,
InvalidURIError,
NotFoundError,
@@ -483,9 +484,6 @@ def map_exception(
message = str(exc)
if is_invalid_uri_error(exc):
return InvalidURIError(resource or message, message)
- if "not a directory" in message.lower():
- details = {"resource": resource} if resource else None
- return FailedPreconditionError(message, details=details)
return InvalidArgumentError(message, details={"resource": resource} if resource else None)
if isinstance(exc, (AGFSConnectionError, AGFSTimeoutError)):
return UnavailableError("storage backend", reason=str(exc))
@@ -511,25 +509,25 @@ def map_exception(
if isinstance(exc, AGFSInvalidPathError):
message = str(exc)
return InvalidURIError(resource or message, message)
- if isinstance(exc, AGFSNotADirectoryError):
- return FailedPreconditionError(str(exc), details=_resource_details(resource))
- if isinstance(exc, AGFSIsADirectoryError):
+ if isinstance(exc, (AGFSNotADirectoryError, NotADirectoryError)):
+ return InvalidArgumentError(str(exc), details=_resource_details(resource))
+ if isinstance(exc, (AGFSIsADirectoryError, IsADirectoryError)):
return InvalidArgumentError(str(exc), details=_file_directory_details(resource))
if isinstance(exc, AGFSDirectoryNotEmptyError):
- return FailedPreconditionError(str(exc), details=_resource_details(resource))
+ return InvalidArgumentError(str(exc), details=_resource_details(resource))
if isinstance(exc, AGFSResourceExhaustedError):
return ResourceExhaustedError(str(exc), details=_resource_details(resource))
if isinstance(exc, AGFSInvalidOperationError):
return InvalidArgumentError(str(exc), details=_resource_details(resource))
+ if isinstance(exc, AGFSInternalError):
+ return InternalError(str(exc))
if isinstance(
exc,
(
AGFSConfigError,
- AGFSInternalError,
AGFSIoError,
AGFSMountPointNotFoundError,
AGFSNetworkError,
- AGFSPluginError,
AGFSSerializationError,
),
):
@@ -542,11 +540,11 @@ def map_exception(
return InvalidURIError(resource or message, message)
lowered = message.lower()
if "not a directory" in lowered:
- return FailedPreconditionError(message, details=_resource_details(resource))
+ return InvalidArgumentError(message, details=_resource_details(resource))
if "is a directory" in lowered:
return InvalidArgumentError(message, details=_resource_details(resource))
if "directory not empty" in lowered:
- return FailedPreconditionError(message, details=_resource_details(resource))
+ return InvalidArgumentError(message, details=_resource_details(resource))
if "permission denied" in lowered:
return PermissionDeniedError(message, resource=resource)
if "already exists" in lowered:
@@ -557,7 +555,11 @@ def map_exception(
or "invalid regular expression" in lowered
):
return InvalidArgumentError(message, details=_resource_details(resource))
- if "timeout" in lowered or "connection refused" in lowered:
+ if (
+ isinstance(exc, AGFSPluginError)
+ or "timeout" in lowered
+ or "connection refused" in lowered
+ ):
return UnavailableError("storage backend", reason=message)
upstream_mapped = _map_upstream_api_error(exc)
if upstream_mapped is not None:
diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.py
index 571997d6a..961e45c98 100644
--- a/openviking/storage/viking_fs/_ops.py
+++ b/openviking/storage/viking_fs/_ops.py
@@ -40,7 +40,6 @@ from openviking.storage.viking_fs._base import (
)
from openviking.utils.time_utils import format_iso8601, parse_iso_datetime
from openviking_cli.exceptions import (
- FailedPreconditionError,
InvalidArgumentError,
NotFoundError,
PermissionDeniedError,
@@ -285,7 +284,7 @@ class _OpsMixin:
if is_dir:
await self._ensure_access(target_uri, ctx, action=AclAction.MANAGE)
if not recursive:
- raise FailedPreconditionError(
+ raise InvalidArgumentError(
f"Cannot remove directory without --recursive: {uri}",
details={"resource": uri, "expected_flag": "recursive"},
)
@@ -330,13 +329,13 @@ class _OpsMixin:
auto_pathlock=auto_pathlock,
)
except AGFSDirectoryNotEmptyError:
- raise FailedPreconditionError(
+ raise InvalidArgumentError(
f"Directory not empty: {uri}. Use recursive=True to delete non-empty directories."
)
except RuntimeError as e:
# Fallback for older versions without typed exceptions
if _is_directory_not_empty_error(str(e)):
- raise FailedPreconditionError(
+ raise InvalidArgumentError(
f"Directory not empty: {uri}. Use recursive=True to delete non-empty directories."
)
raise
@@ -415,7 +414,7 @@ class _OpsMixin:
raise
is_dir = stat.get("isDir", False) if isinstance(stat, dict) else False
if is_dir and not recursive:
- raise FailedPreconditionError(
+ raise InvalidArgumentError(
f"Cannot copy directory without --recursive: {old_uri}",
details={"resource": old_uri, "expected_flag": "recursive"},
)
diff --git a/tests/api_test/filesystem/slow/test_filesystem_deep_ops.py b/tests/api_test/filesystem/slow/test_filesystem_deep_ops.py
index aaf4cf022..e3b20fae0 100644
--- a/tests/api_test/filesystem/slow/test_filesystem_deep_ops.py
+++ b/tests/api_test/filesystem/slow/test_filesystem_deep_ops.py
@@ -112,7 +112,7 @@ class TestFilesystemDeep:
finally:
api_client.fs_rm(file_uri)
- def test_rm_directory_nonrecursive_returns_412(self, api_client):
+ def test_rm_directory_nonrecursive_returns_400(self, api_client):
dir_uri = f"viking://resources/rm_nonrec_{uuid.uuid4().hex[:8]}"
try:
mkdir_resp = api_client.fs_mkdir(dir_uri)
@@ -121,8 +121,8 @@ class TestFilesystemDeep:
api_client.fs_write(f"{dir_uri}/child.md", "child", mode="create", wait=True)
rm_resp = api_client.fs_rm(dir_uri, recursive=False)
- assert rm_resp.status_code == 412, (
- f"non-recursive rm on non-empty dir should return 412 Precondition Failed, got {rm_resp.status_code}: {rm_resp.text[:200]}"
+ assert rm_resp.status_code == 400, (
+ f"non-recursive rm on non-empty dir should return 400 Invalid Argument, got {rm_resp.status_code}: {rm_resp.text[:200]}"
)
finally:
api_client.fs_rm(dir_uri, recursive=True)
diff --git a/tests/api_test/filesystem/test_fs_cp.py b/tests/api_test/filesystem/test_fs_cp.py
index f449ea553..48ce879c6 100644
--- a/tests/api_test/filesystem/test_fs_cp.py
+++ b/tests/api_test/filesystem/test_fs_cp.py
@@ -57,7 +57,7 @@ class TestFsCp:
)
without_recursive = api_client.fs_cp(source, target)
- assert without_recursive.status_code == 412, without_recursive.text
+ assert without_recursive.status_code == 400, without_recursive.text
copied = api_client.fs_cp(source, target, recursive=True)
assert copied.status_code == 200, copied.text
diff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.py
index 9b6a903b4..3e749b22d 100644
--- a/tests/server/test_api_content.py
+++ b/tests/server/test_api_content.py
@@ -195,14 +195,17 @@ async def test_overview_content(client_with_resource, service):
assert body["result"] == f"# {uri}\n\n[Directory overview is not ready]"
-async def test_abstract_file_uri_returns_failed_precondition(client_with_resource):
- client, uri = client_with_resource
- file_uri = await _first_child_uri(client, uri)
- resp = await client.get("/api/v1/content/abstract", params={"uri": file_uri})
- assert resp.status_code == 412
+async def test_ls_file_uri_returns_invalid_argument(client, service):
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+ file_uri = "viking://resources/directory-type-check/file.md"
+ await service.viking_fs.mkdir("viking://resources/directory-type-check", ctx=ctx)
+ await service.viking_fs.write_file(file_uri, "file content", ctx=ctx)
+
+ resp = await client.get("/api/v1/fs/ls", params={"uri": file_uri})
+ assert resp.status_code == 400
body = resp.json()
assert body["status"] == "error"
- assert body["error"]["code"] == "FAILED_PRECONDITION"
+ assert body["error"]["code"] == "INVALID_ARGUMENT"
assert "not a directory" in body["error"]["message"]
diff --git a/tests/server/test_api_fs_content_endpoint_suite.py b/tests/server/test_api_fs_content_endpoint_suite.py
index 777283a09..596da6e12 100644
--- a/tests/server/test_api_fs_content_endpoint_suite.py
+++ b/tests/server/test_api_fs_content_endpoint_suite.py
@@ -6,7 +6,7 @@ from types import SimpleNamespace
import httpx
from openviking.pyagfs.exceptions import AGFSHTTPError
-from openviking_cli.exceptions import ConflictError, FailedPreconditionError, NotFoundError
+from openviking_cli.exceptions import ConflictError, InvalidArgumentError, NotFoundError
def _assert_error(
@@ -231,13 +231,13 @@ async def test_cp_existing_target_returns_conflict(app, service, monkeypatch):
_assert_error(response, status_code=409, error_code="CONFLICT")
-async def test_cp_directory_without_recursive_returns_precondition(
+async def test_cp_directory_without_recursive_returns_invalid_argument(
app,
service,
monkeypatch,
):
async def fake_cp(*args, **kwargs):
- raise FailedPreconditionError("directory copy requires recursive")
+ raise InvalidArgumentError("directory copy requires recursive")
monkeypatch.setattr(service.fs, "cp", fake_cp, raising=False)
response = await _request_with_handler(
@@ -249,7 +249,7 @@ async def test_cp_directory_without_recursive_returns_precondition(
"to_uri": "viking://resources/target",
},
)
- _assert_error(response, status_code=412, error_code="FAILED_PRECONDITION")
+ _assert_error(response, status_code=400, error_code="INVALID_ARGUMENT")
async def test_cp_internal_rollback_error_is_redacted(app, service, monkeypatch):
diff --git a/tests/server/test_error_mapping.py b/tests/server/test_error_mapping.py
index 34dab57d2..bb4f5ccd2 100644
--- a/tests/server/test_error_mapping.py
+++ b/tests/server/test_error_mapping.py
@@ -3,11 +3,17 @@
"""Focused tests for HTTP server exception-to-error mapping."""
+import pytest
+
from openviking.pyagfs.exceptions import (
AGFSClientError,
+ AGFSDirectoryNotEmptyError,
AGFSHTTPError,
+ AGFSInternalError,
AGFSIsADirectoryError,
+ AGFSNotADirectoryError,
AGFSNotSupportedError,
+ AGFSPluginError,
AGFSResourceExhaustedError,
GitConcurrentCommitError,
)
@@ -75,19 +81,32 @@ def test_agfs_http_status_keeps_storage_mapping():
assert mapped.message == "File not found: viking://missing"
-def test_agfs_is_directory_maps_to_structured_invalid_argument():
+ ("error", "expected_details"),
+ [
+ (AGFSIsADirectoryError("is a directory"), {"expected": "file", "actual": "directory"}),
+ (IsADirectoryError("is a directory"), {"expected": "file", "actual": "directory"}),
+ (AGFSNotADirectoryError("not a directory"), {}),
+ (NotADirectoryError("not a directory"), {}),
+ (AGFSPluginError("plugin error: not a directory: /resources/file.md"), {}),
+ (AGFSClientError("not a directory"), {}),
+ (ValueError("not a directory"), {}),
+ (AGFSDirectoryNotEmptyError("directory not empty"), {}),
+ ],
+)
+def test_file_directory_misuse_maps_to_invalid_argument(error, expected_details):
mapped = map_exception(
- AGFSIsADirectoryError("Cannot read directory as file: viking://resources/docs"),
+ error,
resource="viking://resources/docs",
resource_type="file",
)
assert isinstance(mapped, InvalidArgumentError)
assert mapped.code == "INVALID_ARGUMENT"
+ assert ERROR_CODE_TO_HTTP_STATUS[mapped.code] == 400
assert mapped.details == {
"resource": "viking://resources/docs",
- "expected": "file",
- "actual": "directory",
+ **expected_details,
}
@@ -210,20 +229,32 @@ def test_resource_busy_maps_to_structured_conflict():
}
-def test_lock_acquisition_maps_to_structured_conflict():
+ ("error", "expected_code", "expected_status"),
+ [
+ (LockAcquisitionError("Failed to acquire exact lock"), "CONFLICT", 409),
+ (AGFSInternalError("invalid lock token: missing ':' in token"), "INTERNAL", 500),
+ (AGFSInternalError("lock I/O error: failed to create lock dir"), "INTERNAL", 500),
+ (AGFSInternalError("AES-GCM authentication failed: aead::Error"), "INTERNAL", 500),
+ (AGFSPluginError("plugin error: backend connection lost"), "UNAVAILABLE", 503),
+ ],
+)
+def test_storage_conflicts_remain_distinct_from_failures(error, expected_code, expected_status):
mapped = map_exception(
- LockAcquisitionError("Failed to acquire exact lock"),
+ error,
resource="viking://resources/docs/a.md",
)
assert mapped is not None
- assert mapped.code == "CONFLICT"
- assert mapped.details == {
- "resource": "viking://resources/docs/a.md",
- "uri": "viking://resources/docs/a.md",
- "conflict_type": "path_busy",
- "retryable": True,
- }
+ assert mapped.code == expected_code
+ assert ERROR_CODE_TO_HTTP_STATUS[mapped.code] == expected_status
+ if expected_code == "CONFLICT":
+ assert mapped.details == {
+ "resource": "viking://resources/docs/a.md",
+ "uri": "viking://resources/docs/a.md",
+ "conflict_type": "path_busy",
+ "retryable": True,
+ }
def test_git_concurrent_commit_maps_to_conflict():
diff --git a/tests/storage/test_viking_fs_cp.py b/tests/storage/test_viking_fs_cp.py
index 47814f6d6..2ead120b0 100644
--- a/tests/storage/test_viking_fs_cp.py
+++ b/tests/storage/test_viking_fs_cp.py
@@ -13,7 +13,6 @@ from openviking.storage.abstract_overview import parse_abstract_overview
from openviking.storage.acl import AclAction
from openviking.storage.viking_fs import VikingFS
from openviking_cli.exceptions import (
- FailedPreconditionError,
InvalidArgumentError,
NotFoundError,
PermissionDeniedError,
@@ -338,7 +337,7 @@ async def test_cp_directory_requires_recursive_before_locking(monkeypatch):
agfs = _CopyAGFS(source_is_dir=True)
fs = _viking_fs(monkeypatch, agfs)
- with pytest.raises(FailedPreconditionError, match="recursive"):
+ with pytest.raises(InvalidArgumentError, match="recursive"):
await fs.cp(
"viking://resources/source",
"viking://resources/target",
diff --git a/tests/unit/test_accessors_http.py b/tests/unit/test_accessors_http.py
index 62908bfc6..60e51349f 100644
--- a/tests/unit/test_accessors_http.py
+++ b/tests/unit/test_accessors_http.py
@@ -2,15 +2,17 @@
# SPDX-License-Identifier: AGPL-3.0
"""Unit tests for HTTPAccessor."""
+import socket
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import patch
import httpx
-
import pytest
from openviking.parse.accessors import AccessorRegistry, GitAccessor, HTTPAccessor
from openviking.parse.accessors.http_accessor import URLType
+from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS
+from openviking_cli.exceptions import OpenVikingError
def _mock_config():
@@ -45,9 +47,39 @@ class TestHTTPAccessor:
"""Create a HTTPAccessor instance."""
return HTTPAccessor()
- def test_priority(self, accessor: HTTPAccessor) -> None:
- """HTTPAccessor should have correct priority."""
- assert accessor.priority == 50
+ @pytest.mark.parametrize(
+ ("failure", "expected_code", "expected_status"),
+ [
+ (socket.gaierror(socket.EAI_NONAME, "host does not exist"), "INVALID_ARGUMENT", 400),
+ (socket.gaierror(socket.EAI_AGAIN, "temporary DNS failure"), "UNAVAILABLE", 503),
+ (httpx.ConnectError("connection refused"), "UNAVAILABLE", 503),
+ (httpx.ReadTimeout("read timed out"), "DEADLINE_EXCEEDED", 504),
+ (httpx.InvalidURL("invalid host"), "INVALID_ARGUMENT", 400),
+ (403, "PERMISSION_DENIED", 403),
+ (500, "UNAVAILABLE", 503),
+ ],
+ )
+ async def test_source_fetch_errors_preserve_cause(
+ self, accessor: HTTPAccessor, monkeypatch, failure, expected_code, expected_status
+ ) -> None:
+ async def handler(request):
+ if isinstance(failure, socket.gaierror):
+ raise httpx.ConnectError(str(failure)) from failure
+ if isinstance(failure, Exception):
+ raise failure
+ return httpx.Response(failure, request=request)
+
+ client_type = httpx.AsyncClient
+ monkeypatch.setattr(
+ httpx,
+ "AsyncClient",
+ lambda **kwargs: client_type(transport=httpx.MockTransport(handler), **kwargs),
+ )
+ with pytest.raises(OpenVikingError) as caught:
+ await accessor.access("https://source.example/data.txt")
+
+ assert caught.value.code == expected_code
+ assert ERROR_CODE_TO_HTTP_STATUS[caught.value.code] == expected_status
@pytest.mark.parametrize(
"source",