Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Empty file removed logs.txt
Empty file.
15 changes: 15 additions & 0 deletions pyrightconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"pythonVersion": "3.11",
"typeCheckingMode": "standard",
"executionEnvironments": [
{
"root": "tests",
"reportGeneralTypeIssues": "none",
"reportArgumentType": "none",
"reportIndexIssue": "none",
"reportOptionalMemberAccess": "none",
"reportAttributeAccessIssue": "none"
},
{ "root": "src" }
]
}
8 changes: 3 additions & 5 deletions src/fathom/adapters/artifact/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class CloudSink(ArtifactSinkPort):
Sink that uploads to the configured :class:`StoragePort` and requests local cleanup when the upload succeeds.

On any upload failure (network, throttling, auth), the sink reports ``local_cleanup=False``
so the pipeline leaves the EFS file in place. The next process's ``replay()`` will pick it up.
so the pipeline leaves the local copy in place. The next process's ``replay()`` will pick it up.
"""

def __init__(
Expand All @@ -42,10 +42,8 @@ async def persist(
"""
Upload the artifact and report whether local cleanup is safe.

When the upload fails (exception or empty identifier returned by
the underlying composite storage) we set ``local_cleanup=False``
so the pipeline preserves the EFS copy for replay and the
operator sees the artifact route on the next run.
On failure (an exception, or an empty identifier that means the storage backend dropped the
write) we set ``local_cleanup=False`` so the pipeline keeps the local copy for a later replay.
"""

started = time.monotonic()
Expand Down
7 changes: 4 additions & 3 deletions src/fathom/adapters/artifact/efs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@

class EfsSink(ArtifactSinkPort):
"""
Sink that explicitly retains the EFS-staged copy.
Sink that keeps the locally staged copy as the durable artifact.

The pipeline stages bytes to EFS before invoking any sink. This sink reports success without doing any remote work and asks the pipeline to keep the local file,
distinguishing the "local-only by design" path from :class:`NoopSink` (which represents "drop everything; tests don't care about artifacts").
The pipeline stages bytes to local disk before any sink runs; this sink does no remote work
and asks the pipeline to keep that file, marking the local-only-by-design path.
It differs from :class:`NoopSink`, whose empty receipt means no durable artifact is kept.
"""

async def persist(
Expand Down
7 changes: 3 additions & 4 deletions src/fathom/adapters/artifact/noop.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@

class NoopSink(ArtifactSinkPort):
"""
Sink that performs no remote persistence.
Sink that persists nothing and keeps the locally staged copy.

Returns a receipt that asks the pipeline to keep the staged EFS
copy — useful for development, fixture-replay loops, and tests
where cloud upload is not desired.
The receipt carries an empty identifier, so the pipeline records no durable artifact.
Use it in development, fixture-replay loops, and tests where cloud upload is not wanted.
"""

async def persist(
Expand Down
10 changes: 0 additions & 10 deletions src/fathom/adapters/checkpoint/sqlite.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,3 @@
"""
Per-workflow SQLite-backed LangGraph checkpoint store adapter.

This adapter carries the production fix for the shared-checkpoint hang. The
CheckpointStore port alone changes nothing without this implementation: it
isolates each workflow into its own database file, applies fail-fast SQLite
pragmas, discards files on workflow completion, and sweeps orphans on a
throttled schedule.
"""

from __future__ import annotations

import re
Expand Down
29 changes: 11 additions & 18 deletions src/fathom/adapters/device/local/adb.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ def __init__(
configuration: Optional[ADBConfiguration] = None,
) -> None:
"""
Initialize ADB device adapter.
Bind an explicit :class:`ADBConfiguration` when given, or derive one from ``serial`` or defaults,
then precompute the device runtime configuration.
"""

if configuration:
Expand Down Expand Up @@ -97,7 +98,7 @@ def __init__(
@property
def configuration(self) -> DeviceRuntimeConfiguration:
"""
Returns the tool configuration.
The resolved device runtime configuration.
"""

return self.__runtime_configuration
Expand Down Expand Up @@ -212,7 +213,8 @@ async def swipe(
speed: Optional[SwipeSpeed] = None,
) -> ActionResult:
"""
Execute swipe gesture.
Execute a swipe gesture. ADB exposes no speed control, so ``speed`` is ignored;
``duration`` alone drives the gesture.
"""

if speed is not None:
Expand Down Expand Up @@ -289,18 +291,10 @@ async def __abandon_unkillable_subprocess(
"""
Bounded post-kill reap of a still-running subprocess.

``__run_safe_subprocess`` enforces a wall-clock per-command timeout
via :func:`asyncio.wait_for`. Its ``finally`` block sends SIGKILL,
then awaits the process to reap. When the host has wedged IO
(emulator qcow2 backing exhausted, NFS hang, etc.) the kernel
cannot deliver SIGKILL because the process sits in an
uninterruptible-IO state; the await would block indefinitely and
the entire workflow would stall.

This helper caps that reap with ``subprocess_cleanup_timeout`` and
abandons the process (logging at WARNING) rather than waiting
forever. The leaked subprocess will be reaped by the OS once the
underlying IO unwedges.
When the host has wedged IO the kernel cannot deliver SIGKILL — the process sits in
uninterruptible-IO state and the reap await would block forever, stalling the workflow. This
helper caps the reap with ``subprocess_cleanup_timeout`` and abandons the process (logging at
WARNING); the OS reaps the leak once the underlying IO unw-edges.
"""

try:
Expand Down Expand Up @@ -750,7 +744,6 @@ async def get_snapshot(self) -> Tuple[bytes, Optional[str]]:

return image, xml

# Helper methods copied from original tool
async def __shell(self, command: str, *, capture_output: bool = False) -> ActionResult:
"""
Execute ADB shell command with terminal logging.
Expand Down Expand Up @@ -795,7 +788,7 @@ async def __keyevent(self, keycode: int) -> ActionResult:

def __build_arguments(self, parts: List[str]) -> List[str]:
"""
Builds full command list.
Assemble the adb argv: the executable, an optional ``-s <serial>``, then the command parts.
"""

cmd = [self.__configuration.executable_path]
Expand All @@ -807,7 +800,7 @@ def __build_arguments(self, parts: List[str]) -> List[str]:

def __escape(self, text: str) -> str:
"""
Escapes text for ADB.
Escape backslashes and double quotes, and encode spaces as ``%s`` for ``input text``.
"""

return text.replace("\\", "\\\\").replace('"', '\\"').replace(" ", "%s")
4 changes: 2 additions & 2 deletions src/fathom/adapters/device/local/ios.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def __init__(
configuration: Optional[IOSConfiguration] = None,
) -> None:
"""
Initialize native iOS adapter configuration.
Store configuration, build the automation gateway, and precompute the runtime configuration.
"""

self.__configuration = configuration or IOSConfiguration()
Expand Down Expand Up @@ -654,7 +654,7 @@ def __resolve_pixel_scale(

async def close(self) -> None:
"""
Close adapter resources.
No-op; the adapter holds no persistent resources to close.
"""

return None
Expand Down
18 changes: 10 additions & 8 deletions src/fathom/adapters/device/remote/adb.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,16 @@

class ADBRemoteDeviceAdapter(DevicePort):
"""
Adapter for controlling devices hosted on remote providers (e.g., Enricher).
Adapter for controlling devices hosted on a remote device farm.
Implements the standard Fathom Remote Device Protocol.
"""

__ACTION_FAILURE_MESSAGE = "Failed to execute the action on the remote device. Please retry."

def __init__(self, configuration: DeviceConfiguration) -> None:
"""
Initialize remote device adapter.
Validate the remote coordinates, build the runtime configuration, and open the HTTP/2 client
bound to the session's interaction base URL.
"""

remote = configuration.remote
Expand Down Expand Up @@ -110,7 +111,8 @@ def __init__(self, configuration: DeviceConfiguration) -> None:
)
async def __execute_request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
"""
Executes an HTTP request with automatic retries for transient errors (5xx, timeouts). Immediately raises on 4xx errors.
Execute an HTTP request, retrying transient failures like 5xx responses and timeouts;
4xx responses raise immediately.
"""

if self.__client.is_closed:
Expand Down Expand Up @@ -476,20 +478,20 @@ def __parse_response(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
Standardized JSend payload extractor.
"""

# 1. Check for standard JSend 'data' field
# JSend success envelope: unwrap the "data" object.
if "data" in response_data and isinstance(response_data["data"], dict):
return cast("Dict[str, Any]", response_data["data"])

# 2. Fallback to legacy 'content' field
# Older providers wrapped the payload in "content" instead.
if "content" in response_data and isinstance(response_data["content"], dict):
return cast("Dict[str, Any]", response_data["content"])

# 3. Return the root if neither is present (direct response)
# No wrapper present: treat the body itself as the payload.
return response_data

async def __send_command(self, request: RemoteInteractionRequest) -> ActionResult:
"""
Helper to transmit interaction request.
Send one interaction request and map the provider's status envelope to an :class:`ActionResult`.
"""

start = time.time()
Expand Down Expand Up @@ -523,7 +525,7 @@ async def __send_command(self, request: RemoteInteractionRequest) -> ActionResul

async def close(self) -> None:
"""
Cleanup HTTP client.
Close the underlying HTTP client.
"""

await self.__client.aclose()
2 changes: 1 addition & 1 deletion src/fathom/adapters/device/remote/ios.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def __init__(
delegate: Optional[ADBRemoteDeviceAdapter] = None,
) -> None:
"""
Initialize the remote iOS adapter.
Wrap a remote ADB delegate for transport, constructing one from configuration when none is given.
"""

self.__delegate = delegate or ADBRemoteDeviceAdapter(configuration=configuration)
Expand Down
12 changes: 4 additions & 8 deletions src/fathom/adapters/interaction/noop.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,10 @@ class NoopInteraction(InteractionPort):
"""
Interaction adapter that swallows writes and returns empty reads.

Selected when a host explicitly disables conversation recording. Writes
that carry all fields in their request return synthesized entity echoes
so callers and the recorder treat them as successful. Writes that depend
on prior persisted state (sanitize, finish-task, finish-job) raise
InteractionError because there is no state to read; the recorder's
failure-suppression layer handles this without crashing the run.

Reads return None or empty collections.
Selected when a host disables conversation recording. Self-contained writes return synthesized entity
echoes so callers treat them as successful; writes depending on prior persisted state (sanitize,
finish-task, finish-job) raise InteractionError, which the recorder's failure-suppression layer
absorbs without crashing the run. Reads return None or empty collections.
"""

async def initialize(self) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/fathom/adapters/ios/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class IOSAutomationGateway:

def __init__(self, *, configuration: IOSConfiguration) -> None:
"""
Initialize iOS automation gateway configuration.
Bind the WebDriverAgent configuration used to build each request.
"""

self.__configuration = configuration
Expand Down
11 changes: 2 additions & 9 deletions src/fathom/adapters/knowledge/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ def __init__(
database_path: str = "assets/memory/knowledge.db",
) -> None:
"""
Initialize SQLite knowledge adapter.
Resolve the database path (a shared path manager overrides the default), create its parent
directory, and start with an empty in-memory graph.
"""

if path_manager:
Expand Down Expand Up @@ -60,7 +61,6 @@ async def __initialize(self) -> None:
)
await db.commit()

# Load graph from database
await self.__load_graph()
self.__initialized = True

Expand Down Expand Up @@ -104,15 +104,13 @@ async def add_screen(self, *, screen_id: str, metadata: Dict[str, Any]) -> None:

await self.__initialize()

# Add to database
async with aiosqlite.connect(self.__path) as db:
await db.execute(
"INSERT OR REPLACE INTO screens (screen_id, metadata) VALUES (?, ?)",
(screen_id, json.dumps(metadata)),
)
await db.commit()

# Add to in-memory graph
if screen_id not in self.__screen_to_node:
if self.__graph is None:
raise RuntimeError("Knowledge graph not initialized")
Expand All @@ -127,22 +125,19 @@ async def add_transition(self, *, from_screen: str, to_screen: str, action: Acti

await self.__initialize()

# Ensure both screens exist
if from_screen not in self.__screen_to_node:
await self.add_screen(screen_id=from_screen, metadata={})

if to_screen not in self.__screen_to_node:
await self.add_screen(screen_id=to_screen, metadata={})

# Add to database
async with aiosqlite.connect(self.__path) as db:
await db.execute(
"INSERT INTO transitions (from_screen, to_screen, action_json) VALUES (?, ?, ?)",
(from_screen, to_screen, action.model_dump_json()),
)
await db.commit()

# Add to in-memory graph
to_index = self.__screen_to_node[to_screen]
from_index = self.__screen_to_node[from_screen]

Expand All @@ -165,7 +160,6 @@ async def find_path(self, *, from_screen: str, to_screen: str) -> Optional[List[
from_index = self.__screen_to_node[from_screen]

try:
# Use Dijkstra's algorithm to find shortest path
if self.__graph is None:
raise RuntimeError("Knowledge graph not initialized")

Expand All @@ -176,7 +170,6 @@ async def find_path(self, *, from_screen: str, to_screen: str) -> Optional[List[
if to_index not in path_indices:
return None

# Extract actions from path
actions = []
path = path_indices[to_index]

Expand Down
Loading
Loading