OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: append_file failures are unclassifiable - a retryable path-lock CONFLICT reaches clients as 500 INTERNAL

Open Tong-bit-art opened this issue 1 month ago • 1 comments

Issue Origin

Observed or reproduced in a real environment

Bug Description

VikingFS.append_file collapses every failure into a bare IOError:

except Exception as e:
    logger.error(f"[VikingFS] Failed to append to file {uri}: {e}")
    raise IOError(f"Failed to append to file {uri}: {e}")

map_exception has no branch for OSError, so its final fallthrough returns None and general_error_handler answers 500 INTERNAL. Every typed error that the server already knows how to classify is destroyed at this boundary — including the path-lock conflict it maps at error_mapping.py:458.

The rest of _ops.py routes failures through map_exception before re-raising (rm at :267-272, cp at :411-414, and :505, :603, :720, :741). write_file, the sibling write operation directly above it at :2105-2114, does not wrap at all. append_file is the only operation in the file whose failures the server cannot classify.

This is reachable from the session append path. _append_messages_authoritatively writes messages.jsonl two ways (session.py:737-748):

if live_messages_missing:
    await self._viking_fs.write_file(f"{self._session_uri}/messages.jsonl", ...)
else:
    await self._viking_fs.append_file(f"{self._session_uri}/messages.jsonl", ...)

So the same logical append reports a retryable CONFLICT through one branch and an unclassifiable 500 through the other.

Steps to Reproduce

  1. Make pathlock_acquire_exact refuse the lease, as the native fail-fast lock layer does when the path is already held (lock acquire timed out after 0ms).
  2. Call VikingFS.append_file("viking://a.md", "+new").
  3. Pass the raised exception to map_exception.

Expected Behavior

The failure is classified the way the server already defines it: CONFLICT with conflict_type: path_busy and retryable: true for a lock conflict, and the corresponding codes for the other typed errors map_exception handles. CONTRIBUTING states the rule directly:

Preserve meaningful server, network, timeout, authentication, and conflict errors at client-facing boundaries.

Actual Behavior

AssertionError: OSError('Failed to append to file viking://a.md: lock acquire timed out after 0ms')
is unmappable, so the router answers 500 INTERNAL instead of a retryable conflict
assert None is not None

Note the message contains timed out but not timeout, so map_exception's string fallback at :575 does not catch it either — it falls all the way through to None.

Minimal Reproducible Example

from unittest.mock import AsyncMock
from openviking.server.error_mapping import map_exception
from openviking.storage.errors import LockAcquisitionError
from openviking.storage.viking_fs import VikingFS


class _BusyAGFS:
    async def pathlock_acquire_exact(self, path):
        raise LockAcquisitionError("lock acquire timed out after 0ms")


fs = VikingFS(agfs=object())
fs._async_agfs = _BusyAGFS()
fs._ensure_access = AsyncMock()
fs._ensure_parent_dirs = AsyncMock()
fs._uri_to_path = lambda uri, **kw: "/local/default/resources/a.md"

try:
    await fs.append_file("viking://a.md", "+new")
except Exception as exc:
    print(type(exc).__name__, "->", map_exception(exc, resource="viking://a.md"))
    # OSError -> None   (router answers 500)
    # expected: OpenVikingError(code='CONFLICT', details={'conflict_type': 'path_busy', 'retryable': True, ...})

Error Logs

[VikingFS] Failed to append to file viking://a.md: lock acquire timed out after 0ms

OpenViking Version

main @ ee2bb95e7

Python Version

3.11.9

Operating System

Windows

Model Backend

Other

Additional Context

I want to be explicit about scope, because three earlier attempts on this function were closed: #1371 and #1383 (both resolved by #1348) and #1762, which was closed with "Why was it changed this way? Was there a specific issue that this was meant to address?".

Those three all proposed changing the missing-file semantics of append_file — treat a missing target as empty instead of an error. That behaviour is already on main today (_ops.py:2143-2144 catches FileNotFoundError and continues), so this report is not re-opening it.

The defect here is narrower and different: the method's blanket except makes an already-defined, client-facing classification unreachable. I am not proposing new semantics — the intended status for a lock conflict is already written in error_mapping.py:458 and asserted by the SDK tests; it just cannot be reached through append_file.

Relevant to #5558 (closed today), which went to some length to keep the server's structured conflict_type / retryable decision visible to clients. That decision is discarded one layer earlier for this path.

I have a fix and a regression test ready, but per CONTRIBUTING this changes error behaviour at a client-facing boundary, so I would like to confirm the boundary first.

I have not demonstrated how often a lock conflict actually occurs on messages.jsonl; the reachability above is from code path, not from a reproduction under load. What is demonstrated is the classification defect itself.

Tong-bit-art avatar Oct 06 '26 07:10 Tong-bit-art

Claiming this with a PR so the issue is not picked up twice.

  • Fix: #5688 — fix(storage): classify append_file failures instead of collapsing them to IOError
  • Diff: +60/-1 across openviking/storage/viking_fs/_ops.py and tests/storage/test_viking_fs_write_locking.py

Reproduced against unmodified main: a refused exact lock raises OSError('Failed to append to file ...: lock acquire timed out after 0ms'), and map_exception returns None for it, so general_error_handler answers 500 instead of the CONFLICT / path_busy / retryable status already defined at error_mapping.py:458.

I also added the reachability evidence I was missing when I opened this, as a comment on the PR rather than by changing the diff — the lock model does not serialize the two writers of messages.jsonl (Exact locks do not cover descendants, and every automatic write lock uses the 0-second default). That part is static verification, not a live contention run; the PR comment says so explicitly.

I cannot set the assignee field myself (no write access on this repository), so recording the link here instead. Happy to adjust the approach or drop the reachability argument if you would rather merge only the classification fix.

Tong-bit-art avatar Oct 06 '26 07:10 Tong-bit-art