-
Notifications
You must be signed in to change notification settings - Fork 0
Wire SPARQL endpoint to project ontology graph #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JohnRDOrazio
wants to merge
16
commits into
main
Choose a base branch
from
feature/sparql-ontology-loading
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
98ce4c6
Wire SPARQL endpoint to project ontology graph with auth and branch s…
JohnRDOrazio 90cf441
Fix tests for required ontology_id in SPARQL endpoint
JohnRDOrazio db13cc3
Use dependency injection and asyncio.to_thread for git operations
JohnRDOrazio 9fcf842
Remove dead getattr call for git_ontology_path
JohnRDOrazio eaeab9a
Add public get_graph method to OntologyService
JohnRDOrazio 5eb07ef
Use UUID type for SPARQLQuery.ontology_id for automatic validation
JohnRDOrazio 25eec68
Extract shared resolve_branch helper for consistent branch resolution
JohnRDOrazio 833ca53
Merge branch 'main' into feature/sparql-ontology-loading
JohnRDOrazio ff9db86
fix(test): ensure empty SPARQL query test validates the query field
JohnRDOrazio 03494ed
fix: log git-to-storage fallback exceptions in load_project_graph
JohnRDOrazio 36008ba
fix(test): use MagicMock for __iter__ instead of lambda with _self
JohnRDOrazio b4553c2
fix: prevent concurrent duplicate graph loads with per-key async lock
JohnRDOrazio e2d2c89
fix: evict per-key graph load locks after loading completes
JohnRDOrazio 98bb5f9
fix: raise 404 instead of falling back to storage for explicit branches
JohnRDOrazio 1bafa05
fix: relocate lock eviction and add identity check in load_project_graph
JohnRDOrazio 3e68450
Merge branch 'main' into feature/sparql-ontology-loading
JohnRDOrazio File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,3 +31,4 @@ repos: | |
| - pgvector>=0.3.0 | ||
| - sentence-transformers>=3.0.0 | ||
| - cryptography>=42.0.0 | ||
| - pytest>=8.0.0 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| # CLAUDE.md | ||
|
|
||
| This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. | ||
|
|
||
| ## Project Overview | ||
|
|
||
| OntoKit API is a collaborative OWL ontology curation platform built with FastAPI (Python 3.11+). It provides a RESTful API for managing ontologies, semantic web knowledge graphs, and team collaboration with git-based version control. Distributed as the `ontokit` package on PyPI. | ||
|
|
||
| ## Commands | ||
|
|
||
| ### Development Server | ||
| ```bash | ||
| uvicorn ontokit.main:app --reload | ||
| # Or using the installed CLI: | ||
| ontokit --reload | ||
| ``` | ||
|
|
||
| ### Docker Compose (Full Stack) | ||
| ```bash | ||
| docker compose up -d | ||
| ``` | ||
|
|
||
| ### Linting & Formatting | ||
| ```bash | ||
| ruff check ontokit/ --fix # Lint with auto-fix | ||
| ruff format ontokit/ # Format code | ||
| ``` | ||
|
|
||
| ### Type Checking | ||
| ```bash | ||
| mypy ontokit/ | ||
| ``` | ||
|
|
||
| ### Testing | ||
| ```bash | ||
| pytest tests/ -v --cov=ontokit # Run all tests with coverage | ||
| pytest tests/unit/test_health.py -v # Run single test file | ||
| pytest tests/ -k "test_name" -v # Run tests matching pattern | ||
| ``` | ||
|
|
||
| ### Building & Publishing | ||
| ```bash | ||
| uv build # Build sdist + wheel | ||
| uv run twine check --strict dist/* # Validate package | ||
| uv publish # Publish to PyPI | ||
| ``` | ||
|
|
||
| ### Database Migrations | ||
| ```bash | ||
| alembic upgrade head # Apply all migrations | ||
| alembic downgrade -1 # Rollback one migration | ||
| alembic revision --autogenerate -m "description" # Create new migration | ||
| ``` | ||
|
|
||
| ### Release Management | ||
| ```bash | ||
| python scripts/prepare-release.py # Strip -dev suffix, commit | ||
| git tag -s ontokit-X.Y.Z # Tag the release | ||
| git push --tags # Trigger CI/CD publish | ||
| python scripts/set-version.py X.Y.Z # Set next dev version (adds -dev) | ||
| ``` | ||
|
|
||
| ## Architecture | ||
|
|
||
| ### Layer Structure | ||
| ``` | ||
| ontokit/ | ||
| ├── api/routes/ # REST endpoints (FastAPI routers) | ||
| ├── services/ # Business logic layer | ||
| ├── models/ # SQLAlchemy ORM models | ||
| ├── schemas/ # Pydantic v2 request/response schemas | ||
| ├── core/ # Config, database, auth infrastructure | ||
| ├── git/ # Git repository management | ||
| ├── collab/ # WebSocket real-time collaboration | ||
| ├── version.py # Version management (Weblate-style) | ||
| ├── runner.py # CLI entry point | ||
| └── worker.py # ARQ background job queue | ||
| ``` | ||
|
|
||
| The URL prefix `/api/v1/` is preserved in `main.py` router registration — the version is a URL concern, not a directory concern. | ||
|
|
||
| ### Key Services | ||
| - **ontology.py** - RDF/OWL graph operations using RDFLib and OWLReady2 | ||
| - **linter.py** - Ontology validation with 20+ rule checks | ||
| - **pull_request_service.py** - Git-based PR workflow with diff generation | ||
| - **github_service.py** - GitHub App integration for syncing | ||
| - **project_service.py** - Project CRUD and member management | ||
|
|
||
| ### Git Module (`ontokit/git/`) | ||
| The git module uses **pygit2 with bare repositories** for concurrent access: | ||
| - **bare_repository.py** - Core implementation using pygit2 | ||
| - `BareOntologyRepository` - Direct git object manipulation without working directory | ||
| - `BareGitRepositoryService` - Service layer with backward-compatible API | ||
| - **repository.py** - Legacy GitPython implementation (deprecated) | ||
| - Bare repos allow multiple users to work on different branches simultaneously | ||
| - All file operations work directly on git blobs/trees, no checkout needed | ||
|
|
||
| ### Technology Stack | ||
| - **Database**: PostgreSQL 17 (async via asyncpg + SQLAlchemy 2.0) | ||
| - **Cache/Queue**: Redis 7 (ARQ job queue, pub/sub) | ||
| - **Storage**: MinIO (S3-compatible object storage) | ||
| - **Auth**: Zitadel (OIDC/OAuth2 with JWT validation) | ||
| - **RDF**: RDFLib 7.1+ for graph manipulation | ||
| - **Git**: pygit2 with bare repositories for concurrent version control | ||
|
|
||
| ### Key Patterns | ||
| - Async-first: All I/O uses async/await | ||
| - Dependency injection via FastAPI's `Depends()` | ||
| - Pydantic v2 for strict validation with computed fields | ||
| - Service singletons obtained via `get_service_name()` dependencies | ||
| - UTC timezone-aware datetime fields throughout | ||
|
|
||
| ## Configuration | ||
|
|
||
| Environment variables are configured in `.env` (see `.env.example`). Key sections: | ||
| - Database: `DATABASE_URL` (PostgreSQL with asyncpg driver) | ||
| - Auth: `ZITADEL_ISSUER`, `ZITADEL_CLIENT_ID`, `ZITADEL_CLIENT_SECRET` | ||
| - Storage: `MINIO_ENDPOINT`, `MINIO_ACCESS_KEY`, `MINIO_SECRET_KEY` | ||
| - Git: `GIT_REPOS_BASE_PATH` for local repository storage | ||
|
|
||
| ## Code Quality Settings | ||
|
|
||
| From pyproject.toml: | ||
| - Line length: 100 characters | ||
| - Ruff rules: E, W, F, I, B, C4, UP, ARG, SIM | ||
| - MyPy: Strict mode enabled, Python 3.11 target | ||
|
|
||
| ## Scripts | ||
|
|
||
| ### Git Repository Migration | ||
| To migrate existing working-directory repositories to bare repositories: | ||
| ```bash | ||
| python scripts/migrate_to_bare_repos.py --dry-run # Preview changes | ||
| python scripts/migrate_to_bare_repos.py # Execute migration | ||
| python scripts/migrate_to_bare_repos.py --keep-old # Keep old repos after migration | ||
| ``` |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| AGENTS.md |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| AGENTS.md |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| """Shared dependencies for API route handlers.""" | ||
|
|
||
| import asyncio | ||
| import logging | ||
| import os | ||
| from uuid import UUID | ||
|
|
||
| from fastapi import HTTPException, status | ||
| from rdflib import Graph | ||
| from sqlalchemy import select | ||
| from sqlalchemy.ext.asyncio import AsyncSession | ||
|
|
||
| from ontokit.core.auth import CurrentUser | ||
| from ontokit.models.project import Project | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # Per-(project, branch) locks to prevent concurrent duplicate graph loads. | ||
| _graph_load_locks: dict[tuple[UUID, str], asyncio.Lock] = {} | ||
|
|
||
|
|
||
| async def load_project_graph( | ||
| project_id: UUID, branch: str | None, db: AsyncSession | ||
| ) -> tuple[Graph, str]: | ||
| """Load the ontology graph for a project, returning (graph, resolved_branch). | ||
|
|
||
| Resolves the branch to the repository default when not specified, | ||
| loads the ontology from git (falling back to storage), and returns | ||
| the in-memory RDFLib graph. | ||
| """ | ||
| from ontokit.git.bare_repository import get_bare_git_service | ||
| from ontokit.services.ontology import get_ontology_service | ||
| from ontokit.services.storage import get_storage_service | ||
|
|
||
| result = await db.execute(select(Project).where(Project.id == project_id)) | ||
| project = result.scalar_one_or_none() | ||
| if not project: | ||
| raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Project not found") | ||
|
|
||
| if not project.source_file_path: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_400_BAD_REQUEST, | ||
| detail="Project does not have an ontology file", | ||
| ) | ||
|
|
||
| storage = get_storage_service() | ||
| ontology = get_ontology_service(storage) | ||
| git = get_bare_git_service() | ||
|
|
||
| resolved_branch = await resolve_branch(project_id, branch) | ||
|
|
||
| key = (project_id, resolved_branch) | ||
| if key not in _graph_load_locks: | ||
| _graph_load_locks[key] = asyncio.Lock() | ||
|
|
||
| lock = _graph_load_locks[key] | ||
| async with lock: | ||
| if not ontology.is_loaded(project_id, resolved_branch): | ||
| filename = os.path.basename(project.source_file_path) | ||
| try: | ||
| await ontology.load_from_git(project_id, resolved_branch, filename, git) | ||
| except (FileNotFoundError, KeyError, ValueError): | ||
| if branch is not None: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_404_NOT_FOUND, | ||
| detail=f"Ontology file not found on branch '{resolved_branch}'", | ||
| ) from None | ||
| logger.debug( | ||
| "Git loading failed for project %s branch %s, falling back to storage", | ||
| project_id, | ||
| resolved_branch, | ||
| exc_info=True, | ||
| ) | ||
| await ontology.load_from_storage( | ||
| project_id, project.source_file_path, resolved_branch | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
|
|
||
| # Remove the lock once the graph is loaded and no other task is waiting on it. | ||
| if not lock.locked() and _graph_load_locks.get(key) is lock: | ||
| _graph_load_locks.pop(key, None) | ||
|
|
||
| graph = await ontology.get_graph(project_id, resolved_branch) | ||
| return graph, resolved_branch | ||
|
|
||
|
|
||
| async def resolve_branch(project_id: UUID, branch: str | None) -> str: | ||
| """Resolve a branch name, falling back to the repository default.""" | ||
| if branch: | ||
| return branch | ||
| from ontokit.git.bare_repository import get_bare_git_service | ||
|
|
||
| git = get_bare_git_service() | ||
| return await asyncio.to_thread(git.get_default_branch, project_id) | ||
|
|
||
|
|
||
| async def verify_project_access( | ||
| project_id: UUID, db: AsyncSession, user: CurrentUser | None | ||
| ) -> None: | ||
| """Verify the user has access to the project. | ||
|
|
||
| For public projects, unauthenticated users are allowed. | ||
| For private projects, the user must be a member. | ||
| """ | ||
| from ontokit.services.project_service import get_project_service | ||
|
|
||
| service = get_project_service(db) | ||
| await service.get(project_id, user) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.