Skip to content
Open
Show file tree
Hide file tree
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 Mar 10, 2026
90cf441
Fix tests for required ontology_id in SPARQL endpoint
JohnRDOrazio Mar 10, 2026
db13cc3
Use dependency injection and asyncio.to_thread for git operations
JohnRDOrazio Mar 10, 2026
9fcf842
Remove dead getattr call for git_ontology_path
JohnRDOrazio Mar 10, 2026
eaeab9a
Add public get_graph method to OntologyService
JohnRDOrazio Mar 10, 2026
5eb07ef
Use UUID type for SPARQLQuery.ontology_id for automatic validation
JohnRDOrazio Mar 10, 2026
25eec68
Extract shared resolve_branch helper for consistent branch resolution
JohnRDOrazio Mar 10, 2026
833ca53
Merge branch 'main' into feature/sparql-ontology-loading
JohnRDOrazio Mar 11, 2026
ff9db86
fix(test): ensure empty SPARQL query test validates the query field
JohnRDOrazio Mar 11, 2026
03494ed
fix: log git-to-storage fallback exceptions in load_project_graph
JohnRDOrazio Mar 11, 2026
36008ba
fix(test): use MagicMock for __iter__ instead of lambda with _self
JohnRDOrazio Mar 11, 2026
b4553c2
fix: prevent concurrent duplicate graph loads with per-key async lock
JohnRDOrazio Mar 11, 2026
e2d2c89
fix: evict per-key graph load locks after loading completes
JohnRDOrazio Mar 11, 2026
98bb5f9
fix: raise 404 instead of falling back to storage for explicit branches
JohnRDOrazio Mar 11, 2026
1bafa05
fix: relocate lock eviction and add identity check in load_project_graph
JohnRDOrazio Mar 11, 2026
3e68450
Merge branch 'main' into feature/sparql-ontology-loading
JohnRDOrazio Mar 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ repos:
- pgvector>=0.3.0
- sentence-transformers>=3.0.0
- cryptography>=42.0.0
- pytest>=8.0.0
136 changes: 136 additions & 0 deletions AGENTS.md
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
```
136 changes: 0 additions & 136 deletions CLAUDE.md

This file was deleted.

1 change: 1 addition & 0 deletions CLAUDE.md
1 change: 1 addition & 0 deletions GEMINI.md
107 changes: 107 additions & 0 deletions ontokit/api/dependencies.py
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
)

# 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)
Loading
Loading