diff --git a/README.md b/README.md index cbfc5be..d7a3ca4 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ This prints `Name: Alice` (the engine also logs to standard error). `create_data - Columnar results with `to_columns()`, `to_arrow()` and `to_dataframe()`. - Faceted queries: the `FACETS` clause of a `SELECT` with a `COLUMNAR` index, and the counts as a dict in `ResultSet.facets` (needs engine 26.12.1 or later). - An optional in-process HTTP server (`create_server()`), off until you call it, for other processes that need the same data. +- Type hints on every public class and function, and a `py.typed` marker in both packages, so editors and type checkers read them (PEP 561). diff --git a/native/wheel/pyproject.toml b/native/wheel/pyproject.toml index 5fa7c55..8bd78bf 100644 --- a/native/wheel/pyproject.toml +++ b/native/wheel/pyproject.toml @@ -45,4 +45,4 @@ Repository = "https://github.com/ArcadeData/arcadedb-python" where = ["src"] [tool.setuptools.package-data] -arcadedb = ["_native/*.so", "_native/*.dylib", "_native/*.dll"] +arcadedb = ["py.typed", "_native/*.so", "_native/*.dylib", "_native/*.dll"] diff --git a/pyproject.toml b/pyproject.toml index 5f811e7..a80dd87 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -148,6 +148,7 @@ include-package-data = true [tool.setuptools.package-data] arcadedb = [ + "py.typed", # PEP 561: the package carries type hints (issue 476) "jars/*.jar", "jre/**/*", ] diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 7141000..aa60e25 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -966,7 +966,7 @@ def _rollback_state(self) -> int: return self._tx_state(2, "Failed to rollback transaction") def transaction(self) -> TransactionContext: - return TransactionContext(self) + return TransactionContext(self) # type: ignore[arg-type] # the native database has the Database surface def is_transaction_active(self) -> bool: return bool(self._tx_state(3, "Failed to check transaction status") & 1) @@ -1588,7 +1588,13 @@ def export_database( from ..exporter import export_database return export_database( - self, file_path, format, overwrite, include_types, exclude_types, verbose + self, # type: ignore[arg-type] + file_path, + format, + overwrite, + include_types, + exclude_types, + verbose, ) def export_to_csv( @@ -1659,7 +1665,7 @@ def insert_dataframe( self._check_not_closed() table = to_arrow_table(df, what="insert_dataframe()") return insert_table( - self, + self, # type: ignore[arg-type] type_name, table, batch_size=batch_size, @@ -1678,7 +1684,7 @@ def insert_arrow( self._check_not_closed() arrow_table = to_arrow_table(table, what="insert_arrow()") return insert_table( - self, + self, # type: ignore[arg-type] type_name, arrow_table, batch_size=batch_size, diff --git a/src/arcadedb/aio.py b/src/arcadedb/aio.py index 5ce82b1..04893a0 100644 --- a/src/arcadedb/aio.py +++ b/src/arcadedb/aio.py @@ -27,7 +27,11 @@ import contextvars import functools from concurrent.futures import ThreadPoolExecutor -from typing import Any, Callable, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple + +if TYPE_CHECKING: + from .core import Database + from .vector import VectorIndex __all__ = ["AsyncDatabase"] @@ -45,7 +49,7 @@ class AsyncDatabase: Use it as ``async with AsyncDatabase(db) as adb:`` or call ``await adb.close()`` yourself. """ - def __init__(self, db, max_workers: int = _DEFAULT_MAX_WORKERS): + def __init__(self, db: "Database", max_workers: int = _DEFAULT_MAX_WORKERS): if ( isinstance(max_workers, bool) or not isinstance(max_workers, int) @@ -60,7 +64,7 @@ def __init__(self, db, max_workers: int = _DEFAULT_MAX_WORKERS): self._closed = False @property - def database(self): + def database(self) -> "Database": """The wrapped ``Database``.""" return self._db @@ -133,14 +137,14 @@ async def run_in_transaction( async def find_nearest( self, - index, - query_vector, + index: "VectorIndex", + query_vector: Any, k: int = 10, ef_search: Optional[int] = None, - allowed_rids=None, + allowed_rids: Optional[Iterable[Any]] = None, *, include_vector: bool = True, - ): + ) -> List[Tuple[Any, float]]: """``index.find_nearest(...)`` on a worker: a list of ``(record, distance)``, nearest first. ``index`` is the ``VectorIndex`` that ``db.create_vector_index(...)`` or ``db.schema.get_vector_index(...)`` returns. A search diff --git a/src/arcadedb/async_executor.py b/src/arcadedb/async_executor.py index 66b18af..8122730 100644 --- a/src/arcadedb/async_executor.py +++ b/src/arcadedb/async_executor.py @@ -38,7 +38,8 @@ import threading from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, Union +from types import TracebackType +from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, Type, Union import jpype @@ -264,7 +265,7 @@ class AsyncExecutor: >>> async_exec.wait_completion() """ - def __init__(self, java_async_executor, owner: Optional["Database"] = None): + def __init__(self, java_async_executor: Any, owner: Optional["Database"] = None): """ Initialize AsyncExecutor wrapper. @@ -275,10 +276,15 @@ def __init__(self, java_async_executor, owner: Optional["Database"] = None): self._owner = owner self._closed = False - def __enter__(self): + def __enter__(self) -> "AsyncExecutor": return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: self.close() def is_closed(self) -> bool: @@ -433,7 +439,7 @@ def is_processing(self) -> bool: log_swallowed_exception(_LOGGER, "while polling isProcessing()") return False - def kill(self): + def kill(self) -> None: self._java_async.kill() def set_back_pressure(self, percentage: int) -> "AsyncExecutor": @@ -467,10 +473,10 @@ def set_back_pressure(self, percentage: int) -> "AsyncExecutor": def create_record( self, - document, + document: Any, callback: Optional[Callable] = None, error_callback: Optional[Callable[[Exception], None]] = None, - ): + ) -> None: """Queue a document for asynchronous creation. The engine's parallel bucket writers persist it off the calling @@ -508,13 +514,13 @@ def _create_new_record_callback(self, python_callback): def new_edge( self, - source_vertex, + source_vertex: Any, edge_type: str, - destination_vertex_or_rid, + destination_vertex_or_rid: Any, light: bool = False, callback: Optional[Callable[[Any, bool, bool], None]] = None, - **properties, - ): + **properties: Any, + ) -> None: source_vertex = self._unwrap_record(source_vertex) destination_rid = self._to_java_rid(destination_vertex_or_rid) java_callback = self._create_new_edge_callback(callback) if callback else None @@ -541,8 +547,8 @@ def new_edge_by_keys( bidirectional: bool, light: bool, callback: Optional[Callable[[Any, bool, bool], None]] = None, - **properties, - ): + **properties: Any, + ) -> None: java_callback = self._create_new_edge_callback(callback) if callback else None props = self._to_java_varargs(properties) @@ -611,7 +617,7 @@ def append_samples( timestamps: Sequence[int], *column_values: Sequence[Any], primitive: bool = False, - ): + ) -> Any: """Columnar bulk append into a native TIMESERIES type. Columns are positional and must follow the type's declaration order: @@ -781,8 +787,8 @@ def query( callback: Callable[[Any], None], args: Optional[Sequence[Any]] = None, error_callback: Optional[Callable[[Exception], None]] = None, - **params, - ): + **params: Any, + ) -> None: """ Execute async query with callback for each result. @@ -830,8 +836,8 @@ def command( callback: Optional[Callable[[Any], None]] = None, args: Optional[Sequence[Any]] = None, error_callback: Optional[Callable[[Exception], None]] = None, - **params, - ): + **params: Any, + ) -> None: """ Execute async command with optional callback. @@ -900,7 +906,7 @@ def scan_type( callback: Callable[[Any], bool], polymorphic: bool = True, error_callback: Optional[Callable[[Any, Exception], bool]] = None, - ): + ) -> None: java_doc_callback = self._create_document_callback(callback) if error_callback is None: self._java_async.scanType(type_name, polymorphic, java_doc_callback) @@ -920,7 +926,7 @@ def transaction( ok_callback: Optional[Callable[[], None]] = None, error_callback: Optional[Callable[[Exception], None]] = None, slot: Optional[int] = None, - ): + ) -> None: java_tx = self._create_transaction_scope(tx_block) if ( @@ -953,7 +959,7 @@ def transaction( # Control flow - def wait_completion(self, timeout_ms: Optional[int] = None): + def wait_completion(self, timeout_ms: Optional[int] = None) -> None: """ Wait for all async operations to complete. @@ -1025,7 +1031,7 @@ def is_pending(self) -> bool: """ return self.is_processing() - def close(self): + def close(self) -> None: """ Close the async executor and shutdown worker threads. diff --git a/src/arcadedb/callbacks.py b/src/arcadedb/callbacks.py index 17904a8..b62cd27 100644 --- a/src/arcadedb/callbacks.py +++ b/src/arcadedb/callbacks.py @@ -12,7 +12,8 @@ import threading import traceback import weakref -from typing import Callable, Optional, Tuple +from types import TracebackType +from typing import TYPE_CHECKING, Any, Callable, Optional, Tuple, Type import jpype @@ -20,6 +21,9 @@ from .exceptions import ArcadeDBError from .type_conversion import convert_java_to_python, convert_python_to_java +if TYPE_CHECKING: + from .core import Database + _LOGGER = get_logger(__name__) EVENTS = ( @@ -285,7 +289,7 @@ class FunctionRegistration: it registered to remove them when it is closed. """ - def __init__(self, database): + def __init__(self, database: "Database"): # Weak: the Database holds this registry, and a strong reference back would make a # cycle that keeps the Database (and its engine instance) alive until a gc pass # instead of releasing it with its last result (tests/test_results_after_close.py). @@ -356,7 +360,12 @@ class EventHandle: """ def __init__( - self, events, event: str, type_name: Optional[str], java_handle, proxy + self, + events: Any, + event: str, + type_name: Optional[str], + java_handle: Any, + proxy: Any, ): self._events = events self._java_handle = java_handle @@ -382,10 +391,15 @@ def remove(self) -> None: except Exception as e: raise ArcadeDBError(f"Failed to remove '{self.event}' callback: {e}") from e - def __enter__(self): + def __enter__(self) -> "EventHandle": return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: self.remove() def __repr__(self) -> str: @@ -394,7 +408,9 @@ def __repr__(self) -> str: return f"" -def register_event(database, event: str, fn: Callable, type_name: Optional[str]): +def register_event( + database: "Database", event: str, fn: Callable, type_name: Optional[str] +) -> "EventHandle": """Register ``fn`` for ``event`` on the database, or on one type, and return its handle.""" check_event(event, fn) java_db = database.get_java_database() diff --git a/src/arcadedb/core.py b/src/arcadedb/core.py index 13625cb..bd770b0 100644 --- a/src/arcadedb/core.py +++ b/src/arcadedb/core.py @@ -11,9 +11,12 @@ from datetime import date, datetime from decimal import Decimal from os import PathLike -from typing import TYPE_CHECKING, Any, Callable, List, Optional +from types import TracebackType +from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, TypeVar if TYPE_CHECKING: + from .async_executor import AsyncExecutor + from .schema import Schema from .vector import VectorIndex import jpype @@ -49,6 +52,8 @@ _LOGGER = get_logger(__name__) +_T = TypeVar("_T") + _COMMIT_WITNESS_WARNED = False @@ -504,19 +509,24 @@ def _wrap_java_record(java_record, database=None): class Database: """ArcadeDB Database wrapper.""" - def __init__(self, java_database): + def __init__(self, java_database: Any): self._java_db = java_database self._closed = False - self._async_executors = [] + self._async_executors: List[Any] = [] self._functions = FunctionRegistration(self) - def __enter__(self): + def __enter__(self) -> "Database": return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: self.close() - def get_java_database(self): + def get_java_database(self) -> Any: """Expose the wrapped Java database for internal integrations.""" return self._java_db @@ -616,7 +626,7 @@ def _java_parameters(args): return jpype.JObject(params, java_map) return _object_array(Database._convert_args(args)) - def query(self, language: str, command: str, *args) -> ResultSet: + def query(self, language: str, command: str, *args: Any) -> ResultSet: """Execute a query and return results. Parameters bind positionally (``?``) from the extra arguments, or by @@ -646,7 +656,7 @@ def query(self, language: str, command: str, *args) -> ResultSet: raise_pending_interrupt(error, e) raise error from e - def command(self, language: str, command: str, *args) -> Optional[ResultSet]: + def command(self, language: str, command: str, *args: Any) -> Optional[ResultSet]: """Execute a command (non-idempotent operation). Parameters bind as in :meth:`query`. @@ -676,7 +686,9 @@ def command(self, language: str, command: str, *args) -> Optional[ResultSet]: raise_pending_interrupt(error, e) raise error from e - def run_in_transaction(self, fn, retries: int = 12, backoff_s: float = 0.005): + def run_in_transaction( + self, fn: Callable[[], _T], retries: int = 12, backoff_s: float = 0.005 + ) -> _T: """ Execute a callable inside a transaction with automatic retry on concurrent-modification conflicts. @@ -765,6 +777,8 @@ def run_in_transaction(self, fn, retries: int = 12, backoff_s: float = 0.005): if self._partially_committed(tx_at_start, commits_at_start): raise _time.sleep(max(backoff_s * (attempt + 1), retry_after_ms / 1000.0)) + # the last attempt raises, so only retries < 0 (no attempt at all) gets here, and it returned None before the hints too + return None # type: ignore[return-value] def _transaction_stack_mark(self): """Whether a transaction is active, and the nesting depth, before a begin(). @@ -842,7 +856,7 @@ def _partially_committed(tx_at_start, commits_at_start) -> bool: _warn_no_commit_witness("count") return False - def begin(self): + def begin(self) -> None: """Begin a transaction.""" self._check_not_closed() try: @@ -850,7 +864,7 @@ def begin(self): except Exception as e: raise ArcadeDBError(f"Failed to begin transaction: {e}") from e - def commit(self): + def commit(self) -> None: """Commit the current transaction.""" self._check_not_closed() try: @@ -858,7 +872,7 @@ def commit(self): except Exception as e: raise ArcadeDBError(f"Failed to commit transaction: {e}") from e - def rollback(self): + def rollback(self) -> None: """Rollback the current transaction.""" self._check_not_closed() try: @@ -911,7 +925,7 @@ def _parallel_load_failed(self, type_name, error): def insert_many( self, type_name: str, - rows, + rows: Any, commit_every: int = 10_000, parallel: bool = False, ) -> int: @@ -1306,7 +1320,7 @@ def _insert_many_parallel(self, type_name, first, rows): def insert_columns( self, type_name: str, - columns, + columns: Any, commit_every: int = 10_000, parallel: bool = False, ) -> int: @@ -1456,7 +1470,7 @@ def insert_columns( def insert_dataframe( self, type_name: str, - df, + df: Any, *, batch_size: int = 10_000, parallel: bool = False, @@ -1536,7 +1550,7 @@ def insert_dataframe( def insert_arrow( self, type_name: str, - table, + table: Any, *, batch_size: int = 10_000, parallel: bool = False, @@ -1624,7 +1638,7 @@ def insert_arrow( what="insert_arrow()", ) - def close(self): + def close(self) -> None: """Close the database.""" if not self._closed and self._java_db is not None: async_close_error = None @@ -1685,7 +1699,9 @@ def get_database_path(self) -> str: except Exception as e: raise ArcadeDBError(f"Failed to get database path: {e}") from e - def lookup_by_key(self, type_name: str, keys: List[str], values: List[Any]): + def lookup_by_key( + self, type_name: str, keys: List[str], values: List[Any] + ) -> Optional["Document"]: """ Lookup records by indexed key (index-based: O(1) for a hash index, O(log n) for an LSM_TREE index). @@ -1780,7 +1796,7 @@ def _lookup_by_java_rid(self, java_rid) -> Any: java_record = self._java_db.lookupByRID(java_rid, True) return _wrap_java_record(java_record, self) - def to_java_rid(self, value): + def to_java_rid(self, value: Any) -> Any: self._check_not_closed() value = getattr(value, "_java_record", value) @@ -2077,7 +2093,7 @@ def count_type(self, type_name: str) -> int: return 0 raise ArcadeDBError(f"Failed to count type '{type_name}': {e}") from e - def drop(self): + def drop(self) -> None: """ Drop the entire database. @@ -2112,7 +2128,7 @@ def is_transaction_active(self) -> bool: except Exception as e: raise ArcadeDBError(f"Failed to check transaction status: {e}") from e - def set_wal_flush(self, mode: str): + def set_wal_flush(self, mode: str) -> None: """ Configure the Write-Ahead Log (WAL) flush at commit for this database. @@ -2159,7 +2175,7 @@ def set_wal_flush(self, mode: str): except Exception as e: raise ArcadeDBError(f"Failed to set WAL flush mode: {e}") from e - def set_read_your_writes(self, enabled: bool): + def set_read_your_writes(self, enabled: bool) -> None: """ Enable or disable read-your-writes consistency. @@ -2187,7 +2203,7 @@ def is_read_your_writes(self) -> bool: except Exception as e: raise ArcadeDBError(f"Failed to get read-your-writes: {e}") from e - def set_auto_transaction(self, enabled: bool): + def set_auto_transaction(self, enabled: bool) -> None: """ Enable or disable automatic transaction management. @@ -2335,7 +2351,7 @@ def on( self._check_not_closed() return register_event(self, event, fn, type_name) - def async_executor(self): + def async_executor(self) -> "AsyncExecutor": """ Get async executor for parallel operations. @@ -2580,7 +2596,7 @@ def import_documents( ) @property - def schema(self): + def schema(self) -> "Schema": """ Get the schema manipulation API for this database. @@ -2664,7 +2680,7 @@ def export_to_csv( file_path: str, language: str = "sql", fieldnames: Optional[List[str]] = None, - ): + ) -> None: """ Export query results to CSV file. diff --git a/src/arcadedb/dataframe.py b/src/arcadedb/dataframe.py index 196de13..d3b55bd 100644 --- a/src/arcadedb/dataframe.py +++ b/src/arcadedb/dataframe.py @@ -20,12 +20,15 @@ """ import re -from typing import Any, Dict, List, Optional, Tuple +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import jpype from .exceptions import ArcadeDBError +if TYPE_CHECKING: + from .core import Database + _PYARROW_HINT = ( "pyarrow is required for {what}. Install with: uv add pyarrow " "(or uv add 'arcadedb-jvm[arrow]')" @@ -114,7 +117,7 @@ def _kind(pa, arrow_type) -> Optional[str]: return None -def to_arrow_table(data, *, what: str): +def to_arrow_table(data: Any, *, what: str) -> Any: """Normalize a pandas or Polars DataFrame, or anything Arrow can read, to a ``pyarrow.Table``.""" pa = _import_pyarrow(what) module = type(data).__module__.split(".")[0] @@ -464,9 +467,9 @@ def _check_uint64_range(pa, table) -> None: def insert_table( - db, + db: "Database", type_name: str, - table, + table: Any, *, batch_size: int, parallel: bool, diff --git a/src/arcadedb/exporter.py b/src/arcadedb/exporter.py index 20cdf47..a17b4cd 100644 --- a/src/arcadedb/exporter.py +++ b/src/arcadedb/exporter.py @@ -15,11 +15,12 @@ from .jvm import start_jvm if TYPE_CHECKING: + from .core import Database from .results import ResultSet def export_database( - db, + db: "Database", file_path: str, export_format: str = "jsonl", overwrite: bool = False, @@ -200,7 +201,7 @@ def export_to_csv( results: Union[ResultSet, List[Dict[str, Any]]], file_path: str, fieldnames: Optional[List[str]] = None, -): +) -> None: """ Export query results to CSV file. diff --git a/src/arcadedb/graph.py b/src/arcadedb/graph.py index a987dec..543567d 100644 --- a/src/arcadedb/graph.py +++ b/src/arcadedb/graph.py @@ -4,7 +4,7 @@ Wrappers for Document, Vertex, and Edge objects. """ -from typing import Any, Dict, List, Optional, Tuple +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import jpype @@ -12,6 +12,9 @@ from .exceptions import ArcadeDBError from .type_conversion import convert_java_to_python, convert_python_to_java +if TYPE_CHECKING: + from .core import Database + _GRAPH_CLASSES = None @@ -61,7 +64,7 @@ class Document: raises ArcadeDBError instead of returning empty values. """ - def __init__(self, java_document, database=None): + def __init__(self, java_document: Any, database: Optional["Database"] = None): self._java_document = java_document self._database = database # strong reference, see the class docstring self._property_names_cache: Optional[Tuple[str, ...]] = None @@ -90,7 +93,9 @@ def _property_names_tuple(self) -> Tuple[str, ...]: return self._property_names_cache @staticmethod - def wrap(java_record, database=None): + def wrap( + java_record: Any, database: Optional["Database"] = None + ) -> Optional["Document"]: """ Wrap a Java Record object in the appropriate Python wrapper. @@ -160,7 +165,7 @@ def save(self) -> "Document": raise error from e return self - def delete(self): + def delete(self) -> None: """Delete the record. Like every write, it needs an active transaction. A query row is a ``Result``, not a record: reach the record with @@ -192,7 +197,7 @@ def get_property_names(self) -> List[str]: """Get all property names.""" return list(self._property_names_tuple()) - def get_identity(self): + def get_identity(self) -> Any: """Get record identity (RID).""" return self._java_document.getIdentity() @@ -225,7 +230,7 @@ def get_rid(self) -> str: # version read 1.6 times slower per call (ArcadeData/arcadedb-python#395, figure ``j_rid_docobj_100k``). return str(self._java_document.getIdentity()) - def get_java_document(self): + def get_java_document(self) -> Any: """Expose the wrapped Java document for internal integrations.""" return self._java_document @@ -249,7 +254,7 @@ def modify(self) -> "Vertex": self._check_open() return Vertex(self._java_document.modify(), self._database) - def new_edge(self, label: str, target: "Vertex", **kwargs) -> "Edge": + def new_edge(self, label: str, target: "Vertex", **kwargs: Any) -> "Edge": """ Create an edge to another vertex. diff --git a/src/arcadedb/graph_batch.py b/src/arcadedb/graph_batch.py index 2bb819c..6ecfcb8 100644 --- a/src/arcadedb/graph_batch.py +++ b/src/arcadedb/graph_batch.py @@ -6,7 +6,8 @@ import itertools import operator -from typing import Any, Iterable, Optional +from types import TracebackType +from typing import Any, Iterable, Optional, Type import jpype @@ -218,8 +219,8 @@ class GraphBatch: def __init__( self, - java_database, - java_graph_batch, + java_database: Any, + java_graph_batch: Any, ): self._java_db = java_database self._java_graph_batch = java_graph_batch @@ -228,7 +229,7 @@ def __init__( @classmethod def create( cls, - java_database, + java_database: Any, *, batch_size: Optional[int] = None, expected_edge_count: Optional[int] = None, @@ -294,7 +295,12 @@ def create( def __enter__(self) -> "GraphBatch": return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: self.close() def new_vertex(self, type_name: str) -> Vertex: @@ -307,7 +313,7 @@ def new_vertex(self, type_name: str) -> Vertex: f"Failed to create new batch vertex of type '{type_name}': {e}" ) from e - def create_vertex(self, type_name: str, **properties) -> Vertex: + def create_vertex(self, type_name: str, **properties: Any) -> Vertex: """Create and save a single vertex, optionally with properties.""" self._check_not_closed() started_transaction = False @@ -550,10 +556,10 @@ def dumps(chunk_rows): def new_edge( self, - source_vertex_or_rid, + source_vertex_or_rid: Any, edge_type: str, - destination_vertex_or_rid, - **properties, + destination_vertex_or_rid: Any, + **properties: Any, ) -> "GraphBatch": """Buffer an edge for creation during flush or close.""" self._check_not_closed() @@ -583,10 +589,10 @@ def _rid_text(value) -> str: def new_edges( self, - source_rids, + source_rids: Any, edge_type: str, - destination_rids, - properties=None, + destination_rids: Any, + properties: Optional[Any] = None, ) -> "GraphBatch": """ Buffer many edges with one JPype crossing per call. @@ -777,7 +783,7 @@ def flush(self) -> "GraphBatch": except Exception as e: raise ArcadeDBError(f"Failed to flush GraphBatch: {e}") from e - def close(self): + def close(self) -> None: """Flush remaining work and finalize deferred incoming edges. Leaving a ``with`` block calls this. Call it outside your own diff --git a/src/arcadedb/importer.py b/src/arcadedb/importer.py index ded6634..fc730a4 100644 --- a/src/arcadedb/importer.py +++ b/src/arcadedb/importer.py @@ -219,7 +219,7 @@ def _to_java_settings_map(settings: Mapping[str, Any]): def import_documents( - java_database, + java_database: Any, source: str | PathLike[str], *, document_type: str, diff --git a/src/arcadedb/jvm.py b/src/arcadedb/jvm.py index 02aa7b8..f72852d 100644 --- a/src/arcadedb/jvm.py +++ b/src/arcadedb/jvm.py @@ -313,7 +313,7 @@ def start_jvm( common_pool_parallelism: Optional[int] = None, interrupt: Optional[bool] = None, aot: Optional[bool] = None, -): +) -> None: """ Start the JVM with ArcadeDB JARs if not already started. @@ -932,7 +932,7 @@ def _build_jvm_args( return merged_args -def shutdown_jvm(): +def shutdown_jvm() -> None: """Shutdown JVM if it was started by this module. JPype can raise RuntimeError when the JVM is already mid-shutdown or diff --git a/src/arcadedb/py.typed b/src/arcadedb/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/src/arcadedb/results.py b/src/arcadedb/results.py index 1501a65..9b201ce 100644 --- a/src/arcadedb/results.py +++ b/src/arcadedb/results.py @@ -7,7 +7,18 @@ import json from datetime import date, datetime from decimal import Decimal -from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterator, + List, + Optional, + Sequence, + Tuple, + Type, +) import jpype as _jpype from jpype import JException @@ -30,6 +41,9 @@ from .graph import Document, Edge, Vertex from .type_conversion import convert_java_to_python +if TYPE_CHECKING: + from .core import Database + _logger = get_logger(__name__) _BRIDGE_CLASSES: dict = {} @@ -313,12 +327,12 @@ class ResultSet: ArcadeDBError, with the Java exception as its cause. """ - def __init__(self, java_result_set, database=None): + def __init__(self, java_result_set: Any, database: Optional["Database"] = None): self._java_result_set = java_result_set self._database = database # strong reference, see the class docstring self._closed = False self._exhausted = False - self._facets = None + self._facets: Optional[Dict[str, Any]] = None self._facets_read = False def __iter__(self) -> Iterator["Result"]: @@ -614,7 +628,12 @@ def __del__(self): def __enter__(self) -> "ResultSet": return self - def __exit__(self, exc_type, exc_val, exc_tb) -> None: + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: self.close() def to_json_list(self, batch_size: int = 10_000) -> List[Dict[str, Any]]: @@ -730,7 +749,7 @@ def iter_json_batches( return yield batch - def to_dataframe(self, convert_types: bool = True): + def to_dataframe(self, convert_types: bool = True) -> Any: """ Convert results to pandas DataFrame. @@ -785,7 +804,7 @@ def to_dataframe(self, convert_types: bool = True): def to_polars( self, batch_size: int = 25_000, columns: Optional[Sequence[str]] = None - ): + ) -> Any: """ Bulk-materialize all rows as a ``polars.DataFrame``, through Arrow. @@ -829,7 +848,7 @@ def to_polars( def to_columns( self, batch_size: int = 25_000, columns: Optional[Sequence[str]] = None - ): + ) -> Dict[str, Any]: """ Bulk-materialize all rows as columns: dict of column name -> numpy array (int64/float64/bool/datetime64[ms]) or Python list (strings and @@ -925,7 +944,7 @@ def _read_columns_counted(self, batch_size, columns, micros): def to_arrow( self, batch_size: int = 25_000, columns: Optional[Sequence[str]] = None - ): + ) -> Any: """ Bulk-materialize all rows as a ``pyarrow.Table``. @@ -1141,7 +1160,7 @@ class Result: and stays readable. """ - def __init__(self, java_result, database=None): + def __init__(self, java_result: Any, database: Optional["Database"] = None): self._java_result = java_result self._database = database # strong reference, see the class docstring self._property_names_cache: Optional[Tuple[str, ...]] = None diff --git a/src/arcadedb/schema.py b/src/arcadedb/schema.py index b53e14b..7be9846 100644 --- a/src/arcadedb/schema.py +++ b/src/arcadedb/schema.py @@ -12,13 +12,16 @@ """ from enum import Enum -from typing import Any, List, Optional, Union +from typing import TYPE_CHECKING, Any, List, Optional, Union import jpype from ._logging import get_logger, log_swallowed_exception from .exceptions import ArcadeDBError +if TYPE_CHECKING: + from .core import Database + _LOGGER = get_logger(__name__) @@ -68,7 +71,7 @@ class Schema: _db: Reference to the parent Database instance """ - def __init__(self, java_schema, database): + def __init__(self, java_schema: Any, database: "Database"): """Initialize Schema wrapper. Args: @@ -225,7 +228,7 @@ def get_or_create_edge_type(self, name: str, buckets: Optional[int] = None) -> A else: return self._java_schema.getOrCreateEdgeType(name, buckets) - def drop_type(self, name: str): + def drop_type(self, name: str) -> None: """Drop a type and all its data. Args: @@ -424,7 +427,7 @@ def get_or_create_property( f"Failed to get/create property '{property_name}' on type '{type_name}': {e}" ) from e - def drop_property(self, type_name: str, property_name: str): + def drop_property(self, type_name: str, property_name: str) -> None: """Drop a property from a type. Args: @@ -586,7 +589,7 @@ def get_or_create_index( f"Failed to get/create index on '{type_name}[{','.join(property_names)}]': {e}" ) from e - def drop_index(self, index_name: str, force: bool = False): + def drop_index(self, index_name: str, force: bool = False) -> None: """Drop an index. Args: diff --git a/src/arcadedb/server.py b/src/arcadedb/server.py index f62dec5..24cbe91 100644 --- a/src/arcadedb/server.py +++ b/src/arcadedb/server.py @@ -6,7 +6,8 @@ import functools import os -from typing import Any, Dict, Optional +from types import TracebackType +from typing import Any, Dict, Optional, Type import jpype @@ -134,7 +135,7 @@ def __init__( self._config = config or {} self._root_path = root_path self._root_password = root_password - self._java_server = None + self._java_server: Any = None self._started = False # Create configuration @@ -183,7 +184,7 @@ def __init__( # Create server instance self._java_server = JavaArcadeDBServer(context_config) - def start(self): + def start(self) -> None: """Start the ArcadeDB server.""" if self._started: raise ArcadeDBError("Server is already started") @@ -211,7 +212,7 @@ def start(self): raise raise ArcadeDBError(f"Failed to start server: {e}") from e - def stop(self): + def stop(self) -> None: """Stop the ArcadeDB server.""" if not self._started: return @@ -293,12 +294,17 @@ def get_studio_url(self) -> str: port = self.get_http_port() return f"http://{host}:{port}/" - def __enter__(self): + def __enter__(self) -> "ArcadeDBServer": """Context manager entry - starts the server.""" self.start() return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: """Context manager exit - stops the server.""" self.stop() diff --git a/src/arcadedb/transactions.py b/src/arcadedb/transactions.py index 423557c..bfa43a6 100644 --- a/src/arcadedb/transactions.py +++ b/src/arcadedb/transactions.py @@ -4,15 +4,21 @@ Transaction context manager and related utilities. """ +from types import TracebackType +from typing import TYPE_CHECKING, Optional, Type + +if TYPE_CHECKING: + from .core import Database + class TransactionContext: """Context manager for ArcadeDB transactions.""" - def __init__(self, database): + def __init__(self, database: "Database"): self.database = database self.started = False - def __enter__(self): + def __enter__(self) -> "TransactionContext": # The levels the caller already holds are not ours to roll back: begin() inside a caller's transaction pushes a # nested level, so ownership is decided by the stack before the call, not by whether begin() returned (#9970) mark = self.database._transaction_stack_mark() @@ -30,7 +36,12 @@ def __enter__(self): pass raise - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: if self.started: if exc_type is None: self.database.commit() diff --git a/src/arcadedb/type_conversion.py b/src/arcadedb/type_conversion.py index 10c310a..62eaefa 100644 --- a/src/arcadedb/type_conversion.py +++ b/src/arcadedb/type_conversion.py @@ -13,7 +13,7 @@ import sys from datetime import date, datetime, time, timedelta, timezone from decimal import Decimal -from typing import Any, NamedTuple +from typing import Any, List, NamedTuple import jpype @@ -1074,7 +1074,7 @@ def json_bulk_dumps_tagged(rows: Any) -> str: return _dumps_once(rows, True) -def bulk_row_ok(row: Any, skip=()) -> bool: +def bulk_row_ok(row: Any, skip: Any = ()) -> bool: """Whether one insert_many row can go through json_bulk_dumps_tagged; `skip` names properties that cross some other way (float vectors).""" if skip: row = {k: v for k, v in row.items() if k not in skip} @@ -1210,7 +1210,7 @@ def _classify_rows(rows: Any, declared: Any, screen_scalars: bool): return tagged, vetted and not tagged -def classify_vertex_rows(rows: Any, declared: Any, screen_scalars: bool = False): +def classify_vertex_rows(rows: Any, declared: Any, screen_scalars: bool = False) -> Any: """What GraphBatch.create_vertices must know about its rows before it writes any chunk, decided by types. `screen_scalars` is for an input of several chunks, which are sent one after the other: a value the text would change in a late @@ -1231,7 +1231,7 @@ def classify_vertex_rows(rows: Any, declared: Any, screen_scalars: bool = False) return None if verdict is None else verdict[0] -def screen_vertex_rows(rows: Any, declared: Any): +def screen_vertex_rows(rows: Any, declared: Any) -> Any: """classify_vertex_rows with the whole-input screen, for any number of chunks: None, or ``(tagged, vetted)``. `vetted` says that every value of every row is an exact scalar the JSON text carries unchanged (a column holding any other type, @@ -1282,7 +1282,7 @@ def _float_vectors_class(): return _FLOAT_VECTORS or None -def declared_float_vectors(java_db, type_name): +def declared_float_vectors(java_db: Any, type_name: str) -> List[str]: """The names of the ARRAY_OF_FLOATS properties of `type_name` (inherited ones too), [] when there are none or no numpy.""" vectors = _float_vectors_class() if _np is not None else None if vectors is None: @@ -1329,7 +1329,7 @@ def _is_float_array_kind(kind): ) -def is_vector_candidate(value): +def is_vector_candidate(value: Any) -> bool: """A value split_float_vectors may take out of the JSON: a list, a numpy array, or a Java float[] or double[].""" return _is_vector_kind(type(value)) @@ -1358,7 +1358,7 @@ def _without_keys(rows, gone): return [{k: v for k, v in row.items() if k not in gone} for row in rows] -def take_vector_columns(rows, declared, undeclared=False): +def take_vector_columns(rows: Any, declared: Any, undeclared: bool = False) -> Any: """The float vector columns of `rows` as float32 matrices, and the rows without them (the one split of both wheels). A declared (ARRAY_OF_FLOATS) property qualifies when its value in EVERY row is a list, a numpy array or a Java float[] or double[] of @@ -1410,7 +1410,7 @@ def take_vector_columns(rows, declared, undeclared=False): return taken, matrices, _without_keys(rows, taken) -def vector_width(rows, declared): +def vector_width(rows: Any, declared: Any) -> int: """How many floats the vector columns of the first row hold (0 when it holds none): a list, array, Java ``float[]`` or ``double[]`` in a declared property, or a float32 array or Java ``float[]`` in any property. GraphBatch.create_vertices sizes its crossings by it. """ @@ -1429,7 +1429,13 @@ def vector_width(rows, declared): return width -def split_float_vectors(java_db, type_name, rows, declared=None, undeclared=False): +def split_float_vectors( + java_db: Any, + type_name: str, + rows: Any, + declared: Any = None, + undeclared: bool = False, +) -> Any: """Take the float vectors of `rows` out of the JSON text of a bulk load (the JVM wheel). A list of floats costs Python about 450 ns a number to write as text and the diff --git a/src/arcadedb/vector.py b/src/arcadedb/vector.py index 89bf2e9..651bfa0 100644 --- a/src/arcadedb/vector.py +++ b/src/arcadedb/vector.py @@ -4,11 +4,16 @@ Vector index and array conversion utilities for similarity search. """ +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple + import jpype import jpype.types as jtypes from .exceptions import ArcadeDBError +if TYPE_CHECKING: + from .core import Database + try: # optional; hoisted to module scope to keep it out of per-call hot paths import numpy as _np except ImportError: # pragma: no cover - numpy is an optional dependency @@ -33,7 +38,7 @@ def _native_enabled(): return _native.enabled() -def to_java_float_array(vector): +def to_java_float_array(vector: Any) -> Any: """ Convert a Python array-like object to a Java float array. @@ -76,7 +81,7 @@ def to_java_float_array(vector): return float_array(vector) -def to_java_int_array(vector): +def to_java_int_array(vector: Any) -> Any: """ Convert a Python array-like object to a Java int array. @@ -134,7 +139,7 @@ def to_java_int_array(vector): return jtypes.JArray(jtypes.JInt)(vector) -def to_java_byte_array(vector): +def to_java_byte_array(vector: Any) -> Any: """ Convert a Python byte-like or integer array-like object to a Java byte array. @@ -201,7 +206,7 @@ def to_java_byte_array(vector): return jtypes.JArray(jtypes.JByte)(normalized) -def to_python_array(java_vector, use_numpy=True): +def to_python_array(java_vector: Any, use_numpy: bool = True) -> Any: """ Convert a Java array or ArrayList to a Python array. @@ -280,7 +285,7 @@ class VectorIndex: - **BINARY**: 1-bit quantization (for high-dimensional binary vectors). """ - def __init__(self, java_index, database): + def __init__(self, java_index: Any, database: "Database"): """ Initialize VectorIndex wrapper. @@ -593,13 +598,13 @@ def _run_search( def find_nearest( self, - query_vector, - k=10, - ef_search=None, - allowed_rids=None, + query_vector: Any, + k: int = 10, + ef_search: Optional[int] = None, + allowed_rids: Optional[Iterable[Any]] = None, *, - include_vector=True, - ): + include_vector: bool = True, + ) -> List[Tuple[Any, float]]: """ Find k nearest neighbors to the query vector. @@ -664,7 +669,7 @@ def _find_nearest_live( except Exception as e: raise ArcadeDBError(f"Vector search failed: {e}") from e - def get_size(self): + def get_size(self) -> int: """ Get the current number of items in the index. @@ -678,7 +683,7 @@ def get_size(self): except Exception as e: raise ArcadeDBError(f"Failed to get index size: {e}") from e - def get_metadata(self): + def get_metadata(self) -> Dict[str, Any]: """ Get stable metadata for the vector index. @@ -726,7 +731,7 @@ def get_metadata(self): except Exception as e: raise ArcadeDBError(f"Failed to read vector index metadata: {e}") from e - def get_stats(self): + def get_stats(self) -> Dict[str, Any]: """ Get live runtime counters for the vector index. @@ -756,7 +761,7 @@ def get_stats(self): except Exception as e: raise ArcadeDBError(f"Failed to read vector index stats: {e}") from e - stats = {} + stats: Dict[str, Any] = {} for java_key in raw.keySet(): key = str(java_key) value = raw.get(java_key) @@ -779,11 +784,11 @@ def get_stats(self): def find_nearest_by_key( self, - key, - k=10, - ef_search=None, - allowed_rids=None, - ): + key: Any, + k: int = 10, + ef_search: Optional[int] = None, + allowed_rids: Optional[Iterable[Any]] = None, + ) -> List[Tuple[Any, float]]: """ Find nearest neighbors using the indexed vector from an existing record. @@ -802,10 +807,10 @@ def find_nearest_by_key( def find_nearest_approximate( self, - query_vector, - k=10, - allowed_rids=None, - ): + query_vector: Any, + k: int = 10, + allowed_rids: Optional[Iterable[Any]] = None, + ) -> List[Tuple[Any, float]]: """ Find k nearest neighbors using Product Quantization (PQ) approximate search. @@ -842,7 +847,7 @@ def find_nearest_approximate( except Exception as e: raise ArcadeDBError(f"Approximate search failed: {e}") from e - def get_quantization(self): + def get_quantization(self) -> str: """ Get the quantization type of the index. @@ -862,7 +867,7 @@ def _get_quantization_live(self): except Exception: return "NONE" - def warm_up(self): + def warm_up(self) -> None: """ Load the vector graph now instead of on the first search. @@ -897,7 +902,7 @@ def warm_up(self): except Exception as e: raise ArcadeDBError(f"Failed to warm up vector index: {e}") from e - def build_graph_now(self): + def build_graph_now(self) -> None: """ Trigger an immediate rebuild of the underlying vector graph. diff --git a/tests/test_typed_package.py b/tests/test_typed_package.py new file mode 100644 index 0000000..1520a86 --- /dev/null +++ b/tests/test_typed_package.py @@ -0,0 +1,104 @@ +"""Both wheels are typed packages (PEP 561): they ship the py.typed marker, and every public callable carries type hints. + +Issue ArcadeData/arcadedb-python#476. The marker is what tells an editor or a type checker to read the hints; without it +the package counts as untyped. The same file runs on both builds: against the installed wheel in CI it checks the file list of +what was built, and in a source checkout it also checks that both package definitions name the marker. +""" + +import inspect +import tomllib +from pathlib import Path + +import pytest + +import arcadedb +import arcadedb.aio + +ROOT = Path(__file__).resolve().parents[1] +PACKAGE = Path(arcadedb.__file__).resolve().parent + +# Called by the runtime or by Python, not by a user, so there is nothing to hint at the call site: nothing is exempt today. +EXEMPT = frozenset() + + +def test_the_installed_package_ships_the_py_typed_marker(): + assert (PACKAGE / "py.typed").is_file(), f"no py.typed in {PACKAGE}" + + +def test_both_package_definitions_name_the_marker(): + if ( + not (ROOT / "pyproject.toml").exists() + or not (ROOT / "native" / "wheel").exists() + ): + return # the installed-wheel container has no checkout to read + jvm = tomllib.loads((ROOT / "pyproject.toml").read_text()) + native = tomllib.loads((ROOT / "native" / "wheel" / "pyproject.toml").read_text()) + assert "py.typed" in jvm["tool"]["setuptools"]["package-data"]["arcadedb"] + assert "py.typed" in native["tool"]["setuptools"]["package-data"]["arcadedb"] + assert (ROOT / "src" / "arcadedb" / "py.typed").is_file() + + +def _public_callables(): + """(qualified name, function) for every public function, and every public method and property of every public class.""" + targets = [getattr(arcadedb, n) for n in arcadedb.__all__ if hasattr(arcadedb, n)] + targets.append(arcadedb.aio.AsyncDatabase) + for target in targets: + module = getattr(target, "__module__", "") or "" + if not module.startswith("arcadedb"): + continue + if inspect.isclass(target): + if target.__name__.startswith("_") or issubclass(target, BaseException): + continue + for name, member in vars(target).items(): + if name.startswith("_") and name not in ( + "__init__", + "__enter__", + "__exit__", + ): + continue + if isinstance(member, (staticmethod, classmethod)): + member = member.__func__ + elif isinstance(member, property): + member = member.fget + if inspect.isfunction(member): + yield f"{target.__name__}.{name}", member + elif inspect.isfunction(target): + yield target.__name__, target + + +def test_there_are_public_callables_to_check(): + names = [name for name, _ in _public_callables()] + assert ( + "Database.query" in names + and "open_database" in names + and "VectorIndex.find_nearest" in names + ), names + + +def test_every_public_callable_has_type_hints(): + missing = [] + for name, fn in _public_callables(): + if name in EXEMPT: + continue + sig = inspect.signature(fn) + bare = [ + p.name + for p in sig.parameters.values() + if p.name not in ("self", "cls") and p.annotation is inspect.Parameter.empty + ] + if bare: + missing.append(f"{name}: parameters without a hint: {bare}") + if sig.return_annotation is inspect.Signature.empty and not name.endswith( + ".__init__" + ): + missing.append(f"{name}: no return hint") + assert not missing, "\n".join(missing) + + +@pytest.mark.parametrize( + "name", + ["create_database", "open_database", "database_exists"], +) +def test_the_entry_points_name_the_database_type(name): + ret = inspect.signature(getattr(arcadedb, name)).return_annotation + assert ret in (arcadedb.Database, "Database", bool), (name, ret) diff --git a/tests/test_wheel_packages.py b/tests/test_wheel_packages.py index 6bbf34f..7403050 100644 --- a/tests/test_wheel_packages.py +++ b/tests/test_wheel_packages.py @@ -69,3 +69,14 @@ def test_backend_selection_imports_without_native_library(tmp_path): subprocess.run( # nosec B603 - fixed argv, no shell, test-owned code string [sys.executable, "-c", code], check=True, cwd=tmp_path, env=env ) + + +def test_build_ships_py_typed(tmp_path): + """The JVM wheel carries the PEP 561 marker (#476): it is a package-data entry, nothing picks it up by itself.""" + root = _built_root(tmp_path) + if root is None: + import arcadedb + + assert (Path(arcadedb.__file__).parent / "py.typed").exists() + return + assert (root / "arcadedb" / "py.typed").exists()